Handler's post method, Handlerpost Method

Source: Internet
Author: User

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.

Related Article

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.