Android: Migrate Foreground Service to WorkManager

1.1k views Asked by At

My application uses location in the background. From Android 12 onwards, we are not supposed to use Foreground Service and if we use it, the application crashes with the below exception:

Fatal Exception: java.lang.RuntimeException: Unable to start service com.xxx.sdk.location.tracking.xxx.xxx.xxxForegroundService@cb55d82 with Intent { cmp=xxx.xxx.xxx/xxx.xxx.sdk.location.tracking.xxx.service.xxxForegroundService }: android.app.ForegroundServiceStartNotAllowedException: Service.startForeground() not allowed due to mAllowStartForeground false: service com.xxx.xxx/com.xxx.sdk.location.tracking.xxx.service.xxxForegroundService
       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:5110)
       at android.app.ActivityThread.access$2200(ActivityThread.java:310)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:226)
       at android.os.Looper.loop(Looper.java:313)
       at android.app.ActivityThread.main(ActivityThread.java:8663)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

I have gone through the replacement of WorkManager and creating a notification using it.

My goal is to display long running foreground notification to a user as we are fetching location in background. I used WorkManager but the notification appears and disappears as I am not performing any task in doWork() method.

How can I show continuous foreground notification using WorkManager?

0

There are 0 answers