NotificationManager.cancel()不起作用:不会删除通知

时间:2012-07-08 22:44:33

标签: android android-service foreground android-notifications notificationmanager

我一直在尝试使用以下方法删除服务设置的持久通知:

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

澄清我为什么这样做:服务以默认的持久性通知开始。当我的应用运行时,它需要将此通知替换为另一个。但是,在现有通知上使用notify()可以完美地运行,我还需要它来显示新通知的滚动条文本。这就是我决定删除现有通知(使用上面的代码),创建一个新通知,然后再次调用startForeground()并将新通知传递给它的原因,因此我的服务仍然存在。

3 个答案:

答案 0 :(得分:11)

问题是您使用startForeground()以间接方式发布通知。您不能只是取消该通知,原因与系统在启动前台服务时坚持要求您提供通知的原因相同。只要您的前台服务正在运行,该通知就会在那里。

在大多数情况下,服务确实不应该在前台。如果您可以使用服务的正常优先级,那么您可以正常启动和停止通知。

如果你真的在做一些真正需要前台服务的事情,如果你真的想向用户显示一个自动收录文件,我相信你唯一的选择就是发出另一个通知。

答案 1 :(得分:6)

您始终可以通过callng stopForeground(boolean removeNotification)从前台服务中删除通知。然后一个服务退出他的foregroundState,当需要内存时,系统可以再次杀死它。

答案 2 :(得分:0)

您可以通过传入一个空的Builder来更新通知。

if(showNotification){
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setVisibility(Notification.VISIBILITY_SECRET)
            .setSmallIcon(R.mipmap.ic_spotify_white_24dp)
            .setTicker("Playing Now")
            .setContentTitle("Spotify")
            .setContentText("Preview");
    return mBuilder;
}else{
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    return mBuilder;
}