Stop a service when none of the activities are in the foreground
I have a ser开发者_开发知识库vice that is used by all my activities and should be stopped when none of the activities are in the foreground but keep running all the time when one activity is visible. Since Android doesn't keep an internal state to know which is the app in the foreground, is there any clean way to achieve this?
I guess @biquillo misunderstood your question, but I found good idea in CommonsWare answer..
Basically you can start service just by Binding to it and seting flag to create it if it is not created already. Then whenever some activity is created it binds to service, onDestroy it unbinds.. That will make service be destroyed once when no activity is binded to it..
Hope it helps and it solved ur problem ;) Cheers
See the lifecycle of Activity given at http://developer.android.com/reference/android/app/Activity.html
Understand when the methods onStart, onStop and onPause gets invoked. You can then startService/stopService from within them accordingly.
精彩评论