The Android Developer Challenge is back! Submit your idea before December 2.

WorkManager

abstract class WorkManager
kotlin.Any
   ↳ androidx.work.WorkManager

WorkManager is a library used to enqueue deferrable work that is guaranteed to execute sometime 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+
  • Uses a custom AlarmManager + BroadcastReceiver implementation for API 14-22

All work must be done in a ListenableWorker class. A simple implementation, Worker, is recommended as the starting point for most developers. With the optional dependencies, you can also use CoroutineWorker or RxWorker. All background work is given a maximum of ten minutes to finish its execution. After this time has expired, the worker will be signalled to stop.

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

<code>WorkManager workManager = WorkManager.getInstance(Context);
  workManager.enqueue(new OneTimeWorkRequest.Builder(FooWorker.class).build());</code>
A WorkRequest has an associated id that can be used for lookups and observation as follows:
<code>WorkRequest request = new OneTimeWorkRequest.Builder(FooWorker.class).build();
  workManager.enqueue(request);
  LiveData&lt;WorkInfo&gt; status = workManager.getWorkInfoByIdLiveData(request.getId());
  status.observe(...);</code>
You can also use the id for cancellation:
<code>WorkRequest request = new OneTimeWorkRequest.Builder(FooWorker.class).build();
  workManager.enqueue(request);
  workManager.cancelWorkById(request.getId());</code>
You can chain work as follows:
<code>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();</code>
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:
<code>WorkContinuation continuation = workManager.beginWith(A);
  continuation.then(B).then(D, E).enqueue();  // A is implicitly enqueued here
  continuation.then(C).enqueue();</code>
Work is eligible for execution when all of its prerequisites are complete. If any of its prerequisites fail or are cancelled, the work will never run.

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

Initializing WorkManager

By default, WorkManager auto-initializes itself using a built-in ContentProvider. ContentProviders are created and run before the Application object, so this allows the WorkManager singleton to be setup before your code can run in most cases. This is suitable for most developers. However, you can provide a custom Configuration by using Configuration.Provider or WorkManager#initialize(android.content.Context, androidx.work.Configuration).

Renaming and Removing ListenableWorker Classes

Exercise caution in renaming classes derived from ListenableWorkers. WorkManager stores the class name in its internal database when the WorkRequest is enqueued so it can later create an instance of that worker when constraints are met. Unless otherwise specified in the WorkManager Configuration, this is done in the default WorkerFactory which tries to reflectively create the ListenableWorker object. Therefore, renaming or removing these classes is dangerous - if there is pending work with the given class, it will fail permanently if the class cannot be found. If you are using a custom WorkerFactory, make sure you properly handle cases where the class is not found so that your code does not crash.

In case it is desirable to rename a class, implement a custom WorkerFactory that instantiates the right ListenableWorker for the old class name.

Summary

Public methods

WorkContinuation
beginUniqueWork(@NonNull uniqueWorkName: String, @NonNull existingWorkPolicy: ExistingWorkPolicy, @NonNull work: OneTimeWorkRequest)

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
beginUniqueWork(@NonNull uniqueWorkName: String, @NonNull existingWorkPolicy: ExistingWorkPolicy, @NonNull work: MutableList<OneTimeWorkRequest!>)

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.

WorkContinuation
beginWith(@NonNull work: OneTimeWorkRequest)

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

abstract WorkContinuation

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

abstract Operation

Cancels all unfinished work.

abstract Operation
cancelAllWorkByTag(@NonNull tag: String)

Cancels all unfinished work with the given tag.

abstract Operation
cancelUniqueWork(@NonNull uniqueWorkName: String)

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

abstract Operation
cancelWorkById(@NonNull id: UUID)

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

abstract PendingIntent

Creates a PendingIntent which can be used to cancel a WorkRequest with the given id.

Operation
enqueue(@NonNull workRequest: WorkRequest)

Enqueues one or more items for background processing.

abstract Operation
enqueue(@NonNull requests: MutableList<out WorkRequest!>)

Enqueues one or more items for background processing.

