How to stop an Android Service ONLY when there are no other activities in my app running?
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?
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.
精彩评论