1. First look at a general handler usage:
Create a handler in the main thread:
Private New Handler () { @Override publicvoid handlemessage (Message msg) { Super. Handlemessage (msg); Switch (msg.what) { case 0: mtesttv.settext ("The Is Handlemessage") ; update UIbreak;}} ;
Takes a time-consuming action in a child thread, sends a message after it finishes, and updates the UI operation after the main thread receives the message.
New Thread (new Runnable () { @Override publicvoid run () { Try { thread.sleep (+); There is a time-consuming operation on the child thread, such as requesting network mhandler.sendemptymessage (0); Catch (interruptedexception e) { e.printstacktrace ();}}} ). Start ();
2. Now look at the version of Handler.post ():
PrivateHandler Mhandler;//Global Variables@Overrideprotected voidonCreate (Bundle savedinstancestate) {Mhandler=NewHandler (); NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (1000);//There is a time-consuming operation on a child thread, such as requesting a networkMhandler.post (NewRunnable () {@Override Public voidrun () {Mtesttv.settext ("This is post");//Update UI } }); } Catch(interruptedexception e) {e.printstacktrace (); }}). Start ();
after the time-consuming operation is complete, the UI is updated directly in the handler-enabled child thread. Both the post and SendMessage principles are encapsulated into a message, and eventually all call the enqueuemessage () an infinite loop to join the message to the queue (in the form of a list). Looking at the MessageQueue method, we found next (), the code is too long, do not repeat, we know it is used to get the message out of the line. But where is this method called, not in handler, where we find the key to Looper, I call him the ring Messenger, who is specifically responsible for getting messages from the message queue. Reference blog: http://blog.csdn.net/ly502541243/article/details/52062179/
201709013 Business Day Note--android message mechanism Handlerthread