So you are here to learn about WorkManager, before actually teaching you how to use it let me tell you what it is and what it does. WorkManager lets you schedule tasks in the background. Say your app needs to sync data or move a file to different folder or some other database related work, you can use WorkManager to schedule these tasks with a very simple and easy to use API. Under the hood, WorkManager uses JobScheduler, AlarmManager or Firebase JobDispatcher to schedule work.

In this tutorial you will be developing a simple app that schedules work and that work will be sending a notification. The code for this tutorial is available at this GitHub repo.

Adding Dependency

In your app.gradle add the WorkManager dependency.

Understanding the concept of WorkManager

Lets take a look at the concept of WorkManager . Initially you need to create a new class that extends the Worker class and override the doWork method. What ever work you want to do will go in this function. Then you need to create an object of WorkRequest specifying the class that you made previously. Then using WorkManager , you will schedule the work.


Let’s Code!

Go ahead and create a new project and add the WorkManager dependency in it. In the MainActivity layout file add a Button, that is all we need for now.

Now create a class named MyWorker that extends Worker and override 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.

In this class make a method that sends a simple notification with a title and text, call this method in the doWork method.

In your MainActivity create a new WorkRequest. 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 all you have to do is give this object to WorkManager by using the enqueue method. Add a click listener on the Button your created and schedule the work.

Once you click the button, a notification will pop up.


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

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. (If you don’t know about LiveData read this tutorial).

Go ahead and add a TextView in the main_activity.xml layout file.

Get the reference to this TextView in your MainActivity. By getting the ID of OneTimeWorkRequest, you can listen to WorkStatus. The code is pretty simple and self explanatory:

Run the app and click the button to see various states of the WorkRequest.


Communicating Data with Worker

Let’s see how you can send data to and from MyWorker. In the MyWorker class, define 3 String constants.

To send data 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.

In the MyWorker class extract this data (using getInputData method) and pass it to the sendNotification method.

Now let’s see how you can send data from MyWorker to MainActivity. The process is same, you have to create a instance of Data class and add data to it, then pass this object to the setOutputData method in MyWorker.

In MainActivity, where you added the listener for listening to work status changes, add the code to extract the data, make sure to check the work is complete by using isFinished.


Never miss a post from TheTechnoCafe

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.

Disconnect your device from charging and click the button, you will see that no Notification appears. You can see the status of work, it is only enqueued. Once you connect back the cable you won’t immediately get the Notification. WorkManager starts the WorkRequests between certain time windows. So your task might not run immediately once the conditions are met, but it will eventually run. Don’t Worry!


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. Go ahead and add a new Button in the layout file.

Since there is very little happening in the your doWork function, once your press the button you won’t have enough time to cancel the task as it will be completed instantly. So lets add a delay in MyWorker using Thread.sleep().

Now cancel the task using the cancelWorkById provided by WorkManager.

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.

Tap on the button to enqueue the work and then tap the cancel button.



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. Both of them specify the time internal that your request should be run periodically. First one is the the actual value and second one is the TimeUnit for the value.

Chaining Tasks

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

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

There is much more to chaining tasks, I recommend you to look at the documentation on chaining.

That is it for this tutorial. I hope you like it. Many more tutorials to come, so stay connected.

How to create a Widget in Android.

How to make two pane layout in Android.

Guide to Notifications in Android.

Getting Started with Retrofit in Android.

Gurleen Sethi

How can I tell you about myself in just a few lines, to get to know me you can reach out to me, email, text, call, or any other method of communication you like. I am always there for you!

1 Comment

rushang · July 24, 2018 at 11:50 am

Nice workmanager exmaple there are all thinks that you should know about WorkManager.

Leave a Reply

Your email address will not be published. Required fields are marked *

17 − seventeen =