将 activity 绑定到 运行 服务时未调用 onUnbind

onUnbind not being called when binding the activity to a running service

我有这个 activity 启动并绑定到服务:

@Override
protected void onStart() {
    super.onStart();

    Intent intent = new Intent(context, SoundService.class);
    context.startService(intent);
    context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}

我通过以下方式解除绑定:

@Override
protected void onStop() {
    context.unbindService(serviceConnection);

    super.onStop();
}

即使在关闭 activity 后,服务仍保持 运行。看看这个场景:

  1. Activity 启动服务并绑定到它
  2. Activity 被杀死,服务保持 运行,onUnbind() 被调用
  3. Activity 再次启动,并绑定到 运行 服务
  4. Activity 被杀死,onUnbind() 而不是 调用:(

为什么 onUnbind() 没有被调用?

您是如何启动该服务的?请粘贴该代码。

服务只会在您调用 unbindService() 后停止 如果 没有其他客户端连接到此服务 AND服务开始于 bind 调用 AUTO_CREATE。如果服务是用 startService() 启动的,那么服务将不会停止,直到服务调用 stopSelf() 或 android 终止它以释放内存

return true 来自 onUnbind,下次如果您再次调用 bindService 不仅会调用 onRebind,还会在最后一个客户端解除绑定时调用另外onUnbind会被系统调用