Hello, I’ll introduce the proper way to schedule a very important task in the application. Very important work means that it must always succeed, not be interrupted or interrupted by external conditions, and it takes a long time. It might be the main feature of your application, like uploading a video to a server or downloading something.
Android Jetpack includes a library for this kind of task. Right, that is WorkManager! Let’s dive into how to do important background work in Android and learn to use WorkManager step by step.
- Part1 — Basic (We here! 🤚)
- Part2 — Robust Features
Background work in Android
We may meet some situations that have some work in the background of the application. How can we do that? There are some ways to solve these. The following picture describes how can we decide the appropriate way.
If our work needs to be done immediately, we should choose DownloadManager
or Foreground service
. If our work needs to be done precise time but not immediately, then we can use AlarmManager
.
In the remain situations, we can use WorkManager widely❤️
Introduce of WorkManager
WorkManager is an AAC component for executing work that is deferrable or should be handled by the system in the background. WorkManager
has backward compatibility over API 14. Library automatically uses JobScheduler
on devices with API 23+ and BroadcastReceiver
+ AlarmManager
on 14–22.
WorkManager
provides many features. We can execute work for one time or periodically. We can also execute many works continuously with chaining works or monitor the progress of works or construct constraints for executing the environment. The most important thing is the system ensures that the work will be executed even if the app or device restarts.
As explained above, the main concept of WorkManager
is that it is intended for executing deferrable works. The following are the examples for using WorkManager
provided by the document page.
- Periodically syncing application data with a server.
- Sending logs or analytics to backend services.
It’s time to deep dive into a specific way to use WorkManager
!
Add Gradle Dependencies
Add following lines to app-level build.gradle to using WorkManager
!
dependencies {
def work_version = "2.2.0"
// (Java only)
implementation "androidx.work:work-runtime:$work_version"
// Kotlin + coroutines
implementation "androidx.work:work-runtime-ktx:$work_version"
// optional - RxJava2 support
implementation "androidx.work:work-rxjava2:$work_version"
// optional - GCMNetworkManager support
implementation "androidx.work:work-gcm:$work_version"
// optional - Test helpers
androidTestImplementation "androidx.work:work-testing:$work_version"
}
From 2.0.1
release, work-runtime-ktx
has required Java 8, so you need to add this line too.
kotlinOptions { jvmTarget = "1.8" }
Step1. Define our Worker class
The core concept of WorkManager
is declaring a class overriding Worker
class that means our important background task and enqueue it.
UploadWorker
class inherited Worker
class. Do not think about WorkerParameters
parameter. We will not instantiate the instance of Worker
class directly but OneTimeWorkRequestBuilder
or PeriodicWorkRequestBuilder
do that. Parameters are transmitted automatically in the above process.
The most important thing is that you can notify the result of work with returning Result
constants.
Result.success()
= your work is completed successfully.Result.failure()
= your work is failed.Result.retry()
= your work needs to be retried at a later time.
Step2. Set how our work will be executed
Using WorkManager
, we can set how our work is going to execute. If we want our work to execute only one time, we can make Work
request by OneTimeWorkRequestBuilder<T>
. In contrast, we can use PeriodicTimeWorkRequestBuilder<T>
for repeating our work with a specific time interval(minimum = 15min) ⏰
val uploadWorkRequest = OneTimeWorkRequestBuilder<UploadWorker>()
.build()val uploadWorkPeriodicRequest = PeriodicWorkRequestBuilder<UploadWorker>(15,TimeUnit.MINUTES)
.build()
We can add some options or constraints to our request. I will handle this topic next part.
Step3. Handoff your task to the system
Finally, you can send your request to the system for executing work.
WorkManager.getInstance(applicationContext).enqueue(uploadWorkRequest)
Then, the system decides when is the most appropriate time to execute work and execute that. It depends on the constraint of our request and the current environment of the system for optimizing performance.
Done! 😎
We learned what is WorkManager
and basic usage step by step. In the next part, we will take more advantage of using WorkManager
with robust features in WorkManager.
- Github
- Website
- Medium Blog, Dev Blog, Naver Blog
- Contact: mym0404@gmail.com