Basic AsyncTask knowledge, asynctask

Source: Internet
Author: User

Basic AsyncTask knowledge, asynctask

As we all know, the UI cannot be updated in sub-threads, and an asynchronous message processing mechanism must be used. The general practice is to use Handler to send messages to the main thread and process the message update UI in the main thread as needed. If many sub-threads have the need to update the UI, the scene is a bit difficult to control. You must manually process the Handler message request in the code. This issue is obviously complicated. In fact, android has taken into consideration this situation. AsyncTask is designed by android to solve this problem. In fact, looking at the source code, we will know that the underlying encapsulation of AsyncTask is still the Handler Message Processing Mechanism of android. The following articles detail what AsyncTask is and how it is done.

 

I. What is AsyncTask?

AsyncTask is a set of asynchronous message processing tools encapsulated by android. Using this tool can make asynchronous message processing easier, and developers can avoid a lot of trouble. That is to say, AsyncTak is designed to do two things:

(1) Update the UI in the Child thread
(2) asynchronously load data

Next we will learn the most basic knowledge about it.

AsyncTask is an abstract class and must be a subclass of it. However, when inheriting the AsyncTask class, you must specify three generic parameters. The explanations are as follows:

(1) Params
Parameters that need to be passed in when executing AsyncTask can be used in background tasks.
(2) SS
When a background task is executed and the current Progress needs to be displayed on the interface, the generic type specified by Progress is used as the Progress unit.
(3) Result
After the background task is executed, if you need to return the result, use the generic type specified here as the return type.

Then, in the subclass, You need to override the following callback methods. They are all automatically called and do not manually call them in the code.

(1) onPreExexute ()
This method is called before the background task execution, that is, before the doInBackground method is executed. We usually perform initialization operations here, such as displaying a progress bar.
(2) doInBackground (Params ...)
This method is used to execute background tasks. All its code is operated in sub-threads. Once the task is completed, return is used to return the results. Of course, its parameters and types of returned results are the Params and Result we specified above. Please do not
Method to update the UI. To update the UI element, for example, to feedback the Progress of the current task, you can call publishProgress (Progress...) to complete the process.
(3) onProgressUpdate (Progress ...)
After the publishProgress method is called in the background task, the method is automatically called. The parameters in the method are transmitted by the publishProgress method. This method can be used to update the UI.
(4) onPostExecute (Result)
This method is called when the background task is completed, that is, after doInBackground is executed. The result returned by doInBackground is the parameter of this method. Here, you can execute the logic after the task is completed, such as closing a progress bar and updating some UIS.

Note that only the doInBackground method is executed in the Child thread, and others are executed in the main thread. So what are the methods for starting and canceling this task? As follows:

MyAsyncTask.exe cute () where the task
MyAsyncTask. cancel () cancels this task

 

Now, after learning the basic knowledge above, let's make a small exercise to help you better understand it.

2. A practical exercise

Let's compile an AsynTask sub-class and run it. Create a project, and then create a subclass that inherits from AsynTask. The Code is as follows:

1 package com. example. asynctasktest; 2 3 import android. OS. asyncTask; 4 import android. util. log; 5 6 7 8 public class MyAsyncTask extends AsyncTask <Void, Void, Void> {9 10 11 12 protected Void doInBackground (Void... params) {13 Log. d ("Fu Yong ----->", "doInBackground ");
PublishProgress (); 14 return null; 15} 16 17 18 protected void onPreExecute () {19 Log. d ("Fu Yong certificate ----->", "onPreExecute"); 20 super. onPreExecute (); 21} 22 23 24 protected void onPostExecute (Void result) {25 Log. d ("Fu Yong certificate ----->", "onPostExecute"); 26 super. onPostExecute (result); 27} 28 29 30 protected void onProgressUpdate (Void... values) {31 Log. d ("Fu Yong ----->", "onProgressUpdate"); 32 super. onProgressUpdate (values); 33} 34 35 36 37}

 

We have compiled a simplest AsyncTask subclass. All input parameters are null values, and then a sentence is printed in each method to facilitate observation of their execution sequence.

Then, modify the MainActivity Code as follows:

 1 package com.example.asynctasktest; 2  3 import android.os.Bundle; 4 import android.app.Activity; 5  6  7 public class MainActivity extends Activity { 8  9   10     protected void onCreate(Bundle savedInstanceState) {11         super.onCreate(savedInstanceState);12         setContentView(R.layout.activity_main);13         14         MyAsyncTask mTask = new MyAsyncTask();15         mTask.execute();16     }17 18 }

Then run the program and print the result as follows:

It is easy to see the execution sequence of the method from the printed results. As follows:

OnPreExecute ------>OnProgressUpdate(PublishProgress method is called to call this method) -------> doInBackground ---------> onPostExecute

 

Well, this article will give you a general understanding of the basic knowledge of AsynTask. In the next article, let's take a practical example and use this mechanism skillfully!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.