如何解决WorkManager - SystemForegroundService: Context.startForegroundService() 然后没有调用 Service.startForeground()
为了从前台服务获取位置,我们最近迁移了我们的 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) }
...
}
}
在 AndroidManifest.xml 中
<service
android:name="androidx.work.impl.foreground.SystemForegroundService"
android:foregroundServiceType="location"
tools:node="merge" />
发布此版本后,我们的应用 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)
好吧,我们非常清楚,如果服务是使用 startForground()
启动的,我们需要从服务中调用 Context.startForegroundService()
。但由于这是在 SystemForegroundService
附带的内置 WorkManager
的帮助下完成的,我们不知道为什么会发生这种情况?此外,当我们深入挖掘 WorkManager 各自的服务代码时,我们发现它完成了所需的一切。但不确定,为什么它仍然崩溃。
任何帮助将不胜感激。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。