Search code examples
androidalarmmanagerandroid-alarms

Keep track of multiple alarms with Android


I need to set a number of alarms that repeat weekly, to automatically put the phone on vibrate when the user is on some class (it's an academic app) and then reset the volume when the class finishes.

I already have the alarms being created, but I must have a way to deactivate all of them if the user disables this feature. I also know I must do so by passing and intent with the same parameters to the AlarmManager.cancel() method, but the problem here is:

The user can cancel classes and enroll in classes (but not directly in the app), and that's updated and reflected on the DB, that keeps just the current classes. So if I have an alarm setup to a class that doesn't exists anymore, how can I cancel it if I can't replicate the PendingIntent?

One solution I see here is to create a db table to track the current alarms, then I'd have full control on them, another way would be to cancel and reset all alarms when the class list is updated, but doing so takes a fair amount of time, and a 3rd but less friendly option would be to simple wait for the user to boot the phone, and when reseting the alarms just set the ones I need (correct if I'm wrong on this boot behaviour). Is there a fourth option I should try, or one of these if good enough?


Solution

  • First you do not need to set up multiple alarms. Simply set up the NEXT alarm and then when that alarm fires, set up the new next alarm. This also makes it easy to set up the alarms again when they are lost if the phone is rebooted as you only have one alarm to think about.

    I use this small routine to set my alarm. The value of the Set parameter determines if the alarm is set or cancelled.

    public static void SetMyAlarm(Context c, long AlarmTime, Boolean Set) {
        Intent intent = new Intent(c, AlarmReceiver.class); // The broadcast receiver that will handle my alarm 
    
        int UniqueID =8192; // id for this specific alarm, use a different id for each separate alarm
    
        PendingIntent sender = PendingIntent.getBroadcast(c, UniqueID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
        AlarmManager am = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
        if (Set) {
            am.set(AlarmManager.RTC_WAKEUP, AlarmTime, sender);
        } else {
            am.cancel(sender);
        }
    }