Best way get GPS Location in background for Android API level 30 and higher

501 views Asked by At

My application determines the speed limit by the user's location and tells the user if he has exceeded it. Starting with Android API level 30 and higher, Google has defined IntentService as deprecated and suggests using WorkManager or JobIntentService and also states that it is necessary to migrate from Firebase JobDispatcher to WorkManager. I see two ways to solve this problem:

  1. Start OneTimeWorkRequest and specify to restart this method periodically in this method while the application is running in the background.
  2. Run PeriodicWorkRequest with a minimum allowed interval of 15 minutes. In this method, run the JobIntentService method, which runs for up to about 10 minutes, but the method may not run or may be destroyed by the system before it is complete.

I'm worried about:

  • potential memory leaks;
  • potential problems with WorkManager or JobIntentService when going from foreground to background and vice versa
  • the ability to use the MVVM pattern
1

There are 1 answers

0
Nikola Despotoski On BEST ANSWER

I would prefer going with second option, it gives you more time between each rescheduling of the Worker.

Regarding your concerns:

  • Only possible leak is misconducting location callbacks. This can be easily tracked down, you shouldn't worry too much about it.
  • Scheduled Worker are put in the database and are executed independently of the application. Which means, user-visibility of the application has no effect. In your case, I presume you want to cancel your scheduled work once the user resumes the application, that being said you can assign a tag to the Worker and purge any scheduled or on-going once visible to the user.
  • I prefer to keep Workers isolated from the MVVM and just inject Use cases/interactors in the worker and do execute the use case/query the interactor. WorkerManager offers fine APIs to query the Worker status, you might need to write common ground between your previous implementation and for API >= 30. Treat the Worker as different execution container for your use case.