androidx.work


WorkManager the recommended library for persistent work. Scheduled work is guaranteed to execute sometime after its androidx.work.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 androidx.work.ListenableWorker class. A simple implementation, androidx.work.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: androidx.work.OneTimeWorkRequest and androidx.work.PeriodicWorkRequest. OneTimeWorkRequests can be chained together into acyclic graphs. 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 androidx.work.Constraints, inputs (see androidx.work.Data), and backoff criteria. WorkRequests can be tagged with human-readable Strings (see addTag), and chains of work can be given a uniquely-identifiable name with conflict policies. *

Initializing WorkManager

By default, WorkManager is initialized using a ContentProvider with a default androidx.work.Configuration. 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 androidx.work.Configuration by using androidx.work.Configuration.Provider or initialize.

WorkManager and its Interactions with the OS

WorkManager uses BroadcastReceivers to monitor androidx.work.Constraints on devices before API 23. The BroadcastReceivers are disabled on API 23 and up. In particular, WorkManager listens to the following Intents:

  • android.intent.action.ACTION_POWER_CONNECTED
  • android.intent.action.ACTION_POWER_DISCONNECTED
  • android.intent.action.BATTERY_OKAY
  • android.intent.action.BATTERY_LOW
  • android.intent.action.DEVICE_STORAGE_LOW
  • android.intent.action.DEVICE_STORAGE_OK
  • android.net.conn.CONNECTIVITY_CHANGE
In addition, WorkManager listens to system time changes and reboots to properly reschedule work in certain situations. For this, it listens to the following Intents:
  • android.intent.action.BOOT_COMPLETED
  • android.intent.action.TIME_SET
  • android.intent.action.TIMEZONE_CHANGED

WorkManager uses the following permissions:

  • android.permission.WAKE_LOCK to make it can keep the device awake to complete work before API 23
  • android.permission.ACCESS_NETWORK_STATE to listen to network changes before API 23 and monitor network androidx.work.Constraints
  • android.permission.RECEIVE_BOOT_COMPLETED to listen to reboots and reschedule work properly.

