Search code examples
androidkotlinserviceandroid-mediaplayerforeground-service

How can i update UI from service using livedata?


I'm creating player app and i want to use foreground service for my media player. I need to update UI using livedata from service. I'm already read about using broadcast receiver but i want to use livedata.


Solution

  • Suppose you use have a service with live data as follows

    class MusicService: Service() {
        companion object {
            const val STAT_PLAY = "playing"
            const val STAT_PAUSE = "pause"
            val playerStateLiveData = MutableLiveData<String>()
        }
        /*
         * your code here to implement play, pause, etc
         * */
         private fun playAt(duration: Int) {
             /*play music player logic*/
             //update live data
             playerStateLiveData.postValue(STAT_PLAY)
         }
         private fun pause() {
             /*pause music player logic*/
             //update live data
             playerStateLiveData.postValue(STAT_PAUSE)
         }
    }
    

    And then on your activity, you can cast the MutableLiveData as LiveData to get updates

    class MainActivity: AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.main_activity)
            
            val liveData: LiveData<String> = MusicService.playerStateLiveData
            
            liveData.observe(this, { musicPlayerState ->
                //update main activity view based on state changed
            })
        }
    }
    

    Im suggesting you to use viewmodel to get mutable live data from service