views:

151

answers:

3

I'm a little confused on how binding to services works. I understand using Context.startService() starts the service and that bindService doesn't call onStartCommand. But my understanding is that if I use startService, I have to explicitly stop the service. But I want the service to die if there are no more activities bound to it.

My problem is that calling bindService never calls onServiceConnected(), so my Service binder object is null. Does the service have to be explicitly started in order to bind to it? If so, how does it know to terminate when nothing is binding to it anymore, and how do I know if it's started so I can know to use the bound object?

A: 

You should be setting up your binder in onBind and any generic setup in onCreate. The behaviour of starting and binding services is explained at http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle

Al Sutton
+1  A: 

if you call bindService with BIND_AUTO_CREATE as flag the system will bind your activity to the service if it exists, otherwise if it doesn't exist the system will start the service for you and then it will bind your activity to the service. Furthermore if you start a Service in this way the service will remain active only if it has still some context binded.

this is from bindService():

Connect to an application service, creating it if needed. This defines a dependency between your application and the service. The given conn will receive the service object when its created and be told if it dies and restarts. The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed

and this is from ServiceLyfecycle

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

hara
That's how I thought it worked, but even if I pass in BIND_AUTO_CREATE I was getting null pointer exceptions on my binder object. It turns out that the service won't be bound until after onCreate() exits. Or at least that's what I read.
Falmarri
Did you register your service in the manifest file?Could you post your code?
hara
Yeah the service works, what I actually posted is the solution (99% sure). The service doesn't actually get bound until exiting oncreate.
Falmarri
A: 

The answer is that I wasn't waiting for the service to actually be bound before using it, since it gets bound asynchronously

Falmarri