Note that WorkManager may enable or disable some of its BroadcastReceivers at runtime as needed. This has the side-effect of the system sending ACTION_PACKAGE_CHANGED broadcasts to your app. Please be aware of this use case and architect your app appropriately (especially if you are using widgets - see https://issuetracker.google.com/115575872).

Interfaces

Clock

The interface WorkManager uses to access to the current time.

Configuration.Provider

A class that can provide the Configuration for WorkManager and allow for on-demand initialization of WorkManager.

ForegroundUpdater

Manages updating android.app.Notifications when a ListenableWorker transitions to running in the context of a foreground android.app.Service.

Operation

An object that provides information about the execution of an asynchronous command being performed by WorkManager.

ProgressUpdater

Updates progress for a androidx.work.ListenableWorker.

RunnableScheduler

Can be used to schedule Runnables after a delay in milliseconds.

Classes

ArrayCreatingInputMerger

An InputMerger that attempts to merge the inputs, creating arrays when necessary.

Configuration

The Configuration object used to customize WorkManager upon initialization.

Configuration.Builder

A Builder for Configurations.

Constraints

A specification of the requirements that need to be met before a WorkRequest can run.

Constraints.Builder

A Builder for a Constraints object.

Constraints.ContentUriTrigger

This class describes a content uri trigger on the WorkRequest: it should run when a local content: Uri is updated.

CoroutineWorker

A ListenableWorker implementation that provides interop with Kotlin Coroutines.

Data

A persistable set of key/value pairs which are used as inputs and outputs for ListenableWorkers.

Data.Builder

A builder for Data objects.

DelegatingWorkerFactory

A WorkerFactory which delegates to other factories.

ForegroundInfo

The information required when a ListenableWorker runs in the context of a foreground service.

InputMerger

An abstract class that allows the user to define how to merge a list of inputs to a ListenableWorker.

InputMergerFactory

A factory object that creates InputMerger instances.

ListenableWorker

A class that can perform work asynchronously in WorkManager.

ListenableWorker.Result

The result of a ListenableWorker's computation.

OneTimeWorkRequest

A WorkRequest for non-repeating work.

OneTimeWorkRequest.Builder

Builder for OneTimeWorkRequests.

Operation.State

The lifecycle state of an Operation.

Operation.State.FAILURE

This represents an Operation which has failed.

Operation.State.IN_PROGRESS

This represents an Operation which is in progress.

Operation.State.SUCCESS

This represents an Operation which is successful.

OverwritingInputMerger

An InputMerger that attempts to add all keys from all inputs to the output.

PeriodicWorkRequest

A WorkRequest for repeating work.

PeriodicWorkRequest.Builder

Builder for PeriodicWorkRequests.

RxWorker

RxJava2 interoperability Worker implementation.

WorkContinuation

A class that allows you to chain together OneTimeWorkRequests.

WorkInfo

Information about a particular WorkRequest containing the id of the WorkRequest, its current State, output, tags, and run attempt count.

WorkInfo.PeriodicityInfo

A periodic work's interval and flex duration

WorkManager

WorkManager is the recommended library for persistent work.

WorkManagerInitializer

Initializes androidx.work.WorkManager using androidx.startup.

WorkQuery

A specification for querying WorkRequests.

WorkQuery.Builder

A builder for WorkQuery.

WorkRequest

The base class for specifying parameters for work that should be enqueued in WorkManager.

WorkRequest.Builder

A builder for WorkRequests.

Worker

A class that performs work synchronously on a background thread provided by WorkManager.

WorkerExceptionInfo

Represents exceptions occurred from initializing or executing a ListenableWorker.

WorkerFactory

A factory object that creates ListenableWorker instances.

WorkerParameters

Setup parameters for a ListenableWorker.

Annotations

ExperimentalConfigurationApi

Annotation indicating experimental API for new WorkManager's Configuration APIs.

Enums

BackoffPolicy

An enumeration of backoff policies when retrying work.

ExistingPeriodicWorkPolicy

An enumeration of the conflict resolution policies available to unique PeriodicWorkRequests in case of a collision.

ExistingWorkPolicy

An enumeration of the conflict resolution policies available to unique OneTimeWorkRequests in case of a collision.

NetworkType

An enumeration of various network types that can be used as Constraints for work.

OutOfQuotaPolicy

An enumeration of policies that help determine out of quota behavior for expedited jobs.

WorkInfo.State

The current lifecycle state of a WorkRequest.

WorkManager.UpdateResult

An enumeration of results for WorkManager.updateWork method.

Top-level functions summary

inline OneTimeWorkRequest.Builder

Creates a OneTimeWorkRequest with the given ListenableWorker.

inline PeriodicWorkRequest.Builder
@RequiresApi(value = 26)
<W : ListenableWorker> PeriodicWorkRequestBuilder(repeatInterval: Duration)

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

inline PeriodicWorkRequest.Builder
@RequiresApi(value = 26)
<W : ListenableWorker> PeriodicWorkRequestBuilder(
    repeatInterval: Duration,
    flexTimeInterval: Duration
)

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

inline PeriodicWorkRequest.Builder
<W : ListenableWorker> PeriodicWorkRequestBuilder(
    repeatInterval: Long,
    repeatIntervalTimeUnit: TimeUnit
)

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

inline PeriodicWorkRequest.Builder
<W : ListenableWorker> PeriodicWorkRequestBuilder(
    repeatInterval: Long,
    repeatIntervalTimeUnit: TimeUnit,
    flexTimeInterval: Long,
    flexTimeIntervalUnit: TimeUnit
)

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

inline Data
workDataOf(vararg pairs: Pair<StringAny?>)

Converts a list of pairs to a Data object.

Extension functions summary

suspend inline Operation.State.SUCCESS

Awaits an Operation without blocking a thread.

inline Boolean

Returns true if the instance of Data has a value corresponding to the given key with an expected type T.

Boolean
inline OneTimeWorkRequest.Builder

Sets an InputMerger on the OneTimeWorkRequest.Builder.

inline WorkerParameters

Returns a new instance of WorkerParameters representing a WorkRequest that can run in a process corresponding to the provided ComponentName.

WorkerParameters
WorkerParameters.usingRemoteService(
    workerClassName: String,
    componentName: ComponentName
)

Returns a new instance of WorkerParameters representing a WorkRequest that can run in a process corresponding to the provided ComponentName.

Top-level functions

OneTimeWorkRequestBuilder

inline fun <W : ListenableWorker> OneTimeWorkRequestBuilder(): OneTimeWorkRequest.Builder

Creates a OneTimeWorkRequest with the given ListenableWorker.

PeriodicWorkRequestBuilder

@RequiresApi(value = 26)
inline fun <W : ListenableWorker> PeriodicWorkRequestBuilder(repeatInterval: Duration): PeriodicWorkRequest.Builder

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

Parameters
repeatInterval: Duration

@see androidx.work.PeriodicWorkRequest.Builder

PeriodicWorkRequestBuilder

@RequiresApi(value = 26)
inline fun <W : ListenableWorker> PeriodicWorkRequestBuilder(
    repeatInterval: Duration,
    flexTimeInterval: Duration
): PeriodicWorkRequest.Builder

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

PeriodicWorkRequestBuilder

inline fun <W : ListenableWorker> PeriodicWorkRequestBuilder(
    repeatInterval: Long,
    repeatIntervalTimeUnit: TimeUnit
): PeriodicWorkRequest.Builder

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

Parameters
repeatInterval: Long

@see androidx.work.PeriodicWorkRequest.Builder

repeatIntervalTimeUnit: TimeUnit

@see androidx.work.PeriodicWorkRequest.Builder

PeriodicWorkRequestBuilder

inline fun <W : ListenableWorker> PeriodicWorkRequestBuilder(
    repeatInterval: Long,
    repeatIntervalTimeUnit: TimeUnit,
    flexTimeInterval: Long,
    flexTimeIntervalUnit: TimeUnit
): PeriodicWorkRequest.Builder

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

inline fun workDataOf(vararg pairs: Pair<StringAny?>): Data

Converts a list of pairs to a Data object.

If multiple pairs have the same key, the resulting map will contain the value from the last of those pairs.

Entries of the map are iterated in the order they were specified.

Extension functions

suspend inline fun Operation.await(): Operation.State.SUCCESS

Awaits an Operation without blocking a thread.

This method returns the terminal state of the [Operation] which is [Operation.State.SUCCESS] or throws a [Throwable] that represents why the [Operation] failed.

hasKeyWithValueOfType

inline fun <T : Any> Data.hasKeyWithValueOfType(key: String): Boolean

Returns true if the instance of Data has a value corresponding to the given key with an expected type T.

isRemoteWorkRequest

fun WorkerParameters.isRemoteWorkRequest(): Boolean
Returns
Boolean

true if and only if the instance of WorkerParameters corresponds to a WorkRequest that runs in a remote process.

usingRemoteService

inline fun <T : ListenableWorker> WorkerParameters.usingRemoteService(
    componentName: ComponentName
): WorkerParameters

Returns a new instance of WorkerParameters representing a WorkRequest that can run in a process corresponding to the provided ComponentName.

Parameters
<T : ListenableWorker>

The ListenableWorker to delegate to.

componentName: ComponentName

The ComponentName that identifies the RemoteService that hosts the WorkRequest.

Returns
WorkerParameters

A new instance of WorkerParameters

usingRemoteService

fun WorkerParameters.usingRemoteService(
    workerClassName: String,
    componentName: ComponentName
): WorkerParameters

Returns a new instance of WorkerParameters representing a WorkRequest that can run in a process corresponding to the provided ComponentName.

Parameters
workerClassName: String

The fully qualified class name of the ListenableWorker to delegate to

componentName: ComponentName

The ComponentName that identifies the RemoteService that hosts the WorkRequest.

Returns
WorkerParameters

A new instance of WorkerParameters