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 "android.arch.work:work-runtime:1.0.0-beta01"

 

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()
WorkManager.getInstance().enqueue(myWork)

Creating constraints:

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

Task canceling:

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

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 = photoCheckBuilder.build()
// Then enqueue the recurring task:
WorkManager.getInstance().enqueue(photoCheckWork)

Here, in brief, that’s all. CU

Leave a Reply

Close Menu