For fetching the location from foreeground service, we have recently migrated our WorkManager to use ForegroundService. We have followed the below document to achieve this:
https://developer.android.com/topic/libraries/architecture/workmanager/advanced/long-running
Here are the changes:
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) }
...
}
}
and in AndroidManifest.xml
<service
android:name="androidx.work.impl.foreground.SystemForegroundService"
android:foregroundServiceType="location"
tools:node="merge" />
Post this release, our app crashlytics dashboard got filled with below crash:
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)
Well, we are very much aware that, we need to call startForground()
from a Service if that service is started using Context.startForegroundService()
. But since this is done with the help of in-built SystemForegroundService
shipped with WorkManager
, we don't have any clue why this is happening? Moreover, when we digged deeper into the respective service code of WorkManager, we found it does everything required. But not sure, why it is still crashing.
Any help would be appreciated.