user3624383
user3624383

Reputation: 87

PendingIntent For Multiple Alarms

StartAlarmMethod();

AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context,AlarmManagerBroadcastReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_WEEK, day);

    calendar.set(Calendar.HOUR_OF_DAY, hours);
    calendar.set(Calendar.MINUTE, minutes);
    calendar.set(Calendar.SECOND, seconds);


    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 , pi);

I am using PendingIntents for multiple Alarms. How can i properly use TAGS, so i can later cancel only the Alarm that i don't want to use anymore?

Right now i'm seting Alarms with the code above. But if i set more than 1, using the code appears bellow i stop all upcoming Alarms. Instead of that i want to be able to identify somehow this PendingIntents and cancel only the ones that are not required.

CancelMethod();

Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);

Upvotes: 0

Views: 755

Answers (1)

Psypher
Psypher

Reputation: 10829

To support multiple alarms send a different request code each time you call it in the getBroadcast method. To cancel just send the same request code. Below code you can loop it within for.

Note: replace i with any value and when cancelling pass the same value to cancel the particular alarm.

AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, alarmIntent, 0);
        manager.set(AlarmManager.RTC_WAKEUP, 10000, pendingIntent);

To cancel, send the requestcode which you want to cancel,

Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, i, intent, 0);
    alarmManager.cancel(sender);

Upvotes: 2

Related Questions