user5150273
user5150273

Reputation: 195

How to cancel AlarmManager using PendingIntents in different classes?

I am trying to use AlarmManager for doing some tasks upon an alarm time I set. I know that I have to use same PendingIntent to make and cancel alarm. But, the problem is that I am making the alarm in class "ClassA" and cancelling the alarm in class "ClassB" later on.

That's why I wonder if the intents to be broadcast in each class are same or not since they use "different contexts" as they are in different classes, I guess.

Can they be considered as same PendingIntent and Can I cancel the alarm? If not, how can I make them same?

For making an alarm in class "ClassA" (that extends BroadcastReceiver):

alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, myReceiver.class);
PendingIntent pender = PendingIntent.getBroadcast(context, codeNum, intent, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY, pender);

For cancelling the alarm in class "ClassB" (that extends BaseAdapter):

alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, myReceiver.class);
PendingIntent pilocal = PendingIntent.getBroadcast(context, codeNum, intent, 0);
pilocal.cancel();
alarm.cancel(pilocal);

Upvotes: 3

Views: 528

Answers (1)

Ankita
Ankita

Reputation: 433

You can retrieve the same kind of PendingIntent by providing same operation, same Intent action, data, categories, and components, and same flags. Yes, you can cancel your alarm from another class if its still valid. Just make sure you pass the same parameters used, request code used to create the pending intent.

Upvotes: 2

Related Questions