The Amazing WorkManager in Android

Aleesha Kanwal
5 min readDec 8, 2018

--

Android Jetpack was announced recently at Google I/O 2018.

Android Jetpack is basically a set of tools, components or libraries that helps you build modernized, well-architected, less boilerplate and testable apps.

Jetpack manages tedious activities like background tasks, navigation, and lifecycle management, so you can eliminate boilerplate code and focus on what makes your app great. Built around modern design practices, Jetpack components enable fewer crashes and less memory leaks with backwards-compatibility baked in.

Lets discuss JetPack Architectural component WorkManager in detail. When you develop an app you need to give support for lower end devices too. You have to write same logic for devices below API level 21 and above API level 21 twice.

Background processing is integral part of any android app. There are lot of things like Sending logs, upload data, Sync data, and etc that are done by background tasks.There are plenty of ways to do these task such as Job Schedulers, Services, Loaders, AlarmManager etc, But why not the entire tasks to be done with a single savior WorkManager?

Things WorkManager Do

WorkManager offers up the functionality that you would get from other APIs such as JobScheduler, FirebaseJobDispatcher, AlarmManager and Services, without the overhead of having to research which one is available for your device or API.

You don’t need to write device logic to figure out what capabilities the device has and choose an appropriate API. Instead, you can just hand your task off to WorkManager and let it choose the best option. It is a wrapper on all above concepts. It has its own Database to maintain tasks uses Room internally. Moreover it’s easy to schedule, cancel and manage multiple works sequential and parallel order of execution.

WorkManager schedules all the work on different threads and not on the main thread.

Dependency

implementation “android.arch.work:work-runtime:1.0.0-alpha04”

Concept

Components

Worker: Specifies what task you need to perform. The WorkManager APIs include an abstract worker class. You extend this class and perform the work here.

WorkRequest: Specifying things like the circumstances under which the task should run. WorkRequest is an abstract class that you’ll be using with OneTimeWorkRequest or PeriodicWorkRequest.

WorkManager: Receives the work with specific arguments and enqueues that work.

WorkStatus: Provides data for each WorkRequest object.

Now lets see how you can develop a simple application that schedules work and will be sending a notification to understand the concept in better way.

Go ahead and create a class named MyWorker that extends Worker and override the doWork() method for logical implementation to do a task. Sends a simple notification with a title and text, call this method in the doWork method. The return type here defines the result of the work that was conducted. There are 3 types of Result that you can return.

Result.SUCCESS : The work completed successfully.

Result.RETRY: The work failed and WorkManager should retry it again.

Result.FAILURE: The work failed and there is no need to retry.

There are two types of WorkRequest that you can create, OneTimeWorkRequest (runs only one time) and PeriodicWorkRequest(runs periodically over a specified period of time). Create an instance of OneTimeWorkRequest using the builder class.

Now pass the created object to WorkManager by using the enqueue method like below. This way you can schedule the work.

Data Communication with Worker

To send data from Activity to MyWoker you need to create an instance of Data class, put appropriate data and attach it to the OneTimeWorkRequest. OneTimeWorkRequest.Builder provides a method named setInputData that takes in the Data object.

Similarly, You can send data from MyWorker to Activity by creating an instance of Data class and add data to it, then pass this object to the setOutputData method in MyWorker.

Add a listener for listening to work status changes, below is the code to extract the data, make sure to check it by using isFinished.

Listening to Work Status

WorkManager gives you the ability to listen to the status of work. It returns a LiveData object to listen to work status.

Adding Constraints

You can add many conditions to your work request like only execute the work when the device is charging and is idle. There are many other constraints available. You can check all of them out in Android Studio using the code predictor. Use the setContrainsts function to add them to your WorkRequest.

Cancelling Work

So you have enqueued your work, but now you want to cancel it! WorkManager provides support for that.

You can cancel Work by using the work id. To every work request you make, you can assign a tag. You can use this tag to cancel tasks. Suppose you want to cancel all tasks that are uploading images selected by the user, just give all of them the same tag and call cancelWorkByTag.

Periodic Work Request

If you want to schedule work that runs periodically, use PeriodicWorkRequest.

PeriodicWorkRequest provides exactly the same methods and abilities that OneTimeWorkRequest provides, it only takes 2 parameters extra in its constructor Time interval and Time unit.

Chaining Tasks

You can chain multiple tasks together to run in a sequence.

First workA will run and the workB and so and so forth. If any of the task returns Result.FAILURE, then the subsequent tasks won’t run.

Download Source Code

Thanks for spending time on this post hope you found it useful. If you have any questions or comments, please feel free to drop them in the comments section below.

--

--