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
- Chainable
- Queryable
So, let’s start.
As always, add some dependencies.
In the project level build.gradle
file:
allprojects {
repositories {
google()
jcenter()
}
}
In the app level build.gradle
file:
dependencies {
def work_version = 1.0.0
// (Java only)
implementation "android.arch.work:work-runtime:$work_version"
// Kotlin + coroutines
implementation "android.arch.work:work-runtime-ktx:$work_version"
// optional - RxJava2 support
implementation "android.arch.work:work-rxjava2:$work_version"
// optional - Test helpers
androidTestImplementation "android.arch.work:work-testing:$work_version"
}
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.
Conclusion
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:
Read about Android Jetpack here:
A good talk from Google I/O ‘18:
Also you can follow or contact me:
Twitter: https://twitter.com/RobertLevonyan
Github: https://github.com/robertlevonyan
Email: me@robertlevonyan.com
Website: https://robertlevonyan.com