我一直试图使用以下方法删除服务设置的持久通知:
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上使用notify()
非常有效,我还需要它来显示新Notification的自动收录器文本。这就是为什么我决定删除现有的通知(使用上面的代码),创建一个新的,然后我再次调用startForeground()
并将新的通知传递给它,所以我的服务仍然存在。
问题是您使用startForeground()
以间接方式发布通知。您不能只是取消该通知,原因与系统在启动前台服务时坚持要求您提供通知的原因相同。只要您的前台服务正在运行,该通知就会存在。
在大多数情况下,服务确实不应该在前台。如果您可以使用服务的正常优先级,则可以正常启动和停止通知。
如果您实际上正在做一些真正需要前台服务的事情,并且如果您真的想向用户显示自动收录器文本,我相信您唯一的选择是发出另一个通知。
您始终可以通过callng stopForeground(boolean removeNotification)从前台服务中删除通知。然后一个服务退出他的foregroundState,当需要内存时,系统可以再次杀死它。
您可以通过传入一个空的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;
}