从onDestroy()调用的stopForeground(true)不会删除通知

Ale*_*ost 12 android

我想在销毁前台服务后删除通知.我试着打电话stopForeground(true)onDestroy()unbind().尽管调用了onUnbind()和onDestroy()(我可以从日志中看到它),但仍然存在通知.我通过电话unbindService(playerConnection)stopService(this)我的活动来停止服务.

为什么不这样做?有关如何在销毁服务时删除通知的任何想法?

更新:在玩通知时我注意到了一件有趣的事情.我在服务中做了一个特殊的方法:

fun hideNotification() {
    stopForeground(true)
    Log.d("PlayerService", "hideNotification")
}
Run Code Online (Sandbox Code Playgroud)

按下按钮时,我从我的活动中调用它.它删除了通知.但是从activity的onStop()或服务的onUnbind()或onDestroy()调用的相同函数却没有.我无法理解这些情况之间的区别.

小智 -4

要删除通知,您必须使用 notificationManager.cancel(ID); 在 onDestry() 中或当您想要删除通知时。

ID:用于显示通知的ID,在cancel()中需要给出相同的ID

例如:ID = 210;

notificationManager.notify(ID, 通知); ==> 用于显示通知。

notificationManager.cancel(ID) ===> 用于删除通知。

希望这对您有帮助。