Android UI operations are not thread-safe (for improved performance, avoiding delays introduced by mechanisms such as multi-threaded synchronization), which can cause thread-safety problems if multiple threads operate on UI elements at the same time. As a result, there are strict rules in Android: Only the UI main thread can set and manipulate the UI.
In real programming, to avoid theapplication not respondingexception caused by the UI interface being unresponsive for a long time, the time-consuming operations, such as network access, complex operations, and so on, are usually performed in a child thread. This requires that the child thread return the result to the main thread and display it through the UI after it has finished running. In Android, the communication between threads is implemented through Handler+loop+messagequeue.
Let's look at two examples:
Example 1: Simulates downloading data over the network and returning the UI display.
The operating procedure is: 1. The UI thread gets the user request. 2. Start the sub-thread to complete the network data download (the network download process is simulated by forcing the child thread to hibernate for several seconds). 3. The child thread returns the downloaded data to the UI thread and displays it.
The main code is as follows:
Public class mainactivity extends actionbaractivity {private button mbutton ;p rivate textview mtextview;private handler mhandler;private thread mnetaccessthread;private progressdialog mprogressdialog;private int mdownloadcount = 0; @Overrideprotected void oncreate (bundle savedinstancestate) {super.oncreate ( savedinstancestate) Setcontentview (r.layout.fragment_main);mbutton = (Button) findViewById ( r.id.btreqnet);mtextview = (TextView) findviewbyid (r.id.tvdownload);// Set the button's Click event Listener Mbutton.setonclicklistener (New onclicklistener () {@Overridepublic void onclick (view v) {showprogressdialog ("", "Downloading ...");//Start a child thread for network access impersonation mnetaccessthread = new Childtread (); Mnetaccessthread.start ();}); /Inherit the Handler class and overwrite its Handlemessage method Mhandler = new handler () {//Overwrite Handler class Handlemessage method// Receives the data passed by the child thread and displays it in the UI @overridepublIc void handlemessage (message msg) {switch (msg.what) {case 1: Mtextview.settext (String) msg.obj);d ismissprogressdialog (); break;//can add other conditions, such as network transport error//case...default: Break;}}};} class childtread extends thread {@Overridepublic void run () {//sleeps for 6 seconds, Analog Network access delay TRY {THREAD.SLEEP (6000);} catch (interruptedexception e) {e.printstacktrace ();} Returns the result via message to the main thread message msg = new message ();msg.what = 1;mdownloadcount ++; Msg.obj = new string ("+mdownloadcount+" data downloaded from the Internet); Mhandler.sendmessage (msg);}};/ ** * Open progressdialog. * * @param title dialog box title . * @param content dialog box Body . */protected void&nbSp;showprogressdialog (string title,string content) {mProgressDialog = new ProgressDialog (this); if (title != null) mprogressdialog.settitle (title); if (content != null) Mprogressdialog.setmessage (content); Mprogressdialog.show ();} /** * Close progressdialog. * */protected void Dismissprogressdialog () {if (mprogressdialog != null) {Mprogressdialog.dismiss ();}}}
Program Run Effect:
Click the Download button, the UI thread sends a message to the child thread via Handler.sendmessage (), and the child thread receives the message and starts the data download (simulated by a sleep thread).
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/4C/36/wKioL1Q45jnRyNfNAAB1lcKvu-o305.jpg "title=" 360 Mobile Assistant 1011_15_54_01.png "style=" Float:none; "alt=" wkiol1q45jnrynfnaab1lckvu-o305.jpg "/>
When the download is complete, the child thread will download the data back to the main thread and display.
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/4C/37/wKioL1Q4563zuwMZAACM4fmNrKU067.jpg "title=" 360 Mobile Assistant 1011_15_56_02.png "alt=" Wkiol1q4563zuwmzaacm4fmnrku067.jpg "/>
Example 2: An impersonation sub-thread sends a message to the main thread.
The operating procedure is: 1. The UI thread obtains the message content entered by the user. 2. Send the message to the child thread via handler. 3. The child thread obtains the message and prints the content through the toast.
The main code is as follows:
public class mainactivity extends actionbaractivity {private edittext medittext;private button mbutton;private handler mhandler;private thread Mchildtread, @Overrideprotected void oncreate (bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.fragment_main);medittext = (EditText) findViewById ( R.id.etedittext);mbutton = (Button) findviewbyid (R.id.btbutton);// Set the button's Click event Listener Mbutton.setonclicklistener (New onclicklistener () {@Overridepublic void onclick (VIEW V) {message msg = new message (); msg.what = 1;msg.obj = medittext.gettext ();//Send message to child thread Mhandler.sendmessage (msg); Medittext.settext ("");}}); /start child thread for MSG receive Mchildtread = new childtread (); Mchildtread.start ();} The/*** child thread is an inner class that can directly access the Mhandler variable of its outer class **/class childtread extends thread { @Override public void run () { //The following three steps are the fixed mode of handler looper mechanism work looper.prepare ();mhandler = new Handler () { public void handlemessage (message msg) { // process incoming messages hereswitch ( Msg.what) {case 1: //Child threads do not have permission to manipulate the UI, only the messages received by Toast.maketext will be displayed string st = msg.obj.tostring (); if (st == null | | st.equals ("")) st = "received message content is empty"; else st = "received a message from the main thread:" + st; toast.maketext (mainactivity.this, st, 6000). Show (); break;// You can add other conditions, such as transmission errors//case...deFault:break;} }}; Looper.loop (); }};} Program Run Effect:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/4C/37/wKioL1Q46pnjjJMDAAB3ZtMgIgY620.jpg "title=" 360 Mobile Assistant 1011_15_54_01.png "alt=" wkiol1q46pnjjjmdaab3ztmgigy620.jpg "/>650" this.width=650; "src="/HTTP// S3.51cto.com/wyfs02/m01/4c/37/wkiol1q46nedgzh5aacnfaspk8y747.jpg "title=" 360 mobile phone assistant 1011_15_56_02.png "alt=" Wkiol1q46nedgzh5aacnfaspk8y747.jpg "/>
Summary: Android through the handler+looper+messagequeue mechanism for inter-thread communication, this article through two simple instances based on this mechanism to implement the UI thread to the child thread and child thread to the UI thread messaging. The next blog post will take a closer look at the principles of the handler looper mechanism.
This article is from the "sprocessor" blog, make sure to keep this source http://sprocessor.blog.51cto.com/160089/1562589
Android handler Looper message mechanism application examples and detailed explanation (i)