SoFunction
Updated on 2025-04-05

Detailed explanation of the use case of the WorkManager for Android development Jetpack component

1. Introduction

WorkManager is used to handle Android background tasks. We just need to set the task content and when to execute it, and the rest of the work can be completely handed over to the system for processing. It will be automatically backward compatible and adopt different implementation solutions on different Android versions.

Since it is handed over to the system to schedule, it can ensure that the task can still be executed after the application exits or even the phone restarts. WorkManager is very suitable for performing tasks that regularly interact with the server, such as periodic synchronization of data, etc. In addition, WorkManager also supports periodic tasks and chain tasks.

It should be noted that WorkManager cannot guarantee that tasks can be executed on time. This is because in order to reduce battery consumption, the system will put several tasks that are close to the trigger event to perform together to reduce the number of times the CPU is awakened and extend the battery life time.

In addition, WorkManager may not work normally on domestic mobile phones, because most mobile phone manufacturers will add a "one-click shutdown" function when customizing Android systems. This way, the killed applications will not receive broadcasts or run the background tasks of WorkManager. The addition of this feature by domestic mobile phones is also helpless, mainly because there are too many malicious applications on the market that want to occupy the backend. Therefore, we should not use WorkManager to implement core functions on domestic mobile phones.

2. Import

Add dependencies in app/:

implementation ':work-runtime:2.3.2'

3. Basic use

The usage of WorkManager is divided into three steps:

  • Define a background task
  • Configure task running conditions
  • Pass the task to WorkManager

3.1 Defining background tasks

Create a SimpleWorker class, inherited from Worker:

class SimpleWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
    override fun doWork(): Result {
        ("~~~", "do something")
        return ()
    }
}

()Indicates that the task is executed successfully

()Indicates that the task execution failed

()Indicates that the task needs to be tried again. This method needs to be used with task retry configuration

3.2 Configure task running conditions

3.2.1 Tasks that only need to be executed

Build a task that only needs to be performed once using OneTimeWorkRequest

val request = (SimpleWorker::).build()

3.2.2 Tasks executed periodically

Use PeriodicWorkRequest to build tasks that are executed periodically

val request = (SimpleWorker::, 15, ).build()

In order to reduce power consumption, PeriodicWorkRequest requires that the task execution cycle must not be shorter than fifteen minutes. If the source code is checked, you can find that if the incoming value is shorter than fifteen minutes, the system will print a warning and then automatically set the cycle to fifteen minutes:

public static final long MIN_PERIODIC_INTERVAL_MILLIS = 15 * 60 * 1000L; // 15 minutes.
/**
 * Sets the periodic interval for this unit of work.
 *
 * @param intervalDuration The interval in milliseconds
 */
public void setPeriodic(long intervalDuration) {
    if (intervalDuration < MIN_PERIODIC_INTERVAL_MILLIS) {
        ().warning(TAG, (
                "Interval duration lesser than minimum allowed value; Changed to %s",
                MIN_PERIODIC_INTERVAL_MILLIS));
        intervalDuration = MIN_PERIODIC_INTERVAL_MILLIS;
    }
    setPeriodic(intervalDuration, intervalDuration);
}

3.3 Passing the task to WorkManager

(this).enqueue(request)

This is the basic use of WorkManager.

4. Advanced configuration

4.1 Set task delay execution

Set the delay time by setting the setInitialDelay method

val request = (SimpleWorker::)
   .setInitialDelay(5, )
   .build()

4.2 Add tags to tasks

Add tags via addTag method:

val request = (SimpleWorker::)
    .addTag("simple")
    .build()

The purpose of adding tags is to facilitate us to cancel tasks based on tags.

4.3 Cancel the task

4.3.1 Cancel the task according to the tag

(this).cancelAllWorkByTag("simple")

4.3.2 Cancel the task according to the id of the request

(this).cancelWorkById()

4.3.3 Cancel all tasks

(this).cancelAllWork()

4.4 Task retry

Retry the configuration task via setBackoffCriteria:

val request = (SimpleWorker::)
    .setBackoffCriteria(, 10, )
    .build()

As mentioned earlier, () means that the task needs to be retryed, and this method needs to be used in conjunction with the task retry configuration. Task retry configuration refers to the setBackoffCriteria method, which passes in three values, the second and third values ​​represent the retry time configuration. The first value represents the form of retry delay, and there are two values ​​to choose from:

  • The retry time increases linearly each time. According to the configuration in this example, the retry time is 10s, 20s, 30s, 40s...
  • The retry time increases exponentially each time. According to the configuration in this example, the retry time is 10s, 20s, 40s, 80s...

4.5 Listen to task results

(this).getWorkInfoByIdLiveData().observe(this) {
    ("~~~", "state = ${}, tags = ${()}")
    when () {
         -> ("~~~", "success")
         -> ("~~~", "fail")
         -> ("~~~", "running")
         -> ("~~~", "enqueued")
         -> ("~~~", "cancelled")
         -> ("~~~", "blocked")
    }
}

First, get the LiveData<WorkInfo> data of task information through getWorkInfoByIdLiveData, and then observe this data. You can also obtain the LiveData<List<WorkInfo>> of the same tag through getWorkInfosByTagLiveData and observe this task information list. The task state is obtained through WorkInfo's getState method. The main states used are sum, which mark the success and failure of the task.

4.6 Passing data

val request = (SimpleWorker::)
    .setInputData(().apply {
        putString("key", "value")
    }.build())
    .build()

Read this data in the SimpleWorker class:

("key")

4.7 Chain Tasks

val first = (SimpleWorker::)
    .build()
val second = (SimpleWorker::)
    .build()
val third = (SimpleWorker::)
    .build()
(this)
    .beginWith(first)
    .then(second)
    .then(third)
    .enqueue()

Start a chained task through beginWith, and then suffix it, and the tasks will be executed in order of connection. WorkManager requires that the next task must be executed after the previous task is executed successfully. In other words, the failure of any task will lead to the interruption of the chain task.

The above is the detailed explanation of the use cases for the Android development Jetpack component WorkManager. For more information about Android Jetpack component WorkManager, please follow my other related articles!