Background tasks

Background tasks (or background processing) are any task that executes outside Main Thread, i.e., executes on a background thread. Any task that takes more than a few milliseconds should be delegated to a background thread.

Background tasks fall into one of the following main categories:
  • Immediate: task need to complete while the user is interacting with the application.
  • Deferred: task allow for slight variations in when it run that are based on conditions such as network availability and remaining battery.
  • Exact: task need to run at an exact time.
This decision tree (extracted from: Guide to background processing | Android Developers) helps you decide which category is best for your background task:

Each of those categories of background tasks can be implemented in a recommended way:
  • Immediate tasks -> Kotlin coroutines.
  • Deferred tasks -> WorkManager.
  • Exact tasks -> AlarmManager (*).
(*) Note that AlarmManager is not a strict way to implement a background task, because this only notifies your app when a some point in the future is reached. You will still need to define if your app will be launched, if a service will be launched or if you will use a broadcast receiver and how this task will be implemented, generally, on a kotlin coroutine.