Android WorkManager

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 ""

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()

Create restrictions:

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

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

Cancel a task:

val myWorkId:UUID = myWork.getId()

Adding tags (each task can have several):

val cacheCleanupTask =

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 =
// Then enqueue the recurring task:

That, in short, is all.

Leave a reply

Your email address will not be published.

You may also like

More in:Android