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 similar set of constraints as you see with JobScheduler. You can constrain your work based on:

To configure these, we:

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().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.