Chapter 7. Managing the Lifecycle of a Basic Thread
This chapter contains some of the basics of using threads, discusses threads in collaboration with Android components, and finishes with thread management. It covers the cancellation of tasks, how to retain threads across Activity and Fragment objects, and other essential techniques.
Basics
The Thread class in Android is no different from the Thread class in regular Java programming. It is the closest representation of the underlying Linux native thread an application gets. The Thread class creates the execution environment for tasks, represented by Runnable. The Thread implements Runnable, so the task to be executed is either defined by the thread itself or injected during thread creation.
Lifecycle
This section explains the observable states a thread can enter during its existence. These states are defined in the Thread.State class and are illustrated in Figure 7-1.

- New
-
Before the execution of a thread, a
Threadobject is created. The instantiation does not set up the execution environment, so it is no heavier than any other object instantiation. The default construction assigns the newly created thread to the same thread group as the thread that is doing the creation, with the same priority. Specifically, threads created from the UI thread belong to the same thread group, with the same priority, as ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access