Android 覆盖当前警报

Android Overwriting current Alarm

我正在尝试设置一次警报通知,每次用户登录时,覆盖或取消以前的警报并设置一个新警报。主要基于 this post and this post a 尝试了以下代码:

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

}

但只设置第一个闹钟,不设置下一个。

PendingIntent.FLAG_ONE_SHOT 替换为 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.