Search code examples
androidserviceconnection

Do I need to call both unbindService and stopService for Android services?


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);

Later, I attempt to both unbindService andstopService`:

unbindService(conn);
stopService(intent);

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.

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.


Solution

  • The Android documentation for stopService() states:

    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.

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