Last active
November 2, 2022 14:25
-
-
Save alokomkar/8aafdd64a1b2c860120dfb78afc93df1 to your computer and use it in GitHub Desktop.
Step 2: Foreground service : HomeFragment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Intent | |
import android.os.Bundle | |
import android.view.LayoutInflater | |
import android.view.View | |
import android.view.ViewGroup | |
import androidx.appcompat.widget.AppCompatButton | |
import androidx.core.content.ContextCompat | |
import androidx.fragment.app.Fragment | |
import com.alokomkar.javacollections.R | |
import com.alokomkar.service.AudioForegroundLoopService | |
import com.alokomkar.service.AudioLoopService | |
import com.alokomkar.service.ServiceAction | |
class HomeFragment: Fragment() { | |
private val audioLoopServiceIntent: Intent by lazy { | |
Intent( | |
context, | |
AudioLoopService::class.java | |
) | |
} | |
override fun onCreateView( | |
inflater: LayoutInflater, | |
container: ViewGroup?, | |
savedInstanceState: Bundle? | |
): View? { | |
return inflater.inflate(R.layout.fragment_home, container, false) | |
} | |
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | |
super.onViewCreated(view, savedInstanceState) | |
view.apply { | |
findViewById<AppCompatButton>(R.id.startButton).setOnClickListener { | |
context.startService(audioLoopServiceIntent) | |
} | |
findViewById<AppCompatButton>(R.id.stopButton).setOnClickListener { | |
context.stopService(audioLoopServiceIntent) | |
} | |
findViewById<AppCompatButton>(R.id.startButtonForeground).setOnClickListener { | |
ContextCompat.startForegroundService( | |
context, | |
getAudioPlayerForegroundServiceIntent(ServiceAction.START_ACTION) | |
) | |
} | |
findViewById<AppCompatButton>(R.id.stopButtonForeground).setOnClickListener { | |
context.stopService(getAudioPlayerForegroundServiceIntent(ServiceAction.STOP_ACTION)) | |
} | |
} | |
} | |
private fun getAudioPlayerForegroundServiceIntent(action: ServiceAction) = Intent( | |
context, | |
AudioForegroundLoopService::class.java | |
).apply { | |
setAction(action.value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment