Android asynchronous processing-thread+handle/asyntask implement asynchronous update UI

Source: Internet
Author: User

Each Android application runs in a Dalvik virtual machine process, where the process starts with a main thread (Mainthread) that handles and UI-related events, so the main thread is often called the UI thread. Because Android uses the UI single-threaded model, the UI elements can only be manipulated in the main thread. If the UI is directly manipulated on a non-UI thread, an error is made.

First, Thread+handle

Android provides us with a mechanism for message loops that we can use to implement communication between threads. Then we can send a message to the UI thread in a non-UI thread, and eventually let the UI thread do the UI.

For operations with large operations and IO operations, we need new threads to handle these heavy work, so as not to block the UI thread.

 Public classThreadhandleractivityextendsActivity {Private Static Final intmsg_success = 0;//get a picture of a successful identity    Private Static Final intMsg_failure = 1;//gets the identity of the picture failure    PrivateImageView Mimageview; PrivateButton Mbutton; PrivateThread Mthread; PrivateHandler Mhandler =NewHandler () { Public voidHandlemessage (Message msg) {//This method runs on the UI thread            Switch(msg.what) { CaseMSG_SUCCESS:mImageView.setImageBitmap ((Bitmap) msg.obj);//ImageView Display the logo obtained from the networkToast.maketext (Getapplication (), Getapplication (). getString (R.string.get_pic_su                ccess), Toast.length_long). Show ();  Break;  CaseMSG_FAILURE:Toast.makeText (Getapplication (), Getapplication (). getString (R.stri                ng.get_pic_failure), Toast.length_long). Show ();  Break;    }        }    }; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); Mimageview= (ImageView) Findviewbyid (R.id.imageview);//Display the ImageView of a pictureMbutton =(Button) Findviewbyid (R.id.button); Mbutton.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {if(Mthread = =NULL) {Mthread=NewThread (runnable); Mthread.start ();//Thread Start}Else{Toast.maketext (Getapplication (), Getappli                Cation (). GetString (r.string.thread_started), Toast.length_long). Show ();    }            }        }); } Runnable Runnable=NewRunnable () { Public voidRun () {//run () runs in a new threadHttpClient HttpClient =Newdefaulthttpclient (); HttpGet HttpGet=NewHttpGet ("Https://www.baidu.com/img/bd_logo1.png");//Get Pictures            FinalBitmap Bitmap; Try{HttpResponse HttpResponse=Httpclient.execute (HttpGet); Bitmap=Bitmapfactory.decodestream (Httpresponse.getentity (). getcontent ()); } Catch(Exception e) {mhandler.obtainmessage (msg_failure). Sendtotarget ();//failed to get picture                return; }            //get picture successful, send msg_success identity and bitmap object to UI threadmhandler.obtainmessage (msg_success, bitmap). Sendtotarget (); //Mimageview.setimagebitmap (BM);//Error! UI elements cannot be manipulated on non-UI threads//Mimageview.post (New Runnable () {//another more concise way to send messages to the UI thread.             //@Override//Public void Run () {//the Run () method executes on the UI thread//Mimageview.setimagebitmap (BM); // }            // });        }    };}

Second, Asynctask

The Asynctask constructor has three template parameters:

1.Params, the parameter type passed to the background task.
2.Progress, the background calculation of the execution process, the type of progressive unit that the daemon has executed a few percent, the general integer.
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 ...) The callback function is called by the background thread immediately after the execution of the OnPreExecute () method is completed. Typically, time-consuming background calculations are performed. The result of the calculation must be returned by the function and passed to OnPostExecute () to update the UI;

Use Publishprogress (Progress ...) within the function. To publish one or more progress units (unitsof progress). These values will be in Onprogressupdate (Progress ...). is posted to the UI thread;

Oncancelled () is called when the Cancel () method of Asynctask is called.

It is important to note that

1. Asynctask the asynchronous task must be created and run on the UI thread, that is, new Asysnctask (). Execute () to be in the main thread, and execute only once;

2. When overloading a class method, be aware that you cannot update any UI in Doinbackground

Get network picture results displayed in UI Asynctaskactivity.java

 Public classAsynctaskactivityextendsActivity {PrivateImageView Mimageview; PrivateButton Mbutton; PrivateProgressBar Mprogressbar; @Override Public voidonCreate (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 voidOnClick (View v) {getimagetask task=NewGetimagetask (); Task.execute ("Https://www.baidu.com/img/bd_logo1.png");    }        }); }    classGetimagetaskextendsasynctask<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 HttpClient =Newdefaulthttpclient (); Publishprogress (30); HttpGet HttpGet=NewHttpGet (params[0]); FinalBitmap Bitmap; Try{HttpResponse HttpResponse=Httpclient.execute (HttpGet); Bitmap=Bitmapfactory.decodestream (Httpresponse.getentity (). getcontent ()); } Catch(Exception e) {return NULL; } publishprogress (100); //Mimageview.setimagebitmap (result); Cannot manipulate UI in background thread            returnbitmap; }        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         }      }}

Android asynchronous processing-thread+handle/asyntask implement asynchronous update UI

Related Article

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.