我一直在尝试使用以下方法删除服务设置的持久通知:
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()
并将新的通知传递给它,所以我的服务仍然存在。
> 问题是您使用 startForeground()
间接方式发出通知。 您不能只是出于与系统坚持要求您在启动前台服务时提供通知相同的原因取消该通知。 只要前台服务正在运行,该通知就会存在。
在大多数情况下,服务确实不应该位于前台。 如果可以对服务使用正常优先级,则可以正常启动和停止通知。
如果您实际上正在执行确实需要前台服务的操作,并且如果您确实想向用户显示股票代码文本,我相信您唯一的选择就是发出另一个通知。
您始终可以通过调用 stopForeground(boolean removeNotification)从前台服务中删除通知。然后,服务退出其前台状态,并在需要内存时再次被系统终止。
您可以通过传入一个空的生成器来更新通知。
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;
}