0

我有两个活动

在活动 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);

我的代码有问题吗?

4

1 回答 1

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);
于 2012-08-23T06:58:38.053 回答