ryandlf ryandlf - 1 year ago 83
Android Question

Android: Cancel an Alarm Set From Another Activity

I will try to explain this as best as I can. Basically, I have Activity 1 that uses an ExternalClass to do various things. Activity 2 also references Activity 1's object of said ExternalClass. From both of these activities I can set alarms using the AlarmManager, but I want to be able to cancel all the alarms created from either activity, from Activity 1.

All alarms are set using the same intent and the same AlarmManger (both created in the ExternalClass), but when I click my button in Activity 1 that is supposed to call myAlarms.cancel(intent) it only cancels the alarms that were created using the Activity 1 class.

The ExternalClass is referenced in Activity 2 by referencing the object of that class that was created in Activity 1 so they should both be using the same instance of the ExternalClass. I'm pretty sure it isn't canceling the alarms because of the context that was used when setting the alarms, but I can't figure out how to get around that.

Answer Source

To solve this issue I used to following code:

timerAlarmIntent = PendingIntent.getBroadcast(myContext, i, alarmIntent, 0);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
myAM.set(AlarmManager.RTC_WAKEUP, alarmTime, timerAlarmIntent);

I set the requestCode to a unique id. This is within a for loop and i represents 0, 1, 2...

To cancel the alarms I had to add each alarm to a list and loop through the list when I wanted to cancel all alarms.

private void cancelAlarms(){
    for(int i=0; i<intentArray.size(); i++){


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download