如何通过其他活动取消警报

时间:2012-08-23 06:52:05

标签: android

我有两个活动

在活动A中,我设置了闹钟

public static ActivityA contextA;
Intent intent = new Intent(contextA, AlarmReciever.class);
        intent.setAction(MY_ACTION);
        AlarmManager manager = (AlarmManager) contextA
                .getSystemService(Context.ALARM_SERVICE);
        intent.putExtra("TITLE", triggerTitle);
        PendingIntent ShotSender = PendingIntent.getBroadcast(contextA,
                0, intent, 0);
        manager.setRepeat(AlarmManager.RTC_WAKEUP, fireTime, fireTime*2 + 
                        system.currentTimeMillis(), ShotSender);
在活动B中

,我想取消闹钟:

Intent intent = new Intent(ActivityA.contextA, AlarmReciever.class);
        intent.setAction(MY_ACTION);
        AlarmManager manager = (AlarmManager) ActivityA.contextA
                .getSystemService(Context.ALARM_SERVICE);
        intent.putExtra("TITLE", triggerTitle);
        PendingIntent ShotSender = PendingIntent.getBroadcast(ActivityA.contextA,
                0, intent, 0);
        manager.cancel(ShotSender);

但它抛出异常:NullPointerException

发生在活动B中:

 Intent intent = new Intent(ActivityA.contextA, AlarmReciever.class);

我的代码出了问题?

1 个答案:

答案 0 :(得分:1)

创建Intent时需要使用ActivityB的上下文。将ActivityB中的代码更改为:

Intent intent = new Intent(this, AlarmReciever.class);
intent.setAction(MY_ACTION);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
intent.putExtra("TITLE", triggerTitle);
PendingIntent ShotSender = PendingIntent.getBroadcast(this, 0, intent, 0);
manager.cancel(ShotSender);