5

I have a service that runs in the background. It is fine if the system kills this service on low memory conditions, however, I do not want the service to be restarted by the system.

So in order to do this I return the START_NOT_STICKY flag from my onStartCommand as such:

    public int onStartCommand(Intent intent, int flags, int startId) {

        // do stuff here

        return START_NOT_STICKY;
    }

However, when I open a bunch of applications on purpose to create low memory conditions I see this in the logs:

    Process com.myapp (pid 3960) has died.
    Scheduling restart of crashed service com.myapp/.MyService in 5000ms
    Low Memory: No more background processes.
    ...
    Start proc com.myapp for service com.myapp/.MyService: pid=4905 uid=10031 gids={3003, 1015}

So my process IS being restarted when it shouldnt be. Why is this? According to the documentation START_NOT_STICKY should not allow the service to be restarted. Is there any other way to prevent the restart of the service? Or can I tell when my service has been restarted?

Thanks

Nick
  • 6,375
  • 5
  • 36
  • 53
  • Are you sure there are no pending intents that would start said service? If there are intents pending or if a intent that your service handles is fired, you'll still start. – NuSkooler Feb 28 '12 at 23:14
  • There are no pending intents. However, the service does have a couple of BroadcastReceivers...would that affect anything? – Nick Feb 28 '12 at 23:21
  • If a intent is fired for which a BroadcastReciver is registered (e.g. in the AndroidManifest.xml), the service will be fired up to handle it. – NuSkooler Feb 28 '12 at 23:23
  • The BroadcastReceivers are not registered in the Manifest but within the service itself: registerReceiver(myReceiver, new IntentFilter(MY_ID)); – Nick Feb 28 '12 at 23:26
  • I've removed all BroadcastReceivers and Listeners and still have the same issue. – Nick Feb 29 '12 at 00:09
  • Nick did you find why it was like that, fond any solution ? thanks – Ahmed Dec 18 '12 at 12:58
  • This [solution](http://stackoverflow.com/questions/17768932/service-crashing-and-restarting) works for me as expected. – Sabari Karthik Dec 22 '16 at 05:51

2 Answers2

0

There can be multiple reasons for restarting a service even though it is NOT_STICKY:

  • If your service is bound, by using bindService with BIND_AUTO_CREATE
  • If you have pending intents on the Service

The best way to resolve this issue is by unbinding the service.

joecks
  • 4,539
  • 37
  • 48
0

Have you looked at the IntentService? Starts, does what it needs to do, and then stops itself. I have better luck with it.

bytebender
  • 7,371
  • 2
  • 31
  • 54
  • Unfortunately, that wont work for my case. I need to keep the service running until the system decides it's time to kill it. – Nick Feb 28 '12 at 23:31