Android handler message distribution mechanism source code Analysis _android

Source: Internet
Author: User
Tags getmessage message queue prepare prev

Note: This is just a procedure for SendMessage, post is similar
If we need to send a message, we call the SendMessage method

 Public Final Boolean SendMessage (Message msg)
{return
 sendmessagedelayed (msg, 0);
} 

This method will call the following method

Public Final Boolean sendmessagedelayed (Message msg, long Delaymillis)
{
 if (Delaymillis < 0) {
  Delaymillis = 0;
 }
 Return Sendmessageattime (MSG, systemclock.uptimemillis () + delaymillis);


Then set the delay time and continue calling the Sendmessageattime method

public boolean sendmessageattime (msg, long Uptimemillis) {
 MessageQueue queue = mqueue;
 if (queue = = null) {
  runtimeexception e = new RuntimeException (This
    + sendmessageattime () called with no Mqueue ");
  LOG.W ("Looper", E.getmessage (), e);
  return false;
 }
 return Enqueuemessage (Queue, MSG, uptimemillis);


This gets the message queue, checks whether the queue exists, and then returns the execution result of the Enquemessage method, which is a Boolean value indicating whether the message can enter the queue

Private Boolean enqueuemessage (MessageQueue queue, MSG, long Uptimemillis) {
 msg.target = this;
 if (masynchronous) {
  msg.setasynchronous (true);
 }
 Return Queue.enqueuemessage (msg, uptimemillis);


Here is the message to the team, the following is the message in the MessageQueue in the team

Boolean Enqueuemessage (msg, long when) {if (Msg.target = = null) {throw new IllegalArgumentException ("message
 Must have a target. ");}
 if (Msg.isinuse ()) {throw new IllegalStateException (msg + "This message being already in use."); } synchronized (this) {if (mquitting) {illegalstateexception e = new IllegalStateException (Msg.target + "s
   Ending message to a Handler on a dead thread ");
   LOG.W (TAG, E.getmessage (), E);
   Msg.recycle ();
  return false;
  } msg.markinuse ();

  Msg.when = when;
  Message p = mmessages;
  Boolean needwake;
   If p = null | | when = = 0 | | When < p.when) {//New head, Wake up the event queue if blocked.
   Msg.next = p;
   Mmessages = msg;
  Needwake = mblocked; else {//Inserted within the middle of the queue. Usually we don ' t have to wake//up the event queue unless there are a barrier at the head of the queue//The Me
   The Ssage is the earliest asynchronous message in the queue. Needwake = MblockeD && p.target = null && msg.isasynchronous ();
   Message prev; for (;;)
    {prev = p;
    p = p.next;
    if (p = = NULL | | When < p.when) {break;
    } if (Needwake && p.isasynchronous ()) {needwake = false; } msg.next = P;
  Invariant:p = = Prev.next Prev.next = msg;
  }//We can assume mptr!= 0 because mquitting is false.
  if (needwake) {nativewake (mptr);
} return true;

 }

is to pass over the message to do some encapsulation and then put into the queue, so our sendmessage processing, the return of the result is the success of the Boolean, then how is the message after the deal?
We can see that a Looper object is recorded in the handler construct, and a callback function is recorded.

Public Handler (Callback Callback, Boolean async) {
 if (find_potential_leaks) {
  final class<? extends handler& Gt Klass = GetClass ();
  if ((Klass.isanonymousclass () | | klass.ismemberclass () | | klass.islocalclass ()) &&
    (Klass.getmodifiers () & modifier.static) = = 0) {
   log.w (TAG, "the following Handler class should be STATIC or leaks might:" +
    Klass.getcanonicalname ());
  }

 Mlooper = Looper.mylooper ();
 if (Mlooper = = null) {
  throw new RuntimeException (
   "Can" t create handler inside thread that is has not called Loope R.prepare () ");
 }
 Mqueue = Mlooper.mqueue;
 Mcallback = callback;
 masynchronous = async;
}

The Mylooper method here returns a Looper object associated with the current thread

 public static @Nullable Looper Mylooper () {return
 sthreadlocal.get ();
} 

When the Looper is instantiated and then executes its own prepare method and then executes the loop method, the loop method is a way of constantly reading messages in message queues and then performing the appropriate actions, because loops that are executed in other threads do not affect other threads

public static void Loop () {final Looper me = Mylooper (); if (me = = null) {throw new RuntimeException ("No looper;
 Looper.prepare () wasn ' t called on this thread. ");

 Final MessageQueue queue = Me.mqueue; Make sure the identity of the ' This thread is ' the local process,//and keep track of what that identity token ACTU
 Ally is.
 Binder.clearcallingidentity ();

 Final Long ident = Binder.clearcallingidentity (); for (;;) {Message msg = Queue.next ();//might blocks if (msg = null) {//No message indicates the ' message ' queue is Q
   Uitting.
  Return
  }//This must is 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 ();

 }
}

If the message is read in the loop, the DispatchMessage method is executed, and then a recycleunchecked method is executed once the message is dispatched, and we see the DispatchMessage method

public void DispatchMessage (message msg) {
 if (msg.callback!= null) {
  handlecallback (msg);
 } else {
  if ( Mcallback!= null) {
   if (Mcallback.handlemessage (msg)) {return
    ;
   }
  }
  Handlemessage (msg);
 }


Here to see a direct implementation of a Handlermessage method, this method is a callback method, we must implement, otherwise handler nothing will do, why? Remember when we just said the construction handler we recorded a callback back off? The Handlermessage method in handler is an empty method, and if we rewrite this method, we will execute the code we wrote first in the callback, which is what to do after we receive the message.

Public interface Callback {public
 boolean handlemessage (msg);
}

public void Handlemessage (message msg) {
}

Here's a simple talk about the whole process:
After we instantiate a handler subclass and rewrite the Handlemessage method, this time the system has done a few things for us
1. Instantiated a message queue MessageQueue
2. Instantiate an associated Looper object and allow Looper to continuously read message queues
3. Record our rewritten Handlemessage method as we need a callback
When we execute the handler SendMessage method, the system adds the message object that we passed in to the queue, and if Looper reads the message, it distributes the message. Then callback the Handlemessage method to execute the code we set.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.