Android Thread Communication

Source: Internet
Author: User

Summary

Andriod provides Handler and Looper to meet the communication between threads. For example, a sub-thread downloads a picture from the network and sends a message to the main thread when it is downloaded, and this message is passed by binding to the handler of the main thread.

Body

Graphic:

code example:

/** * @authorAllin.dev *http://allin.cnblogs.com */ Public classMainthreadextendsactivity{Private Static FinalString TAG = "Mainthread"; PrivateHandler Mmainhandler, Mchildhandler; PrivateTextView Info; PrivateButton msgbtn; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); Info=(TextView) Findviewbyid (r.id.info); MSGBTN=(Button) Findviewbyid (R.ID.MSGBTN); Mmainhandler=NewHandler () {@Override Public voidhandlemessage (Message msg) {log.i (TAG,"Got an incoming message from the child thread-" +(String) msg.obj); //receive messages for child threadsInfo.settext ((String) msg.obj);        }          }; NewChildthread (). Start (); Msgbtn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {if(Mchildhandler! =NULL )        {                    //send a message to a child threadMessage childmsg =Mchildhandler.obtainmessage (); Childmsg.obj=mmainhandler.getlooper (). GetThread (). GetName ()+ "says Hello";                    Mchildhandler.sendmessage (CHILDMSG); LOG.I (TAG,"Send a message to the child thread-" +(String) childmsg.obj);      }      }    } ); }     Public voidOnDestroy () {Super. OnDestroy (); LOG.I (TAG,"Stop Looping the child thread ' s message queue");  Mchildhandler.getlooper (). Quit (); }    classChildthreadextendsThread {Private Static FinalString Child_tag = "Childthread";  Public voidrun () { This. SetName ("Childthread" ); //Initialize the message loop queue before handler is createdLooper.prepare (); Mchildhandler=NewHandler () {@Override Public voidhandlemessage (Message msg) {log.i (Child_tag,"Got an incoming message from the main thread-" +(String) msg.obj); Try          {                        //you can do some time-consuming work in a child threadSleep (100 ); Message Tomain=Mmainhandler.obtainmessage (); Tomain.obj= "This is" + This. Getlooper (). GetThread (). GetName ()+ ". Did you send me \ "" + (String) msg.obj + "\"? ";                        Mmainhandler.sendmessage (Tomain); LOG.I (Child_tag,"Send a message to the main thread-" +(String) tomain.obj); }          Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace ();            }        }              }; LOG.I (Child_tag,"Child handler was bound to-" +mchildhandler.getlooper (). GetThread (). GetName ()); //Start a child thread message loop queueLooper.loop (); }  }}

Ps:

Using the Handlerthread Looper object to create the handler, if you use the default construction method, it is likely to block the UI thread, referring to http://www.cnblogs.com/ccdc/p/3837798.html. Improvement scheme A new thread will be used to replace the handler of the main course with the looper of the main thread looper, as below,

Reference

Shangdawei.android inter-thread communication [2014-07-11] (2013-03-26). http://www.cnblogs.com/shangdawei/archive/2013/03/26/2983217.html

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.