abstract Operation
enqueueUniquePeriodicWork(@NonNull uniqueWorkName: String, @NonNull existingPeriodicWorkPolicy: ExistingPeriodicWorkPolicy, @NonNull periodicWork: PeriodicWorkRequest)

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

open Operation
enqueueUniqueWork(@NonNull uniqueWorkName: String, @NonNull existingWorkPolicy: ExistingWorkPolicy, @NonNull work: OneTimeWorkRequest)

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

abstract Operation
enqueueUniqueWork(@NonNull uniqueWorkName: String, @NonNull existingWorkPolicy: ExistingWorkPolicy, @NonNull work: MutableList<OneTimeWorkRequest!>)

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

open static WorkManager

Retrieves the default singleton instance of WorkManager.

open static WorkManager
getInstance(@NonNull context: Context)

Retrieves the default singleton instance of WorkManager.

abstract ListenableFuture<Long!>

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

abstract LiveData<Long!>

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

abstract ListenableFuture<WorkInfo!>
getWorkInfoById(@NonNull id: UUID)

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

abstract LiveData<WorkInfo!>

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

abstract ListenableFuture<MutableList<WorkInfo!>!>
getWorkInfosByTag(@NonNull tag: String)

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

abstract LiveData<MutableList<WorkInfo!>!>

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

abstract ListenableFuture<MutableList<WorkInfo!>!>
getWorkInfosForUniqueWork(@NonNull uniqueWorkName: String)

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

abstract LiveData<MutableList<WorkInfo!>!>
getWorkInfosForUniqueWorkLiveData(@NonNull uniqueWorkName: String)

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

open static Unit
initialize(@NonNull context: Context, @NonNull configuration: Configuration)

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

abstract Operation

Prunes all eligible finished work from the internal database.

Public methods

beginUniqueWork

@NonNull fun beginUniqueWork(@NonNull uniqueWorkName: String, @NonNull existingWorkPolicy: ExistingWorkPolicy, @NonNull work: OneTimeWorkRequest): WorkContinuation

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.

If any work in the chain fails or is cancelled, all of its dependent work inherits that state and will never run. This is particularly important if you are using APPEND as your ExistingWorkPolicy.

Parameters
uniqueWorkName String: A unique name which for this chain of work
existingWorkPolicy String: An ExistingWorkPolicy
work String: The 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.
Return
WorkContinuation: A WorkContinuation that allows further chaining

beginUniqueWork

@NonNull abstract fun beginUniqueWork(@NonNull uniqueWorkName: String, @NonNull existingWorkPolicy: ExistingWorkPolicy, @NonNull work: MutableList<OneTimeWorkRequest!>): WorkContinuation

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.

If any work in the chain fails or is cancelled, all of its dependent work inherits that state and will never run. This is particularly important if you are using APPEND as your ExistingWorkPolicy.

Parameters
uniqueWorkName String: A unique name which for this chain of work
existingWorkPolicy String: An ExistingWorkPolicy; see below for more information
work String: 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.
Return
WorkContinuation: A WorkContinuation that allows further chaining

beginWith

@NonNull fun beginWith(@NonNull work: OneTimeWorkRequest): WorkContinuation

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

If any work in the chain fails or is cancelled, all of its dependent work inherits that state and will never run.

Parameters
work OneTimeWorkRequest: One or more OneTimeWorkRequest to start a chain of work
Return
WorkContinuation: A WorkContinuation that allows for further chaining of dependent OneTimeWorkRequest

beginWith

@NonNull abstract fun beginWith(@NonNull work: MutableList<OneTimeWorkRequest!>): WorkContinuation

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

If any work in the chain fails or is cancelled, all of its dependent work inherits that state and will never run.

Parameters
work MutableList<OneTimeWorkRequest!>: One or more OneTimeWorkRequest to start a chain of work
Return
WorkContinuation: A WorkContinuation that allows for further chaining of dependent OneTimeWorkRequest

cancelAllWork

@NonNull abstract fun cancelAllWork(): Operation

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.

Upon cancellation, ListenableWorker#onStopped() will be invoked for any affected workers.

Return
Operation: An Operation that can be used to determine when the cancelAllWork has completed

cancelAllWorkByTag

