How to restart a killed service automatically?
Asked Answered
D

3

8

When a service has been killed, how to restart it automatically?

sometimes without even calling onDestroy()

Daunt answered 12/1, 2011 at 7:10 Comment(2)
If your service was killed, it's because either the user killed it or the OS was low on memory. That means you probably shouldn't restart it. You shouldn't leave long running services like thatMicrotome
thanks for reply, but there're some services,when i killed them,they will restart themself soon.Daunt
T
6

I inherited an IntentService, so I had to be gentle. It worked for me when I overrode onStartCommand() but

public int onStartCommand(Intent intent, int flags, int startId) {
   super.onStartCommand(intent, flags, startId);
   return START_STICKY;
}

That is, let the parent do what it should and return START_STICKY.

Towill answered 8/12, 2012 at 7:46 Comment(2)
I am doing same. working fine in nexus 5. But in xiaomi service is getting killed as soon as my application is killing.Sihunn
In bad cases, you can start an alarm clock intent to make sure your service is a live. Beware of using it too often, as waking the CPU costs battery life. Do you have an app that does revive swipe to dismiss?Towill
F
3

Overrides the onStartCommand() and give START_STICKY or START_REDELIVER_INTENT (depends on your needs) as the return value. The system will then make sure to restart your service until you explicitly stop the service.

http://developer.android.com/reference/android/app/Service.html#START_REDELIVER_INTENT

http://developer.android.com/reference/android/app/Service.html#START_STICKY

Fitzwater answered 25/6, 2012 at 16:40 Comment(1)
I am doing START_STICKY. working fine in nexus 5 and restarting the service. But in xiaomi service is getting killed as soon as my application is killing.Sihunn
C
0

If you have your service killed, the system will try to restart it later. Read more.

Chauncey answered 12/1, 2011 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.