views:

189

answers:

1

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.

+1  A: 

As you can see here it depends what you want to achieve and how you bind the service. If you want to have a long time reference to the service, it is better to use bindService than startService. If in the bindService method, the flag BIND_AUTO_CREATE is used, then you don't have to call startService, because the service starts itself when necessary.

If you call unBind service, then you assoication to the service is deleted. You dont' have to explicitly stop the service but you can. But it's importatnt to note, that if you call unBind(), then the service is allowed to stop at any time.

Roflcoptr
Thanks, but I've been there, and it's not clear if I need to both unbind and stop the service if I manually started it before binding to it with the BIND_AUTO_CREATE flag.
Matt Huggins