Android: Cancel an Alarm Set From Another Activity

2019-06-03 20:11发布

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.

2条回答
Explosion°爆炸
2楼-- · 2019-06-03 20:20

To cancel and alarm you need to pass an equivalent PendingIntent (meaning p1.equals(p2) returns true) to the one used to create it. It doesn't matter from where you created the AlarmManager reference. How are you initializing the PendingIntent in both cases?

Two PendingIntents are considered equal if they both represent the same operation from the same package. Basically if you initialize two PendingIntents with equivalent Intents, they would be considered equal. EDIT: the documentation is obviously wrong about this, the requestCode is also used when comparing PendingIntents. See comments and other answer.

查看更多
冷血范
3楼-- · 2019-06-03 20:30

To solve this issue I used to following code:

timerAlarmIntent = PendingIntent.getBroadcast(myContext, i, alarmIntent, 0);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
intentArray.add(timerAlarmIntent);
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(){
if(intentArray.size()>0){
    for(int i=0; i<intentArray.size(); i++){
        myAM.cancel(intentArray.get(i));
    }
    intentArray.clear();
}

}

查看更多
登录 后发表回答