我如何使用 livedata 从服务更新 UI?

How can i update UI from service using livedata?

我正在创建播放器应用程序,我想为我的媒体播放器使用前台服务。我需要使用来自服务的实时数据更新 UI。我已经阅读过有关使用广播接收器的信息,但我想使用实时数据。

您可以在这里找到答案:


您可以在服务中使用单例模式来初始化 LiveData 对象并从您的 activity

观察

假设您的服务是 TestingService,代码如下:

class TestingService : LifecycleService() {
    
    companion object {
        val testingNumber = MutableLiveData<Int>()
    }

    override fun onCreate() {
        super.onCreate()
        initValues()
    }

    private fun initValues() {
        testingNumber.postValue(0)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        intent?.let {
            when (it.action) {
                ACTION_START_SERVICE -> {
                    // Starting service
                    testingNumber.postValue(2)
                    startForegroundService()
                }
                ACTION_STOP_SERVICE -> {
                    // Stopping service
                    stopService()
                }
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }
}

并且您可以通过这种方式从 activity 观察 LiveData:

 class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setObservers()
    }

    private fun setObservers() {
        TestingService.testingNumber.observe(this, Observer {
            updateUi(it)
        })
    }
}

假设您使用具有以下实时数据的服务

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)
     }
}

然后在您的 activity 上,您可以将 MutableLiveData 转换为 LiveData 以获取更新

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
        })
    }
}

我建议您使用 viewmodel 从服务中获取可变的实时数据