Android WorkManager. Manage periodic tasks
Since Android O, it is no longer possible to have any background services and there are lots of broadcasts, which will not work as well. So, if you want to implement a task, which will work in the background, you have only few choices for the moment, and one if them is WorkManager.
The WorkManager is a part of Android Jetpack and recently, it becomes stable with the version 1.0.0. Google already has libraries like this: JobScheduler and Firebase Job Dispatcher. Also, there is a great and popular third party library: Evernote’s Android Job. The WorkManager has many advantages on these libraries.
- Backward compatibility (API 14+)
- No dependency on Google Play Services
So, let’s start.
As always, add some dependencies.
In the project level
In the app level
def work_version = 1.0.0
// (Java only)
// Kotlin + coroutines
// optional - RxJava2 support
// optional - Test helpers
Okay, let’s see an example of a work, which will do some staff in the background (download some data, send your current location or whatever you want to do) twice a day. We will also add some constraints to the task. It will work only if the device is connected to the WiFi and you’re not running out of storage.
The worker is created, now let’s enqueue a periodic work.
We can also chain multiple works together. Let’s see how it should be done.
Let’s go a bit deeper, and see, what is under the hood of the WorkManager and how it works.
The Worker is the implementation of what work we want to do. We need to describe our work in the doWork() method.
The WorkRequest takes a Worker with some arguments (e.g. Input data) and Constraints (e.g. Network Connection).
The WorkManager takes the WorkRequest and start to enqueue it. WorkManager saves the work in the Room database and chooses the best way to schedule your work. After that it calls doWork(). The Result is published using LiveData.
WorkManager is a simple and effective solution to implement deferrable and asynchronous tasks that are expected to run even if the app exits or device restarts. And, of course, because of this library you will reduce the power consumption for your app.
Also you can find more in the Android Developers web documentation:
Schedule tasks with WorkManager | Android Developers
Create multiple APKs for different screen sizes
Read about Android Jetpack here:
Jetpack is a collection of Android software components to make it easier for you to develop great Android apps. These…
A good talk from Google I/O ‘18: