Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 634
Matt Huggins Avatar asked Aug 02 '10 06:08

Matt Huggins


People also ask

What is binding and querying Android service?

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.

What is the difference between bound and unbound service in Android?

The Unbound service runs in the background indefinitely. Where As The Bound service does not run in the background indefinitely.

Which method is used to stop service in Android?

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.

Can a service start another service in Android?

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.


2 Answers

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

like image 135
Mike Lowery Avatar answered Nov 03 '22 16:11

Mike Lowery


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.

like image 29
rmc47 Avatar answered Nov 03 '22 14:11

rmc47