为什么unregisterReceiver()永远不会调用onServiceDisconnected?

我绑定到我的活动中的服务:

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()? 

你误解了onServiceDisconnected()的用途

在与服务的连接丢失时调用。 当托管服务的进程崩溃或死亡时,通常会发生这种情况。 这不会删除ServiceConnection本身 – 与服务的绑定将保持活动状态,并且在下次运行服务时,您将收到对onServiceConnected(ComponentName, IBinder)的调用。

所以这实际上只有在你断开与实际服务的连接时才被调用。 当您从服务中解除绑定时,您必须手动进行清除。 更好地处理与ServiceConnection不同(其他)级别的接收器 – 例如onStart() / onStop()