Android. Is WorkManager running when app is closed?

Tuesday Four AM picture Tuesday Four AM · Jun 4, 2018 · Viewed 30.4k times · Source

I want to schedule nightly database updates. So I use new Android WorkManager. My understanding is that once scheduled it will always run in the background independently from the app's lifecycle. Is that right? My first tests show that Work is only being performed when the app is running.

val locationWork = PeriodicWorkRequest.Builder(UpdateDatabaseWorker::class.java, 24, TimeUnit.HOURS)
                        .addTag("DATABASE_UPDATE_SERVICE")
                        .build()
WorkManager.getInstance().enqueue(locationWork)

Answer

mikepenz picture mikepenz · Oct 2, 2018

Based on various issues reported on the WorkManager bugtracker, their documentation is not completely precise about the exact behavior of the WorkManager in such edge cases.

On certain devices, apps are force stopped when the app is cleared from task manager, so that part is expected. ... source


Unfortunately, some devices implement killing the app from the recents menu as a force stop. Stock Android does not do this. When an app is force stopped, it cannot execute jobs, receive alarms or broadcasts, etc. So unfortunately, it's infeasible for us to address it - the problem lies in the OS and there is no workaround. source


The only issue that we have come across is the case where some Chinese OEMs treat swipe to dismiss from Recents as a force stop. When that happens, WorkManager will reschedule all pending jobs, next time the app starts up. Given that this is a CDD violation, there is not much more that WorkManager can do given its a client library. source


To add to this, if a device manufacturer has decided to modify stock Android to force-stop the app, WorkManager will stop working (as will JobScheduler, alarms, broadcast receivers, etc.). There is no way to work around this. Some device manufacturers do this, unfortunately, so in those cases WorkManager will stop working until the next time the app is launched. source


With intense testing of a OneTimeWorkRequest (without constraints) on a Pixel 2 XL with stock android the behavior is the following:

  • Task manager close:
    • Work continues (after a bit)
  • Reboot device (work running):
    • Work continues after reboot done
  • App info "Force stop":
    • Work stops, will only continue when app is started again
  • Reboot device (work was "Force Stopped"):
    • Work does not continue until the app is started again

You can find a complete list of different OEM behaviors on dontkillmyapp.com. It seems the Android team also acknowledges this issue and added a test for this into their CTS test for Android Q. source