@NonNull abstract fun cancelAllWorkByTag(@NonNull tag: String): Operation

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. Upon cancellation, ListenableWorker#onStopped() will be invoked for any affected workers.

Parameters
tag String: The tag used to identify the work
Return
Operation: An Operation that can be used to determine when the cancelAllWorkByTag has completed

cancelUniqueWork

@NonNull abstract fun cancelUniqueWork(@NonNull uniqueWorkName: String): Operation

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. Upon cancellation, ListenableWorker#onStopped() will be invoked for any affected workers.

Parameters
uniqueWorkName String: The unique name used to identify the chain of work
Return
Operation: An Operation that can be used to determine when the cancelUniqueWork has completed

cancelWorkById

@NonNull abstract fun cancelWorkById(@NonNull id: UUID): Operation

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. Upon cancellation, ListenableWorker#onStopped() will be invoked for any affected workers.

Parameters
id UUID: The id of the work
Return
Operation: An Operation that can be used to determine when the cancelWorkById has completed

createCancelPendingIntent

@NonNull abstract fun createCancelPendingIntent(@NonNull id: UUID): PendingIntent

Creates a PendingIntent which can be used to cancel a WorkRequest with the given id.

Parameters
id UUID: The WorkRequest id.
Return
PendingIntent: The PendingIntent that can be used to cancel the WorkRequest.

enqueue

@NonNull fun enqueue(@NonNull workRequest: WorkRequest): Operation

Enqueues one or more items for background processing.

Parameters
workRequest WorkRequest: One or more WorkRequest to enqueue
Return
Operation: An Operation that can be used to determine when the enqueue has completed

enqueue

@NonNull abstract fun enqueue(@NonNull requests: MutableList<out WorkRequest!>): Operation

Enqueues one or more items for background processing.

Parameters
requests MutableList<out WorkRequest!>: One or more WorkRequest to enqueue
Return
Operation: An Operation that can be used to determine when the enqueue has completed

enqueueUniquePeriodicWork

@NonNull abstract fun enqueueUniquePeriodicWork(@NonNull uniqueWorkName: String, @NonNull existingPeriodicWorkPolicy: ExistingPeriodicWorkPolicy, @NonNull periodicWork: PeriodicWorkRequest): Operation

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 String: An ExistingPeriodicWorkPolicy
periodicWork String: 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.
Return
Operation: An Operation that can be used to determine when the enqueue has completed

enqueueUniqueWork

@NonNull open fun enqueueUniqueWork(@NonNull uniqueWorkName: String, @NonNull existingWorkPolicy: ExistingWorkPolicy, @NonNull work: OneTimeWorkRequest): Operation

This method allows you to enqueue work requests to a uniquely-named WorkContinuation, where only one continuation 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 WorkContinuation.

Parameters
uniqueWorkName String: A unique name which for this operation
existingWorkPolicy String: An ExistingWorkPolicy; see below for more information
work String: The OneTimeWorkRequests 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 OneTimeWorkRequests only if there is no pending work labelled with uniqueWorkName. APPEND will append the OneTimeWorkRequests as leaf nodes labelled with uniqueWorkName.
Return
Operation: An Operation that can be used to determine when the enqueue has completed

enqueueUniqueWork

@NonNull abstract fun enqueueUniqueWork(@NonNull uniqueWorkName: String, @NonNull existingWorkPolicy: ExistingWorkPolicy, @NonNull work: MutableList<OneTimeWorkRequest!>): Operation

This method allows you to enqueue work requests to a uniquely-named WorkContinuation, where only one continuation 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 WorkContinuation.

Parameters
uniqueWorkName String: A unique name which for this operation
existingWorkPolicy String: An ExistingWorkPolicy
work String: OneTimeWorkRequests 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 OneTimeWorkRequests only if there is no pending work labelled with uniqueWorkName. APPEND will append the OneTimeWorkRequests as leaf nodes labelled with uniqueWorkName.
Return
Operation: An Operation that can be used to determine when the enqueue has completed

getInstance

@NonNull open static fun getInstance(): WorkManager

Deprecated: Call WorkManager#getInstance(Context) instead.

