Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

57. A Basic Overview of Threads and AsyncTasks

The next chapter will be the first in a series of chapters intended to introduce the use of Android Services to perform application tasks in the background. It is impossible, however, to understand the steps involved in implementing services without first gaining a basic understanding of the concept of threading in Android applications. Threads and the AsyncTask class are, therefore, the topic of this chapter.

57.1 An Overview of Threads

Threads are the cornerstone of any multitasking operating system and can be thought of as mini-processes running within a main process, the purpose of which is to enable at least the appearance of parallel execution paths within applications.

57.2 The Application Main Thread

When an Android application is first started, the runtime system creates a single thread in which all application components will run by default. This thread is generally referred to as the main thread. The primary role of the main thread is to handle the user interface in terms of event handling and interaction with views in the user interface. Any additional components that are started within the application will, by default, also run on the main thread.

Any component within an application that performs a time consuming task using the main thread will cause the entire application to appear to lock up until the task is completed. This will typically result in the operating system displaying an “Application is not responding” warning to the user. Clearly, this is far from the desired behavior for any application. This can be avoided simply by launching the task to be performed in a separate thread, allowing the main thread to continue...

57.3 Thread Handlers

Clearly, one of the key rules of Android development is to never perform time-consuming operations on the main thread of an application. The second, equally important, rule is that the code within a separate thread must never, under any circumstances, directly update any aspect of the user interface. Any changes to the user interface must always be performed from within the main thread. The reason for this is that the Android UI toolkit is not thread-safe. Attempts to work with non-thread-safe code from within multiple threads will typically result in intermittent problems and unpredictable application behavior.

If a time consuming task needs to run in a background thread and also update the user interface the best approach is to implement an asynchronous task by subclassing the AsyncTask class.

57.4 A Basic AsyncTask Example

The remainder of this chapter will work through some examples intended to provide an introduction to threads and the use of the AsyncTask class. The first step will be to highlight the importance of performing time-consuming tasks in a separate thread from the main thread.

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter AsyncDemo into the Name field and specify com.ebookfrenzy.asyncdemo as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java.

Load the activity_main.xml file for the project into the Layout Editor tool. Select the default TextView component and change the ID for the view to myTextView in the Attributes tool window.

Add a Button view to the user interface, positioned directly beneath...

57.5 Subclassing AsyncTask

In order to create a new thread, the code to be executed in that thread needs to be performed within an AsyncTask instance. The first step is to subclass AsyncTask in the MainActivity.java file as follows:

.

.

import android.os.AsyncTask;

.

.

public class MainActivity extends AppCompatActivity {

.

.

    private class MyTask extends AsyncTask<String, Void, String> {

 

        @Override

        protected void onPreExecute() {

        }

 

        @Override

        protected String doInBackground(String... params) {

        }

 

        @Override

       ...

57.6 Testing the App

When the application is now run, touching the button causes the delay to be performed in a new thread leaving the main thread to continue handling the user interface, including responding to additional button presses. During the delay, the user interface will be updated every second showing the counter value. On completion of the timeout, the TextView will display the “Button Pressed” message.

57.7 Canceling a Task

A running task may be canceled by calling the cancel() method of the task object passing through a Boolean value indicating whether the task can be interrupted before the in-progress task completes:

AsyncTask task = new MyTask().execute();

task.cancel(true);

57.8 Summary

This chapter has provided an overview of threading within Android applications. When an application is first launched in a process, the runtime system creates a main thread in which all subsequently launched application components run by default. The primary role of the main thread is to handle the user interface, so any time consuming tasks performed in that thread will give the appearance that the application has locked up. It is essential, therefore, that tasks likely to take time to complete be started in a separate thread.

Because the Android user interface toolkit is not thread-safe, changes to the user interface should not be made in any thread other than the main thread. Background tasks may be performed in a separate thread by subclassing the AsyncTask class and implementing the class methods to perform the task and update the user interface.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth