我是 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/