1
votes

I have created a BroadCastReceiver which schedules some events using alarm manager.

In the BroadcastReceiver I am using following code to schedule.

Intent localIntent = new Intent("com.test.sample");

        PendingIntent  pi = PendingIntent.getBroadcast(context, 0,
                    localIntent, 0);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime() + (5 * 60 * 1000),
                    pi);

Here context comes from the onReceive method of the receiver.

I want to cancel this alarm on receive of other broadcast. I am aware that alarm can be cancelled by alarmManager.cancel(pi);

However if the alarmanager was set from any other activity that how to get hold of PendingIntent to cancel it?

Thanks

1
just create a new PendingIntentpskink

1 Answers

8
votes

You need to create a new PendingIntent with the same id then pass it as argument in cancelAlarm() method like follows:

To create alarm

int alarmId = 0; /* Dynamically assign alarm ids for multiple alarms */
Intent intent = new Intent(context, AlarmReceiver.class); /* your Intent localIntent = new Intent("com.test.sample");*/
intent.putExtra("alarmId", alarmId); /* So we can catch the id on BroadcastReceiver */
PendingIntent alarmIntent;
alarmIntent = PendingIntent.getBroadcast(context,
        alarmId, intent,
        PendingIntent.FLAG_CANCEL_CURRENT);

To cancel alarm (in BroadcastReceiverwhitin onReceive(Context context, Intent intent)method)

int alarmId = intent.getExtras().getInt("alarmId");
PendingIntent alarmIntent;
alarmIntent = PendingIntent.getBroadcast(this, alarmId, 
        new Intent(this, AlarmReceiver.class),
        PendingIntent.FLAG_CANCEL_CURRENT);
cancelAlarm(alarmIntent);