Android: Application of asynchronous Processing Asynctask (II.)

Source: Internet
Author: User


In the previous article, Android: Application of Asynchronous Processing (handler+thread), we know that the main thread of the Android UI is primarily responsible for handling user key events, user touch-screen events, and screen drawing events; Since the UI is so busy, We developers must not play gooseberry to mess up the UI thread or something, otherwise the UI should stop responding-isn't that the rhythm of the curse?! So we know that with the Handler+thread method, the time-consuming task is handled in the sub-thread, and the UI is updated via the handler notification UI after the task is completed.

However, there are some people think that using handler+thread code will be more cumbersome, of course, some of these people include our great Google. So Asynctask (asynchronous task) turned out in Android 1.5; Compared to handler, because of the relatively good package, the Asynctask appears more lightweight, suitable for simple asynchronous processing, of course, the use of the relatively concise, sure enough is Google's pro-son!


Asynctask is an abstract class, usually an inherited life. The internal of the asynctask will maintain a static thread pool, each background task will naturally be committed to the thread pool to run, but also use the handler+thread mechanism to invoke Asynctask's various callback methods, the callback method is run in the main thread, so we all know what to do (~ o ~) ~zz (hurry up with the UI interface set near it).

We know that Asynctask<params, Progress, result> are abstract classes, and we can see here that it supports three generic types:

1.Params: Our asynctask to start working, we give him the type of the input parameter, which is the parameter passed to the background

2,Progress: Asynctask report to us the parameter type of its work progress, for example, the percentage of download progress

3,result: The background performs the task completion, the returned result of the parameter type

If a generic type we do not need to specify, we can openly specify void, nothing asynctask will not be sad drop.

Of course, Google also help us to Asynctask background task running five states, namely:1, ready to run, 2, is running in the background, 3, progress updates, 4, complete background tasks, 5, cancel the task . Each state has a corresponding callback method in the Asynctask.

1. Ready to run : OnPreExecute (), the callback method is called immediately in the UI thread when the task is opened, and is also called before the background time-consuming operation is performed, usually to do some initialization work, such as displaying the progress bar on the interface.

2, is running in the background: Doinbackground (Params ...), the callback function is called by the background thread at the end of the OnPreExecute () method execution, overriding the method is the time-consuming task that the background thread will complete Because it is called by a background thread, we cannot update the UI interface directly here, we should use Publishprogress (Progress ...). Trigger callback method Onprogressupdate (Progress ...) The result of the task calculation must be returned by the function and passed to OnPostExecute ().

3. Progress update:onprogressupdate (Progress ...), call the Publishprogress () method in Doinbackground () to update the execution progress of the task, which will trigger the method in the main thread. Typically used to dynamically display a progress bar.

4, complete the background task:onpostexecute (Result), when Doinbackground () completes, the system will automatically call the OnPostExecute () method, and will Doinbackground () is passed to the method by the return value of the

5. Cancel the task:oncancelled (), called when the Cancel () method of Asynctask is called.


Reference code:

 Public classMainactivityextendsActionbaractivityImplementsonclicklistener{PrivateButton startdownload; PrivateProgressBar Probar; PrivateTextView TV; Privatedowntask task; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Startdownload=(Button) Findviewbyid (; Probar=(ProgressBar) Findviewbyid (; TV=(TextView) Findviewbyid (; Startdownload.setonclicklistener ( This); } @Override Public voidOnClick (View v) {task=NewDowntask ();//execute of the same asynctask can only be called onceTask.execute ("input parameter, can be empty");//calling execute will callback the OnPreExecute method    }        classDowntaskextendsAsynctask<string, Integer, string>{@Override//This method is not run in the main thread, can be time-consuming operation, the UI interface cannot be updated, other methods run for the main thread        protectedString Doinbackground (String ... params) {//parameters of the params input for execute             for(inti = 1; I <= 100; i++){                Try{//Simulating download OperationsThread.Sleep (333); Publishprogress (i);//Pass the parameter I and trigger the Onprogressupdate callback method}Catch(interruptedexception e) {e.printstacktrace (); }} String result= "Task Completed"; returnResult//The OnPostExecute is called and the result is passed to the callback method} @Overrideprotected voidOnPreExecute () {//when the callback method finishes executing, the doinbackground will be calledProbar.setmax (100); Probar.setprogress (0); Tv.settext ("Start Download"); } @Overrideprotected voidOnPostExecute (String result) {//Doinbackground The method after the end of the callback. Toast.maketext (mainactivity. This, result, Toast.length_short). Show (); Tv.settext ("Download Complete"); } @Overrideprotected voidOnprogressupdate (Integer ... values) {//notifies UI interface updatesProbar.setprogress (values[0]); }            }}

Layout file:

<LinearLayoutxmlns:android= "Http://"Xmlns:tools= "Http://"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" >        <ButtonAndroid:id= "@+id/startdownload"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Start Download"/>    <ProgressBarAndroid:id= "@+id/probar"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"style= "@android: Style/widget.progressbar.horizontal"        />    <TextViewAndroid:id= "@+id/tv"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:textcolor= "#000000"android:textsize= "20SP"        /></LinearLayout>

Code Explanation:

1. When you click the button, instantiate an inherited subclass of Asynctask, and a task will be created. Next, the Execute execute (params) method starts the asynchronous task. (an instance of the same asynctask can execute only once, and multiple executions will throw an error).

2. After execute () is executed, the OnPreExecute () callback method is triggered to set the initial properties of the progress bar. After OnPreExecute () is executed, the Doinbackground (params) will be executed in the background thread, which receives the execute incoming parameters and takes time to operate, here is the simulation network file download task.

3, Doinbackground () in a background thread run, if you need to interact with the UI main thread to update progress, you can call the Publishprogress (values) method, which will trigger the onprogressupdate that is running on the main thread of the UI ( Values) callback method, where the progress bar is updated in the code.

4. When the background task executes, call OnPostExecute (Result) and the passed-in parameter is the object returned in Doinbackground ().


1. Do not execute execute () multiple times in the same Asynctask instance, and the correct method is to execute execute () once for the new asynctask.

2, time-consuming tasks must be handled in Doinbackground (), do not handle time-consuming tasks in other callback methods to avoid blocking the main thread of the UI.

3. Do not update the UI interface in Doinbackground (), you should update the UI by calling the callback method via Publishprogress ().

4, oncancelled () can only trigger the Cancel () method of Asynctask, and cannot cancel the thread task that is running on the thread pool, but can stop the thread task through the flag bit.

5, in different versions of Android, Asynctask multi-tasking, some can be parallel some are sequential execution, but in the high version of Android, you can set the thread pool execution rules by specifying parameters.

6, Asynctask suitable for short-term operation, long-term operation, such as downloading a large video, which requires you to use their own threads to download, whether it is a breakpoint download or other.

Enjoy wind chimes
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph statement, and in the article page obvious location to the original connection, or next time not to you reproduced.

Android: Application of asynchronous Processing Asynctask (II.)

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.