【发布时间】:2020-08-21 10:53:59
【问题描述】:
我正在开发一个在Service 中使用LiveData 实例的项目。
我们将 Service 初始化为与我们的 Activity 绑定的服务,因此我们使用 bindService() 和 unBindService() 来连接和断开连接。我们分别在活动生命周期的onResume() 和onPause() 中调用这些函数。
class TestActivity: Activity() {
lateinit var ourService: OurService
val serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
val binder = service as OurService.LocalBinder
ourService = binder.getService()
// Does this cause ourService to be retained beyond unbind the only client
ourService.liveReading.observe(this@TestActivity, Observer {}
}
}
override fun onResume() {
Intent(this, OurService::class.java).also { intent ->
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
}
override fun onPause() {
unBindService(serviceConnection)
}
}
我注意到有一种极端情况,即我在 OurService 的 LiveData 属性中获得了不止一个发射。我想知道这是否是因为将所有者设置为活动,该活动在 onPause/onResume 循环中存活,导致服务在 onPause 情况下不会被销毁,因此导致在另一个循环 onPause/ 后将多个观察者分配给 livedata onResume。
【问题讨论】:
-
您的服务是否通过其
onDestroy?
标签: android android-service android-livedata