问题
Trying to cancel an AlarmManager alarm, isn't quite working.
I create a PendingIntent like so:
static PendingIntent makePendingIntent(int id, Bundle bundle)
{
Intent intent = new Intent(mContext.getApplicationContext(), mfLocalNotificationManager.class);
if(bundle != null)
{
intent.putExtra(BUNDLE_ID, bundle);
}
return PendingIntent.getBroadcast(mContext.getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
Called from SendLocalNotification:
public static int SendLocalNotification(String title, String text, String tickerText,
int timeSent, int timeOffset, String sound)
{
AlarmManager alarmMgr =
(AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
Bundle notificationData = new Bundle();
notificationData.putString("title", title);
notificationData.putString("text", text);
notificationData.putString("tickerText", tickerText);
/*snip, bundle stuff*/
int noteID = title.hashCode();
notificationData.putInt("noteID", noteID);
PendingIntent pendingIntent = makePendingIntent(noteID, notificationData);
if( pendingIntent == null )
{
//This should probably be flagged as an error or an assertion.
Log.d("[MF_LOG]", "Java intent is null");
return -1;
}
//This isn't my timing code, don't hate me for it
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, timeOffset);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
pendingIntent);
return noteID;
}
And attempt to cancel it like so (passing the id we previously got back from SendLocalNotification):
public static void CancelNotification(int id)
{
String ns = Context.NOTIFICATION_SERVICE;
AlarmManager alarmMgr =
(AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = makePendingIntent(id, null);
//This doesn't work...
pendingIntent.cancel(); //<- added based on SO post, doesn't help
alarmMgr.cancel(pendingIntent);
}
Nothing seems to work, and I've followed as much of the advice on other posts as I can find (making sure the ID is the same, ensuring the PendingIntent is recreated exactly the same) and it still seems to crash. As a side note, trying to check if a notification exists using the flag PendingIntent.FLAG_NO_CREATE also doesn't work, creating a new object instead of returning null.
The device I'm testing this on is a Nexus 7 and I'm building against API 9.
回答1:
You need to recreate your intent and CANCEL it like this:
AlarmManager alarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
PendingIntent peding = PendingIntent.getActivity(context, code, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
alarm.cancel(peding);
来源:https://stackoverflow.com/questions/18343708/android-alarmmanager-cancel-not-actually-cancelling-alarm-pendingintent