Android asynchronous processing Two: Updating the UI interface asynchronously with Asynctask

Source: Internet
Author: User

In the Android asynchronous processing one: using Thread+handler to implement non-UI thread update UI interface, we implemented the asynchronous update UI interface using Thread+handler, in this article, We introduce a more concise implementation: using Asynctask to update the UI interface asynchronously.

Overview: Asynctask is an auxiliary class that is introduced after Android SDK 1.5 to facilitate the writing of background threads interacting with the UI thread. Asynctask's internal implementation is a thread pool, where each background task is committed to a thread in the thread pool, and then calls the callback function using Thread+handler (see "Android Asynchronous Processing four: the implementation principle of asynctask" for further understanding of the principle).

Asynctask abstract out the background thread running five states, namely: 1, ready to run, 2, is running in the background, 3, progress Update, 4, complete the background task, 5, cancel the task, for these five stages, Asynctask provides five callback functions:

1. Ready to run: OnPreExecute (), the callback function is called by the UI thread immediately after the task is executed. This step is typically used to create a task that displays a progress bar on the user interface (UI).

2. Running in the background: Doinbackground (Params ...), the callback function is called by the background thread immediately after the execution of the OnPreExecute () method. The time-consuming background computation is usually performed here. The result of the calculation must be returned by the function and passed to OnPostExecute (). You can also use Publishprogress (Progress ...) within this function. To publish one or more progress units (unitsof progress). These values will be in Onprogressupdate (Progress ...). is published to the UI thread.

3. Progress update: Onprogressupdate (Progress ...), the function by the UI thread in Publishprogress (Progress ...) Called when the method call is complete. Typically used to dynamically display a progress bar.

4. Complete background task: OnPostExecute (Result), called when the background calculation is finished. The results of the background calculation are passed as parameters to this function.

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

The Asynctask constructor has three template parameters:

1.Params, the parameter type passed to the background task.

2.Progress, the type of progressive unit (Progress units) during the execution of the background calculation. (that is, the background program has been executed a few percent.) )

3.Result, the type of the result returned by the background execution.

Asynctask does not always need to use all 3 of the above types. It is simple to identify types that are not in use, just use void types.

Example: Same as the example of "Android asynchronous processing one: using Thread+handler to implement a UI interface for non-UI thread Updates", we download the CSDN logo in the background, display it on the UI interface after the download is complete, and simulate the download progress update.

Example Project file download

Asynctaskactivity.java

 PackageCom.zhuozhuo;ImportOrg.apache.http.HttpResponse;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpGet;Importorg.apache.http.impl.client.DefaultHttpClient;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.ImageView;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.Toast; Public classAsynctaskactivityextendsActivity {PrivateImageView Mimageview; PrivateButton Mbutton; PrivateProgressBar Mprogressbar; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.main); Mimageview=(ImageView) Findviewbyid (R.id.imageview); Mbutton=(Button) Findviewbyid (R.id.button); Mprogressbar=(ProgressBar) Findviewbyid (R.id.progressbar); Mbutton.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {getcsdnlogotask task=NewGetcsdnlogotask (); Task.execute ("Http://csdnimg.cn/www/images/csdnindex_logo.gif");    }        }); }        classGetcsdnlogotaskextendsasynctask<string,integer,bitmap> {//Inherit Asynctask@OverrideprotectedBitmap doinbackground (String ... params) {//handles tasks performed in the background, executed in a background threadPublishprogress (0);//the Onprogressupdate (Integer ... progress) method will be calledHttpClient HC =Newdefaulthttpclient (); Publishprogress (30); HttpGet HG=NewHttpGet (Params[0]);//get CSDN's logo            FinalBitmap BM; Try{HttpResponse hr=Hc.execute (Hg); BM=Bitmapfactory.decodestream (Hr.getentity (). getcontent ()); } Catch(Exception e) {return NULL; } publishprogress (100); //Mimageview.setimagebitmap (result); Cannot manipulate UI in background thread            returnBM; }                protected voidOnprogressupdate (Integer ... progress) {//Called after calling publishprogress, the UI thread executes theMprogressbar.setprogress (Progress[0]);//Update progress bar Progress         }         protected voidOnPostExecute (Bitmap result) {//after the background task is executed, it is called after the UI thread executes             if(Result! =NULL) {Toast.maketext (asynctaskactivity. This, "Get pictures successfully", Toast.length_long). Show ();             Mimageview.setimagebitmap (result); }Else{toast.maketext (asynctaskactivity). This, "Get Picture Failed", Toast.length_long). Show (); }         }                  protected voidOnPreExecute () {//in Doinbackground (Params ...) is called before the UI thread executes theMimageview.setimagebitmap (NULL); Mprogressbar.setprogress (0);//progress bar Reset         }                  protected voidOncancelled () {//executing on the UI threadMprogressbar.setprogress (0);//progress bar Reset         }            }    }

Main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:orientation=" vertical "android:layout_width=" fill_parent "    android:layout_ Height= "fill_parent" >    <progressbar android:layout_width= "fill_parent" android:layout_height= "wrap _content "android:id=" @+id/progressbar "style="? Android:attr/progressbarstylehorizontal "></ProgressBar>    <button android:id= "@+id/button" android:text= "Download Picture" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" ></Button>    <imageview android:id= "@+id/imageview" android:layout_height= " Wrap_content "        android:layout_width=" Wrap_content "/></linearlayout>

Manifest.xml

 <?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package  =" Com.zhuozhuo " Android:versi Oncode  = "1"  Android:versionname  =" 1.0 "> <uses-sdk android:minsdkv ersion= "/><uses-permission android:name=" Android.permission.INTERNET "></uses-permission> < Application android:icon= "@drawable/icon" android:label= "@string/app_name" > <activity android:name= ". Asynctaskactivity " Android:label  =" @string/app_name "> &  lt;intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category Android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </ Application></manifest> 

Operation Result:

Process Description:

1. When the button is clicked, create a task and pass in the CSDN's logo address (string type parameter, so the first template parameter of Asynctask is a string type)

2, the UI thread executes OnPreExecute (), the picture of ImageView is emptied, the Progrssbar progress is zeroed.

3, Background thread execution Doinbackground (), can not be in the Doinbackground () operation UI, call publishprogress (0) Update progress, this time will call Onprogressupdate (Integer ... Progress) Update the progress bar (progress is represented by shaping, so the second template parameter for Asynctask is integer). The function returns the result (in the example, the bitmap type is returned, so the first three template parameter of Asynctask is bitmap).

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

Summarize:

Asynctask for us to abstract a background task of five states, corresponding to five callback interfaces, we only need to implement these five interfaces according to different requirements (Doinbackground must be implemented), you can complete some simple background tasks. Using Asynctask to make the code that interacts with the background process and UI process more concise and easier to use, but there are some drawbacks to asynctask, and we'll leave it to you later.

This blog address: http://blog.csdn.net/mylzc/article/details/6772129, reprint please indicate the source

Android asynchronous processing Two: Updating the UI interface asynchronously with Asynctask

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.