android - 取消android中所有使用闹钟服务的pendingIntent

标签 android notifications alarmmanager android-pendingintent

我是 android 新手。我已经使用 PendingIntent 设置通知,如下所示

        Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
        myIntent.putExtra("Msg", "Title");
        myIntent.putExtra("Msgdetail", "Description of notification");
        myIntent.putExtra("username","name");

       //for uniquely broadcast request

       Random random = new Random();
       int m = random.nextInt(9999 - 1000) + 1000;
       PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, m, myIntent, 0);

      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, c.getTimeInMillis(),pendingIntent);

现在我想取消我使用上面的代码设置的所有通知(PendingIntent)。我在谷歌上搜索过,我发现我必须再次创建相同的 Intent ,但有两件事缺少 ID 号和时间。虽然我已经厌倦了这个,但不幸的是没有成功。

private void removenotifications() {
    Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,PendingIntent.FLAG_ONE_SHOT, myIntent, Intent.FILL_IN_DATA);
    AlarmManager alarmManager = (AlarmManager) MainActivity.this.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);
}

任何建议表示赞赏。谢谢。

最佳答案

要取消 Intent,您必须向 alarmManager.cancel() 传递一个 Intent,该 Intent 等于您传递给 alarmManager.set() 的 Intent 。 Intent 必须与 Intent.filterEquals() 指定的规则相同:

Determine if two intents are the same for the purposes of intent resolution (filtering). That is, if their action, data, type, class, and categories are the same. This does not compare any extra data included in the intents.

因此,就您而言,问题在于您在设置警报时使用的随机值。您必须以某种方式存储这些随机值,并使用它们来创建相同的取消 Intent 。

关于android - 取消android中所有使用闹钟服务的pendingIntent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32560614/

相关文章:

android - 我想在 8 :00 am everyday 显示通知

android - 在 Android 日志中禁用 ViewRootImpl?

java - 需要通知/仪表板系统的框架吗?

java - 如何在eclipse中使用和导入eSpeak?

php - 结合 ios (Push notification) 和 android (GCM) API (webservice) 进行通知

iphone - Apple 推送通知服务器 - 反馈始终返回零元组

java - 计算闹钟的闹钟时间

android - 如何在报警管理器的setExact()函数中设置重复时间

android - Kotlin:如何将图像 Uri 转换为 Bitmap 到 Base64

android - Android 4.4 浏览器/webview 上的 HTML5 日期输入