Working With WorkManager in Android Like A Pro

Dheeraj Andra
MindOrks
Published in
9 min readMay 1, 2019

How can we schedule our application tasks at a particular time or periodically? How can we add constraints to our scheduled task like network availability(only Wifi some times) or if the device is charging? We see such tasks occurring in our day to day applications like WhatsApp and PlayStore App updates. Can we chain up such tasks together? We have a solution for all these questions and many more in Android Development.

Work Manager

Welcome to the Android-Work Manager blog.

Work Manager is part of Architecture components of the Android Jetpack Library.

So let’s discuss Work Manager and its use in background processing in this blog.

We have a lot of ways to do background processing in Android, like AsyncTasks, Loaders, Alarm Managers, etc., Which one to use when? How can we come to a decision on the same?

For more information, please refer to background processing guide

As an Android Developer, we should have an idea of the latest optimizations Android is coming up with its newer versions of OS being released for better performance. Also, we cannot guarantee every android device being used in the market contains the latest version of the Android OS installed. So, we should think about backward compatibility to reach the maximum number of devices that are present in the market(at least a min SDK of KitKat).

So how do we categorize our work that needs to be scheduled based on its importance?

Let’s say our work is to open a contacts screen by clicking on the Contacts button. This is something that is only related to the UI part. Hence the main thread or the UI thread is enough to perform this piece of work. We don’t need this to be done when our device is in doze state. This is an example of a Foreground Service. It’s a guaranteed execution and it needs to be done immediately.

Now, let’s say we have to perform a task but it need not be immediate. Like you want to set a reminder for the day after tomorrow at 8 pm. Now, this reminder will occur nearly after 48 hrs. So the device can be in a doze mode or alive during this period. We have a handful of APIs to perform these tasks. Like Job Schedulers, Firebase Job dispatchers, or Alarm manager with Broadcast receivers in the previous versions.

Now, what if we have a functionality that needs all the properties of these APIs. We tend to come with a combination of all the APIs discussed. That’s a lot of APIs to be used for in a single application. This is where WorkManager comes into the picture.

BackWard Compatible

WorkManager is Backward compatible up to API 14 -Uses JobScheduler on devices with API 23+, Uses a combination of BroadcastReceiver + AlarmManager on devices with API 14–22

WorkManager is intended for tasks that are deferrable — that is, not required to run immediately — and required to run reliably even if the app exits or the device restarts. For example:

  • Sending logs or analytics to backend services
  • Backing up user data with Server on a Periodic basis (Eg: WhatsApp, Google, etc.,)

Constraint Aware

WorkManager is constraint aware. In our day to day usage, we see our phone getting the latest software updates and we are requested to keep our devices in charging mode for these updates to happen as it may take time and insufficient charge can lead to improper installation of software. Sometimes, we see our apps getting updated as soon as we connect our phones to our power adapters. These kinds of tasks are constraint aware.

// Create a Constraints object that defines when the task should run
val constraints = Constraints.Builder()
.setRequiresDeviceIdle(true)
.setRequiresCharging(true)
.build()

// ...then create a OneTimeWorkRequest that uses those constraints
val compressionWork = OneTimeWorkRequestBuilder<CompressWorker>()
.setConstraints(constraints)
.build()

Accepts Queries

WorkManager is Queryable. A work that is handed off to the system by the WorkManager can be in a Blocked State, Running State or a Cancelled State. We can get the state of the work by passing the id of the Work like below:

WorkManager.getInstance().getWorkInfoByIdLiveData(uploadWorkRequest.id)
.observe(lifecycleOwner, Observer { workInfo ->
if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
progressbar.visibility = View.GONE
}
})

By doing this, we can improve the UX by displaying a progress bar while the task is being executed by the work manager.

Chainable

WorkManager is Chainable. Let’s say we have a series of works that are dependent on each other, we can chain them up with Work Manager. You can also specify the order in which the works that are chained should be done.

Eg:

WorkManager.getInstance()
// Candidates to run in parallel
.beginWith(listOf(work 1, work 2, work 3))
// Dependent work (only runs after all previous work in chain)
.then(work 4)
.then(work 5)
// Don't forget to enqueue()
.enqueue()

