Java

// Create a Constraints object that defines when the task should run
Constraints constraints = new Constraints.Builder()
.setRequiresDeviceIdle(true)
.setRequiresCharging(true)
.build();
// ...then create a OneTimeWorkRequest that uses those constraints
OneTimeWorkRequest compressionWork =
new OneTimeWorkRequest.Builder(CompressWorker.class)
.setConstraints(constraints)
.build();

When multiple constraints are specified, your task will run only when all the constraints are met.

In the event that a constraint fails while your task is running, WorkManager will stop your worker. The task will then be retried when the constraint(s) are met.

Initial Delays

In the event that your work has no constraints or that all the constraints are met when your work is enqueued, the system may choose to run the task immediately. If you do not want the task to be run immediately, you can specify your work to start after a minimum initial delay.

Here is an example of how to set your task to run atleast 10 minutes after it has been enqueued.

Java

Note: The exact time that the worker is going to be executed also depends on the constraints that are used in your WorkRequest and on system optimizations. WorkManager is designed to give the best possible behavior under these restrictions.

Retries and Backoff Policy

If you require that WorkManager retry your task, you can return Result.retry() from your worker.

Your work is then rescheduled with a default backoff delay and policy.
The backoff delay specifies the minimum amount of time to wait before retrying the work.
The backoff policy defines how the backoff delay is going to increase over time for the following retry attempts; it is EXPONENTIAL by default.

Defining input/output for your task

Your task may require data to be passed in as input parameters or be returned as a result.
For example, a task that handles uploading an image requires the URI of the image to be uploaded as input and may require the URL of the uploaded image as the output.

Input and output values are stored as key-value pairs in a Data object.
The code below shows how you can set input data in your WorkRequest.

Note:Data objects are intended to be small and values can be Strings, primitive types, or their array variants. If you need to pass more data in and out of your Worker, you should put your data elsewhere, such as a Room database.
There is a maximum size limit of 10KB for Data objects.

Tagging work

You can group your tasks logically by assigning a tag string to any
WorkRequest object. This allows you to operate on all tasks with a particular tag.