Android Async mechanism One: use Thread+handler to implement non-UI thread update UI interface

Source: Internet
Author: User

Overview: 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:

Calledfromwrongthreadexception only the original thread that created a view hierarchy can touch it views

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.

Example: Below we take the example of obtaining the CSDN logo, demonstrating how to implement the UI thread update interface by using Thread+handler to send message notifications on non-UI threads.;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.impl.client.DefaultHttpClient;;;;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.ImageView;ImportAndroid.widget.Toast; Public  class threadhandleractivity extends Activity {    Private Static Final intMsg_success =0;//Get pictures of successful logos    Private Static Final intMsg_failure =1;//Get a picture of failed identities    PrivateImageView Mimageview;PrivateButton Mbutton;PrivateThread Mthread;PrivateHandler Mhandler =NewHandler () { Public void Handlemessage(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_success), Toast.length_long). Show (); Break; CaseMSG_FAILURE:Toast.makeText (Getapplication (), Getapplication (). getString ( t_pic_failure), Toast.length_long). Show (); Break; }        }    };@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.main); Mimageview = (ImageView) Findviewbyid (;//Show picture of ImageViewMbutton = (Button) Findviewbyid (; Mbutton.setonclicklistener (NewOnclicklistener () { Public void OnClick(View v) {if(Mthread = =NULL) {Mthread =NewThread (runnable); Mthread.start ();//thread start}Else{Toast.maketext (Getapplication (), Getapplicatio                N (). getString (r.string.thread_started), Toast.length_long). Show ();    }            }        }); } Runnable Runnable =NewRunnable () { Public void Run() {//Run () runs in a new threadHttpClient HttpClient =NewDefaulthttpclient (); HttpGet HttpGet =NewHttpGet ("Http://");//Get CSDN's logo            FinalBitmap Bitmap;Try{HttpResponse HttpResponse = Httpclient.execute (HttpGet);            Bitmap = Bitmapfactory.decodestream (Httpresponse.getentity (). getcontent ()); }Catch(Exception e) {mhandler.obtainmessage (msg_failure). Sendtotarget ();//Get Picture failed                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            // (new Runnable () {///Another more concise way to send messages to the UI thread.             //            //@Override            the//public void Run () {//run () method executes on the UI thread            //Mimageview.setimagebitmap (BM);            // }            // });}    };}

Main.xml file:

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout  xmlns: Android  = ""  android:layout_width  =" fill_parent " android:layout_height  =" fill_parent " android:orientation  =;     <buttonandroid:id="@+id/button"android:layout_width="Wrap_ Content "android:layout_height=" Wrap_content "android:text=" Get Picture " >                                     </Button>    <ImageViewandroid:id="@+id/imageview"android:layout_width="Wrap _content "android:layout_height=" wrap_content " />                        </linearlayout>

Strings.xml file:

    <stringname="thread_started">Thread started</string>    <stringname="get_pic_success">Get pic success</string>    <stringname="get_pic_failure">Get pic failure</string>

To include access to network permissions in the manifest file:

<!-- 不要忘记设置网络访问权限 -->    <uses-permission android:name="android.permission.INTERNET" />

Then set "" as the startup page

The results are as follows:

In the case we use handler and thread to notify handler in the structure of the thread execution, and to set the picture in handler.

Android Async mechanism One: use Thread+handler to implement non-UI thread update UI interface

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: 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.