前台服务问题 - 然后没有调用 Service.startForeground()

问题描述

前台服务中发现了一个有趣的观察结果,如果我们在启动前台服务后立即停止服务,我们会收到此错误,因为 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);

解决方法

启动服务不是同步的,并且当 start 调用返回时服务没有启动和运行。可以将其视为将消息发布到稍后处理的主线程 Looper 队列。

现在你的 Handler 方法也在做同样的事情来推迟执行 - 将一个 runnable 发布到主线程循环队列。它在队列中的先前消息处理完毕后进行处理,因此在调用 Service 之前已经执行了一些 stopService() 启动生命周期代码。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...