Detailed explanation of Android multithreaded asynctask

This essay will explain the knowledge of Android multithreading and how to realize the communication between threads through the asynctask mechanism.

1、 Multithreading in Android

In Android, when an application component starts and no other application component is running, the Android system will open up a new thread for the application component to execute. By default, in the same Android application, its components run in the same thread, which we call the main thread. When we start another component through one component, it is completed in the same thread by default. Of course, we can manage the threads of our Android application by ourselves, and we can create additional threads for the application according to our own needs.

2、 Main thread and worker thread

In Android, threads are usually divided into two types. One is called main thread. Threads other than main thread can be called worker thread.

When an application is running, the Android operating system will start a thread for the application. This thread is our main thread. This thread is very important. It is mainly used to load our UI interface, complete the interaction between the system and our users, and display the interaction results to our users, Therefore, the main thread is also called UI thread.

The Android system will not create an additional thread for our application components by default. All these components run in the same thread by default. However, sometimes when our application needs to complete a time-consuming operation, such as accessing the network or querying the database, our UI thread will be blocked. For example, when we click a button and want it to get some data from the network, if this operation is completed in the UI thread, when we click the button, the UI thread will be blocked. At this time, our system will not schedule any other events. What's worse, if the blocking time of our whole site exceeds 5 seconds (the official says so). At this time, the phenomenon of anr (application not responding) will appear. At this time, the application will pop up a box to let users choose whether to exit the program. For Android development, the phenomenon of anr is absolutely not allowed.

In addition, because our Android UI control is thread unsafe, we cannot operate our UI control in threads other than UI thread. Therefore, in the multi-threaded programming of Android, we have two very important principles to abide by:

We must not perform time-consuming operations in UI threads, block our UI threads, or manipulate our UI elements in threads other than UI threads

3、 How to handle the communication between UI thread and worker thread

Since there are two important principles to follow in Android, we may have questions? We can neither handle time-consuming operations in the main thread nor access our UI control in the working thread. For example, if we want to download a picture from the network, how can we update it to the UI control? This is related to the communication between our main thread and worker thread. Android provides two ways to solve the direct communication problem of threads, one is through the handler mechanism (this method will be described in detail in the following essays), and the other is the asynctask mechanism to be explained in detail today.

4、 Asynctask

Asynctask: asynchronous task, literally, is to complete some operations asynchronously when our UI main thread is running. Asynctask allows us to execute an asynchronous task in the background. We can execute time-consuming operations in asynchronous tasks, and return the results of task execution to our UI thread at any time to update our UI controls. Through asynctask, we can easily solve the communication problem between multiple threads.

How to understand asynctask? Generally speaking, asynctask is equivalent to Android providing us with a framework for multithreading programming, which is between thread and handler. If we want to define an asynctask, we need to define a class to inherit the abstract class asynctask and implement its only doinbackground abstract method. To master asynctask, we must have a concept, which can be summarized as three generics and four steps.

What do the three generics mean? Let's take a look at the definition of the abstract class asynctask. When we define a class to inherit asynctask, we need to specify three generic parameters:

AsyncTask <Params,Progress,Result>

Params: this generic specifies the type of parameters we pass to the asynchronous task during execution. Progress: this generic specifies the type of parameters that our asynchronous task returns the execution progress to the UI thread during execution. Result: this generic specifies the type of results returned to the UI thread after the asynchronous task is executed

When defining a class to inherit the asynctask class, we must specify the types of these three generic types. If none is specified, they will be written as void,

For example:

AsyncTask <Void,Void,Void>

Four steps: when we execute an asynchronous task, we need to follow the following four steps

Onpreexecute(): this method is executed before executing asynchronous tasks and is executed in the UI thread. Usually, we do some UI control initialization operations in this method, such as pop-up to give ProgressDialog doinbackground (params... Params): this method will be executed immediately after the onpreexecute() method is executed, This method is to handle asynchronous tasks. The Android operating system will open a worker thread in the background thread pool to execute our method, so this method is executed in the worker thread. After this method is executed, we can send our execution results to our last onpostexecute method. In this method, We can obtain data from the network and other time-consuming operations onprogressupdate (Advances... Values): this method is also executed in the UI thread. When we execute asynchronous tasks, sometimes we need to return the execution progress to our UI interface, such as downloading a network picture, and we need to display the download progress at all times, We can use this method to update our progress. Before this method is called, we need to call a publishProgress (Progress) method in the doInBackground method to transfer our progress to onProgressUpdate method to update onPostExecute (Result... Result): when our asynchronous task is executed, the result will be returned to this method. This method is also invoked in UI Thread, and we can display the returned results on the UI control.

Why does our asynctask abstract class only have one doinbackground abstract method?? The reason is that if we want to do an asynchronous task, we must open a new thread for it to complete some operations. When completing this asynchronous task, I may not need to pop up the ProgressDialog. I do not need to update the progress bar of my ProgressDialog at any time, and I do not need to update the results to our UI interface, Therefore, the three methods other than the doinbackground method are not necessary, so the method we must implement is the doinbackground method.

5、 Download an image from the network through asynctask

Let's use two code examples to see how to download an image from the network through asynctask and update it to our ImageView control.

① When downloading pictures, a ProgressDialog pops up, but the real-time progress is not displayed. Let's take a look at the layout file:

It is a very simple ImageView control and a button control. When you click the button control, a ProgressDialog pops up, and then start an asynchronous task to download a picture from the network and update it to our ImageView. It should also be noted that if we want to use mobile phones to access the network, we must authorize them. In the follow-up study, we will explain the authorization knowledge in android in detail. Let's take a look at the androidmanifest.xml file:

Next, let's look at our activity Code:

Let's take a look at the renderings:

② Download a Web picture with a progress bar update

The following code example will show the update of the progress bar when downloading the picture. The configuration file remains unchanged. Let's take a look at the activity Code:

Let's take a look at the renderings:

In this way, we can download a picture from the network through asynctask, update it to the UI control, and update the current progress from time to time.

6、 Key knowledge points of asynctask

The working principle of asynctask has been explained in detail in the above two sections. Here, we need to add some other knowledge points of asynctask:

1.Cancelling a Task

We can cancel the execution of our asynchronous tasks at any time. After calling the cancel (Boolean) method, after calling this method, the system will then call the isCancelled () method and return true. If this method is called, the onpostexecute () method will not be called after the doinbackground () method is executed. Instead, the oncancelled () method will be called. In order to ensure that the task has been cancelled, we need to call the iscancelled () method frequently to judge if necessary.

2. Principles to be followed when using asynctask for asynchronous tasks:

Asynctask class must be loaded in UI thread, which is in Android jelly_ After the Bean version, these are automatically completed. The object of AsyncTask must be instantiated in UI Thread. The execute method must be invoked in UI Thread. Do not manually invoke AsyncTask onPreExecute, doInBackground, publishProgress, onPreExecute, and square method. These are automatically executed by the calling system.

This concludes the summary of asynctask. This essay mainly explains the multithreading knowledge in Android, explains the concept and implementation mechanism of asynctask asynchronous task in detail, and understands the execution process of asynctask through examples. Finally, it also supplements some important knowledge points of asynctask, including how to cancel an asynctask and, The rules we must follow when using asynctask.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>