Android-handler, Looper, message (-) source code first recognized

Source: Internet
Author: User

This article only shows you the source code of handler, logoff, and message.

Android message processing has three core classes: logoff, handler, and message. There is also a message queue ),

Asynchronous processing Master Handler:

What is handler? Handler plays the role of adding and processing messages to MQ (only processing messages sent by itself), that isNotify MQ that it needs to execute a task (sendmessage) and execute this task (handlemessage) when the loop is reached itself. The whole process is asynchronous.. The handler is associated with a logoff when it is created. The default constructor will be associated with the Logoff of the current thread, but this can also be set. Default constructor:

Public class handler {final messagequeue mqueue; // the MQ final logoff mlogoff; // The logoff final callback mcallback; // other attributes public handler () {If (find_potential_leaks) {// did not understand, skipped directly, final class <? Extends handler> Klass = getclass (); If (Klass. isanonymousclass () | Klass. ismemberclass () | Klass. islocalclass () & (Klass. getmodifiers () & modifier. static) = 0) {log. W (TAG, "The following handler class shocould be static or leaks might occur:" + Klass. getcanonicalname () ;}// by default, it will be associated with the current thread's logoff mlogoff = logoff. mylogoff (); // logoff cannot be blank. That is, the default constructor can only be used in the logoff thread.
// By default, the main UI thread contains a logoff if (mlogoff = NULL) {Throw new runtimeexception (// handler cannot be created on a thread without logoff, "can't create handler inside thread that has not called logoff. prepare () ") ;}// important !!! Directly use the MQ associated with the logoff as its own MQ, so its messages will be sent to the MQ associated with the logoff mqueue = mlogoff. mqueue; mcallback = NULL;} // other methods}

Of course, this is only a construction method of handler. Handler itself has four constructors. You can view the source code to parse the other three constructors, which are roughly the same.

Handler sends messages

With handler, we can usepost(Runnabl),sendMessage(Message)These methods have sent messages to MQ. By looking at these APIs, you may think that handler can send two types of messages: a runnable object and a message object. This is an intuitive understanding, however, the runnable object sent by post is finally encapsulated as a message object. For details, see the source code:
Form of post Transmission

Public final Boolean post (runnable R) {// use post to send the message return sendmessagedelayed (getpostmessage (R), 0 );}
Private final message getpostmessage (runnable R) {// convert a runnable packet into a message m = message. Obtain (); M. Callback = r; return m ;}
public final boolean sendMessageDelayed(Message msg, long delayMillis){       if (delayMillis < 0) {           delayMillis = 0;       }       return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);}
public boolean sendMessageAtTime(Message msg, long uptimeMillis){        boolean sent = false;        MessageQueue queue = mQueue;        if (queue != null) {
/* The handler object, which ensures that the handler that handles the message can be found when the logoff executes the message. The straightforward point is that the three handler ABC sends the message, and the message is sent when the handler is executed.
It is also executed by them, rather than receiving messages sent by B. */msg.tar get = This ;//
Sent = queue. enqueuemessage (MSG, uptimemillis); // press into Message Queue} else {runtimeexception E = new runtimeexception (This + "sendmessageattime () called with no mqueue"); log. W ("logoff", E. getmessage (), e);} return sent ;}

Sendmessage (Message) Format

 public final boolean sendMessage(Message msg){        return sendMessageDelayed(msg, 0);}
public final boolean sendMessageDelayed(Message msg, long delayMillis){       if (delayMillis < 0) {           delayMillis = 0;       }       return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }

From the source code, we can clearly see whether psot (runnable) or sendmessage (Message) is used, finally, they all call the same method and press it into a queue.

Handler processes messages

Then how does handler process messages. The core method of message processing is through dispatchmessage (Message). The source code is as follows:

Public void dispatchmessage (Message MSG) {If (msg. callback! = NULL) {// post (runnable) form finally calls this method handlecallback (MSG);} else {
/* This method allows the activity to implement the handler. Callback interface or construct the handler (callback, avoiding writing handler to override the handlemessage Method */If (mcallback! = NULL ){
If (mcallback. handlemessage (MSG) {return ;}} handlemessage (MSG); // The handlermessage method is rewritten for the lowest priority }}

Encapsulate task message

There are no special methods in the source code of message. For message, we should remember the following knowledge points (waiting for your attention)

1. Although we can directly instance a message, we 'd better get an empty message object from the message pool through message. Obtain () to save resources.

2. If your message only needs to carry simple int information, use message. arg1 and message. arg2 to transmit information first, which saves memory usage compared with bundle.

3. Use the message. What field to indicate code,
That is, the type of the message.
Everything is in the namespace of the handler,
We only need to ensure that the attributes of the messages processed by the same Handler are not repeated. This is equivalent to the discriminative type.

4. Message. When the Message Size is arranged in ascending order, the message at the top will be processed first,
Therefore, the message queue is not a strict first-in-first-out queue.

5.message.tar get determines which handler will execute the message when you finally execute the message. Generally, when a queue is pushed to a queue, it is executed when the queue is extracted. We can query the source code above.

Lofter pipeline brother

First, it is clear that the activity itself gives him a logoff by default at startup.

Logoff structure:

Private Looper () {mqueue = new messagequeue (); // when the looper is initialized, we configure an MQ queue for this Looper, one to one for mrun = true; mthread = thread. currentthread (); // bind the thread to which it belongs}
// When we call this method, The logoff object public static final void prepare () {If (sthreadlocal. Get () will be created in the TLS of the call thread ()! = NULL) {// an attempt to create a logoff in a logoff thread will throw an exception throw new runtimeexception ("only one logoff may be created per Thread");} sthreadlocal. set (New logoff ());}

Public static final void loop () {Looper me = mylooper (); // obtain the corresponding loageobject messagequeue queue = me from this thread. mqueue; // get the message queue object... while (true) {message MSG = queue. next (); // The might block method is not very familiar. Get out a pending message // If (! Me. mrun) {// break; //} If (MSG! = NULL) {If (msg.tar get = NULL) {// No target is a magic identifier for the quit message. Return;} If (Me. mlogging! = NULL) me. mlogging. println (">>>>> dispatching to" + msg.tar get + "" + MSG. callback + ":" + MSG. what); msg.tar get. dispatchmessage (MSG); // message extraction. The final execution method, if (Me. mlogging! = NULL) me. mlogging. println ("<finished to" + msg.tar get + "" + msg. Callback); msg. Recycle ();}}}

The above is a superficial understanding of the source code of handler, message, and logoff.


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: 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.