Learn to implement non-UI thread update UI components via Thread+handler

Source: Internet
Author: User
Tags object object

"Android threading Mechanism"

For performance reasons,Android UI operations are not thread-safe, which means that if there are multiple threads concurrently manipulating the UI component, it can cause thread safety issues. To solve this problem , Android has a simple rule : only allow the UI thread to modify the UI components in the Activity

When a program is started for the first time, Android initiates a main thread , which is primarily responsible for handling UI -related events, such as user key events, The user touches the screen of events and screen drawing events, and distributes the relevant events to the corresponding components for processing. So the main thread is often called the UI thread

"Introduction toHandler class"

The main functions of the Handler class are two:

--send messages on the newly started thread

--Get and process messages in the main thread

Principle

In order for a thread to handle the messages sent by the newly-started thread "in a timely manner", it is clear that only the callback method can be implemented---the developer only needs to rewrite the method of processing the message in the Handler class, and when the newly started thread sends the message, the message is sent to the associated MessageQueue, and Handler will constantly fetch and process messages from MessageQueue -This will cause the method of processing messages in the Handler class to be callback

"Methods for sending and processing messages in theHandler class"

. void Handlemessage (Message msg): The method that processes the message. This method is typically used to override
. Final Boolean hasmessages (int what): Checks whether Message Queuing contains a message with a value specified by what property
. Final Boolean hasmessages (int what,object Object): Checks whether the message queue contains the What property is the specified value
Message and the object property is a message for the specified objects
. Multiple overloaded Message obtainmessage (): Getting messages
. Sendemptymessage (int): Send an empty message
. Final Boolean sendemptymessagedelayed (int what,long delaymills): Specifies the number of seconds after which an empty message is sent
. Final Boolean sendMessage (Message msg): Send Message now
. Final Boolean sendmessagedelayed (Message Msg,long delaymills): Specifies the number of seconds after which a message is sent

--------------------------------------------------------------------------------------------------------------- --

Here's an example of how the Android threading mechanism is implemented

Eg: the CSDN logo can be loaded asynchronously by clicking the button

Code

Package Cn.edu.bzu.asynchronous_processomg;import Org.apache.http.httpresponse;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.app.activity;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.imageview;import  android.widget.toast;/** * Learn to implement non-UI thread updates through Thread+handler UI components * Learn the use of asynchronous loading * @author Monster * date:2015-05-28 * Introduce:  Android only allows UI threads to modify UI components in Activity * Aim: Click the button to read the logo of the CSDN website */public class Mainactivity extends Activity {private Button   Mbutton;       Private ImageView Mimageview; Private final static int msg_success = 0; Gets the image of the successful identity private final static int msg_failure = 1;      Gets the image of the failed identity private Thread mthread; Private HandLer mhandler=new Handler () {public void Handlemessage (Message msg) {//This method runs switch in the UI thread (msg.what) { Case MSG_SUCCESS:mImageView.setImageBitmap ((Bitmap) msg.obj); Get obj, and force the type to convert to bitmap type--->>>obj contains picture information Toast.maketext (Getapplication (), "Success", Toast.len                   Gth_long). Show ();                   Break                   Case MSG_FAILURE:Toast.makeText (Getapplication (), "error", Toast.length_long). Show ();           Break    }       }          };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        When instantiating a control, the write context mbutton= (Button) Findviewbyid (R.id.mbutton) is not required if it is the current context;                mimageview= (ImageView) Findviewbyid (R.id.mimageview); Mbutton.setonclicklistener (New Onclicklistener () {@Override public void OnClick (ViewV) {if (mthread==null) {mthread=new Thread (runnable);                Mthread.start ();    }            }        }); } Runnable runnable=new Runnable () {@Override public void run ()                    {//run () runs HttpClient hc=new defaulthttpclient () in a new thread; HttpGet hg=new httpget ("Http://csdnimg.cn/www/images/csdnindex_logo.gif");                    CSDN's logo final Bitmap BM; try {HttpResponse Hr=hc.execute (Hg);//respond to requests made bm=bitmapfactory.decodestre                    AM (Hr.getentity (). getcontent ());                        } catch (Exception e) {mhandler.obtainmessage (msg_failure). Sendtotarget ();//failed to get picture                    return;    } mhandler.obtainmessage (MSG_SUCCESS,BM). Sendtotarget ();//Get Picture Success}}; @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu);    return true; }    }

Summary

Handle in the code for a main thread, runnable as a new thread, the new thread through the request response method to get the site's logo, and then through the handle message passing mechanism to pass the image read from the Web site, this picture is a bitmap, is by converting the file into bitmap and then delivering the message.

"Link Sharing"

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

"Source Code"

https://github.com/monsterLin/Asy_Processing

Learn to implement non-UI thread update UI components via Thread+handler

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.