Search code examples
androidalarmmanager

AlarmManager not creating an alarm


I'm attempting to add some "reminders" functionality to my app. I want to set up an AlarmManager and fire a Notification when the alarm happens.

I've added a few methods to create an alarm, cancel an alarm, and see if an alarm is active.

The following code is in Settings.class which extends Activity:

private boolean getRemindersEnabled() {
    return (PendingIntent.getBroadcast(this,
            1,
            new Intent(this, Main.class),
            PendingIntent.FLAG_NO_CREATE) != null);
}

private void enableReminders() {
    AlarmManager alarmMgr;
    PendingIntent alarmIntent;

    alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, Main.class);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, mDayStart);
    calendar.set(Calendar.MINUTE, 0);

    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            SIXY_MINUTES,
            alarmIntent);

    mRemindersEnabled = getRemindersEnabled();
    populateReminders();
}

private void disableReminders() {
    AlarmManager service = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, Main.class);
    PendingIntent pending = PendingIntent.getBroadcast(this,
            0,
            intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    service.cancel(pending);

    mRemindersEnabled = getRemindersEnabled();
    populateReminders();
}

When I call enableReminders(), it creates the alarm. However, getRemindersEnabled() returns false. Is there something I'm failing to do?


Solution

  • getRemindersEnabled() should use the same requestCode from the PendingIntent that creates the Alarm. In this case, you are using 1, the correct will be 0.

    private boolean getRemindersEnabled() {
        return (PendingIntent.getBroadcast(this,
                0,
                new Intent(this, Main.class),
                PendingIntent.FLAG_NO_CREATE) != null);
    }
    

    [EDIT]

    To cancel the Alarm, before calling service.cancel(intent);, call pending.cancel(); using the flag FLAG_UPDATE_CURRENT

    PendingIntent pending = PendingIntent.getBroadcast(this,
            0,
            intent,
            PendingIntent. FLAG_UPDATE_CURRENT);
    pending.cancel();
    service.cancel(pending);