Processing data in the background is an important part of creating an Android application that is both responsive for your users as well as a good citizen on the Android platform. This guide defines background task categories, provides you with criteria to categorize your tasks, and recommends APIs that you should use to execute them.
In general, any task that takes more than a few milliseconds should be delegated to a background thread. Common long-running tasks include things like decoding a bitmap, accessing storage, working on a machine learning (ML) model, or performing network requests.
Categories of background tasks
Background tasks fall into one of the following main categories:
To categorize a task, answer the following questions, and traverse the corresponding decision tree in figure 1:
- Does the task need to complete while the user is interacting with the application?
- If so, this task should be categorized for immediate execution. If not, proceed to the second question.
- Does the task need to run at an exact time?
- If you do need to run a task at an exact time, categorize the task as exact.
Most tasks don't need to be run at an exact time. Tasks generally allow for slight variations in when they run that are based on conditions such as network availability and remaining battery. Tasks that don't need to be run at an exact time should be categorized as deferred.
The following sections describe recommended solutions for each background task type.
We recommend Kotlin coroutines for tasks that should
end when the user leaves a certain scope or finishes an interaction.
Many Android KTX libraries contain ready-to-use coroutine
scopes for common app components like
For Java programming language users, see Threading on Android for recommended options.
For tasks that should be executed immediately and need continued processing,
even if the user puts the application in background or the device restarts,
we recommend using
and its support for long-running tasks.
In specific cases, such as with media playback or active navigation, you might want to use foreground Services directly.
Every task that is not directly connected to a user interaction and can run
at any time in the future can be deferred. The recommended solution for
deferred tasks is
WorkManager makes it easy to schedule deferrable, asynchronous tasks that
are expected to run even if the app exits or the device restarts. See the
to learn how to schedule these types of tasks.
A task that needs to be executed at an exact point in time can use
To learn more about
Schedule repeating alarms.