rah*_*hul 94 notifications android
是否可以以编程方式清除通知?
我尝试了它NotificationManager
但它不起作用.还有其他办法吗?
Jan*_*usz 221
使用以下代码取消通知:
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
Run Code Online (Sandbox Code Playgroud)
在此代码中,始终存在用于通知的相同ID.如果您有不同的通知需要取消,则必须保存用于创建通知的ID.
小智 41
来自:http: //developer.android.com/guide/topics/ui/notifiers/notifications.html
要在用户从"通知"窗口中选择状态栏通知时清除状态栏通知,请将"FLAG_AUTO_CANCEL"标志添加到Notification对象.您也可以使用cancel(int)手动清除它,向其传递通知ID,或使用cancelAll()清除所有通知.
但是Donal是对的,你只能清除你创建的通知.
NPi*_*ike 32
由于没有人发布代码答案:
notification.flags = Notification.FLAG_AUTO_CANCEL;
Run Code Online (Sandbox Code Playgroud)
..如果你已经有了旗帜,你可以像这样:或者FLAG_AUTO_CANCEL:
notification.flags = Notification.FLAG_INSISTENT | Notification.FLAG_AUTO_CANCEL;
Run Code Online (Sandbox Code Playgroud)
Roh*_*har 18
请尝试在NotificationManager中提供的默认方法.
NotificationManager.cancelAll()
删除所有通知.
NotificationManager.cancel(notificationId)
删除特定通知.
从API级别18(Jellybean MR2)开始,您可以通过NotificationListenerService取消您自己的通知.
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class MyNotificationListenerService extends NotificationListenerService {...}
Run Code Online (Sandbox Code Playgroud)
...
private void clearNotificationExample(StatusBarNotification sbn) {
myNotificationListenerService.cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您正在使用在前台启动的服务生成通知
startForeground(NOTIFICATION_ID, notificationBuilder.build());
Run Code Online (Sandbox Code Playgroud)
然后发行
notificationManager.cancel(NOTIFICATION_ID);
Run Code Online (Sandbox Code Playgroud)
最终不会取消通知,通知仍然出现在状态栏中。在这种特殊情况下,您需要发出
stopForeground( true );
Run Code Online (Sandbox Code Playgroud)
从服务内部将其恢复到后台模式并同时取消通知。或者,您可以将其推送到后台,而无需取消通知,然后再取消通知。
stopForeground( false );
notificationManager.cancel(NOTIFICATION_ID);
Run Code Online (Sandbox Code Playgroud)
Notification mNotification = new Notification.Builder(this)
.setContentTitle("A message from: " + fromUser)
.setContentText(msg)
.setAutoCancel(true)
.setSmallIcon(R.drawable.app_icon)
.setContentIntent(pIntent)
.build();
Run Code Online (Sandbox Code Playgroud)
.setAutoCancel(true)
当您点击通知时,打开相应的活动并从通知栏中删除通知
我相信最近和更新的 AndroidX 和向后兼容性。最好的方法(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 或支持库而设计。
归档时间: |
|
查看次数: |
113972 次 |
最近记录: |