2012-10-06 90 views
0

我給自己定的通知是這樣的:如何取消通知一旦設置?

public void onReceive(Context context, Intent intent) { 
    nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

    Bundle bundle = intent.getExtras(); 

    CharSequence from = bundle.getString("alarm_title"); 
    CharSequence message = bundle.getString("alarm_text"); 
    int notify_id = bundle.getInt("notify_id"); 

    Intent notifyIntent = new Intent(context, AppActivity.class); 
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notifyIntent, 0); 

    Notification notif = new Notification(R.drawable.ic_menu_glases, "App Information", System.currentTimeMillis()); 
    notif.contentIntent = contentIntent; 
    notif.setLatestEventInfo(context, from, message, contentIntent); 
    notif.flags = Notification.FLAG_AUTO_CANCEL; 

    nm.notify(notify_id, notif); 

}

一切正常,我很高興。現在我想通過ID來通知cancel

1日試失敗(報警還是來了):

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
Intent intent = new Intent(getApplication(), AlarmReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplication(), notifyID, intent, PendingIntent.FLAG_ONE_SHOT); 
if(pendingIntent != null) { 
    am.cancel(pendingIntent); 
    pendingIntent.cancel(); 
} 

而且第二個嘗試失敗過:

NotificationManager nm = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE); 
nm.cancel(notify_id); 

任何人有如何暫時停止通知的想法組?謝謝!

回答

0

使用此代碼

String ns = Context.NOTIFICATION_SERVICE; 
NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns); 
nMgr.cancel(notify_id); 

在你的代碼,我改變notifyIDnotify_id。通知ID應與創建通知時使用的ID相同。只要檢查一下,它應該正常工作,如api中所述。

+0

我的錯 - notifyID被設定爲相同的值。錯過了要複製它:)這不是錯誤*更新我的問題* – Thomas

+1

只需在創建通知之前和取消之前嘗試記錄ID。只要檢查它們是否相同,因爲你的第二種方法是完全正確的。 – Antrromet

+0

這是一個好點 - 我會試試看。 **編輯**發現錯誤。謝謝! – Thomas

0

試試這個代碼:

String ns = Context.NOTIFICATION_SERVICE; 
NotificationManager mNotificationManager; 
mNotificationManager = (NotificationManager) getSystemService(ns); 
mNotificationManager.cancel(MY_NOTIFICATION_ID);