Mr.Z Mr.Z - 1 year ago 136
Android Question

Stop the Service on Destroy of Application

I am confused right now , about service concept of running and stopping:

what i want to do:

  • Start Location service at the very start of application.

  • Keep getting location updates and store them to shared preference

  • Stop the service in onDestroy of Application scope!

So far i have searched and studied we can only do following things with service(correct me if i'm wrong):

  • Stop the service automatically by binding it to related activities/fragments/views , when all of them destroyed service unbind itself automatically so we can call
    method in unbind

  • return START_NOT_STICKY in onStartCommand to tell OS , don't recreate it , and create intent local service , after completion of some work it will destroy itself.

  • Stopping the service manually , by declaring it's intent in some kind of static scope and stopping the service in on
    of Application class [I am not sure what will happen? , maybe service will destroy each time any activity will be destroyed ? or it will be destroyed only when overall application get's destroyed?]

Either way , i am bit confused and beat , been trying to adjust my
Location service
with given details for 2 days

Answer Source

First of all, launch the "LocationService" on your app start:

public class MyApp extends Application {

    private static final String TAG = "MyApp";

    public void onCreate() {
        Log.d(TAG, "App started up");
        startService(new Intent(this, MyLocationService.class));

Second : As you said, the Service should better run with the "START_NOT_STICKY" flag

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;


Once the system kills your app, the Service will automatically be killed, so no problems at all.

There is no onDestroy() method on the Application object, the only similar event is onTerminated() and it is not being launched on production devices.


Added in API level 1 void onTerminate () This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so.

More information:

Btw, If you want the MyLocationService to send updates of the location to your app (when it is open), you should consider to use Otto or EventBus (I recommend you this last one because of the simplicity to use it). You can even configure the @Suscriber to receive updates of old retrieved locations if you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download