lightbulb_outline Please take our October 2018 developer survey. Start survey

WorkManager

public abstract class WorkManager
extends Object

java.lang.Object
   ↳ androidx.work.WorkManager


WorkManager is a library used to enqueue work that is guaranteed to execute after its constraints are met. WorkManager allows observation of work status and the ability to create complex chains of work.

WorkManager uses an underlying job dispatching service when available based on the following criteria:

  • Uses JobScheduler for API 23+
  • For API 14-22
    • If using Firebase JobDispatcher in the app and the optional Firebase dependency, uses Firebase JobDispatcher
    • Otherwise, uses a custom AlarmManager + BroadcastReceiver implementation

All work must have a corresponding Worker to perform the computations. Work is performed in the background thread.

There are two types of work supported by WorkManager: OneTimeWorkRequest and PeriodicWorkRequest. You can enqueue requests using WorkManager as follows:

 WorkManager workManager = WorkManager.getInstance();
 workManager.enqueue(new OneTimeWorkRequest.Builder(FooWorker.class).build());
A WorkRequest has an associated id that can be used for lookups and observation as follows:
 WorkRequest request = new OneTimeWorkRequest.Builder(FooWorker.class).build();
 workManager.enqueue(request);
 LiveData<WorkStatus> status = workManager.getStatusByIdLiveData(request.getId());
 status.observe(...);
You can also use the id for cancellation:
 WorkRequest request = new OneTimeWorkRequest.Builder(FooWorker.class).build();
 workManager.enqueue(request);
 workManager.cancelWorkById(request.getId());
You can chain work as follows:
 WorkRequest request1 = new OneTimeWorkRequest.Builder(FooWorker.class).build();
 WorkRequest request2 = new OneTimeWorkRequest.Builder(BarWorker.class).build();
 WorkRequest request3 = new OneTimeWorkRequest.Builder(BazWorker.class).build();
 workManager.beginWith(request1, request2).then(request3).enqueue();
Each call to beginWith(OneTimeWorkRequest) or beginWith(List) returns a WorkContinuation upon which you can call WorkContinuation.then(OneTimeWorkRequest) or WorkContinuation.then(List) to chain further work. This allows for creation of complex chains of work. For example, to create a chain like this:
            A
            |
      +----------+
      |          |
      B          C
      |
   +----+
   |    |
   D    E             
you would enqueue them as follows:
 WorkContinuation continuation = workManager.beginWith(A);
 continuation.then(B).then(D, E).enqueue();  // A is implicitly enqueued here
 continuation.then(C).enqueue();
WorkRequests can accept Constraints, inputs (see Data), and backoff criteria. WorkRequests can be tagged with human-readable Strings (see WorkRequest.Builder.addTag(String)), and chains of work can be given a uniquely-identifiable name (see beginUniqueWork(String, ExistingWorkPolicy, OneTimeWorkRequest)).

Summary

Public methods

abstract WorkContinuation beginUniqueWork(String uniqueWorkName, ExistingWorkPolicy existingWorkPolicy, List<OneTimeWorkRequest> work)

This method allows you to begin unique chains of work for situations where you only want one chain with a given name to be active at a time.

final WorkContinuation beginUniqueWork(String uniqueWorkName, ExistingWorkPolicy existingWorkPolicy, OneTimeWorkRequest... work)

This method allows you to begin unique chains of work for situations where you only want one chain with a given name to be active at a time.

abstract WorkContinuation beginWith(List<OneTimeWorkRequest> work)

Begins a chain with one or more OneTimeWorkRequests, which can be enqueued together in the future using WorkContinuation.enqueue().

final WorkContinuation beginWith(OneTimeWorkRequest... work)

Begins a chain with one or more OneTimeWorkRequests, which can be enqueued together in the future using WorkContinuation.enqueue().

abstract ListenableFuture<Void> cancelAllWork()

Cancels all unfinished work.

abstract ListenableFuture<Void> cancelAllWorkByTag(String tag)

Cancels all unfinished work with the given tag.

abstract ListenableFuture<Void> cancelUniqueWork(String uniqueWorkName)

Cancels all unfinished work in the work chain with the given name.

abstract ListenableFuture<Void> cancelWorkById(UUID id)

Cancels work with the given id if it isn't finished.

abstract ListenableFuture<Void> enqueue(List<? extends WorkRequest> requests)

Enqueues one or more items for background processing.

final ListenableFuture<Void> enqueue(WorkRequest... workRequests)

