从AlarmManager中删除报警时,我是否也应该取消PendingIntent?

When deleting alarm from AlarmManager, should I also cancel PendingIntent?

我正在尝试从 AlarmManager 中删除闹钟。我刚刚调用了 AlarmManager.cancel(),它似乎工作正常。我是否也应该取消 PendingIntent,为什么?

PendingIntent p; // prepare a pending intent which matches target alarm's intent.
alarmManager.cancel(p);
p.cancel() // should I do that? 

没有必要这样做。但这对您的使用很重要。

A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it. If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token if that is still valid, and can thus call cancel() to remove it.

如果您一次只需要一个 PendingIntent 激活您将使用的任何 Intent,那么您可以选择使用标志 FLAG_CANCEL_CURRENTFLAG_UPDATE_CURRENT 来取消或修改任何当前的 PendingIntent与您提供的 Intent 相关联。

切勿将 FLAG_CANCEL_CURRENT 与您在设置闹钟时使用的 PendingIntents 一起使用。如果您想将闹钟重新安排在不同的时间,则根本不需要任何标志;只需创建一个标志为零的重复 PendingIntent,然后使用它来设置()一个警报:这将隐式取消现有警报,然后将其设置为新指定的时间。但是,如果您在创建新的 PendingIntent 时使用了 FLAG_CANCEL_CURRENT,它会破坏警报管理器将其识别为 "the same" 作为现已取消的 PendingIntent 的能力,并且您最终会使用旧的 PendingIntent,无法投递,占用内存和CPU。我已经看到有这个错误的应用程序在系统中堆积了数百个陈旧的警报,足以对性能和内存使用造成明显的影响。

如果您只是想更改附加功能而不实际重新安排现有闹钟,这就是 FLAG_UPDATE_CURRENT 的用途。如果您想重新安排或取消现有闹钟,请不要使用任何标志。