A few key concepts 1, MessageQueue: is a data structure, see the name of righteousness, is a message queue, the place to store messages. Each thread can have a maximum of one MessageQueue data structure. When a thread is created, its MessageQueue is not created automatically. A Looper object is typically used to manage the MessageQueue of the thread. When the main thread is created, it creates a A default Looper object, and the creation of the Looper object automatically creates a message Queue. Other non-main thread, does not automatically create looper, when needed, by adjusting the Implemented using the Prepare function. 2. Message: The object that is stored in the messages queue. A message queue contains multiple message. The acquisition of the message instance object, usually using the static method obtain () in the message class, has multiple overloaded versions to choose from, and it does not necessarily create a new instance directly, Instead, see if there is an available message instance from the message pool, and there is a direct fetch to return to this instance. If there is no message instance available in the message pool, A Message object is created with the given parameters. When Removemessages () is called, the message is removed from the message queue and placed in the message pool. Except for the above method, you can also get a message instance from the handler object's Obtainmessage (). 3, Looper: Is the manager of MessageQueue. Each MessageQueue can not be separated from the Looper, Looper object is created by the prepare function to achieve. At the same time, each Looper object associated with a thread. The Looper object of the current thread can be obtained by calling Looper.mylooper () When you create a Looper object, a MessageQueue object is created at the same time. In addition to the default looper of the main thread, other threads do not have MessageQueue objects by default, so they cannot be Accept the message. If you need to accept, you define a Looper object (via the Prepare function) so that the thread has its own Looper object and MessageQueue data structure. Looper remove the message from the MessageQueue and leave it to Handler's handlemessage for processing. When processing is complete, call Message.recycle () to put it in the message pool. 4, Handler: The processor of the message, handler, is responsible for encapsulating the information that needs to be passed into a message, by invoking the Obtainmessage () of the handler object; The message is passed to Looper, which is implemented by the handler object's SendMessage (). The message is then placed into the MessageQueue by Looper. When the Looper object sees that the MessageQueue contains a message, it broadcasts it. After the handler object receives the message, the Handlemessage () method of the corresponding handler object is called To handle it. The service, activity, and broadcast we create are a primary thread processing, which we can understand as a UI thread . However, in the operation of some time-consuming operations, such as I/O read and write large file read and write, database operations and network download takes a long time, in order not to block the user interface, a ANR response prompt window, this time we can consider using thread threads to solve. For programmers who have engaged in J2ME development, the thread is simpler, directly anonymous create rewrite the Run method, call the Start method execution. or inherited from the Runnable interface, but for the Android platform the UI controls are not designed to be thread-safe , so you need to introduce some synchronous mechanisms to refresh them. Google in the design of Android when the reference to the next WIN32 message processing mechanism. 1. For a thread to refresh a view-based interface, you can use the Postinvalidate () method to process it in the threads, which also provides some overriding methods such as postinvalidate (int left,int top,int Right,int bottom) to refresh a rectangular area, as well as delay execution, such as postinvalidatedelayed (long delaymilliseconds) or postinvalidatedelayed (long Delaymilliseconds,int left,int top,int Right,int Bottom) method, where the first parameter is a millisecond 2. Of course, the recommended method is to handle these through a handler , you can invoke the handler object's PostMessage or SendMessage method in a thread's Run method, The Android program maintains a message queue that will handle these rotation, and if you are a WIN32 programmer can understand these message handling well, but there is no way to pretranslatemessage these internal interferences with Android. 3. What is Looper? , in fact, every thread in Android follows a looper,looper to help thread maintain a message queue, but Looper and handler have nothing to do with it. We can see from the open source code that Android also provides a thread inheriting class Handerthread can help us to handle, in the Handlerthread object can get a Looper object control handle through the Getlooper method, We can map this Looper object to a handler to implement a thread synchronization mechanism, The execution of the Looper object requires initialization of the Looper.prepare method, which is the problem we saw yesterday, as well as releasing the resources, using the Looper.release method. What is 4.Message on Android? For Android handler can pass some content, through the bundle object can encapsulate string, integer and Blob binary object, we through the thread Use the Sendemptymessage or SendMessage method of the handler object to pass a bundle object to the handler processor . The handler class provides an overriding method Handlemessage (Message msg) to judge by Msg.what to differentiate each piece of information . The bundle is unpacked to implement the handler class to update the contents of the UI thread to implement the refresh operation of the control. Related handler object about message sending Sendxxxx related methods are as follows, and there are postxxxx related methods, these and Win32 the rationale is basically consistent, one for send after the direct return, one for processing before returning. 5. Java.util.concurrent object analysis, for programmers in the past Java development will not be unfamiliar with concurrent objects, he is the JDK 1.5 new important features as handheld devices, we do not advocate the use of this class, Considering that Android is a task mechanism that we have designed, there is no too much to repeat here, the related reasons refer to the following description: 6. In Android, there is a different threading approach, task and Asynctask, which can be seen in the open source code for the concurrent package, and developers can easily handle these asynchronous tasks. Second, how the message between threads is passed 1, the main thread to send themselves a message Package test.message; Import android.app.Activity; Import Android.os.Bundle; Import Android.os.Handler; Import Android.os.Looper; Import Android.os.Message; Import Android.view.View; Import Android.widget.Button; Import Android.widget.TextView; public class Mainactivity extends Activity { Private Button btntest; Private TextView TextView; Private Handler Handler; @Override public void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); btntest = (Button) This.findviewbyid (r.id.btn_01); TextView = (TextView) This.findviewbyid (r.id.view_01); Btntest.setonclicklistener (New View.onclicklistener () { @Override public void OnClick (View arg0) { Looper Looper = Looper.getmainlooper (); The Looper object of the main thread This creates the handler with the Looper object of the main thread, Therefore, the message sent by this handler is passed to the MessageQueue of the main thread. Handler = new MyHandler (looper); Handler.removemessages (0); Building a Message Object First parameter: Is the message code of your own designation, convenient to receive in handler selectively The 23rd parameter doesn't make any sense. The fourth parameter needs to encapsulate the object Message msg = Handler.obtainmessage (1,1,1, "The main thread has sent Messages"); Handler.sendmessage (msg); Send Message } }); } Class MyHandler extends handler{ Public MyHandler (Looper Looper) { Super (Looper); } public void Handlemessage (Message msg) { Super.handlemessage (msg); Textview.settext ("I am the main thread of the handler, received the message:" + (String) msg.obj); } } } 2. Other threads send a message to the main thread Package test.message; Import android.app.Activity; Import Android.os.Bundle; Import Android.os.Handler; Import Android.os.Looper; Import Android.os.Message; Import Android.view.View; Import Android.widget.Button; Import Android.widget.TextView; public class Mainactivity extends Activity { Private Button btntest; Private TextView TextView; Private Handler Handler; @Override public void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); btntest = (Button) This.findviewbyid (r.id.btn_01); TextView = (TextView) This.findviewbyid (r.id.view_01); Btntest.setonclicklistener (New View.onclicklistener () { @Override public void OnClick (View arg0) { As you can see here, a thread is started to manipulate the encapsulation and sending of messages. So the original main thread of the send will become the other thread of the send, simple it? Oh New MyThread (). Start (); } }); } Class MyHandler extends handler{ Public MyHandler (Looper Looper) { Super (Looper); } public void Handlemessage (Message msg) { Super.handlemessage (msg); Textview.settext ("I am the main thread of the handler, received the message:" + (String) msg.obj); } } Add a thread class Class MyThread extends thread{ public void Run () { Looper Looper = Looper.getmainlooper (); The Looper object of the main thread This creates the handler with the Looper object of the main thread, Therefore, the message sent by this handler is passed to the MessageQueue of the main thread. Handler = new MyHandler (looper); Building a Message Object First parameter: Is the message code of your own designation, convenient to receive in handler selectively The 23rd parameter doesn't make any sense. The fourth parameter needs to encapsulate the object Message msg = Handler.obtainmessage (1,1,1, "Other threads have sent messages"); Handler.sendmessage (msg); Send Message } } } 3. The main thread sends a message to other threads Package test.message; Import android.app.Activity; Import Android.os.Bundle; Import Android.os.Handler; Import Android.os.Looper; Import Android.os.Message; Import Android.view.View; Import Android.widget.Button; Import Android.widget.TextView; public class Mainactivity extends Activity { Private Button btntest; Private TextView TextView; Private Handler Handler; @Override public void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); btntest = (Button) This.findviewbyid (r.id.btn_01); TextView = (TextView) This.findviewbyid (r.id.view_01); Start thread New MyThread (). Start (); Btntest.setonclicklistener (New View.onclicklistener () { @Override public void OnClick (View arg0) { Here handler is instantiated in the thread It was instantiated when the thread started. Message msg = Handler.obtainmessage (1,1,1, "message sent by the main thread"); Handler.sendmessage (msg); } }); } Class MyHandler extends handler{ Public MyHandler (Looper Looper) { Super (Looper); } public void Handlemessage (Message msg) { Super.handlemessage (msg); Textview.settext ("I am the main thread of the handler, received the message:" + (String) msg.obj); } } Class MyThread extends thread{ public void Run () { Looper.prepare (); Creates a Looper object for the thread that receives the message Note: Here the handler is defined in the main thread of Oh, hehe, Before you see the direct use of the handler object, is not looking for, where to instantiate it? Now you see it??? Oh, at the beginning of the instantiation is not, because the thread of the Looper object It doesn't exist yet. You can now instantiate the Here Looper.mylooper () gets the Looper object for that thread. Handler = new Threadhandler (Looper.mylooper ()); This method, have doubts? is actually a loop that loops through the MessageQueue messages. Don't often go to see, how do you know you have new news??? Looper.loop (); } Defining a message processing class in a thread class Class Threadhandler extends handler{ Public Threadhandler (Looper Looper) { Super (Looper); } public void Handlemessage (Message msg) { The message in the MessageQueue in this thread is processed here Here we return to the main thread a message Handler = new MyHandler (Looper.getmainlooper ()); Message MSG2 = Handler.obtainmessage (1,1,1, "Child thread Received:" + (String) msg.obj); Handler.sendmessage (MSG2); } } } } 4. Other threads send themselves a message Package test.message; Import android.app.Activity; Import Android.os.Bundle; Import Android.os.Handler; Import Android.os.Looper; Import Android.os.Message; Import Android.view.View; Import Android.widget.Button; Import Android.widget.TextView; public class Mainactivity extends Activity { Private Button btntest; Private TextView TextView; Private Handler Handler; @Override public void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); btntest = (Button) This.findviewbyid (r.id.btn_01); TextView = (TextView) This.findviewbyid (r.id.view_01); Btntest.setonclicklistener (New View.onclicklistener () { @Override public void OnClick (View arg0) { Start thread New MyThread (). Start (); } }); } Class MyHandler extends handler{ Public MyHandler (Looper Looper) { Super (Looper); } public void Handlemessage (Message msg) { Super.handlemessage (msg); Textview.settext ((String) msg.obj); } } Class MyThread extends thread{ public void Run () { Looper.prepare (); Create the Looper object for the thread Here Looper.mylooper () gets the Looper object for that thread. Handler = new Threadhandler (Looper.mylooper ()); Message msg = Handler.obtainmessage (1,1,1, "myself"); Handler.sendmessage (msg); Looper.loop (); } Defining a message processing class in a thread class Class Threadhandler extends handler{ Public Threadhandler (Looper Looper) { Super (Looper); } public void Handlemessage (Message msg) { The message in the MessageQueue in this thread is processed here Here we return to the main thread a message Add judgment to see if the thread is sending its own messages if (Msg.what = = 1 && msg.obj.equals ("Myself")) { Handler = new MyHandler (Looper.getmainlooper ()); Message MSG2 = Handler.obtainmessage (1,1,1, "The main thread: I received a message from myself"); Handler.sendmessage (MSG2); } } } } } Note: The layout file for the above four examples is the same file Main.xml <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" android:rientation= "Vertical" Android:layout_width= "Fill_parent" android:layout_height= "Fill_parent" > <textview android:id= "@+id/view_01" Android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:text= "@string/hello" /> <button android:id= "@+id/btn_01" Android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:text= "test Message"/> </LinearLayout> Original: http://blog.csdn.net/yhb5566/article/details/7342786 |