【问题标题】:Is it bad practice to store PendingIntent's in an object for later retrieval to cancel an Alarm?将 PendingIntent 存储在对象中以供以后检索以取消警报是不好的做法吗?
【发布时间】:2017-09-08 15:26:04
【问题描述】:

我正在使用PendingIntent 和AlarmManager 制作闹钟应用。我知道要取消 PendingIntent,您需要准确地重新创建它。在我的应用程序中,就像许多其他闹钟应用程序一样,有一个带有开关的闹钟列表,可以打开/关闭每个闹钟。关闭时,我目前重新创建 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 是否有优势?

谢谢!

【问题讨论】:

    标签: android alarmmanager android-pendingintent android-alarms


    【解决方案1】:

    将 PendingIntent 存储在对象中并稍后使用它而不是重新创建它有什么问题吗?

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

    这似乎是一个直截了当的答案,但我以前从未见过有人这样做。

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

    重新创建我不知道的 PendingIntent 有什么好处吗?

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 2011-10-21
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多