如何设置取消通知?

时间:2012-10-06 13:19:15

标签: android android-notifications android-alarms

我以这种方式设置了通知:

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发送通知。

我的第一次尝试失败(警报仍然响起):

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);

有人知道如何设置后停止通知吗?谢谢!

2 个答案:

答案 0 :(得分:0)

使用此代码

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

在您的代码中,我将notifyID更改为notify_id。通知ID应与创建通知时使用的通知ID相同。只需检查它,它应该正常工作,如api中所述。

答案 1 :(得分:0)

试试这段代码:

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