Android asynchronous processing two: Asyntask introduction and Using Asynctask Asynchronous update UI interface

Source: Internet
Author: User

The method steps for updating the UI interface using Thread+handler to implement a non-UI thread are described in the previous article (http://blog.csdn.net/xlgen157387/article/details/45269389). Let's do a little bit about how to asynctask asynchronous tasks to update the UI interface.

(1) Introduction of Asynctask

Through the source code structure of the Asynctask can be seen, the main method for overloading is Doinbackground (), OnPreExecute (), OnPostExecute (), Onprogressupdate (), Oncancelled (), publishprogress () and so on are the "yellow diamond" icons, the following details the functions of these methods:

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.

Doinbackground (Params ...)

SOURCE Comment:

/** * Override This method toPerform a computation onA background thread. The * specified parameters is theParameters passed to{@link#execute}* by  theCaller ofThis task. * * This method can call {@link#publishProgress} to publish updates* on  theUI thread. * * @param params the parameters of  theTask. *     * @returnAresult, defined by  theSubclass ofThis task. * * @see#onPreExecute ()* @see#onPostExecute* @see#publishProgress*/protected abstract Result doinbackground (params ... params);

Running in the background: Doinbackground (Params ...), which is called by the background thread immediately after the OnPreExecute () method execution finishes. 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.

OnPreExecute ()
  /**     * Runs on the UI thread before {@link #doInBackground}.     *     * @see #onPostExecute     * @see #doInBackground     */    protectedvoidonPreExecute() {    }

Ready to run: OnPreExecute (), which 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).

OnPostExecute ()
/** * <p>runs on  theUI thread After{@link#doInBackground}. the* Specifiedresult  is  theValue returned by{@link#doInBackground}.</p>* * <p>this method won ' t be invokedif  theTask was cancelled.</p> * * @paramresultTheresult  of  theOperation computed by{@link#doInBackground}.* * @see#onPreExecute* @see#doInBackground* @see#onCancelled (Object)*/@SuppressWarnings ({"Unuseddeclaration"}) protected void OnPostExecute (Resultresult) {    }

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.

Onprogressupdate ()
/**     * Runs on the UI thread after {@link #publishProgress} is invoked.     * The specified values are the values passed to {@link #publishProgress}.     *     * @param values The values indicating progress.     *     * @see #publishProgress     * @see #doInBackground     */    @SuppressWarnings({"UnusedDeclaration"})    protectedvoidonProgressUpdate(Progress... values) {    }

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.

Oncancelled ()

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

Publishprogress ()
/** * This method can is invoked from {@link #doInBackground} to * Publish updates on the UI thread while the Background computation is * still running.     Each call to this method would trigger the execution of * {@link #onProgressUpdate} on the UI thread.     * {@link #onProgressUpdate} 'll note is called if the task has been * canceled.     * * @param values The progress values to update the UI with. * * @see #onProgressUpdate * @see #doInBackground * *    protected Final void publishprogress(Progress ... values) {if(!iscancelled ()) {Shandler.obtainmessage (message_post_progress,NewAsynctaskresult<progress> ( This, values). Sendtotarget (); }    }

Used primarily to show progress.

(2) Updating the UI interface asynchronously with Asynctask

Asynctaskactivity. Java as the startup page file

 Public  class asynctaskactivity extends Activity {    PrivateImageView Mimageview;PrivateButton Mbutton;PrivateProgressBar Mprogressbar;@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.asyntask_main);        mimageview= (ImageView) Findviewbyid (R.id.imageview);        Mbutton = (Button) Findviewbyid (R.id.button);        Mprogressbar = (ProgressBar) Findviewbyid (R.id.progressbar); Mbutton.setonclicklistener (NewOnclicklistener () { Public void OnClick(View v) {Getimagetask task =NewGetimagetask (); Task.execute ("Http://g.hiphotos.baidu.com/image/pic/item/b3119313b07eca80d340a3e0932397dda1448374.jpg");    }        }); } class Getimagetask extends Asynctask<string,integer,bitmap> {//Inherit Asynctask        @Override        protectedBitmapDoinbackground(String ... params) {//Handle tasks performed in the background, execute in background threadPublishprogress (0);//Will call the Onprogressupdate (Integer ... progress) methodHttpClient HttpClient =NewDefaulthttpclient (); Publishprogress ( -); HttpGet HttpGet =NewHttpGet (params[0]);//Get CSDN's logo            FinalBitmap Bitmap;Try{HttpResponse HttpResponse = Httpclient.execute (HttpGet);            Bitmap = Bitmapfactory.decodestream (Httpresponse.getentity (). getcontent ()); }Catch(Exception e) {return NULL; } publishprogress ( -);//mimageview.setimagebitmap (result); Cannot manipulate UI in background thread            returnBitmap }protected void onprogressupdate(Integer ... progress) {//called after calling Publishprogress, executed on the UI threadMprogressbar.setprogress (progress[0]);//Update progress bar Progress}protected void OnPostExecute(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 void OnPreExecute() {//In Doinbackground (Params ...) is called before the UI thread executes theMimageview.setimagebitmap (NULL); Mprogressbar.setprogress (0);//progress bar Reset}protected void oncancelled() {//In UI thread executionMprogressbar.setprogress (0);//progress bar Reset}      }}

Layout file:

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:layout_width  =" fill_parent " android:layout_height  =" fill_parent " android:orientation  =;     <ProgressBarandroid:id="@+id/progressbar"style="? android:attr/ Progressbarstylehorizontal "android:layout_width=" Fill_parent "android:layout_height ="Wrap_content" >                                    </ProgressBar>    <buttonandroid:id="@+id/button"android:layout_width="Wrap_ Content "android:layout_height=" Wrap_content "android:text=" Download Picture " >                                     </Button>    <ImageViewandroid:id="@+id/imageview"android:layout_width="Wrap _content "android:layout_height=" wrap_content " />                        </linearlayout>

Also need to open access to the network and set the boot interface

In addition, when we use asyntask, it is important to note that

Android asynchronous processing two: Asyntask introduction and Using Asynctask Asynchronous update UI interface

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.