Context.startForegroundService() ANR 没有实际调用它

Context.startForegroundService() ANR without actually calling it

将我的应用更新为目标 API 27(之前为 25)后,我遇到了很多用户的 ANR,但我无法重现。它们似乎与 Oreo 后台执行限制有关,带有 ANR 消息

Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{73bc351 u0 com.xxx.xxxx/.player.PlayFileService}

但是我没有在我的代码中的任何地方调用 Context.startForegroundService()。产生此 ANR 而不是直接调用此方法的原因有哪些?

基于文档:

Prior to Android 8.0, the usual way to create a foreground service was to create a background service, then promote that service to the foreground. With Android 8.0, there is a complication; the system doesn't allow a background app to create a background service. For this reason, Android 8.0 introduces the new method startForegroundService() to start a new service in the foreground.

After the system has created the service, the app has five seconds to call the service's startForeground() method to show the new service's user-visible notification. If the app does not call startForeground() within the time limit, the system stops the service and declares the app to be ANR

您可以按照这个 SO 来操作,它描述了使用 Notification Channel 正确启动前台服务的方法。

在我的例子中,即使我没有直接调用 Context.startForegroundService(),它被调用是因为我的音乐应用程序会进入后台并且服务会被系统破坏。然后,当用户在几分钟后按下媒体按钮恢复播放时,该服务将由系统重新启动,因为应用程序在后台进行调用。我最终确实调用了 startForeground(),但这是在进行了一系列配置之后。我在服务 onCreate() 的开头添加了对 startForeground() 的调用,并显示空白通知,我所有的 ANR 都消失了。