views:

435

answers:

1

Is there a way I can test if there are any other activities in my app still alive? I am looking to stop a service in an onDestroy method, but only want to do this if there are no other activities from my app still alive on the stack.

I have the call stop the service in the main activity's onDestroy() method. This works perfect EXCEPT that if a user launches my app, then launches a few activities in my app, then hits the home screen and RELAUNCHES my app, they will subvert my order and the main activity will now be above other activities of my app. From this state, if they hit the back button and 'back out' of my home screen they will trigger the onDestroy() method and kill the service even though there are other activities open on the stack. I want to avoid this by stopping the service ONLY if I am sure there are no other activities of mine open on the stack. Possible?

+1  A: 

How can I launch a service that will continue to run as long as any of my app's activities are still on the stack, yet be stopped when none remain?

Don't use startService() and stopService(). Instead, use bindService() and unbindService(), even if you don't really need the bound connection. The bind/unbind is reference counted. If you call bindService() with the BIND_AUTO_CREATE flag, the first bindService() call will start your service. Then, when all bindService() calls have had matching unbindService() calls, Android will automatically shut down your service.

CommonsWare
Thank you for this. Are you saying then that EVERY action in my app needs to call bindService() in order to keep it alive ? And, should each activity then also call unbindservice in its destroy method? How does the service push data to the active bound activity?
"Are you saying then that EVERY action in my app needs to call bindService() in order to keep it alive ?" Assuming you meant to say "EVERY Activity", then I have no idea. You're the guy in charge of what activities keep the service in memory and what ones don't. "And, should each activity then also call unbindservice in its destroy method?" Every activity that binds to the service must unbind from the service. "How does the service push data to the active bound activity?" Same way you have it doing that today.
CommonsWare
Every Activity, where you want the Service to start/remain running, needs to call `bindService()` during `onStart()` and `unbindService()` in `onStop()`. See also: http://stackoverflow.com/questions/2304086/binding-to-service-in-oncreate-or-in-onresume/2304794#2304794Your service 'pushes' data to bound activities in the same way it would as if you used `startService()`: you would register a callback with the service.
Christopher