尝试取消AlarmManager警报,但效果不佳。
我像这样创建一个PendingIntent:
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);
}
从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;
}
尝试取消它(传递我们之前从SendLocalNotification返回的id):
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);
}
似乎没有任何作用,我已经按照我能找到的其他帖子中的那些建议(确保ID是相同的,确保PendingIntent重新创建完全相同)并且它似乎仍然崩溃。作为旁注,尝试使用标志PendingIntent.FLAG_NO_CREATE检查是否存在通知也不起作用,创建新对象而不是返回null。
我正在测试的设备是Nexus 7,我正在建立针对API 9的设备。
答案 0 :(得分:1)
你需要重新创建你的意图,然后取消它:
AlarmManager alarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
PendingIntent peding = PendingIntent.getActivity(context, code, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
alarm.cancel(peding);