Android:从通知栏中删除通知

我已经创build了一个应用程序,并与事件我设法在android通知栏添加通知。 现在我需要示例如何从事件通知栏中删除该通知?

这很简单。 您必须在NotificationManager上调用cancelcancelAll 。 取消方法的参数是应该取消通知的ID。

查看API: http : //developer.android.com/reference/android/app/NotificationManager.html#cancel(int)

你可以试试这个快速的代码

 public static void cancelNotification(Context ctx, int notifyId) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns); nMgr.cancel(notifyId); } 

您也可以在通知pipe理器上调用cancelAll ,这样您甚至不必担心通知ID。

 NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notifManager.cancelAll(); 

编辑:我downvoted所以也许我应该指定这只会删除您的应用程序的通知。

只需像下面的代码一样设置setAutoCancel(True):

 Intent resultIntent = new Intent(GameLevelsActivity.this, NotificationReceiverActivityAdv.class); PendingIntent resultPendingIntent = PendingIntent.getActivity( GameLevelsActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT ); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( getApplicationContext()).setSmallIcon(R.drawable.icon) .setContentTitle(adv_title) .setContentText(adv_desc) .setContentIntent(resultPendingIntent) //HERE IS WHAT YOY NEED: .setAutoCancel(true); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(547, mBuilder.build());` 

如果您正在使用在前台启动的服务生成通知

 startForeground(NOTIFICATION_ID, notificationBuilder.build()); 

然后发行

 notificationManager.cancel(NOTIFICATION_ID); 

没有工作取消通知和通知仍然出现在状态栏中。 在这种情况下,你将通过两种方式解决这些问题:

1>在服务里面使用stopForeground(false):

 stopForeground( false ); notificationManager.cancel(NOTIFICATION_ID); 

2>通过调用活动销毁该服务类:

 Intent i = new Intent(context, Service.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); if(ServiceCallingActivity.activity != null) { ServiceCallingActivity.activity.finish(); } context.stopService(i); 

第二种方式更喜欢音乐播放器通知更多,因为不仅通知删除,而且还删除播放器… …方式…!

这将有助于:

 NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNotificationManager.cannelAll(); 

如果你通过调用创build一个通知

 startForeground(); 

在一个Service.you可能不得不打电话

 stopForeground(false); 

先取消通知。

使用NotificationManager取消您的通知。 你只需要提供你的通知ID

mNotificationManager.cancel(YOUR_NOTIFICATION_ID);

也检查这个链接看开发者链接