Enqueues one or more items for background processing.

abstract ListenableFuture<Void> enqueueUniquePeriodicWork(String uniqueWorkName, ExistingPeriodicWorkPolicy existingPeriodicWorkPolicy, PeriodicWorkRequest periodicWork)

This method allows you to enqueue a uniquely-named PeriodicWorkRequest, where only one PeriodicWorkRequest of a particular name can be active at a time.

static WorkManager getInstance()

Retrieves the default singleton instance of WorkManager.

abstract ListenableFuture<Long> getLastCancelAllTimeMillis()

Gets a ListenableFuture of the last time all work was cancelled.

abstract LiveData<Long> getLastCancelAllTimeMillisLiveData()

Gets a LiveData of the last time all work was cancelled.

abstract ListenableFuture<WorkStatus> getStatusById(UUID id)

Gets a ListenableFuture of the WorkStatus for a given work id.

abstract LiveData<WorkStatus> getStatusByIdLiveData(UUID id)

Gets a LiveData of the WorkStatus for a given work id.

abstract ListenableFuture<List<WorkStatus>> getStatusesByTag(String tag)

Gets a ListenableFuture of the WorkStatus for all work for a given tag.

abstract LiveData<List<WorkStatus>> getStatusesByTagLiveData(String tag)

Gets a LiveData of the WorkStatus for all work for a given tag.

abstract ListenableFuture<List<WorkStatus>> getStatusesForUniqueWork(String uniqueWorkName)

Gets a ListenableFuture of the WorkStatus for all work in a work chain with a given unique name.

abstract LiveData<List<WorkStatus>> getStatusesForUniqueWorkLiveData(String uniqueWorkName)

Gets a LiveData of the WorkStatus for all work in a work chain with a given unique name.

static void initialize(Context context, Configuration configuration)

Used to do a one-time initialization of the WorkManager singleton with a custom Configuration.

abstract ListenableFuture<Void> pruneWork()

Prunes all eligible finished work from the internal database.

Inherited methods

Public methods

beginUniqueWork

public abstract WorkContinuation beginUniqueWork (String uniqueWorkName, 
                ExistingWorkPolicy existingWorkPolicy, 
                List<OneTimeWorkRequest> work)

This method allows you to begin unique chains of work for situations where you only want one chain with a given name to be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work. The uniqueWorkName uniquely identifies this set of work. If this method determines that new work should be enqueued and run, all records of previous work with uniqueWorkName will be pruned. If this method determines that new work should NOT be run, then the entire chain will be considered a no-op.

Parameters
uniqueWorkName String: A unique name which for this chain of work

existingWorkPolicy ExistingWorkPolicy: An ExistingWorkPolicy

work List: One or more OneTimeWorkRequest to enqueue. REPLACE ensures that if there is pending work labelled with uniqueWorkName, it will be cancelled and the new work will run. KEEP will run the new sequence of work only if there is no pending work labelled with uniqueWorkName. APPEND will create a new sequence of work if there is no existing work with uniqueWorkName; otherwise, work will be added as a child of all leaf nodes labelled with uniqueWorkName.

Returns
WorkContinuation A WorkContinuation that allows further chaining

beginUniqueWork

public final WorkContinuation beginUniqueWork (String uniqueWorkName, 
                ExistingWorkPolicy existingWorkPolicy, 
                OneTimeWorkRequest... work)

This method allows you to begin unique chains of work for situations where you only want one chain with a given name to be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work. The uniqueWorkName uniquely identifies this set of work. If this method determines that new work should be enqueued and run, all records of previous work with uniqueWorkName will be pruned. If this method determines that new work should NOT be run, then the entire chain will be considered a no-op.

Parameters
uniqueWorkName String: A unique name which for this chain of work

existingWorkPolicy ExistingWorkPolicy: An ExistingWorkPolicy

work OneTimeWorkRequest: One or more OneTimeWorkRequest to enqueue. REPLACE ensures that if there is pending work labelled with uniqueWorkName, it will be cancelled and the new work will run. KEEP will run the new sequence of work only if there is no pending work labelled with uniqueWorkName. APPEND will create a new sequence of work if there is no existing work with uniqueWorkName; otherwise, work will be added as a child of all leaf nodes labelled with uniqueWorkName.

Returns
WorkContinuation A WorkContinuation that allows further chaining

beginWith

public abstract WorkContinuation beginWith (List<OneTimeWorkRequest> work)

