Constrained Work
Frequently, the work that we want to do has some requirements. For example, in the case of DownloadWorker, it helps to have an Internet connection, as otherwise we may not be able to download the content.
WorkManager exposes a set of constraints. You can constrain your work based on:
- Whether the device has an Internet connection, or perhaps a particular type of Internet connection (e.g., an unmetered connection)
- Whether the device has a decent amount of battery life remaining, or perhaps is on a charger
- Whether the device has a decent amount of storage space available
- Whether the device is idle (so your work is less likely to interfere with the user)
To configure these, we:
- Create a
Constraints.Builder, - Call setter methods on that
Builderto specify our constraints, -
build()theBuilder, and - Call
setConstraints()on the requestBuilderto attach the constraints
This Java snippet illustrates what this might look like:
Constraints constraints=new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build();
OneTimeWorkRequest downloadWork=
new OneTimeWorkRequest.Builder(DownloadWorker.class)
.setConstraints(constraints)
.setInputData(new Data.Builder()
.putString(DownloadWorker.KEY_URL,
"https://commonsware.com/Android/Android-1_0-CC.pdf")
.putString(DownloadWorker.KEY_FILENAME, "oldbook.pdf")
.build())
.build();
WorkManager.getInstance(getApplicationContext()).enqueue(downloadWork);
Here, we say that we need a network connection (of any type) and that the battery should not be low.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.