【问题标题】:Android AlarmManager: is there a way to cancell ALL the alarms set?Android AlarmManager:有没有办法取消所有设置的警报?
【发布时间】:2020-06-16 15:47:21
【问题描述】:

我正在构建一个应用程序,该应用程序为一周中的每一天(在特定的小时和分钟)设置 2 个闹钟,这些闹钟会一直重复一周又一周。

现在的重点是:如果用户更改了闹钟,我需要取消之前设置的闹钟。

有没有办法简单地取消我的应用程序设置的所有警报?

【问题讨论】:

    标签: android alarmmanager


    【解决方案1】:

    如果您要取消之前的警报,那么在PendingIntent 中,您的标志应该是PendingIntent.FLAG_CANCEL_CURRENT。如果它已经创建,它将阻止生成新的PendingIntent。并确保在设置闹钟之前取消相同的PendingIntent,然后设置闹钟。你应该这样尝试:

    AlarmManager 2AlarmsInWeekAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getService/getActivity(context, int, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    
    2AlarmsInWeekAlarmManager.cancel(pendingIntent);
    

    然后你可以使用 set 或 setRepeating 方法。 在你的情况下应该是

    2AlarmsInWeekAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, "timeInMillis", "repetitionTimeInMillis", pendingintent);
    

    这保证了在设置闹钟之前会取消所有之前使用相同PendingIntent的闹钟。

    希望你得到这个!

    【讨论】:

    • 我需要澄清一下。 cancel() 文档说“删除任何具有匹配 Intent 的警报”。这是否意味着请求代码 im getBroadcast (Context context, int requestCode, , Intent intent, int flags) 也需要相同?请澄清。
    • 你好,文档没有说太多关于requestCode。但是,如果您在PendingIntent 中看到getBroadcast,它会检索到PendingIntent。所以据我所知如果您输入不同的requestCodes,那么您将获得2 个不同的PendingIntents,因此在取消时它将是另一个PendingIntent,而不是所需的一个!另请查看this link
    • 感谢您回复我。让我再次阅读文档。无论如何,我也没有看到请求班级安排的警报列表。有什么想法吗?
    • 很抱歉我没听懂:/
    • 要取消警报,您需要重新创建确切的PendingIntent,我想没有办法直接从代码中检索它。您仍然可以在 shell 中看到待处理的警报!如果您熟悉 adb shell,您可以使用以下命令来实现它:adb shell dumpsys alarm > log.txt 其中log.txt 将包含所有带有包名称的待处理警报,因此您可以检查您的。我不确定如何从代码中获取它。
    【解决方案2】:

    我想你可以关注一下:AlarmManager.Cancel

    关于那个问题/答案:Android: Get all PendingIntents set with AlarmManager

    如那里所述,您不能要求 AlarmManager 告诉您其中的 PendingIntent 是什么。但我认为您可以制作一些类似于您要取消的 PendingIntent ;)。

    【讨论】:

      【解决方案3】:

      我在取消警报时遇到了同样的问题,并解决了它。你应该做的只是做 -

      1. 创建警报时,保存 PendingIntent 对象的请求代码(共享偏好)。
      2. 稍后,当您想取消警报时,使用相同的请求代码创建相同的 PendingIntent(显然来自共享偏好)。
      3. 调用AlarmManager的cancel(),传入PendingIntent对象,报警就会被取消。

        private void cancelAlarm(int requestCode) {
        
        AlarmManager alarmManager2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        
        PendingIntent pendingIntent2 = PendingIntent.getBroadcast(getApplicationContext(),requestCode,new Intent(this, MyBroadCastReceiver.class),0);
        alarmManager2.cancel(pendingIntent2);
        
        Toast.makeText(getApplicationContext(), "Alarm Cancelled - "+ requestCode, Toast.LENGTH_LONG).show();
        

        }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多