我想在用户选择通知时关闭通知。这是我用来向用户显示通知的代码。我在 GCM(Google云消息传递)中使用此代码
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle(" Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg.toString());
mBuilder.build().flags = Notification.FLAG_AUTO_CANCEL;
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(notificationSound);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
但是,当我选择通知它正在打开活动时,这对我不起作用,但它没有关闭通知。请告诉我这里出了什么问题
答案 0 :(得分:3)
尝试
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(NOTIFICATION_ID); // use this to cancel notification
或者你可以尝试
mBuilder.setAutoCancel(true);
//因此,当用户在面板中单击时,通知会自动取消
答案 1 :(得分:1)
只需删除这些行:
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
和
mBuilder.setContentIntent(contentIntent);
答案 2 :(得分:1)
使用setAutoCancel (boolean autoCancel)
Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel. The PendingIntent set with setDeleteIntent(PendingIntent) will be broadcast when the notification is canceled.
答案 3 :(得分:0)
Notification notification = new Notification(
YOUR_DRAWABLE_RESOURCE, "Message",
System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL;
您可以使用FLAG_AUTO_CANCEL
在选中时取消通知。