Chapter 11. Services

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 cannot 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 ...

Get Efficient Android Threading now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.