Retrieves the default singleton instance of WorkManager.

Return
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).
Exceptions
IllegalStateException If WorkManager is not initialized properly as per the exception message.

getInstance

@NonNull open static fun getInstance(@NonNull context: Context): WorkManager

Retrieves the default singleton instance of WorkManager.

Parameters
context Context: A Context for on-demand initialization.
Return
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).
Exceptions
IllegalStateException If WorkManager is not initialized properly

getLastCancelAllTimeMillis

@NonNull abstract fun getLastCancelAllTimeMillis(): ListenableFuture<Long!>

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.

Return
ListenableFuture<Long!>: A ListenableFuture of the timestamp (System#getCurrentTimeMillis()) when cancelAllWork() was last invoked; this timestamp may be 0L if this never occurred

getLastCancelAllTimeMillisLiveData

@NonNull abstract fun getLastCancelAllTimeMillisLiveData(): LiveData<Long!>

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.

Return
LiveData<Long!>: A LiveData of the timestamp (System#getCurrentTimeMillis()) when cancelAllWork() was last invoked; this timestamp may be 0L if this never occurred

getWorkInfoById

@NonNull abstract fun getWorkInfoById(@NonNull id: UUID): ListenableFuture<WorkInfo!>

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

Parameters
id UUID: The id of the work
Return
ListenableFuture<WorkInfo!>: A ListenableFuture of the WorkInfo associated with id; note that this WorkInfo may be null if id is not known to WorkManager

getWorkInfoByIdLiveData

@NonNull abstract fun getWorkInfoByIdLiveData(@NonNull id: UUID): LiveData<WorkInfo!>

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

Parameters
id UUID: The id of the work
Return
LiveData<WorkInfo!>: A LiveData of the WorkInfo associated with id; note that this WorkInfo may be null if id is not known to WorkManager.

getWorkInfosByTag

@NonNull abstract fun getWorkInfosByTag(@NonNull tag: String): ListenableFuture<MutableList<WorkInfo!>!>

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

Parameters
tag String: The tag of the work
Return
ListenableFuture<MutableList<WorkInfo!>!>: A ListenableFuture list of WorkInfo for work tagged with tag

getWorkInfosByTagLiveData

@NonNull abstract fun getWorkInfosByTagLiveData(@NonNull tag: String): LiveData<MutableList<WorkInfo!>!>

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

Parameters
tag String: The tag of the work
Return
LiveData<MutableList<WorkInfo!>!>: A LiveData list of WorkInfo for work tagged with tag

getWorkInfosForUniqueWork

@NonNull abstract fun getWorkInfosForUniqueWork(@NonNull uniqueWorkName: String): ListenableFuture<MutableList<WorkInfo!>!>

Gets a ListenableFuture of the WorkInfo 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
Return
ListenableFuture<MutableList<WorkInfo!>!>: A ListenableFuture of the WorkInfo for work in the chain named uniqueWorkName

getWorkInfosForUniqueWorkLiveData

@NonNull abstract fun getWorkInfosForUniqueWorkLiveData(@NonNull uniqueWorkName: String): LiveData<MutableList<WorkInfo!>!>

Gets a LiveData of the WorkInfo 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
Return
LiveData<MutableList<WorkInfo!>!>: A LiveData of the WorkInfo for work in the chain named uniqueWorkName

initialize

open static fun initialize(@NonNull context: Context, @NonNull configuration: Configuration): Unit

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.
  • Invoke this method in Application#onCreate or a ContentProvider. Note that this method must be invoked in one of these two places or you risk getting a NullPointerException in getInstance(Context).

This method throws an exception if it is called multiple times.

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 Context: The Configuration for used to set up WorkManager.

pruneWork

@NonNull abstract fun pruneWork(): Operation

Prunes all eligible finished work from the internal database. Eligible work must be finished (WorkInfo.State#SUCCEEDED, WorkInfo.State#FAILED, or WorkInfo.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 WorkInfo 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 OneTimeWorkRequest.Builder#keepResultsForAtLeast(long, TimeUnit) policy.

Return
Operation: An Operation that can be used to determine when the pruneWork has completed