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.
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, so the task to be executed is either defined by the thread itself or injected during thread creation.
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.
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, worker threads created from the UI thread belong to the same thread group, with the same priority, ...