How to save scheduled alarm after app was killed by Android or task killer?

Divers picture Divers · May 6, 2011 · Viewed 11.7k times · Source

Code that schedules alarm.

    PendingIntent sender = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, time, sender);

Its working fine, but when I kill my app in task killer, I lost my scheduleed alarm. How to solve this problem?

Answer

JoxTraex picture JoxTraex · May 6, 2011

have your application broadcast a message as its being killed, and when this message is broadcast, then have a listener check if the service is still running.. if its not run it. This will insure that your service is running even if the application is killed.

Update

I'll try to create a flow diagram for you

Death/Restart of a service

The onDestroy() method is part of a service.

I hope this helps.

UPDATE 2

One thing I forgot to mention is the fact that you ideally only want one instance of the service to be run. So just looking at the ID that is present within the onStart() should be == to 1 to start it else.. ignore it.

Methods of notice of the Service Class:

onStart() : This method is called when the service is being started

onDestroy() : This is the method that is called when a service is being killed

Methods of notice of the BroadcastReciever class:

onReceive(): This methods receives all intents that are sent to it (unless filtered)

Look up examples on BroadcastRecievers (Message Broadcasting) and Service (Starting a service)

References:

http://developer.android.com/reference/android/content/BroadcastReceiver.html

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