I have a background service which sets a repeating alarm, does its task and stops itself. Then when the alarm wakes up it starts the service again. If the program crashes the alarm is still around and wakes up the alarm broadcastreceiver. Is there any way to cancel the alarm on a crash – I suppose I might be able to cancel the alarm from any caught exceptions but what about other causes?
Or when the alarm Broadcast receiver is triggered is there any way to tell if the program that set it has crashed?
The activity lifecycle can detect a clean finish from an “unexpected” termination through use of the isFinishing() function in the onDestroy() callback. You could add this to each activity in your app:
Then in your BroadcastReceiver, pull the result back from the SharedPreferences framework (or wherever you decide to store it), and cancel the action if the value is true:
Remember to reset it back to false on next launch though! Something like this should do:
This should capture your crash events; but remember it will also detect other times when your app is force-closed – such as if the memory is low on the device. To distinguish between these kinds of events you would need to inspect the system status as well as isFinishing().
EDIT – Services
Your Service has a separate lifecycle, you have to treat it almost like a separate app. As you’ve noticed, there is no “isFinishing()” here, but Services are actually quite simple since they are only terminated cleanly by your code, which you can trap pretty easily.
In your Service, add a new boolean (perhaps called “isFinishing”) and set it to true when your service is finished with. Then override onDestroy() as well and add a check similar to the one I described for your activities:
The broadcast receiver will then use the same code we added earlier to detect if either the service or an activity crashed.