views:

329

answers:

1

In my android app, I'm setting an alarm that I want to occur repeatedly, hence using AlarmManager.setRepeating().

I don't want to keep track of whether the alarm is set myself (sounds like a bad idea that's prone to fail at some point), and there seems to be no API support for checking whether a particular alarm is already set for a given Intent.

Hence, I am pessimistically resetting the alarm each time my app activates:

alarmManager.cancel(pendingIntent);
...
alarmManager.setRepeating(..., pendingIntent); 

Question: is calling setRepeating() idempotent i.e. do I need to explicitly cancel() any prior alarm or can I safely just call setRepeating() and be done with it?

+2  A: 

The API documentation states:

If there is already an alarm scheduled for the same IntentSender, it will first be canceled.

I know that's not entirely clear, but what they are saying is that AlarmManager will examine the PendingIntent you pass to setRepeating() and if there is already an alarm scheduled with an identical PendingIntent then that alarm will be canceled before the new one is scheduled. So you don't need to cancel any prior alarms as long as the PendingIntent you are using isn't changing (oldPendingIntent.equals(newPendingIntent) == true)

From PendingIntent API documentation:

equals(Object otherObj)
Comparison operator on two PendingIntent objects, such that true is returned then they both represent the same operation from the same package.
mbaird