Android Handler source code in-depth analysis, androidhandler

Source: Internet
Author: User

Android Handler source code in-depth analysis, androidhandler

Let's take a look at the source code and look at the various principles of the source code. It's easy to use and know why it is the most awesome.

Handler source code analysis, from the steps used to use edge analysis:

1. Create a Handler object: new Handler (getMainLooper (), this );

This is a common method. getmainlogoff is used to obtain the Logoff of the main thread, and this is the interface for implementing CallBack.

Let's take a look at the Handler constructor.

Public Handler (){

This (null, false );

}

Public Handler (Callback callback ){

This (callback, false );

}

Public Handler (low.logoff ){

This (logoff, null, false );

}

Public Handler (Looper looper, Callback callback ){

This (logoff, 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 shocould be static or leaks might occur:" +

Klass. getCanonicalName ());

}

}

 

Mlogoff = logoff. mylogoff ();

If (mloiter = null ){

Throw new RuntimeException (

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

}

MQueue = mloue. mQueue;

MCallback = callback;

MAsynchronous = async;

}

 

 

@ Hide

Public Handler (Looper looper, Callback callback, boolean async ){

Mlogoff = logoff;

MQueue = logoff. mQueue;

MCallback = callback;

MAsynchronous = async;

}

 

The main function of the constructor code is to assign values to parameters during initialization:

 

Mloue = loue; mQueue = loue. mQueue; mCallback = callback; mAsynchronous = async;

 

These four parameters are the main parameters.

 

2. Create a Message. Message msg = handler. obtainMessage ();

Directly call the Handler source code:

Public final Message obtainMessage ()

{

Return Message. obtain (this );

}

 

Source code in Message:

 

Public static Message obtain (Handler h ){

Message m = obtain ();

M.tar get = 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 Message is the concept of reuse, which can be maintained at maximum

Private static final int MAX_POOL_SIZE = 50;

Objects of 50 messages.

The sPool variable is equivalent to the currently empty unused Message. The current empty Message is returned through conversion.

The Message will be recycled after use, which will be mentioned below.

 

3. assign values to the Message and send the Message: msg. what = 100; handler. sendMessage (msg );

 

What is a stored value variable in Message.

When a Message is sent, the Handler finally points to the following source code:

 

Private boolean enqueueMessage (MessageQueue queue, Message msg, long uptimeMillis ){

Msg.tar get = this;

If (mAsynchronous ){

Msg. setAsynchronous (true );

}

Return queue. enqueueMessage (msg, uptimeMillis );

}

OK, sendMessage is sent to the MessageQueue class to see how MessageQueue handles it.

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

// Up the event queue unless there is a barrier at the head of the queue

// And the message is the earliest asynchronous message in the queue.

NeedWake = mBlocked & p.tar get = 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 );

}

}

.......

}

 

 

Let's take a look at the important code in the middle. What is this ??

In fact, it is used for sorting. We know that there are delayed messages in the Message, and the delay time is different. when there is a large size, put the subsequent executed messages to the back.

MessageQueue does not use a set or an array to store messages. The next variable sorts messages and stores the next Message of the current Message.

After sending the message, a native method nativeWake is executed, which will not be explored here.

 

 

4. Callback for handler message processing.

 

Public static void loop (){

 

........

 

For (;;){

Message msg = queue. next (); // might block

.....

Msg.tar get. dispatchMessage (msg );

 

.......

 

Msg. recycleUnchecked ();

}

......

}

This is the logoff source code, and the loop is the method for looping the Message in MessageQueue. After removing the code, we can see that the target variable called Messa stores Handler and dispatchMessage is used to distribute messages. View the source code 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 much less!

The callback is called back. This completes the entire loop process.

 

 

Let's talk about the above
Msg. recycleUnchecked () method. Similarly, check the source code:

 

Void recycleUnchecked (){

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

// Clear out 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 ++;

}

}

}


We can know from the method name that this is used to recycle the Message.

After the Message is used, it is not to destroy the MEssage object, but to store it and use it again next time.

 

 

The process of Handler running is like this.

Logoff class source code analysis, and then parse.

 

 

Android Development Group: 417270671

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



 

 

 

 



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.