Android uses Thread + Handler to implement non-UI Thread update Interface

Source: Internet
Author: User

Every Android application runs in a dalvik virtual machine process. When a process starts, a main thread (MainThread) is started. The main thread is responsible for processing ui-related events, therefore, the main thread is often called the UI thread. Because Android uses a single-threaded UI model, you can only operate the UI elements in the main thread. If you operate the UI directly in a non-UI thread, the following error occurs: CalledFromWrongThreadException: only the original thread that created a view hierarchy can touch its views. Android provides a message loop mechanism. We can use this mechanism to implement inter-thread communication. Then, we can send messages to the UI thread in a non-UI thread, and finally let the Ui thread perform ui operations. For operations and IO operations that require a large amount of computing, we need to open a new thread to handle these heavy tasks to avoid blocking the ui thread. ThreadHandlerActivity. activity [java] public class ThreadHandlerActivity extends Activity {/** Called when the activity is first created. */private static final int MSG_SUCCESS = 0; // ID of the image retrieved: private static final int MSG_FAILURE = 1; // ID of the failed image retrieval: private ImageView mImageView; private Button mButton; private Thread mThread; private Handler mHandler = new Handler () {public void handleMessage (Messa Ge msg) {// This method runs switch (msg. what) {case MSG_SUCCESS: mImageView. setImageBitmap (Bitmap) msg. obj); // imageview displays the logo Toast obtained from the network. makeText (getApplication (), "successful! ", Toast. LENGTH_LONG). show (); break; case MSG_FAILURE: Toast. makeText (getApplication ()," failed! ", Toast. LENGTH_LONG ). show (); break ;}}; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. threadhandler); mImageView = (ImageView) findViewById (R. id. threadhandler_imageView); // display the image's ImageView mButton = (Button) findViewById (R. id. threadhandler_download_btn); mButton. setOnClickListener (new OnClickListener () {@ Override public voi D onClick (View v) {if (mThread = null) {mThread = new Thread (runnable); mThread. start (); // thread start} else {Toast. makeText (ThreadHandlerActivity. this, "the thread has been started! ", Toast. LENGTH_LONG ). show () ;}}) ;}runnable Runnable = new runnable () {@ Override public void run () {// run () run HttpClient hc = new DefaultHttpClient (); HttpGet hg = new HttpGet ("http://pic7.nipic.com/20100517/4945412_113951650422_2.jpg"); // get the compass picture final Bitmap bm; try {HttpResponse hr = hc.exe cute (hg); bm = BitmapFactory. decodeStream (hr. getEntity (). getContent ();} catch (Exception e ){ MHandler. obtainMessage (MSG_FAILURE ). sendToTarget (); // return;} mHandler failed to get the image. obtainMessage (MSG_SUCCESS, bm ). sendToTarget (); // The image is obtained successfully, and MSG_SUCCESS ID and bitmap object are sent to the ui thread };} threadhandler. xml [html] <? 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 = "vertical"> <Button android: id = "@ + id/threadhandler_download_btn" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "ThreadHandler download"> </Button> <ImageView android: id = "@ + id/threadhandler_imageView" Ndroid: layout_width = "wrap_content" android: layout_height = "wrap_content"/> </LinearLayout> running result: A non-UI thread sends messages to the UI thread in two steps. 1. The Message queue that sends messages to the UI thread constructs a Message Object by using the Handler Message obtainMessage (int what, object Object, this object stores whether the image's identifier "what" and "bitmap" are successfully obtained, and then uses the message. the sendToTarget () method places the message in the message queue. 2. process the messages sent to the UI thread. In the ui thread, We overwrite the public void handleMessage (Message msg) of handler. This method processes the messages distributed to the ui thread and judges msg. the value of what indicates whether mThread has successfully obtained the image. If the image has been obtained successfully, you can use msg. obj gets this object. Finally, we use mImageView. setImageBitmap (Bitmap) msg. obj); To set the bitmap object of ImageView and complete UI updates.

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.