Android handler source in-depth analysis

Source: Internet
Author: User

Idle Nothing, just to look at the source code, look at the various principles of the source code, will use just simple, know why is the best.

Handler source analysis that, from the steps used to edge with edge analysis:

1. Create a Handler object: New Handler (Getmainlooper (), this);

This is a common way, getmainlooper is to get the main thread of the looper,this is to implement the callback interface

Take a look at the handler constructor

Public Handler () {

This (null, false);

}

Public Handler (Callback Callback) {

This (callback, false);

}

Public Handler (Looper Looper) {

This (Looper, NULL, FALSE);

}

Public Handler (Looper Looper, Callback Callback) {

This (Looper, callback, false);

}

@hide

Public Handler (Boolean async) {

This (null, async);

}

@hide

Public Handler (Callback Callback, Boolean async) {

if (Find_potential_leaks) {

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 should be static or leaks might occur:" +

Klass.getcanonicalname ());

}

}

Mlooper = Looper.mylooper ();

if (Mlooper = = null) {

throw New RuntimeException (

"Can ' t create handler inside thread that have not called looper.prepare ()");

}

Mqueue = Mlooper.mqueue;

Mcallback = callback;

masynchronous = async;

}

@hide

Public Handler (Looper Looper, Callback Callback, Boolean async) {

Mlooper = Looper;

Mqueue = Looper.mqueue;

Mcallback = callback;

masynchronous = async;

}

The primary code function of the constructor is the initialization of the parameter:

Mlooper = Looper;mqueue = Looper.mqueue;mcallback = callback; masynchronous = async;

These four parameters are the main parameters.

2. Create a message. Message msg = Handler.obtainmessage ();

Direct call to Handler source:

Public final Message Obtainmessage ()

{

Return Message.obtain (this);

}

Source code in message:

public static Message obtain (Handler h) {

Message m = obtain ();

M.target = h;

return m;

}

public static Message obtain () {

Synchronized (Spoolsync) {

if (SPool! = null) {

Message m = sPool;

SPool = M.next;

M.next = null;

m.flags = 0; Clear In-use Flag

spoolsize--;

return m;

}

}

return new Message ();

}

Here the message is the concept of reuse, the maximum ability to maintain

private static final int max_pool_size = 50;

An object of 50 message.

The spool variable corresponds to the current empty, unused message, which is returned by converting the current empty message.

The message will be recycled after it has been used, as mentioned below.

3. Assign a value to message and send Message:msg.what = 100; Handler.sendmessage (msg);

What is a stored value variable in the message.

Sending a message in the handler will eventually point to the following source code:

Private Boolean enqueuemessage (MessageQueue queue, Message msg, long Uptimemillis) {

Msg.target = this;

if (masynchronous) {

Msg.setasynchronous (TRUE);

}

Return Queue.enqueuemessage (msg, uptimemillis);

}

Ok,sendmessage sent to the MessageQueue class, see MessageQueue how to deal with.

Boolean enqueuemessage (Message msg, long when) {

...........

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 has to wake

Up the event queue unless there are a barrier at the head of the queue

The message 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;

}

if (Needwake) {

Nativewake (MPTR);

}

}

.......

}

Intercept the important code in the middle and say it. What's this for?

In fact, it is used to sort, we know that the message has a delay, the time to delay the message is not the same, when there is a size, after the execution of the message is put back.

MessageQueue is not using a collection or using an array to store the message, the real sort is the next variable of the message, and the next variable holds the next message of the current message.

After sending, a native method Nativewake is executed, which is not explored here.

The processing callback for the 4.handler message callback.

public static void Loop () {

........

for (;;) {

Message msg = Queue.next (); Might block

.....

Msg.target.dispatchMessage (msg);

.......

Msg.recycleunchecked ();

}

......

}

This is the source of Looper species, loop is the way to recycle the message in MessageQueue. I removed the code, and we can see that the Messa target variable is called, and this variable holds that handler,dispatchmessage is the way to distribute the message. Look at the source of DispatchMessage:

public void DispatchMessage (Message msg) {

if (msg.callback! = null) {

Handlecallback (msg);

} else {

if (mcallback! = null) {

if (Mcallback.handlemessage (msg)) {

Return

}

}

Handlemessage (msg);

}

}

This is a lot less!

See the put, callback the callback. This completes the entire loop process.

Say the above
Msg.recycleunchecked () method. Similarly, look at the source code:

void recycleunchecked () {

Mark the message as in use while it remains in the recycled object pool.

Clear all other details.

Flags = Flag_in_use;

what = 0;

arg1 = 0;

arg2 = 0;

obj = null;

ReplyTo = null;

Sendinguid =-1;

when = 0;

target = null;

callback = NULL;

data = null;

Synchronized (Spoolsync) {

if (Spoolsize < max_pool_size) {

Next = SPool;

SPool = this;

spoolsize++;

}

}

}


You can tell from the method name that this is used to recycle the message.

After the message has been used, instead of destroying the message object, it is stored and reused for the next time.

Handler running the approximate process is like this.

Looper of the class of source analysis, back to the resolution.

Android Development Exchange Group: 417270671

My github Address: https://github.com/flyme2012





Android handler source in-depth analysis

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.