WorkManager - SystemForegroundService:Context.startForegroundService()然后没有调用Service.startForeground()

Cha*_*har 17 android foreground-service android-workmanager

为了从前台服务获取位置,我们最近将 WorkManager 迁移为使用 ForegroundService。我们遵循以下文件来实现这一目标:

https://developer.android.com/topic/libraries/architecture/workmanager/advanced/long-running

以下是变化:

class ... : Worker(appContext, params) {
    val forgroundInfo: ForegroundInfo? = null
        get() {
            val notification = NotificationUtils.getNotificationBuilder(appContext, ...)
                .setContentTitle(...)
                .setContentText(...)
                .setStyle(Notification.BigTextStyle().bigText(...))
                .setSmallIcon(...)
                .setLargeIcon(...)
                .setOngoing(true)
                .build()

            return if (Utils.isAndroid10OrAbove()) {
                ForegroundInfo(
                    FOREGROUND_NOTIFICATION_ID,
                    notification,
                    FOREGROUND_SERVICE_TYPE_LOCATION
                )
            } else {
                ForegroundInfo(FOREGROUND_NOTIFICATION_ID, notification)
            }
        }

    override fun doWork(): Result {
        forgroundInfo?.let { setForegroundAsync(it) }
        
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

并在 AndroidManifest.xml 中

<service
        android:name="androidx.work.impl.foreground.SystemForegroundService"
        android:foregroundServiceType="location"
        tools:node="merge" />
Run Code Online (Sandbox Code Playgroud)

发布此版本后,我们的应用程序 crashlytics 仪表板充满了以下崩溃:

Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{efecaf7 u0 .../androidx.work.impl.foreground.SystemForegroundService}
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2137)
   at android.os.Handler.dispatchMessage(Handler.java:107)
   at android.os.Looper.loop(Looper.java:237)
   at android.app.ActivityThread.main(ActivityThread.java:7948)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Run Code Online (Sandbox Code Playgroud)

好吧,我们非常清楚,startForground()如果该服务是使用Context.startForegroundService(). 但由于这是在内置的SystemForegroundService附带的帮助下完成的WorkManager,我们不知道为什么会发生这种情况?而且,当我们深入研究 WorkManager 各自的服务代码时,我们发现它完成了所需的一切。但不确定为什么它仍然崩溃。

任何帮助,将不胜感激。

Bet*_*eto 0

您声明了使用许可吗?

<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION"/>
Run Code Online (Sandbox Code Playgroud)