Use WorkManager for Android Background Processing

January 22, 2019

Why use WorkManager?

If WorkManager executes one of your tasks while the app is running, WorkManager can run your task in a new thread in your app’s process.

If your app is not running, WorkManager chooses an appropriate way to schedule a background task–depending on the device API level and included dependencies, WorkManager might use JobScheduler, Firebase JobDispatcher, or AlarmManager.

It does comes with a few nice features:

  • Ability to schedule one time or periodic request.
  • Ability to put on constraint, such as only run when network is available, or don’t run when battery is low.
  • Support for a retry policy.
  • Support to ensure only one unique instance of the task is running.
  • LiveData support to get task updates.
  • Chain multiple tasks together.

Dependencies

WorkManager classes are already in the androidx.work package, but currently depend on Support Library 27.1, and associated Arch component versions. Version of WorkManager with AndroidX dependencies will be released in the future.

WorkManager requires compileSdk version 28 or higher.

// https://mvnrepository.com/artifact/android.arch.work/work-runtime
def work_version = "1.0.0-beta02"
// use -ktx for Kotlin+Coroutines
implementation "android.arch.work:work-runtime-ktx:$work_version"

// optional - RxJava2 support
// implementation "android.arch.work:work-rxjava2:$work_version"

// optional - Test helpers
// androidTestImplementation "android.arch.work:work-testing:$work_version"

NOTE: Refer available dependencies.

Code

class BackupWorker(context : Context, params : WorkerParameters)
    : Worker(context, params) {

    companion object {
        fun run() : LiveData<WorkInfo> {
            val work = OneTimeWorkRequestBuilder<BackupWorker>().build()
            WorkManager.getInstance().enqueue(work)

            return WorkManager.getInstance().getWorkInfoByIdLiveData(work.id)
        }
    }

    override fun doWork(): Result {
        

        return Result.success()
    }
}

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.