Let’s say we want to upload photos to the server. For this task to be done, let’s say we want to compress the images first and then upload it. These tasks need to be done on a background thread as they are time taking tasks and it is evident in this case that they are dependent on each other. We can chain up these tasks by using the Work Manager.

In the above code snippet, work 1, work 2 and work 3 can be referred to as three different images that are extracted in parallel since they are a part of beginWith(). work 4 can be referred for compress and then work 5 can be upload. This way we can chain up our tasks.

WorkManager can be used to perform a unique task(OneTimeWorkRequest) or a recurring task(PeriodicWorkRequest) based on the requirement.

A PeriodicWorkRequest minimum period length is 15 minutes

In order to execute a OneTimeWorkRequest or the PeriodicWorkRequest, we have to pass the work to these requests which are our Worker class. This is where our business logic is written in the doWork() method:

class UploadWorker(appContext: Context, workerParams: WorkerParameters)
: Worker(appContext, workerParams) {

override fun doWork(): Result {
// Do the work here--in this case, upload the images.

uploadImages()

// Indicate whether the task finished successfully with the Result
return Result.success()
}
}

The doWork() method runs on the background thread. We can see here a success result is returned once the uploadImages is successful. The other two enum values for the return type are a failure and retry. Return types success and failure are fairly obvious, but what does retry do here? Let’s say we are performing a task with a Work Manager with a constraint that is network connected. If the network get’s disconnected in the midst of the work being done, we can retry the task.

Inputs and Outputs

Not just this, we can create data as inputs and get outputs as data with respect to WorkManager requests. The inputs and outputs are stored as key-value pairs in the Data object.

So, how do we create a data object? Let’s create a simple map in kotlin and convert it into a workData so that it gives a Data object

val inputData: Data = mapOf(
"image_name" to "android.png"
).toWorkData()
val compressionWork = OneTimeWorkRequestBuilder<CompressWorker>()
.setInputData(inputData)
.build()

Now, where can we retrieve this data? It can be done in the overridden doWork method in our Worker class

class CompressWorker(appContext: Context, workerParams: WorkerParameters)
: Worker(appContext, workerParams) {

override fun doWork(): Result {
val inputData: Data = getInputData()
val imageName = inputData.getString("image_name","default_val")
val images: Map = compressImages(imageName)
return Result.success()
}
}
fun compressImages(imageName: String) : Map{
//returns a map of image mapped to its size
}

Now, we see that the compressImages is returning a map of images mapped to their respective sizes. Let’s say we need this data. We can set the output from our worker thread as a Data object.

class CompressWorker(appContext: Context, workerParams: WorkerParameters)
: Worker(appContext, workerParams) {

override fun doWork(): Result {
val inputData: Data = getInputData()
val imageName = inputData.getString("image_name","default_val")
val compressedImages: Map = compressImages(imageName)
val outputData: Data = compressedImages.toWorkData()
setOutputData(outputData)

return Result.success()
}
}
fun compressImages(imageName: String) : Map{
//returns a map of image mapped to its size
}

If we are using a chain of work requests here, the key observation is that the output of a worker will become input for its child workRequests.

Let’s say we use a UploadWorker after the CompressWorker, the compressedImages that is executed in the CompressWorker can be an input to the UploadWorker. It can be retrieved similarly in the doWork method of the UploadWorker class.

This works fine if we have only one worker request chained with another work request. What if we have multiple work requests(running parallel) chained with another work request that needs input from all these parallelly running work requests like

WorkManager.getInstance()
// Candidates to run in parallel
.beginWith(listOf(work 1, work 2, work 3))
// Dependent work (only runs after all previous work in chain)
.then(work 4)
.then(work 5)
// Don't forget to enqueue()
.enqueue()

What if the input for work 4 should be the combined output of work 1, work 2 and work 3? InputMerger to the rescue.

InputMerger

InputMerger is a class that combines data from multiple sources into one Data object. There are two different types of InputMergers provided by WorkManager:

