Android WorkManager

Suchi Bansal
4 min readMar 31, 2019

--

WorkManager is a part of the Android Jetpack library and one of the android architecture components. So let's get an understanding of the basics of the Jetpack library.

Android Jetpack: Android Jetpack is a collection of software components that helps us develop great apps. These components help us to follow best practices and simplify complex tasks. Jetpack comprises androidx.* package library and it's backward compatible. you can read more about Jetpack on the android developer's official blog and video.

Use cases :

So we use work manager when work is not required to be done at the exact timing so if the device enters the Doze mode work can be done after the Doze mode exit. Let's say you want to upload logs to the server in that scenario Work manager can be used because it doesn't require exact timing. There are other ways also to achieve these kinds of requirements.

1. Job scheduler ≥ API level 23 +google play service required

2. Job dispatcher — google play service required

3. Alarm manager

4. Broadcast receiver

Use Case

ExamplesSolution

WorkManager:

Guaranteed execution of deferrable work

  • Upload logs to your server
  • Encrypt/Decrypt content to upload/download

FCM + WorkManager:

A task initiated in response to an external event

  • Syncing new online content like email

Foreground Service

Continue user-initiated work that needs to run immediately even if the user leaves the app

  • Music player
  • Tracking activity
  • Transit navigation

AlarmManager

Trigger actions that involve user interactions, like notifications at an exact time.

  • Alarm clock
  • Medicine reminder
  • Notification about a TV show that is about to start

You can also apply execution constraints to them such as triggering when the device is idle or charging, or executing when a content provider changes.

Another nice feature of WorkManager is that it respects power-management features so that if a job is scheduled to run at a defined time and the device is in Doze at that time, WorkManager will try to run the task during a maintenance window if the constraints are met or after Doze is lifted.

If you need to run a task at an exact time that triggers actions, involves user interactions, and cannot be deferred, use AlarmManager (more specifically the method setExactAndAllowWhileIdle).

Core classes:

Worker

WorkRequest:

OneTimeWorkRequest

PeriodicWorkRequest

Under the hood:

Implementation Details :

  1. JobScheduler and Firebase JobDispatcher provides a central load balancing mechanism across apps.

Build.gradle:

Creating a Worker:

For creating a worker we need to create a class and then in the class, we need to extend the Worker

Performing the Work:

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

Determining Work Status:

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

If you run the application you will see the status Running/Success/Failure

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

Receiving Data:

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

Adding Constraints:

Now let’s add some constraints to 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 to 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.

  • 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 which 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 the 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.

That’s all for now, Thanks for reading!

--

--

Suchi Bansal

Software Engineer (Android)| Forever falling for waterfalls and wanderlust.” Reach me at: suchibansal2007@gmail.com | www.linkedin.com/in/suchi-bansal