Begins a chain with one or more OneTimeWorkRequests, which can be enqueued together in the future using WorkContinuation.enqueue().

Parameters
work List: One or more OneTimeWorkRequest to start a chain of work

Returns
WorkContinuation A WorkContinuation that allows for further chaining of dependent OneTimeWorkRequest

beginWith

public final WorkContinuation beginWith (OneTimeWorkRequest... work)

Begins a chain with one or more OneTimeWorkRequests, which can be enqueued together in the future using WorkContinuation.enqueue().

Parameters
work OneTimeWorkRequest: One or more OneTimeWorkRequest to start a chain of work

Returns
WorkContinuation A WorkContinuation that allows for further chaining of dependent OneTimeWorkRequest

cancelAllWork

public abstract ListenableFuture<Void> cancelAllWork ()

Cancels all unfinished work. Use this method with extreme caution! By invoking it, you will potentially affect other modules or libraries in your codebase. It is strongly recommended that you use one of the other cancellation methods at your disposal.

Returns
ListenableFuture<Void> A ListenableFuture that completes when the cancelAllWork operation is completed

cancelAllWorkByTag

public abstract ListenableFuture<Void> cancelAllWorkByTag (String tag)

Cancels all unfinished work with the given tag. Note that cancellation is a best-effort policy and work that is already executing may continue to run.

Parameters
tag String: The tag used to identify the work

Returns
ListenableFuture<Void> A ListenableFuture that completes when the cancelAllWorkByTag operation is completed

cancelUniqueWork

public abstract ListenableFuture<Void> cancelUniqueWork (String uniqueWorkName)

Cancels all unfinished work in the work chain with the given name. Note that cancellation is a best-effort policy and work that is already executing may continue to run.

Parameters
uniqueWorkName String: The unique name used to identify the chain of work

Returns
ListenableFuture<Void> A ListenableFuture that completes when the cancelUniqueWork operation is completed

cancelWorkById

public abstract ListenableFuture<Void> cancelWorkById (UUID id)

Cancels work with the given id if it isn't finished. Note that cancellation is a best-effort policy and work that is already executing may continue to run.

Parameters
id UUID: The id of the work

Returns
ListenableFuture<Void> A ListenableFuture that completes when the cancelWorkById operation is completed

enqueue

public abstract ListenableFuture<Void> enqueue (List<? extends WorkRequest> requests)

Enqueues one or more items for background processing.

Parameters
requests List: One or more WorkRequest to enqueue

Returns
ListenableFuture<Void> A ListenableFuture that completes when the enqueue operation is completed

enqueue

public final ListenableFuture<Void> enqueue (WorkRequest... workRequests)

Enqueues one or more items for background processing.

Parameters
workRequests WorkRequest: One or more WorkRequest to enqueue

Returns
ListenableFuture<Void> A ListenableFuture that completes when the enqueue operation is completed

enqueueUniquePeriodicWork

public abstract ListenableFuture<Void> enqueueUniquePeriodicWork (String uniqueWorkName, 
                ExistingPeriodicWorkPolicy existingPeriodicWorkPolicy, 
                PeriodicWorkRequest periodicWork)

This method allows you to enqueue a uniquely-named PeriodicWorkRequest, where only one PeriodicWorkRequest of a particular name can be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work. The uniqueWorkName uniquely identifies this PeriodicWorkRequest.

Parameters
uniqueWorkName String: A unique name which for this operation

existingPeriodicWorkPolicy ExistingPeriodicWorkPolicy: An ExistingPeriodicWorkPolicy

periodicWork PeriodicWorkRequest: A PeriodicWorkRequest to enqueue. REPLACE ensures that if there is pending work labelled with uniqueWorkName, it will be cancelled and the new work will run. KEEP will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.

Returns
ListenableFuture<Void> A ListenableFuture that completes when the enqueue operation is completed

getInstance

public static WorkManager getInstance ()

Retrieves the default singleton instance of WorkManager.

Returns
WorkManager The singleton instance of WorkManager; this may be null in unusual circumstances where you have disabled automatic initialization and have failed to manually call initialize(Context, Configuration).

Throws
IllegalStateException If WorkManager is not initialized properly. This is most likely because you disabled the automatic initialization but forgot to manually call initialize(Context, Configuration).

getLastCancelAllTimeMillis

public abstract ListenableFuture<Long> getLastCancelAllTimeMillis ()

