Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android NotificationManager.cancel()不';t工作:通知不可用';t删除_Android_Android Service_Foreground_Android Notifications_Notificationmanager - Fatal编程技术网

Android NotificationManager.cancel()不';t工作:通知不可用';t删除

Android NotificationManager.cancel()不';t工作:通知不可用';t删除,android,android-service,foreground,android-notifications,notificationmanager,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, do

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

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(布尔removeNotification)从前台服务中删除通知。然后一个服务退出他的foregroundState,当需要内存时,系统会再次终止该服务。

您可以通过传递一个空的构建器来更新通知

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;
}

您正在尝试删除从其他应用程序启动的通知?不,它是同一个应用程序。它们应该将此内容放在文档中,或者在尝试此操作时使其抛出错误。。。