tags:

views:

34

answers:

1

I'm binding to a local Service (that is, not using IPC and AIDL) from several activities. I want to ensure that I'm not holding references to this service from activities that the user isn't using.

My options are: 1.) to bind to the service in onCreate() and unbind in onDestroy(). 2.) bind in onStart() and unbind in onStop(). 3.) bind in onResume() and unbind in `onPause(). Or some combination of these.

Which is the best-practice way of binding and unbinding to a local service? Do I not need to be concerned with holding local connections from stopped activities?

Additionally, once bound to this particular service I am retrieving a Cursor which is attached to my ListActivity via a CursorAdapter. The data retrieved by the Cursor may have changed while the Activity was out of view so I want to requery it when the Activity is shown again. If I bind in onCreate() I can requery in onRestart(). If I bind in onResume() each time the data will be fresh because I'll query it in the Service's connected callback.

Thoughts, comments, critiques or suggestions?

A: 

It depends if the service was started by binding to it, or by calling startService(). If startService(), there is very little difference where/when you bind/unbind.

If it was started by binding to it, we can't answer that question without knowing the specifics.

It looks like your service will always be running (ie started by startService()), so it appears that it doesn't matter where you bind/unbind. Just choose the most logical place.

Falmarri
Thanks! This service is a dual service so it is both started and bound to by Activities. What additional specifics would you need to better understand my question?
kpdvx
Is it both at separate times? Or are you starting it with startService, and then binding to it? If the latter, then binding to it doesn't affect it very much and you can just put it in the most logical place.
Falmarri
The service can be started first then bound to, or bound to while having not been started.
kpdvx
Well those are 2 entirely different licecycles with vastly different use cases. You should probably use 1 method or the other. You should read up on the service lifecycle http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle
Falmarri
Not entirely true, yes they're different lifecycles but their use-cases are not entirely dissimilar. For example, hosting a long-running process in a Service (and starting the service via startService()) and then binding to it from an activity to find out the processes' status. I believe the Music app does this.
kpdvx
But that's not STARTING the service via binding to it. That's what makes the use case different. Once a service is started with startService(), binding to it doesn't change the lifecycle of the service
Falmarri