Handler Message transmission mechanism (2) working principles of Handler, Loop, Message, and MessageQueue

Source: Internet
Author: User

Handler Message transmission mechanism (2) working principles of Handler, Loop, Message, and MessageQueue

Loop, Message, and MessageQueue concepts:

Message: the Message object sent, received, and processed by Handler.

Loler: Each thread can have only one loue. Its Looper () method is used to read messages in MessageQueue cyclically and send the read messages to the handler who sends the messages for processing.

MessageQueue: a Message queue, which uses the first-in-first-out method to manage messages. When the program creates a logoff object, it will create MessageQueue in its constructor

Logoff provides the following source code:

private Looper(boolean quitAllowed) {        mQueue = new MessageQueue(quitAllowed);         mThread = Thread.currentThread();     }

From the source code line 2nd, we can see that a MessageQueue object associated with it will be created when a logoff object is created. The constructor is private, so programmers cannot create logoff objects, that is A MessageQueue object is created when a logoff is created.

 

Handler: As mentioned earlier, Handler has two functions: sending messages and processing messages. The messages sent by Handler must be sent to the specified MessageQueue. That is to say, if Handler works properly, there must be a MessageQueue in the current thread, otherwise, messages cannot be saved.While MessageQueue is managed by LogoffSo if Handler works properly,There must be a logoff object in the current threadIn two cases:

1> the main thread (UI thread), the system has initialized a logoff object, so the program can directly create a Handler.
2> A subthread created by the programmer. In this case, the programmer must create a logoff object and start it.

Create loe: Use Looper. prepare () to view the source code.

public static void prepare() {        prepare(true);     }     private static void prepare(boolean quitAllowed) {          if (sThreadLocal.get() != null) {             throw new RuntimeException("Only one Looper may be created per thread");          }          sThreadLocal.set(new Looper(quitAllowed));    }    private Looper(boolean quitAllowed) {         mQueue = new MessageQueue(quitAllowed);         mThread = Thread.currentThread();     }

 

Call the method to create a logoff object in line 1. A MessageQueue object (Row 3) is created when a logoff object is created ). In addition, we can see that prepare () allows a thread to have at most one loose created

Start loage: Looper. loop (), loop () uses an endless loop to retrieve messages in MessageQueue, and sends the messages to the corresponding Handler for processing. The following is the source code of the logoff () method in the logoff class.

for (;;) {              Message msg = queue.next(); // might block              if (msg == null) {                // No message indicates that the message queue is quitting.                  return;              }                // This must be in a local variable, in case a UI event sets the logger              Printer logging = me.mLogging;             if (logging != null) {                 logging.println(">>>>> Dispatching to " + msg.target + " " +                         msg.callback + ": " + msg.what);            }            msg.target.dispatchMessage(msg);             if (logging != null) {                 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);            }              // Make sure that during the course of dispatching the             // identity of the thread wasn't corrupted.             final long newIdent = Binder.clearCallingIdentity();             if (ident != newIdent) {                 Log.wtf(TAG, "Thread identity changed from 0x"                         + Long.toHexString(ident) + " to 0x"                         + Long.toHexString(newIdent) + " while dispatching to "                         + msg.target.getClass().getName() + " "                        + msg.callback + " what=" + msg.what);             }              msg.recycleUnchecked();        }
Obviously, 1st rows use an infinite loop, 2nd rows extract the Message from the queue, and 15th rows send the Message to the Handler through the dispatchMessage (Message msg) method.

Logoff, MessageQueue, and Handler have the following functions:

Loage: each thread has only one loue, which is responsible for managing MessageQueue. It will continuously retrieve messages from MessageQueue and deliver the messages to the corresponding Handler for processing.

MessageQueue: it is managed by the logoff, which is used to store the messages put by the thread.

Handler: it sends a message to the MessageQueue managed by logoff, and is responsible for processing the message assigned by logoff.

In the thread, Handler is used as follows:

(1) Call The logoff prepare () method to create a logoff object for the current thread. When a logoff object is created, its constructor will create a matching MessageQueue.
(2) After loaning, create an instance of the Handler subclass and override the HandlerMessage () method to process messages from other threads.
(3) Call logoff's loop () method to start logoff.
 

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.