[Androidthread&handler] thread3-Case 2

Source: Internet
Author: User

using Thread+handler to implement a non-UI thread update UI interface

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

Uiupdateactivity.java

 public class Uiupdateactivity extends activity{private static final int msg_success = 0;//Get picture successful identity private static final int msg_failure = 1;//Gets the image of the failed identity protected static final String TAG = "Raylee"; Protected static final String TITLE = "uiupdate through Workerthread"; Private ImageView Mimageview; Private Button Mbutton; Private Thread Mthread; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.LAYOUT.EXAMPLE2); mimageview= (ImageView) Findviewbyid (R.id.imageview);//Show picture ImageView Mbutton = (Button) Findviewbyid (R.id.button);  Mbutton.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {if (Mthread = = null) {Mthread = New Thread (runnable); Mthread.start ();//thread Start} else {Toast.maketext (getapplication (), Getapplication (). getString (r.string.thread_started ), Toast.length_long). Show (); } } }); } @SuppressLint ("Handlerleak") private Handler Mhandler = new Handler () {public void Handlemessage (MessAge msg) {//This method runs switch (msg.what) {case MSG_SUCCESS:mImageView.setImageBitmap ((Bitmap) msg.obj) on the UI thread;// ImageView Displays the logo log.i (TAG, "Handler Success--->" + msg.obj) obtained from the network; Toast.maketext (Getapplication (), Getapplication (). getString (r.string.get_pic_success), Toast.length_long). Show () ; Break Case MSG_FAILURE:LOG.I (TAG, "Handler failure!"); Toast.maketext (Getapplication (), Getapplication (). getString (R.string.get_pic_failure), Toast.length_long). Show () ; Break } } };  Runnable Runnable = new Runnable () {@Override public void run () {//run () runs in a new thread HttpClient HC = new Defaulthttpclient (); HttpGet hg = new HttpGet ("Http://csdnimg.cn/www/images/csdnindex_logo.gif");//Get CSDN's logo log.i (TAG + TITLE, "Hg not nul L---> "+ hg); Bitmap BM = NULL; try {HttpResponse hr = Hc.execute (hg); bm = Bitmapfactory.decodestream (Hr.getentity (). getcontent ()); LOG.I (TAG + TITLE, "BM NOT NULL--->" + BM);} catch (Exception e) {mhandler.obtainmessage (msg_failure). Sendtotarget ();//Get Picture failed LOG.I (TAG + TITLE, "failure!"); Return } log.i (TAG + TITLE, "Success--->" + BM); Mhandler.obtainmessage (MSG_SUCCESS,BM). Sendtotarget ();//Get picture successful, send msg_success identity and bitmap object to UI thread}}; }

Example2.xml

 <?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="match_parent" android:orientation="vertical" > <Button android:id="@+id/button" android:text="@string/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="30dp" /> <ImageView android:id="@+id/imageView" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="100dp" android:layout_width="wrap_content" android:contentDescription="@android:string/untitled" /> </LinearLayout>

Androidmanifest.xml

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="home.lee.example2UIupdate" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".UIupdateActivity

Operation result :

To not block the UI thread, we used Mthread to get the CSDN logo from the web

and stores the pixel information of this logo with the bitmap object.

At this point, if you call in the run () method of this thread

 mImageView.setImageBitmap(bm)

will appear: Calledfromwrongthreadexception:only the original thread that created a view hierarchy can touch it views. The reason is that the run () method is executed in the newly opened thread, and we mentioned above that we cannot manipulate UI elements directly in a non-UI thread.

A non-UI thread sends a message to the UI thread in two steps

One, Message Queuing for sending messages to the UI thread

By using the handler

Constructs a message object that stores the successful acquisition of the image's identity what and bitmap object, and then puts the message into the queue of messages through the Message.sendtotarget () method.

II. handling messages sent to the UI thread

In the UI thread, we covered the handler

 public void handleMessage (Message msg)

This method is to handle the message distributed to the UI thread, to determine the value of msg.what can know whether Mthread successfully obtained the picture, if the picture is successfully obtained, then you can get to this object through Msg.obj. Finally, we pass

Set the ImageView Bitmap object to complete the UI update. Add:

In fact, we can also call the view's post method to update the UI

This method sends the Runnable object to the message queue, which executes the Runnable object when the UI thread receives the message. From the example we can see that handler both send messages and processing messages, will mistakenly think that handler implementation of the message loop and message distribution, in fact, Android in order to make our code look more concise, Interacting with the UI thread only requires the use of the handler object created on the UI thread.

http://blog.csdn.net/mylzc/article/details/6736988

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.