- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想在我的前台服务被销毁后删除一个通知。我尝试从 onDestroy()
和 unbind()
调用 stopForeground(true)
。尽管调用了 onUnbind() 和 onDestroy()(我可以从日志中看到)通知仍然存在。我通过从我的 Activity 中调用 unbindService(playerConnection)
和 stopService(this)
来停止服务。
为什么这样不行?关于如何在服务被破坏时删除通知有什么想法吗?
更新:我在玩弄通知时注意到一件有趣的事。我在服务中做了一个特殊的方法:
fun hideNotification() {
stopForeground(true)
Log.d("PlayerService", "hideNotification")
}
然后我在按下按钮时从我的 Activity 中调用它。它删除了通知。但是从 Activity 的 onStop() 或服务的 onUnbind() 或 onDestroy() 调用的相同函数不会。我无法理解这些情况之间的区别。
最佳答案
我在尝试停止前台服务并删除所有通知时遇到了同样的问题。
作为解决方法,我删除通知 channel 并在需要时重新创建。
对我来说解决它的方法如下:
例子:
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
var stopService : Boolean # Service stop condition
var isRunning : Boolean # stopSelf() raise exception if service is not running.
if (stopService}){
stopForeground(true)
notificationManager.deleteNotificationChannel("channel_id");
if (isRunning){
Log.d(TAG, "Service is running, stopping.")
stopSelf()
}else
Log.d(TAG, "Service is not running, no need to stop.")
return START_NOT_STICKY
}
一些引用资料:
How to remove old notification channels?
What is the proper way to stop a service running as foreground
关于android - 从 onDestroy() 调用的 stopForeground(true) 不会删除通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43669965/
我使用通知 ID 启动了一个前台服务,但是当我尝试调用 stopForeground(false) 时,该服务正在重新启动。但根据 android 文档,调用此方法不会停止服务。 @Override
我目前正在尝试制作某种音乐播放器应用程序。为了播放,我创建了一个单独的服务。因为我想让它一直播放,所以我调用了 Service.startForeground()。在为 Android O(SDK 级
代替 stopForeground(true) 打电话, stopForeground(false) 应按原样保留通知(没有正在进行的状态),除非它被用户关闭/以编程方式删除。这也应该可以防止通知闪烁
我有一个媒体服务,它使用 startForeground() 在播放开始时显示通知。播放时有暂停/停止按钮,暂停时有播放/停止按钮。 NotificationCompat.Builder mBuild
我正在尝试停止我的前台服务,但我的代码似乎无法正常工作 Intent intent = new Intent(SplashScreenActivity.this, DNSService.class);
我想在我的前台服务被销毁后删除一个通知。我尝试从 onDestroy() 和 unbind() 调用 stopForeground(true)。尽管调用了 onUnbind() 和 onDestroy
我是一名优秀的程序员,十分优秀!