androidalarmmanagerandroid-alarmsrepeatingalarmalarms

Re-enabling the Android Alarm


I am having one alarm that can be created by the user and can be disabled by the user. When user disables the alarm, I simply cancel the alarm using AlarmManager and store the alarm time somewhere.

Now, when the user re-enable the alarm, I create the alarm and set the stored time in alarm. The problem is that when I recreate the alarm with the stored time, the onReceive() method of alarm broadcast getting called instantly.

I am setting the alarm as below:

alarmManager.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_DAY,
    PendingIntent.getBroadcast(
        this, alarmUniqueCode, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));

How I disable the alarm when the user clicks on disable:

sender = PendingIntent.getBroadcast(this, 1, intent, 0);
alarmManager.cancel(sender);

I have added the alarm receiver in manifest file like below:

<receiver
    android:name="com.sign.android.myscheduler.app.AlarmReceiver"
    android:enabled="true"
    android:exported="true" >
</receiver>

One more question: When I disable the alarm, I call cancel method. Should I need to unregister the broadcast receiver too? If yes, then what if I have two different alarms then? How can I unregister the broadcast receiver for only one alarm?


Solution

  • For your problem, the alarm will be triggered immediately if you set the time in the past

    From AlarmManager API documentation:

    If the stated trigger time is in the past, the alarm will be triggered immediately, with an alarm count depending on how far in the past the trigger time is relative to the repeat interval.

    In this case, you have to check first whether the stored time is in the past. If yes, then you have to add intervals until the time is in the future.

    Try changing the code to:

    long now = new Date().getTime();
    while (time < now) {
        time += AlarmManager.INTERVAL_DAY;
    }
    alarmManager.setRepeating(AlarmManager.RTC, time,
        AlarmManager.INTERVAL_DAY, PendingIntent.getBroadcast(this,
        alarmUniqueCode, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
    

    Regarding your second question, I cannot really answer. However, based on my self-experience, I don't have any problems even if I leave the receiver on.