Akoder
Akoder

Reputation: 149

How to cancel a particular pendingIntent with specific request_code?

I want to make an app which can ADD, VIEW & CANCEL an alarm. I have designed a database for that. Viewing and creating new alarm works perfectly.

But the problem is to CANCEL the alarm. All alarms are set by the same pendingIntent with a different request_code. The request_code is taken from database entries (i.e. the ID field). If I use the cancel(pendingIntent) method, it will cancel all alarms. But I just want to cancel the specific alarm with a specific request_code. Here is my creating alarm code:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
Intent intent = new Intent(this, d1_on.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, user_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

Now when I click the CANCEL button it will ask for user_id. Then it will delete that row from database. It's ok... but now I want to stop that specific alarm with request_code set to user_id.

Or please explain to me how to cancel a pendingIntent created in alarmActivity class through alarmReceiver class.

Upvotes: 2

Views: 984

Answers (1)

codeMagic
codeMagic

Reputation: 44571

Recreate the pendingIntent just as you originally created it

PendingIntent pendingIntent = PendingIntent.getActivity(this, user_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

then you can cancel it with

am.cancel(pendingIntent);

Upvotes: 3

Related Questions