如何在android中以编程方式从通知栏中删除通知?

Jay*_*tra 66 notifications android android-notifications android-pendingintent

任何人都知道我们如何以编程方式从应用程序中删除使用Pending intent调用的通知.

我曾经使用以下方法取消通知.

AlarmManager am=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(Display.this, TwoAlarmService.class);
PendingIntent pi = PendingIntent.getBroadcast(Display.this, AlarmNumber, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(pi);
Run Code Online (Sandbox Code Playgroud)

但问题是已经解雇的通知没有从通知栏中删除.

提前致谢...

在此输入图像描述

An-*_*oid 183

也许试试这个:

NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
Run Code Online (Sandbox Code Playgroud)

或者,您也可以执行此操作以取消给定上下文中的所有通知:

notificationManager.cancelAll();
Run Code Online (Sandbox Code Playgroud)

请参阅文档链接:NotificationManager

  • 我没有看到`if(Context.NOTIFICATION_SERVICE!= null)`这一点,因为它是一个String常量,永远不会为null. (7认同)
  • 你是对的,这个测试没用,我不知道为什么我这样做(删除它):/ (5认同)

Xen*_*ion 10

我相信最近更新的方法(Kotlin 和 Java)应该这样做:

NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
Run Code Online (Sandbox Code Playgroud)

或者取消所有通知是:

NotificationManagerCompat.from(context).cancelAll()
Run Code Online (Sandbox Code Playgroud)

专为 AndroidX 或支持库而设计。


Fax*_*yev 5

通知保持可见,直到发生以下情况之一:

用户可以单独或通过使用“全部清除”(如果可以清除通知)来关闭通知。用户单击通知,并在创建通知时调用了 setAutoCancel()。您为特定的通知 ID 调用 cancel()。此方法还会删除正在进行的通知。您调用 cancelAll(),它会删除您之前发出的所有通知。如果在使用 setTimeoutAfter() 创建通知时设置超时,系统会在指定的持续时间过后取消通知。如果需要,您可以在指定的超时持续时间结束之前取消通知

public void cancelNotification() {

    String ns = NOTIFICATION_SERVICE;
    NotificationManager nMgr = (NotificationManager) getActivity().getApplicationContext().getSystemService(ns);
    nMgr.cancel(NOTIFICATION_ID);
}
Run Code Online (Sandbox Code Playgroud)