Starting from Android 8.0 all services, which we used for background tasks, loose your rights and opportunities.

But now Android has a new tool, which can start and manage background tasks. Let’s talk about WorkManager.

Before start using WorkManager, we need to add dependency:

implementation "android.arch.work:work-runtime:1.0.0-beta01"

Main classes:

  • Worker – in fact, the task itself. You need to extend this class and describe the task in the doWork() method
  • WorkRequest – task. It should contain at least a class that extends Worker, but you can add more details: conditions or runtime. It has a unique generated identifier with which you can, for example, cancel a task. Contains helper classes:
    • Builder – a helper class for building
    • Constraints – constraints builder
  • WorkManager – queues and manages processes. The WorkRequest object is passed to the WorkManager to queue the task. WorkManager plans the task in such a way as to distribute the load on system resources, while observing the specified restrictions.
  • WorkInfo – contains information about a specific task. WorkManager provides LiveData for each WorkRequest object. LiveData contains a WorkInfo object. Observing this data, you can determine the current status of the task and get any returned values ​​after its completion.

Declare a new class:

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

    override fun doWork(): Result {
        // Do something
        return Result.success()

        // (Returning Result.retry() tells WorkManager to try this task again
        // later; Result.failure() says not to try again.)
    }
}

It can be started:

val myWork = OneTimeWorkRequestBuilder<MyWorker>().build()
WorkManager.getInstance().enqueue(myWork)

Create restrictions:

// Create a Constraints object that defines when the task should run
val myConstraints = Constraints.Builder()
        .setRequiresDeviceIdle(true)
        .setRequiresCharging(true)
        // Many other constraints are available, see the
        // Constraints.Builder reference
        .build()

// ...then create a OneTimeWorkRequest that uses those constraints
val myWork = OneTimeWorkRequestBuilder<MyWorker>()
        .setConstraints(myConstraints)
        .build()

Cancel a task:

val myWorkId:UUID = myWork.getId()
WorkManager.getInstance().cancelWorkById(myWorkId)

Adding tags (each task can have several):

val cacheCleanupTask =
        OneTimeWorkRequestBuilder<MyCacheCleanupWorker>()
    .setConstraints(myConstraints)
    .addTag("cleanup")
    .build()

Repetitive tasks:

val photoCheckBuilder =
        PeriodicWorkRequestBuilder<PhotoCheckWorker>(12, TimeUnit.HOURS)
// ...if you want, you can apply constraints to the builder here...

// Create the actual work object:
val photoCheckWork = photoCheckBuilder.build()
// Then enqueue the recurring task:
WorkManager.getInstance().enqueue(photoCheckWork)

That, in short, is all.

Leave a Reply