Since Android 8 services, previously used for background tasks, were severely cut in rights and opportunities.

Now in Android we have WorkManager, wich helps use background tasks.

For start using WorkManager, we need to connect it:

implementation ""


Base classes:

  • Worker – task. Need to extend it and decribe work in doWork()  method
  • WorkRequest – schedule. Must include class, wich extends Worker, but we can add details: conditions or timers. Have unique generated identifier, with which you can, for example, cancel a task. Contains helper classes:
    • Builder – construction helper class
    • Constraints – constraint builder
  • WorkManager – queues and manages processes.WorkRequest object will send in WorkManager, for queue task. WorkManager schedules the task in such a way as to balance the load on the system resources, while respecting the specified limitations.
  • WorkInfo – contains information about a specific task. WorkManager provides LiveData for each WorkRequest object. LiveData contains a WorkInfo object. Watching this data, you can determine the current status of the task and get any values returned after it is completed.

So there is class declaration:

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

Now we can run it:

val myWork = OneTimeWorkRequestBuilder<MyWorker>().build()

Creating constraints:

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

Task canceling:

val myWorkId:UUID = myWork.getId()

Adding tags (each task can have several):

val cacheCleanupTask =

Repeating task:

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:

Here, in brief, that’s all. CU

Leave a Reply

Close Menu