How do I pause/disable and then unpause/reenable AlarmManager from settings page?

StackOverflow https://stackoverflow.com/questions/23200574

  •  07-07-2023
  •  | 
  •  

سؤال

In my AlarmManagerUtils.java page I am creating multiple, single alarms using this method:

public static void createSingleAlarm(Context thisContext, int intDiaryEntryID, long lngAlarmTime){
    AlarmManager am = (AlarmManager)thisContext.getSystemService(Context.ALARM_SERVICE);
    Intent thisIntent = new Intent(thisContext, AlarmReceiver.class);
    thisIntent.setAction("StartSingleAlarm");
    thisIntent.putExtra("DiaryEntryID", intDiaryEntryID);

    PendingIntent thisPendingIntent = PendingIntent.getBroadcast(thisContext, intDiaryEntryID, thisIntent, 0);
    am.set(AlarmManager.RTC_WAKEUP, lngAlarmTime, thisPendingIntent);
}

So I have a bunch of those for different days and times. What I want to do is allow the user to "toggle" alarms off and on from the preferences page. Is there a way to do this? I want to do something like this:

public static void turnOffAllAlarms(Context thisContext){
    AlarmManager am = (AlarmManager)thisContext.getSystemService(Context.ALARM_SERVICE);
    am.disable(thisContext);
}

and this:

public static void turnOnAllAlarms(Context thisContext){
    AlarmManager am = (AlarmManager)thisContext.getSystemService(Context.ALARM_SERVICE);
    am.enable(thisContext);
}
هل كانت مفيدة؟

المحلول

You have two choices:

  1. The best approach is to cancel() all your outstanding events in turnOffAllAlarms(), then re-establish them in turnOnAllAlarms(). The turnOnAllAlarms() part should not be difficult, as you need that code anyway to handle reboots, "Force Stop", etc.

  2. Have AlarmReceiver check whether alarms are off (e.g., via a SharedPreference) and skip doing your normal work if they are indeed off. This is less efficient, as you still wake up the device at these points in time. However, it may be less code.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top