Android multi-threading mechanism and the use of handler

Source: Internet
Author: User

Reference Tutorial: Imooc about handler,http://www.imooc.com/learn/267

Reference: Google offers Android documentation communicating with the UI Thread

The role of handler:

Thread updates outside of the UI main thread are not allowed in Android development, so it is one of the methods that Android provides to establish a handler object to receive data from other lines Cheng (carried by message) under the main thread. The other is the more lightweight Asynctask class that we know, which does not unfold here, the difference between the detailed handler+thread and Asynctask see the merits and demerits of Asynctask and handler. The time-consuming operation is executed with the other thread, which is then routed to the handler object with a message, which is then handed to the UI master thread by handler.

Handler the fundamental problem to solve is that the Android thread concurrency, if there is no corresponding mechanism to constrain the collaboration of each thread concurrency, it is easy to lead to development and running chaos. The way Android handles multithreading is not the traditional locking mechanism (performance factor bar), but the MessageQueue, that is, the message queue, developers can directly control the message queue display order and way, so that there is no data synchronization confusion problem.

Write a small demo to help understand the use of handler. Two operations for downloading pictures and displaying pictures with new thread processing.

Add a new thread to the OnCreate method in Mainactivity:

        // Initialize View        ImageView = (ImageView) Findviewbyid (R.id.imageview);         // add thread for downloading pictures and updating UI        New Thread (new myrunnable ()). Start ();     

  

Myrunnable class

 Public classMyrunnableImplementsRunnable {Activity mactivity; PrivateMessage msg; PrivateBitmap Imagebitmap; Private Static FinalString urldata = "http://sfault-avatar.b0.upaiyun.com/166/281/166281916-1140000000145114_huge128"; @Override Public voidrun () {msg=NewMessage (); Imagebitmap=gethttpimage (Urldata); Msg.obj=Imagebitmap; //Pass Imagebitmap to handler in mainactivity with MSGMainActivity.handler.sendMessage (msg); }    //bitmap to read images with URL urldata    PrivateBitmap gethttpimage (String urldata) {Bitmap Bitmap=NULL; Try{URL URL=NewURL (Urldata); HttpURLConnection HttpURLConnection=(HttpURLConnection) url.openconnection (); Httpurlconnection.setconnecttimeout (5*1000); Httpurlconnection.setdoinput (true);            Httpurlconnection.connect (); InputStream InputStream=Httpurlconnection.getinputstream (); Bitmap=Bitmapfactory.decodestream (InputStream);            Inputstream.close ();        Httpurlconnection.disconnect (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        returnbitmap; }}

Go back to Mainactivity, initialize handler, and rewrite its Handlemessage method, the code is as follows:

 public  static  Handler Handler = Span style= "color: #0000ff;" >new   Handler (Looper.getmainlooper ()) {@Override  public  void   Handlemessage (Message msg)            { super  .handlemessage (msg);  //  get pictures from msg Bitmap  Bitmap b            Itmap = (Bitmap) msg.obj;              //  update UI  

Summing up, it is really tedious to execute a single thread in a Handler+thread way, and it will be more concise and efficient with asynctask. But in the more complex multi-threaded application scenario, using handler to establish MessageQueue mechanism to manage the thread operation more orderly.

Android multi-threading mechanism and the use of 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.