将 PendingIntent 存储在对象中以供以后检索以取消警报是否是一种不好的做法?

Is it bad practice to store PendingIntent's in an object for later retrieval to cancel an Alarm?

我正在使用 PendingIntentAlarmManager 制作一个闹钟应用程序。我知道要取消 PendingIntent,您需要准确地重新创建它。在我的应用程序中,与许多其他闹钟应用程序非常相似,有一个闹钟列表,带有用于切换每个闹钟的开关 on/off。关闭时,我目前重新创建 PendingIntent 并使用以下命令取消它:

Intent intent = new Intent(context, MyBroadcastReceiver.class);
String id = this.getId().replaceAll("[^0-9]+", "");
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, id, intent, 0);
alarmIntent.cancel();

我认为上面代码的前 3 行是不必要的。当我切换警报时,我可以访问自定义警报对象,其中包含 id 以及警报的许多其他详细信息。当我创建新警报时,如果我将新创建的 PendingIntent 存储在警报对象中,我可以访问用于创建警报的 PendingIntent,只需检索它并在 1 行中取消它,如下所示:

this.getPendingIntent().cancel();

我不必从前面显示的代码中重新创建意图、获取 ID 或重新创建 PendingIntent。这最终会节省时间和资源(虽然不多,但这是很好的做法),所以我有几个问题:

1) 将 PendingIntent 存储在对象中并在以后使用它而不是重新创建它有什么问题吗?这似乎是一个直截了当的答案,但我以前从未见过有人这样做过。

2) 重新创建我不知道的 PendingIntent 是否有优势?

谢谢!

Is there anything wrong with storing the PendingIntent in an object and use it later instead of recreating it?

假设底层 Intent 没有大量有效载荷(例如,额外的 Bitmap),你应该没问题。

It seems like a straightforward answer but I haven't seen anyone do this before.

https://github.com/commonsguy/cw-omnibus/tree/v8.7/AlarmManager/Simple,尽管这是一个微不足道的例子。

Is there an advantage to recreating the PendingIntent that I'm not aware of?

它适用于您没有 PendingIntent 的情况。你的过程不会永远存在。如果您想使用缓存的 PendingIntent 作为优化,那很好,但是如果需要,您需要准备好创建 PendingIntent