【发布时间】:2021-04-10 14:51:17
【问题描述】:
在前台服务中发现了一个有趣的现象,如果我们在启动前台服务后立即停止服务,我们会收到此错误,因为 Context.startForegroundService() 没有调用 Service.startForeground()。不管我们是从服务的 onCreate 还是 onStartCommand 开始通知。
Intent intent = new Intent(this, MyService.class)
startForegroundService(intent);
stopService(intent);
但是如果我添加延迟,那么它会按预期工作,对此有什么想法吗?
Intent intent = new Intent(this, MyService.class)
startForegroundService(intent);
new Handler(Looper.getMainLooper()).postDelayed(() -> stopService(intent), 0);
为了摆脱这个错误,我就是这样修复的
我没有在开发者网站上找到任何合适的文档,但这就是 我这样做是为了解决 Context.startForegroundService() 没有 然后调用 Service.startForeground() 问题。
如果我们要停止前台服务,请不要在服务外调用 类使用 stopService(intent) 而不是创建一个意图动作, 启动前台服务,然后使用 stopSelf 停止服务 服务 onStartCommand。
Intent serviceIntent = new Intent(context, MyService.class); serviceIntent.setAction(ACTION_STOP_SERVICE); ContextCompat.startForegroundService(context, serviceIntent);
【问题讨论】:
标签: android android-service foreground-service