OverwritingInputMerger (default) attempts to add all keys from all inputs to the output. In case of conflicts, it overwrites the previously-set keys.

ArrayCreatingInputMerger attempts to merge the inputs, creating arrays when necessary.

Important note:

There might be instances where we get outputs containing similar keys. So, we must be cautious in choosing our Inputmergers. If we want to override the key values, we can go for OverwritingInputMerger. If we want to save all the instances of the respective Key, we have to use ArrayCreatingInputMerger. It creates an array of values(if the values for a key are more than one) for the respective key.

Exception-Example case study for ArrayCreatingInputMerger:

Let’s say we have a key, “age”. One work request has value 30(Int) in it for this key. Another work request has value “three days”(String) in it for the same key. Can the ArrayCreatingInputManager merger these values and create an array for the key “age”? No. It gives an exception. So, it is expected that the datatypes of the values for similar keys should be the same.

How to use InputMerger

val compress: OneTimeWorkRequest = OneTimeWorkRequestBuilder<CompressWorker>()
.setInputMerger(ArrayCreatingInputMerger::class)
.setConstraints(constraints)
.build()
WorkManager.getInstance()
.beginWith(compress)
.then(upload)
.enqueue()

Work Manager can cancel the unwanted tasks or tasks that are scheduled by mistake. All that we need to do is to send the task id to cancelWorkById() method :

WorkManager.cancelWorkById(workRequest.id)

The Tag Support

The ids that we are referring to here are auto-generated and generally large numbers that are not easily readable by humans. Let’s say we have to log them we are unsure whether we are logging the correct workRequest Id. To overcome this issue, each work request can have zero or more tags. We can query or delete our work requests by using these tags.

// ...then create a OneTimeWorkRequest with a tag
val compressionWork = OneTimeWorkRequestBuilder<CompressWorker>()
.addTag("image_1")
.build()
workmanager.enqueue(compressionWork)

Now, if we want to see the status of all the works that are associated with a given tag, we can just use

val statusLiveData:LiveData<List<WorkStatus>> = workManager.getStatusesByTag("image_1")

The above statement returns a LiveData<List<WorkStatus>> as more than one work request can be associated with a single tag. We can use this result to get the statuses like

statusLiveData.observe(lifeCycleOwner, Observer { statuses->
//...
})

Similarly, we can use the tags to cancel the work like:

workManager.cancelAllWorkByTag("image_1")

Existing Work-Keep it unique or Add Operations with Keep, Replace and Append

Keep, Replace and Append

These three properties add advantage to using Work Manager.

Keep

Let’s say we have a work request with tag “image_1” that is already enqueued with the WorkManager.

Let’s say we define this work request to upload a particular image. And if by mistake, we click on upload the same image, this property helps us in not repeating the task.

workManager.beginUniqueWork("upload", KEEP, uploadRequest).enqueue()

So, if there is work already with “upload” ongoing, it will keep that request. If there isn’t one, it will enqueue this particular request.

Replace

workManager.beginUniqueWork("upload", REPLACE, uploadRequest).enqueue()

This will replace any ongoing work with the name “upload” and replaces it by enqueuing this particular work.

Append

workManager.beginUniqueWork("upload", APPEND, uploadRequest).enqueue()

This helps in appending the respective work request to an already existing unique work request with the name “upload”(if it exists)

Note: Please be careful when you add the constraints to the work requests in a chain of work requests. Each and every work request that is being chained may not need the same constraints. For example, if our work request contains image upload and we are chaining compress image and upload image work requests together, compressing an image may have constraints related to storage and uploading image can have a constraint with respect to the network connection. So, add the constraints accordingly.

References

Work Manager-Android Developers

Work Manager from the Android Developers Youtube Channel from Google i/o 18.- This video link also describes how the Work Manager operates under the hood. A snapshot of the same is being give here:

That’s all about WorkManager! Hope this article has been of use to you and has given you a basic idea of how Work Manager is useful for us.

Thank you so much for your time.

Let’s connect on Twitter and LinkedIn

--

--