我在我的活动中绑定了一个服务:
override fun onStart() {
Timber.d("onStart")
super.onStart()
val intent = Intent(this, MyService::class.java)
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
到目前为止有效。然后bindService()
调用了onServiceConnected()
:
/** Defines callbacks for service binding, passed to bindService() */
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName,
service: IBinder) {
// We've bound to MyService, cast the IBinder and get MyService instance
val binder = service as MyService.MyBinder
myService = binder.service
isBound = true
registerReceiver(myBroadcastReceiver, filter)
}
override fun onServiceDisconnected(arg0: ComponentName) {
myService!!.removeRecevier(this@MainActivity)
isBound = false
unregisterReceiver(myBroadcastReceiver)
}
}
在我的onStop()
我也有unbindService(serviceConnection)
,但这里的onServiceDisconnected()从未被触发过? 我做错了什么?
因此我得到:
Activity MainActivity has leaked IntentReceiver com.example.MyBroadcastReceiver@68091a2 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Activity MainActivity has leaked IntentReceiver com.example.MyBroadcastReceiver@68091a2 that was originally registered here. Are you missing a call to unregisterReceiver()?
答案 0 :(得分:0)
与服务的连接丢失时调用。这通常发生在托管服务的进程崩溃或被杀死时。这不会删除ServiceConnection本身 - 这种对服务的绑定将保持活动状态,当服务下次运行时,您将收到
onServiceConnected(ComponentName, IBinder)
的调用。
因此,只要您松开与实际服务的连接,实际上只会调用它。解除绑定服务后,必须手动进行清理。更好地处理与ServiceConnection
不同的(其他)级别的接收器 - 如onStart()
/ onStop()
。