Android如何取消AlarmManager.setAlarmClock()方法设置的闹钟?

7

在 API 21 中,有一个新的 AlarmManager.setAlarmClock(...) 方法,可以设置新的闹钟并显示状态栏警报图标。我是这样使用它的:

AlarmManager.setAlarmClock(...)

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(ALARM_ALERT_ACTION);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setAlarmClock(new AlarmManager.AlarmClockInfo(time, sender), sender);

问题在于我不知道如何取消这个闹钟,因为这段代码不起作用:
am.cancel(PendingIntent.getBroadcast(context, 0, new Intent(ALARM_ALERT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT));

闹钟本身已经取消(我的BroadcastReceiver的onReceive方法没有被调用),但状态栏中的闹钟图标仍然显示,AlarmManager.getNextAlarmClock()方法返回这个闹钟。

尝试从您的cancel()调用中删除PendingIntent.FLAG_CANCEL_CURRENT - CommonsWare
@CommonsWare 那个可以用 :) 非常感谢! - Smuggler
@CommonsWare @Smuggler,我如何去掉PendingIntent.FLAG_CANCEL_CURRENT?因为它不是可选参数。 - AVEbrahimi
@AVEbrahimi:将其替换为0 - CommonsWare
1个回答

13

PendingIntent.FLAG_CANCEL_CURRENT表示“取消当前的PendingIntent”。这会让AlarmManager困惑,当你尝试去cancel()它时,一个困惑的AlarmManager从来不是好事。

只有在有明确理由时才使用PendingIntent.FLAG_CANCEL_CURRENT。不要将其用作默认值,例如“哦,我将使用这个而不是0,因为我喜欢打很多字符”。


此外,对于两个用途使用相同的PendingIntent “sender”,这种做法不太可能正常工作。 AlarmClockInfo构造函数中的“showIntent”参数告诉操作系统用户在通知抽屉或锁屏上点击闹钟信息时该做什么。 setAlarmClock()方法的“operation”参数告诉AlarmManager当闹钟响起时该做什么。据推测应将后者传递给“cancel()”方法。 - Jerry101
@CommonsWare,PendingIntent.FLAG_NO_CREATEAlarmManager.AlarmClockInfosetAlarmClock 中都可以使用吗? - Vyacheslav
@Vyacheslav:FLAG_NO_CREATE 实际上与 AlarmManager 没有任何特定关系。我建议您提出一个新的 Stack Overflow 问题,详细说明您的关注点是什么。 - CommonsWare
@CommonsWare,我已经创建了它:http://stackoverflow.com/questions/36110837/check-if-charged-setalarmclock-of-alarmmanager - Vyacheslav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接