- Introducing WorkManager
- Pietro Maggi
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: Rickon
- Proofread by DevMcryYu
Illustration by Virginia Poltrack
There are a number of DOS and don ‘ts and best practices for handling backend work on Android, as described in Google’s Power Blog Post Series. One of the recurring calls is an Android Jetpack library called WorkManager, which extends the functionality of the JobScheduler framework API and supports Android 4.0+ (API 14+). WorkManager beta was just released today!
This article is the first in the WorkManager series. We’ll explore the basics of WorkManager, how and when to use it, and what goes on behind the scenes. Then we’ll dive into more complex use cases.
What is a WorkManager?
WorkManager, one of the Android architecture components and part of Android Jetpack, is a new insight into how to build modern Android applications.
WorkManager is an Android library that runs delayable background work when constraints on the work are met.
WorkManager is for tasks that need to be secured, and the system will run them even if the application exits.
In other words, WorkManager provides a battery-friendly API that encapsulates the evolution of Android’s background behavior constraints over the years. This is crucial for Android applications that need to perform background tasks!
When to use WorkManager
WorkManager handles the background work that needs to run when various constraints are met, whether or not the application process exists. Background work can start when the application is in the background, in the foreground, or when the application is opened in the foreground and about to go to the background. Background work should continue regardless of what the application is doing, or restart it when Android terminates its process.
A common misconception about WorkManager is that it needs to run in a “background” thread, but doesn’t need to survive process death. That’s not the case. There are other solutions to this use case, such as Kotlin’s coroutines, ThreadPools or libraries such as RxJava. You can find more information about this use case in the background processing guide.
There are many different situations where you need to run background work, so you need to use different solutions to run background work. This blog post about running in the background provides a lot of useful information about when to use Workmanager. Take a look at this chart from the blog:
The illustration comes from modern background running in Android
For the WorkManager, the best place to deal with is the background work that must be done and can be deferred.
First, ask yourself:
-
Does the task need to be completed? If the application is closed by the user, do you still need to complete tasks? One example is a note-taking application with remote synchronization; Every time you finish writing a note, you expect the application to synchronize your notes with the back-end server. Even if you switch to another application and the operating system needs to close the application to reclaim some memory. This happens even when the device is restarted. WorkManager ensures that tasks are completed.
-
Can this task be delayed? Can we run the task later or only run it now? A task is delayable if it can be run later. Going back to the previous example, it’s fine to sync your notes right away, but it’s not a big deal if you can’t sync them right away and do it later. WorkManager respects the limitations of the operating system background and tries to run your work in a battery-efficient manner.
Therefore, as a guideline, WorkManager is suitable for tasks that need to ensure that the system will run them, even if the application exits. It is not suitable for background work that needs to be executed immediately or at a precise time. Use AlarmManager if you need to perform work (such as alarm clocks or event alerts) at the exact time. For work that requires immediate execution but runs for a long time, you usually want to make sure that work is performed in the foreground; Whether by limiting execution to the foreground (in which case the work is no longer really background work) or using the foreground service.
WorkManager can and should be paired with other apis when you need to trigger some background work in more complex scenarios:
- If your server triggers work, WorkManager can be paired with Firebase Cloud Messaging.
- If you are using a broadcast receiver to listen for broadcasts and then need to trigger long-running work, you can use WorkManager. Note that WorkManager supports many common Constraints that are normally propagating as broadcasts — in these cases, you don’t need to register your own broadcast receivers.
Why use WorkManager?
WorkManager runs in the background while addressing battery and system health compatibility issues and best practices for you.
In addition, you can use WorkManager to schedule scheduled tasks and complex chains of subordinate tasks: background work can be executed in parallel or sequentially, and you can specify the order in which it is executed. WorkManager seamlessly handles input and output passing between tasks.
You can also set standards for how long background tasks take to run. For example, if the device does not have a network connection, there is no reason to make an HTTP request to a remote server. Therefore, you can set constraints that the task can only run when the network is connected.
As part of ensuring execution, the WorkManager is responsible for keeping the device or application working when it restarts. You can also easily define retry policies if your work has stopped and you want to try again later.
Finally, WorkManager allows you to observe the status of work requests so that you can update the UI.
In summary, WorkManager provides the following benefits:
- Deal with compatibility between different system versions
- Follow system health best practices
- Supports asynchronous one-off and periodic tasks
- Support for chained tasks with input/output
- Allows you to set constraints while the task is running
- The task can be executed even if the application or device is restarted
Let’s look at a concrete example where we build a pipeline of concurrent tasks that apply filters to images. The results are then sent to the compression task, and then to the upload task.
We can define a set of constraints for these tasks and specify when they can be executed:
Example of a task chain with constraints
All of these workers define a precise sequence: we do not know the order in which the images are filtered, but we do know that the Compress work will start only after all the filter work is complete.
How the WorkManager scheduler works
To ensure compatibility at API 14 level, WorkManager selects the appropriate way to schedule background tasks based on the device API level. The WorkManager may use JobScheduler or a combination of BroadcastReceiver and AlarmManager.
How does WorkManager determine which scheduler to use
Is WorkManager ready for production?
WorkManager is now in beta. This means that there will be no major API changes in this major revision.
When the stable version of WorkManager is released, it will be the preferred way to run background tasks. So this is a good time to start using WorkManager and help improve it!
Thank youLyla Fujiwara.
WorkManager related resources
- The official documentation
- Reference guide
- The WorkManager 1.0.0 – beta01 Release notes
- Codelab
- Source code (Part of AOSP)
- IssueTracker
- WorkManager related issues on the StackOverflow site
- Google’s Power blog post series
Thanks to Florina Munt, Ben Weiss, and Lyla Fujiwara.
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.