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 and
stopService`:
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.
It allows components (such as activities) to bind to the service, send requests, receive responses, and perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.
The Unbound service runs in the background indefinitely. Where As The Bound service does not run in the background indefinitely.
Stopping a service. You stop a service via the stopService() method. No matter how frequently you called the startService(intent) method, one call to the stopService() method stops the service. A service can terminate itself by calling the stopSelf() method.
You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.
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).
A gotcha that I hit with this:
Ensure you call unbindService on the same context that you called bindService. In my case, I was doing the following to bind it:
Context c = getApplicationContext();
c.bindService(...);
Then to unbind it, just:
unbindService(...);
Making sure both bind and unbind used the same context solved the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With