Android:取消其他活动的警报集 [英] Android: Cancel an Alarm Set From Another Activity

查看:67
本文介绍了Android:取消其他活动的警报集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会尽力解释这一点。基本上,我有使用外部类做各种事情的活动1。活动2还引用了该ExternalClass的活动1的对象。在这两个活动中,我都可以使用AlarmManager设置警报,但是我希望能够从活动1中取消从任何一个活动创建的所有警报。

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.

所有警报使用相同的意图和相同的AlarmManger设置(均在ExternalClass中创建),但是当我在活动1中单击应该调用myAlarms.cancel(intent)的按钮时,它只会取消使用活动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.

在活动2中通过引用在活动1中创建的该类的对象来引用ExternalClass,因此它们都应使用相同的ExternalClass实例。我很确定由于设置警报时使用的上下文,它不会取消警报,但是我不知道该如何解决。

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.

推荐答案

要解决此问题,我曾经使用以下代码:

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);

我将requestCode设置为唯一的ID。这在for循环中,我代表0、1、2 ...

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();
}

}

这篇关于Android:取消其他活动的警报集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