Gets a ListenableFuture of the last time all work was cancelled. This method is intended for use by library and module developers who have dependent data in their own repository that must be updated or deleted in case someone cancels their work without their prior knowledge.

Returns
ListenableFuture<Long> A ListenableFuture of the timestamp in milliseconds when method that cancelled all work was last invoked; this timestamp may be 0L if this never occurred

getLastCancelAllTimeMillisLiveData

public abstract LiveData<Long> getLastCancelAllTimeMillisLiveData ()

Gets a LiveData of the last time all work was cancelled. This method is intended for use by library and module developers who have dependent data in their own repository that must be updated or deleted in case someone cancels their work without their prior knowledge.

Returns
LiveData<Long> A LiveData of the timestamp in milliseconds when method that cancelled all work was last invoked; this timestamp may be 0L if this never occurred.

getStatusById

public abstract ListenableFuture<WorkStatus> getStatusById (UUID id)

Gets a ListenableFuture of the WorkStatus for a given work id.

Parameters
id UUID: The id of the work

Returns
ListenableFuture<WorkStatus> A ListenableFuture of the WorkStatus associated with id; note that this WorkStatus may be null if id is not known to WorkManager

getStatusByIdLiveData

public abstract LiveData<WorkStatus> getStatusByIdLiveData (UUID id)

Gets a LiveData of the WorkStatus for a given work id.

Parameters
id UUID: The id of the work

Returns
LiveData<WorkStatus> A LiveData of the WorkStatus associated with id; note that this WorkStatus may be null if id is not known to WorkManager.

getStatusesByTag

public abstract ListenableFuture<List<WorkStatus>> getStatusesByTag (String tag)

Gets a ListenableFuture of the WorkStatus for all work for a given tag.

Parameters
tag String: The tag of the work

Returns
ListenableFuture<List<WorkStatus>> A ListenableFuture list of WorkStatus for work tagged with tag

getStatusesByTagLiveData

public abstract LiveData<List<WorkStatus>> getStatusesByTagLiveData (String tag)

Gets a LiveData of the WorkStatus for all work for a given tag.

Parameters
tag String: The tag of the work

Returns
LiveData<List<WorkStatus>> A LiveData list of WorkStatus for work tagged with tag

getStatusesForUniqueWork

public abstract ListenableFuture<List<WorkStatus>> getStatusesForUniqueWork (String uniqueWorkName)

Gets a ListenableFuture of the WorkStatus for all work in a work chain with a given unique name.

Parameters
uniqueWorkName String: The unique name used to identify the chain of work

Returns
ListenableFuture<List<WorkStatus>> A ListenableFuture of the WorkStatus for work in the chain named uniqueWorkName

getStatusesForUniqueWorkLiveData

public abstract LiveData<List<WorkStatus>> getStatusesForUniqueWorkLiveData (String uniqueWorkName)

Gets a LiveData of the WorkStatus for all work in a work chain with a given unique name.

Parameters
uniqueWorkName String: The unique name used to identify the chain of work

Returns
LiveData<List<WorkStatus>> A LiveData of the WorkStatus for work in the chain named uniqueWorkName

initialize

public static void initialize (Context context, 
                Configuration configuration)

Used to do a one-time initialization of the WorkManager singleton with a custom Configuration. By default, this method should not be called because WorkManager is automatically initialized. To initialize WorkManager yourself, please follow these steps:

  • Disable androidx.work.impl.WorkManagerInitializer in your manifest
  • In Application#onCreate or a ContentProvider, call this method before calling getInstance()

This method has no effect if WorkManager is already initialized.

Parameters
context Context: A Context object for configuration purposes. Internally, this class will call Context.getApplicationContext(), so you may safely pass in any Context without risking a memory leak.

configuration Configuration: The Configuration for used to set up WorkManager.

pruneWork

public abstract ListenableFuture<Void> pruneWork ()

Prunes all eligible finished work from the internal database. Eligible work must be finished (State.SUCCEEDED, State.FAILED, or State.CANCELLED), with zero unfinished dependents.

Use this method with caution; by invoking it, you (and any modules and libraries in your codebase) will no longer be able to observe the WorkStatus of the pruned work. You do not normally need to call this method - WorkManager takes care to auto-prune its work after a sane period of time. This method also ignores the WorkRequest.Builder.keepResultsForAtLeast(long, TimeUnit) policy.

Returns
ListenableFuture<Void> A ListenableFuture that completes when the pruneWork operation is completed