I have a PendingIntent
which is used in an AlarmManager
The PendingIntent
s have unique ids which I keep track of. Because of this, I should be able to cancel the PendingIntent
by passing the unique id when I try to cancel it. I am trying to cancel it in a different Fragment
from the one I created it in, if that makes any difference.
But I have not been able to cancel it even after looking at many past questions.
I have looked at eg.: https://stackoverflow.com/a/4350149/2442638 , https://stackoverflow.com/a/12257277/2442638 , https://stackoverflow.com/a/11682008/2442638
This is how I create the PendingIntent
and set it with the AlarmManager
:
// remCounter is unique for each PendingIntent
Intent remIntent = new Intent();
remIntent.setAction("com.example.test.remBroadcast");
Bundle extras = new Bundle();
extras.putString("content_title", (String) s_content_title);
extras.putString("content_text", (String) s_content_text);
extras.putBoolean("bOngoing", boolean_ongoing);
extras.putInt("remCounter", remCounter); // This is how I keep track of the unique id. I have proved this to work.
remIntent.putExtras(extras);
PendingIntent remPendingIntent = PendingIntent.getBroadcast(
getActivity(), remCounter, remIntent,
PendingIntent.FLAG_ONE_SHOT);
getActivity(); // (Do I need this?)
AlarmManager remAlarmManager = (AlarmManager) getActivity()
.getSystemService(Context.ALARM_SERVICE);
remAlarmManager.set(AlarmManager.RTC_WAKEUP,
setForCal,
remPendingIntent);
This is how I'm trying to cancel a PendingIntent:
// cancelCounter is the value of the unique id of the PendingIntent I want to cancel
Intent intent = new Intent();
PendingIntent pi = PendingIntent.getBroadcast(getActivity(),
cancelCounter, intent, PendingIntent.FLAG_UPDATE_CURRENT);
pi.cancel();
AlarmManager am = (AlarmManager) getActivity()
.getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);