O'Reilly logo

Efficient Android Threading by Anders Goransson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 Activities and Fragments, 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, worker threads created from the UI thread belong to the same thread group, with the same priority, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required