If save the PendingIntent id in SharedPreference or db, you will get wrong value when Android reboot or your package force-stop
You can save all your previous PendingIntent to another new PendingIntent, then cancel all later
for example
void createSomeAlarmAndSave() {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, MyReceiver.class).setAction(ACTION_XXX), 0);
getSystemService(AlarmManager.class).setInexactRepeating(AlarmManager.RTC_WAKEUP, 1000 * 60 * 15, 1000 * 60 * 15, pendingIntent);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 1, new Intent(this, MyReceiver.class).setAction(ACTION_XXX), 0);
getSystemService(AlarmManager.class).setInexactRepeating(AlarmManager.RTC_WAKEUP, 1000 * 60 * 20, 1000 * 60 * 20, pendingIntent1);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 2, new Intent(this, MyReceiver.class).setAction(ACTION_XXX), 0);
getSystemService(AlarmManager.class).setInexactRepeating(AlarmManager.RTC_WAKEUP, 1000 * 60 * 25, 1000 * 60 * 25, pendingIntent2);
//save all previous PendingIntent to another new PendingIntent
PendingIntent.getBroadcast(this, 0, new Intent(this, MyReceiver.class).putExtra("previous", new PendingIntent[]{pendingIntent, pendingIntent1, pendingIntent2}), PendingIntent.FLAG_UPDATE_CURRENT);
}
cancel all previous PendingIntent
void cancelAllPreviousAlarm() {
//acquire the dedicated PendingIntent
PendingIntent pendingIntentAllPrevious = PendingIntent.getBroadcast(this, 0, new Intent(this, MyReceiver.class), PendingIntent.FLAG_NO_CREATE);
if (pendingIntentAllPrevious != null) {
try {
pendingIntentAllPrevious.send(this, 0, null, new PendingIntent.OnFinished() {
@Override
public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, String resultData, Bundle resultExtras) {
for (Parcelable parcelable : intent.getParcelableArrayExtra("previous")) {
//alarm will cancel when the corresponding PendingIntent cancel
((PendingIntent) parcelable).cancel();
}
}
}, null);
pendingIntentAllPrevious.cancel();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
}
}