0

I have to implement a periodic request to the server every 15 minutes to update database info, that should be running async while the user is using the app and if the app is closed or paused it shouldn't keep working until the app is resumed

I'm using WorkManager to do that and is already working but I realized that when I minimize my app, the worker keeps calling doWork() every 15 minutes. Killing the app works well because the doWork() is not called.

So the question is how I can disable my worker when app is minimized? Or what I should use instead of WorkManager?

1 Answers1

0
  1. extend Application class (and register it in manifest)
  2. use registerActivityLifecycleCallbacks and inside registered Application.ActivityLifecycleCallbacks set up some value, e.g. activitiesStarted++ in onStart and activitiesStarted-- in onStop
  3. when your WorkManager fire your code just check at first how many your Activities are started, if ==0 then all are "homed" (or killed)

in HERE you have some samples how to do this properly

there is also some clever lib for your purpose - Lifecycle

snachmsm
  • 17,866
  • 3
  • 32
  • 74