Android provides the
Service component to run operations that are invisible to the user or that should be exposed to other applications. This chapter focuses on asynchronous execution with
Service, although it is not an asynchronous execution environment by itself. The
Service runs in the UI thread, so it can degrade responsiveness and cause ANRs, even though it does not interact directly with the UI. Still, the
Service in combination with an asynchronous executor is a powerful tool for background task execution.
Why Use a Service For Asynchronous Execution?
Two risks are inherent in using regular threads instead of services for background operation.
Decouple lifecycles of components and threads
The thread lifecycle is independent of the Android components and their underlying Java object lifecycles. A thread continues to run until the task either finishes or the process is killed, even after the component that started the thread finishes itself. Threads may keep references to Java objects so that they can not be garbage collected until the thread terminates, as described in Chapter 6.
Lifecycles of the hosting processes
If the runtime terminates the process, all of its threads are terminated. Thus, background tasks are terminated and not restarted by default when the process is restored. The runtime terminates processes depending on their process rank–as described in Application Termination–and a process with no active components has a low ranking and is likely ...