NotificationManager.cancel()不起作用:通知未删除 [英] NotificationManager.cancel() doesn't work: Notification isn't removed
问题描述
我一直在尝试使用以下方法删除服务的持久性通知集:
I've been trying to remove a persistent Notification set by a Service using:
startForeground(1337, notification);
我用来取消它的代码:
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(1337); // cancel existing service notification, doesn't take effect
nManager.cancelAll(); //surpluous, but also doesn't take effect
要弄清为什么我要这样做:该服务以默认的持久性Notification开头.当我的应用运行时,它需要用另一个通知来代替.在现有Notification上使用notify()
可以完美地工作,但是,我还需要它显示新Notification的代码文本.这就是为什么我决定删除现有的Notification(使用上面的代码),创建一个新的Notification,然后再次调用startForeground()
并将新的Notification传递给它,以便我的服务继续存在的原因.
To clarify why I am doing this: the Service starts with a default persistent Notification. When my app runs, it needs to replace this Notification with another. Using notify()
on the existing Notification works perfectly, however, I need it to show the ticker text for the new Notification as well. This is why I decided to remove the existing Notification (using the code above), create a new one, and then I call startForeground()
again and pass the new Notification to it, so my Service persists.
推荐答案
问题是您正在使用startForeground()
间接发布通知.您不能只是出于与系统在启动前台服务时坚持要您提供通知的相同原因而取消该通知.只要您的前台服务正在运行,该通知就会在那里.
The problem is that you're issuing the Notification in an indirect way by using startForeground()
. You can't just cancel that Notification for the same reason the system insists on you providing a Notification when starting a foreground Service. As long as your foreground Service is running, that Notification will be there.
在大多数情况下,服务实际上不应该放在前台.如果您可以为服务使用正常的优先级,则可以正常启动和停止通知.
In most cases, Services really shouldn't be in the foreground. If you can use a normal priority for your Service, then you can start and stop your Notification normally.
如果您实际上在做确实需要前台服务的事情,并且如果您确实想向用户显示代码文本,那么我相信您唯一的选择就是发出另一个通知.
If you're actually doing something that truly does require a foreground Service, and if you really want to show the user a ticker text, I believe your only option is to issue another Notification.
这篇关于NotificationManager.cancel()不起作用:通知未删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!