Search code examples
androidalarmmanagerandroid-preferencesandroid-alarms

about alarm manager in android


I have made an alarm manager to schedule some user defined events and it is working successfully then I have made a setting screen (from preference activity) to let the user to change some setting like (days before alarm)

my question is If I schedule the event before event start date by 3 days, then the user change the days before from setting to one day only

then I schedule the event again before event start date by 1 day, is that mean the user will be notified twice

  • one before 3 days
  • one before 1 day

if that is true so how can I prevent that from happening

Thanks in Advance


Solution

  • Each alarm is accompanied by a PendingIntent which has a unique hash identifier. When using the same identifier, that alarm will overwrite the former as stated in the documentation: http://developer.android.com/reference/android/app/AlarmManager.html#set(int, long, android.app.PendingIntent)

    Schedule an alarm. Note: ...If there is already an alarm scheduled for the same IntentSender, it will first be canceled...

    Note that PendingIntent are characterized by their parameters and identifiers.

    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);
    }