Stop MediaPlayer service when app goes in Background

前端 未结 5 1103
不思量自难忘°
不思量自难忘° 2020-12-10 21:25

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         


        
5条回答
  •  被撕碎了的回忆
    2020-12-10 22:15

    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"
    

提交回复
热议问题