【问题标题】:Is AlarmManager.setRepeating idempotent?AlarmManager.setRepeating 是幂等的吗?
【发布时间】:2010-04-10 10:01:00
【问题描述】:

在我的 android 应用程序中,我设置了一个我想重复发生的警报,因此使用 AlarmManager.setRepeating()。

我不想自己跟踪是否设置了闹钟(听起来是个坏主意,在某些时候很容易失败),而且似乎没有 API 支持来检查是否已经设置了特定的闹钟对于给定的 Intent。

因此,每次我的应用启动时,我都会悲观地重置闹钟:

alarmManager.cancel(pendingIntent);
...
alarmManager.setRepeating(..., pendingIntent); 

问题:调用 setRepeating() 是幂等的,即我是否需要显式取消任何先前的警报,或者我可以安全地调用 setRepeating() 并完成它?

【问题讨论】:

    标签: android alarmmanager


    【解决方案1】:

    API documentation 声明:

    如果已经安排了闹钟 对于同一个 IntentSender,它将 首先被取消。

    我知道这并不完全清楚,但他们的意思是AlarmManager 将检查您传递给setRepeating()PendingIntent,如果已经安排了一个具有相同PendingIntent 的警报,那么该警报将在安排新的之前取消。因此,只要您使用的 PendingIntent 没有发生变化,您就不需要取消任何先前的警报(oldPendingIntent.equals(newPendingIntent) == true)

    来自PendingIntent API documentation

    equals(Object otherObj)
    Comparison operator on two PendingIntent objects, such that true is returned then they both represent the same operation from the same package.
    

    【讨论】:

    • 关于这个的问题 - 我正在开发一个允许用户设置多个警报的应用程序,但所有警报都会触发相同的 PendingIntent。所以似乎每个新的都会取消前一个。如果我在我的 PendingIntent 中使用唯一的 requestCode 会阻止覆盖,还是它们仍会被视为相同的 PendingIntent?
    猜你喜欢
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 2015-05-25
    • 2012-02-13
    相关资源
    最近更新 更多