Q:

Android Start/Stop a service

I have an App that consists of multiple activities. All activities have to access a local service. I want the service to be started when I start the app, and stopped when 
a) The App is destroyed (back key)
b) The App is stopped (home key)
c) The device is in deep sleep (power key)
Basically, the service should not run when there is no visible activity. 
I bind the service in every activity in onResume() and unbind the service in every activity in onPause(). Unfortunately that recreates the service every time when I switch an activity, because the service gets unbound before the new activity binds it.
Does anybody now how to prevent that?

A:

Assuming you are binding with Context.BIND_AUTO_CREATE, then you are nearly there. Bind the service in onStart() and unbind it in onStop(). You should find that the start of the second activity occurs before the stop of the first one as the application switches from the first to the second. I've used this technique in my app and logged all the on.. methods; they occur in this order when I switch:
 FIRST Activity onCreate
 FIRST Activity onStart
 FIRST Activity onResume
 FIRST Activity onPause
 SECOND Activity onCreate
 SECOND Activity onStart
 SECOND Activity onResume
 FIRST Activity onStop

So for a brief moment two activities are bound to the service, which does no harm at all. When no activities are bound, the service will stop.

