Search code examples
androidalarmmanagerandroid-alarms

Android Overwriting current Alarm


I'm trying to set an alarm notification once, and each time a User logs in, overwrite or cancel the previous alarm and set a new one. Based primarily on this post and this post a tried the following code:

private void cancelPreviousAlarm(){
    Intent alarmIntent = new Intent(context, AlertReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
            REQUEST_CODE, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.cancel(pendingIntent);
    pendingIntent.cancel();
}

public void setAlarmBirthday (String message, String fechaNacimiento, boolean notified, boolean isLogin){

    Long time2 = calculateNextBirthday(fechaNacimiento, notified, isLogin);
    Long alertTime2 = new GregorianCalendar().getTimeInMillis()+time2;

    AlarmManager alarmManager3 = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent alertIntentBirthday = new Intent(context, AlertReceiver.class);

    cancelPreviousAlarm();

    alertIntentBirthday.putExtra(EXTRA_BIRTHDAY_MESSAGE, message);
    alertIntentBirthday.putExtra(EXTRA_ALARM_LOCAL_NOTI, true);

    alarmManager3.set(AlarmManager.RTC_WAKEUP, alertTime2, PendingIntent.getBroadcast(context, REQUEST_CODE,
            alertIntentBirthday, PendingIntent.FLAG_ONE_SHOT));

}

But only sets the first alarm and not the next ones.


Solution

  • Replace PendingIntent.FLAG_ONE_SHOT with PendingIntent.FLAG_UPDATE_CURRENT.

    FLAG_ONE_SHOT:

    Flag indicating that this PendingIntent can be used only once. For use with {@link #getActivity}, {@link #getBroadcast}, and {@link #getService}.

    If set, after {@link #send()} is called on it, it will be automatically canceled for you and any future attempt to send through it will fail.

    FLAG_UPDATE_CURRENT:

    Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new
    Intent. For use with {@link #getActivity}, {@link #getBroadcast}, and {@link #getService}.

    This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.