我需要通话双方unbindService和stopService为Android服务?双方、unbindService、Android、stopService

2023-09-03 23:13:27 作者:しovё搁浅

在我的Andr​​oid应用程序,我呼吁双方 startService bindService

In my Android app, I call both startService and bindService:

Intent intent = new Intent(this, MyService.class);
ServiceConnection conn = new ServiceConnection() { ... }

startService(intent)
bindService(intent, conn, BIND_AUTO_CREATE);

后来,我尝试将两种 unbindService和 stopService`:

Later, I attempt to both unbindService andstopService`:

unbindService(conn);
stopService(intent);

不过,我到 unbindService 在电话会议上的异常。如果我删除该调用,应用程序似乎通过 stopService 通话正常运行。

However, I get an exception on the call to unbindService. If I remove this call, the app seems to run properly through the stopService call.

我是不是做错了什么?我想到了一个 bindService 的呼叫必须与 unbindService 呼叫相关的,和 startService 电话必须用 stopService 呼叫关联。但这似乎不是这里的情况,虽然。

Am I doing something wrong? I thought a bindService call had to be associated with an unbindService call, and a startService call had to be associated with a stopService call. This doesn't seem to be the case here, though.

推荐答案

Android的文档stopService()规定:

The Android documentation for stopService() states:

请注意,如果已停止的服务仍具有绑定到它与BIND_AUTO_CREATE集ServiceConnection对象,也不会被破坏,直到所有这些绑定被除去。请参阅服务文档上的服务的生命周期的更多细节。

Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed. See the Service documentation for more details on a service's lifecycle.

所以调用stopService()首先其次​​是unbindService()应该工作(它的工作对我来说)。

So calling stopService() first followed by unbindService() should work (it's working for me).