Android Background Service is restarting when application is killed

duncanportelli picture duncanportelli · Mar 16, 2013 · Viewed 40.6k times · Source

I am developing an application in which a background service is created to collect sensor data. I am starting the service from my activity:

startService(new Intent(this, MyService.class));

I created the service so if the application is destroyed, the background service still continues to collect data. I tried this, and it worked to a certain extent. My problem is that when I kill the application, the service seems to restart because the onCreate() service and the onStart() methods are invoked. Is there any way with which the service isn't restarted please?

UPDATE:

As suggested in an answer below, I added the following method in the service but no luck.

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

Answer

fedepaol picture fedepaol · Mar 16, 2013

It depends on the value returned in onStartCommand.

You must return START_NOT_STICKY

According to the documentation:

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them

In short: If you return START_STICKY the service gets recreated whenever the resources are available. If you return START_NOT_STICKY you have to re-activate the service sending a new intent.

Since all of this triggered my curiosity, I made a sample app to test this. You can find the zip with all the sources here There are a startService button and a stopService button that do what you would expect from them. The service returns START_NOT_STICKY in onStartCommand. I placed toasts in onCreate, onStartCommand and onDestroy.

Here what happens:

  • If I press start, onCreate and onStart are called
  • If I press stop, onDestroy is triggered
  • If I press start twice, onCreate is called once and onStartCommand twice

So it behaves as one would expect.

If I start the service and kill the app as you described, onDestroy does not get called but neither onCreate or onStart.

If I get back to the app and I press start again, onCreate gets called which means that, as I wrote before, START_NOT_STICKY prevents the service to getting restarted automatically.

I guess you have something else in your app that starts the service again (maybe a pending intent).