0

尝试取消 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。

4

1 回答 1

1

您需要重新创建您的意图并像这样取消它:

AlarmManager alarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
PendingIntent peding = PendingIntent.getActivity(context, code, intent,     
                                                 PendingIntent.FLAG_CANCEL_CURRENT);
alarm.cancel(peding);
于 2015-11-04T14:24:40.997 回答