I have a media player service that plays music in the background of my app throughout activities like :
public class Music extends Service {
MediaPlayer play
Can be less boilerplate with LifecycleObserver:
class App : Application(), LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppInBackground() {
sendStatus(0)
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppInForeground() {
sendStatus(1)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onAppDestroyed() {
sendStatus(2)
}
private fun sendStatus(statusCounter: Int) {
val intent = Intent("status")
intent.putExtra("status", statusCounter)
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
}
Add to build.gradle (app)
implementation "androidx.lifecycle:lifecycle-runtime:2.1.0"
implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.1.0"