关于android中的报警管理器

时间:2013-03-24 09:21:54

标签: android alarmmanager android-preferences android-alarms

我已经建立了一个警报管理器来安排一些用户定义的事件并且它正在成功运行 然后我做了一个设置屏幕(来自偏好活动)让用户改变一些设置,如(闹钟前几天)

我的问题是如果我在活动开始日期之前安排活动3天,那么用户将设置的日期从设置更改为仅一天

然后我在事件开始日期之前再次安排事件1天,这意味着用户将被通知两次

  • 3天前一次
  • 一天前一天

如果这是真的那么我怎样才能防止这种情况发生

先谢谢

2 个答案:

答案 0 :(得分:2)

每个警报都附带一个PendingIntent,它具有唯一的哈希标识符。使用相同的标识符时,该警报将覆盖文档中所述的前者: http://developer.android.com/reference/android/app/AlarmManager.html#set(int,long,android.app.PendingIntent)

  

安排闹钟。注意:...如果已经为同一个IntentSender安排了警报,它将首先被取消...

请注意,PendingIntent的特征在于它们的参数和标识符。

Intent intent = new Intent(mContext, YourTarget.class);
// The hashcode works as an identifier here. By using the same, the alarm will be overwrriten
PendingIntent sender = PendingIntent.getBroadcast(mContext, hashCode, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    mAlarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
} else {
    mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
}

答案 1 :(得分:1)

public void cancel (PendingIntent operation)

Remove any alarms with a matching Intent. Any alarm, of any type, whose Intent 
     

匹配这个(由filterEquals(Intent)定义),   将被取消。

所以你可以在你的待定意图alarmManager.cancel(myPendingIntent)上调用cancel 并用新的时间创造一个新的。

但你不必明确地调用cancel,因为只要filterEquals在你的新PendingIntent与前一个PendingIntent比较时返回true,那么你的警报将仅在前一天开始。

  

public boolean filterEquals(Intent other)

Determine if two intents are the same for the purposes of intent resolution 
     

(滤波)。也就是说,如果他们的行动,数据,类型,类,   和类别是一样的。这不会比较任何额外的数据   包含在意图中。