Android WorkManager Tutorial – Performing Tasks in Background

Another important thing introduced with Android Jetpack is WorkManager. In this Android WorkManager Tutorial we are going to learn how we can use the WorkManager API to schedule the tasks that we want to run …

android workmanager tutorial

Another important thing introduced with Android Jetpack is WorkManager. In this Android WorkManager Tutorial we are going to learn how we can use the WorkManager API to schedule the tasks that we want to run in the background.

I have already posted a tutorial about Android AlarmManager. But now we should use WorkManager as it is recommended and very easy.

Android WorkManager Tutorial – Video

An step by step explanation of everything about WorkManager is also available in my YouTube channel you can check it out if you want.

What is WorkManager?

WorkManager is part of Android Jetpack. WorkManager helps us to execute our tasks immediately or an appropriate time.

Earlier we had AlarmManager, JobScheduler, FirebaseJobDispatcher for scheduling the background tasks. But the issues were

  • JobScheduler – Available only for API >= 21
  • FirebaseJobDispatcher – For backward compatibility

So developer had to understand which method to use when. To overcome these issue we have WorkManager, and it will automatically choose the best method for your task and you do not need to write logic for it. So basically WorkManager is providing an abstraction layer. It gives us a clean interface hiding all the complexities and giving the guaranteed execution of the task.

WorkManager Features

  • It is fully backward compatible so in your code you do not need to write if-else for checking the android version.
  • With WorkManager we can check the status of the work.
  • Tasks can be chained as well, for example when one task is finished it can start another.
  • And it provides guaranteed execution with the constraints, we have many constrained available that we will see ahead.

Android WorkManager Tutorial

Now let’s learn how you can use WorkManager in your Android Project. So I would recommend you to start a new Android Studio project and yes you can name it anything like “Work Manager Example” or something.

Remember WorkManager is not available by default so first we need to add the dependency.

Adding WorkManager

  • And it is very simple, just go to app level build.gradle file and add the following implementation line.

Understanding WorkManager Classes

Before writing the actual codes first we should understand the WorkManager classes.

  • Worker: The main class where we will put the work that needs to be done.
  • WorkRequest: It defines an individual task, like it will define which worker class should execute the task.
  • WorkManager: The class used to enqueue the work requests.
  • WorkInfo: The class contains information about the works. For each WorkRequest we can get a LiveData using WorkManager. The LiveData holds the WorkInfo and by observing it we can determine the Work Informations.

Creating a Worker

  • For creating a worker we need to create a class and then in the class we need to extend Worker. So here I am creating a class named MyWorker.

  • So our worker class is ready that is going to perform the work.
  • For this work I am going to execute it immediately, on a button click. So first we will also create a button inside activity_main.xml.

Performing the Work

  • Now let’s perform the work that we created. For this first come inside MainActivity.java and write the following code.

  • In the above code you can see first we created an object of OneTimeWorkRequest. Above I told you that we use WorkRequest but here we are using OneTimeWorkRequest. This is because WorkRequest is an abstract class and we have to use the direct subclasses of it. So we have two subsclasses for WorkRequest
    • OneTimeWorkRequest: Used when we want to perform the work only once.
    • PeriodicWorkRequest: Used when we need to perform the task periodically.
  • Finally to enqueue the work we simple used the enqueue() method from WorkManager.
  • Now you can run your application to see it is working fine.
android workmanager tutorial
Android WorkManager Tutorial
  • But you will say now why do we need to do a lot of things just to display a notification. So the answer here is this is only an example and we executed the work immediately. But you can set many constraints for your work and the best thing is it gets executed in background and it is needed in many scenarios. 

Determining Work Status

So we successfully performed the work. Now let’s learn how we can determine the status of the work.

  • First we will add a TextView in activity_main.xml to display the status.

  • Now we will modify the MainActivity.java as below.

  • Now if you will run your application you will see the following output.
android workmanager tutorial
Android WorkManager Tutorial

Sending And Receiving Data to/from WorkManager

We can also pass to data to our WorkManager class and we can also get back some data after finishing the work. So let’s see how we can do this.

Sending Data

  • So to receive data we will do the following modification in our MyWorker class.

  • And we will do the following changes in our MainActivity class.

  • Now if you will run it you will see the string passed from the MainActivity in the notification.
android workmanager tutorial
Android WorkManager Tutorial

Receiving Data

  • For receiving we can again use the same concept inside doWork() method.

  • And we can receive this data inside the observer in MainActivity.

Adding Constraints

Now let’s add some constraint in our work so that it will execute at a specific time. We have many constraints available for example.

  • setRequiresCharging(boolean b): If it is set true the work will be only done when the device is charging.
  • setRequiresBatteryNotLow(boolean b): Work will be done only when the battery of the device is not low.
  • setRequiresDeviceIdle(boolean b): Work will be done only when the device is idle.

For all the methods that are available you can refer to this official link.

Now let’s see how to add the constraints.

  • We will do the following modification in the MainActivity.

  • Now after doing this change if you will run your application then the work will only be executed if the device is charging.

Canceling Work

  • We can also cancel the work if required. For this we have a method cancelWorkById(). It takes the work id as an argument that we can get from our WorkRequest object.

  • We also have the following methods to cancel the work.
    • cancelAllWork(): To cancel all the work.
    • cancelAllWorkByTag(): To cancel all works of a specific tag.
    • cancelUniqueWork(): To cancel a unique work.

PeriodicWorkRequest

Till now we were using OneTimeWorkRequest that will perform the work only once. But sometimes it is needed to perform the work periodically for example taking backup to the server. In scenarios like this we can use PeriodicWorkRequest class. Everything else is same.

In the above code we are defining that the work should be done after every 10 hours. 

Chaining Works

We can also chain the works that we need to perform.

I hope the above code is explaining itself.

For now that’s all for this post, there are many things to learn but we will do this while creating some real apps in coming tutorials. Meanwhile if you found this post helpful then please SHARE it with your friends. And for any question you can leave your comments below. Thank You 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

Expand Your Knowledge: Next Tutorial Picks

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x