如何观察服务类内的实时数据

Pet*_*ter 4 android android-studio

我想将从 API 获得的一些记录插入到数据库中,我正在使用服务类来执行此过程,我试图在服务类中使用实时数据的概念,但它要求我的服务类是生命周期所有者。

我一直在思考如何让我的服务类观察者实时数据的变化

任何帮助都会很好!

Key*_*öze 12

如果您的服务不应受到活动生命周期(等)的影响,onStop()那么onStart()您可以使用LiveData<T>.observeForever(Observer<T>)方法。就像这样,

val observer = Observer<YourDataType> { data ->
    //Live data value has changed
}

liveData.observeForever(observer)
Run Code Online (Sandbox Code Playgroud)

要停止观察,您必须致电LiveData.removeObserver(Observer<T>)。就像这样:

liveData.removeObserver(observer)
Run Code Online (Sandbox Code Playgroud)

如果您需要在应用程序处于后台时停止观察,您可以在调用 ActivityonStart()的方法中绑定您的服务,并在该onStop()方法中取消绑定您的服务。就像这样:

override fun onStart() {
   super.onStart()

   val serviceIntent = Intent(this, myService::class.java)
   bindService(serviceIntent, myServiceConnection, Context.BIND_AUTO_CREATE)
}

override fun onStop() {
    unbindService(myServiceConnection)
    super.onStop()
}
Run Code Online (Sandbox Code Playgroud)

在此处阅读绑定服务

然后,在服务中

  1. 覆盖onBind(Intent)onRebind(Intent)方法并开始观察LiveData(应用程序位于前台)
override fun onBind(intent: Intent?): IBinder? {
    liveData.observeForever(observer)

    return serviceBinder
}

override fun onRebind(intent: Intent?) {
    liveData.observeForever(observer)

    super.onRebind(intent)
}
Run Code Online (Sandbox Code Playgroud)
  1. 删除LiveData观察者onUnbind(Intent)(应用程序在后台)
override fun onUnbind(intent: Intent?): Boolean {
    liveData.removeObserver(observer)
    return true
}
Run Code Online (Sandbox Code Playgroud)