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.

Thread lifecycle
Figure 7-1. Lifecycle of a thread
New
Before the execution of a thread, a Thread object 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 ...

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.