How to restart a Service after getting Killed by apps like "Advanced Task Killer"?

user1406716 picture user1406716 · Dec 13, 2013 · Viewed 17.4k times · Source

I have a public class that 'extends Service' and this service is launched from an activity using startService(...). But after I use Advanced Task Killer, the service is killed and never restarted again.

I noticed that some apps like the Facebook Messenger Android App restart automatically even after killing them from Advanced Task Killer ... how are the facebook/twitter apps doing it??

enter image description here

Answer

Carlos Robles picture Carlos Robles · Dec 13, 2013

Android system, or the user, may terminate a service at any time. For this reason if you want to ensure something is always running, you can schedule a periodic restart by means of AlarmManager class. The following code demonstrates how to do this.

Calendar cal = Calendar.getInstance();

Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every minute
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*1000, pintent); 

You can run this code when the user starts the app (i.e. in the oncreate of the first activity) but you have to check if it is already done, so probably it will be better if you create a broadcast receiver, than launches this code on system reboot.