WorkManager in Android

September 27, 2021 Publish By : EXPERT APP DEVS 4 min read Viewed By : 992
work manager in android

What is a WorkManager?

WorkManager is basically a task scheduler and a part of the Android Jetpack component which makes it easy to schedule deferrable and asynchronous tasks that are expected to run even if the app exits or device reboot i.e. even if your app kill or restarts due to any issue or reason Work Manager makes sure the scheduled task executes again.

WorkManager Features

  1. It is fully compatible with all android versions so no need to write an if-else for different OS versions.
  2. Using WorkManager we can check the status of the given task or work.
  3. Tasks can be scheduled in chained, for eg. when one task is done it can start another task automatically.
  4. it provides guaranteed execution with the constraints.

Advantages of WorkManager

  1. It provides guarantees of the task execution. In other terms, You can schedule a task depending on the condition when it should be run or implemented. So WorkManager will take care of all the scenarios and give the guarantee that the task will be executed even when the device is rebooted or else if the user exited the app without executing the task.
  2. It provides backward compatibility so you don’t need to figure out the device capabilities or choose an appropriate API. You have to just assign the task to the WorkManager. It will choose the best option as per your device for the execution of the task.
  3. WorkManager supports task queries. You can not only schedule the task but if you have quite some work or the tasks, you can check the status or state of the particular task, whether it is running or it is quit or task status is a success or failure. so you can capture the status of tasks from the task queue.
  4. Work manager supports task chaining, which means you can enqueue one by one task in work manager.

 So, Let's start.

To Integrate work manager in your project,

dependencies {
  def work_version = "2.2.0"
    implementation "androidx.work:work-runtime:$work_version"
  }

Now, the next step is, we are going to create a Worker class. The worker’s class role is to perform work synchronously on a background thread provided by the work manager.

class WorkerClass(con: Context, params: WorkerParameters): Worker(con, params) {

    override fun doWork(): Result {
        // Your work here.

        // Your task result
        return Result.success()
    }
}

We need to create a work request which defines how and when work should be scheduled and run. there is a two type of request,

  • OneTimeWorkRequest - Runs the task only once
  • PeriodicWorkTimeRequest - Runs the task after a given time interval.

val yourWorkRequest = OneTimeWorkRequestBuilder<WorkerClass>().build()

We have defined our work request then we can schedule the task using,

WorkManager.getInstance(context).enqueue(your work request)
That is it about creating requests, this is how you can schedule your task using Work Manager.

Let's discuss the customization we can do in our task execution.

We need to add some specific constraints in our WorkRequest to customize it. For adding constraints, we can use the methods below.

val customConstraints = Constraints.Builder()
  .setRequiresDeviceIdle(true) //checks whether device should be idle for run workmanager request
 .setRequiresCharging(true) 
  .setRequiredNetworkType(NetworkType.CONNECTED)     .setRequiresBatteryNotLow(true) // checks device battery should have a specific level for run work request
    .build()

To add it to our work request, we use the given line of code

val yourWorkRequest = OneTimeWorkRequestBuilder<WorkerClass>()
    .setConstraints(customConstraints)
    .build()

We apply the above-defined constraints to the previously defined work request. Now, this work request will only execute or run if all given constraints are satisfied.

We can also add the Periodic Task which will run after a certain time duration. To run a work request which runs periodically we need to write the below code snippet,

Val periodicWorkRequest =
PeriodicWorkRequestBuilder<WorkerClass>(2, TimeUnit.HOURS)
    .setConstraints(myConstraints)
    .build()
This task will run every 2 hours periodically as we have set the period to be 2 hours.

If you don’t want to run the task immediately, you can define your work to start after a minimum initial delay using below code,

val yourWorkRequest = OneTimeWorkRequestBuilder<WorkerClass>()
        .setInitialDelay(20, TimeUnit.MINUTES)
        .build()

This task will run after an initial delay of 20 minutes.

This blog helps you to integrate Work manager in your project.
 

Need a consultation?

Drop us a line! We are here to answer your questions 24/7.