Handler's post method, Handlerpost Method
Example of using the post (Runnable r) method of Handler
According to the explanation, the post method parameter of Handler is a Runnable object, which is added to the Message Queue. the Runnable object runs in the thread attached to Handler.
Because the Handler object is generated in MainThread, The logoff object corresponding to the Handler object is also generated in MainThread, And the Runnable object is stored in message queue, in MainThread, what does logoff take out the Runnable object?
Guess: generate a thread object, pass the Runnable object as the thread body, and call the start method.
However, we can see that the Runnable object runs in MainThread! Incorrect guess
View the source code of the post method of Handler.
The getPostMessage method generates the Message object and assigns the Runnable object to the callback attribute of the Message object.
The sendMessageDelayed method is used to send Message objects and set the delayed sending time.
In fact, the post method puts the Runnable object into the callback attribute of the Message object, and then puts the Message object into the Message queue, so what operations does logoff perform to retrieve the Message object carrying the Runnable object?
Attackers can call the msg.tar get. dispatchMessage method after passing through the looptings of parameter looperations.
Call the handleCallback method when the callback property is not empty.
Message. callback. run (); that is, Runnable. run ();
Directly calling the Runnable run method will not open a new thread, but will be executed in the original thread, so it will print that the current thread is Main. Based on this mechanism, we can directly define the MainThread update code in the Runnable run method, and then call the post method of Handler to send it out.