如果将 PendingIntent id 保存在 SharedPreference 或 db 中,当 Android 重启 或 您的包强制停止
时,您将得到错误的值
您可以将之前的所有 PendingIntent 保存到另一个新的 PendingIntent 中,然后再全部取消
例如
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);
}
取消所有之前的 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();
}
}
}