Android source code analysis Message

Source: Internet
Author: User

Preparing to write something is a record/Note for yourself to read the source code, and hope to be helpful to people of the same interest.

Stick to it, hey.

In Android development, we often use the Handler. postXXX method or the View. postXXX method for the next logoff.

Execute when it comes. I am such a person, and it is best to know what internal implementation mechanism is, otherwise I may feel uncomfortable when using it,

Or it is not natural and unwilling to use it. A typical example is that I have always insisted on using SparseArray introduced by Android.

Java HashMap <Key, Value> is not bold until I read the source code of SparseArray <E>.

As a matter of fact, why did I suddenly decide to write this? One day I saw code like this:

 Runnable mRunnable =          removeCallbacks(

The first intuition tells me that removeCallbacks (this) in the run method is obviously redundant. This is true through the code reading, because any Message

(Even if the post is Runnable, it will be packaged into the Message.) before being processed, it has been removed from MessageQueue (delete, so the client

The Code does not have to have such code ). Here, by the way, use the View. removeCallbacks return value with caution. See the source code:

                                    (action !=               AttachInfo attachInfo =              (attachInfo !=                            Choreographer.CALLBACK_ANIMATION, action,              }                                    }

We can see that this method always returns true, so do not do anything based on its return value, and pay special attention to the significance of its return value.

When I saw this method for the first time, I thought that the returned value must indicate whether the Runnable action was successfully removed from MessageQueue. true indicates that the operation was successful.

Removed. false indicates that the removal failed. Take a closer look at the doc of the method. What people say is "return true", indicating that this view can make its Handler

The processing result is not mentioned. Even if true is returned, Runnable has been removed from MessageQueue,

For example, Runnable is no longer in MessageQueue; otherwise, false is returned. Here, by the way, we can see the View. postDelayed method:

   postDelayed(Runnable action,           AttachInfo attachInfo =          (attachInfo !=                                        }

Here, both postDelayed and removeCallbacks check their own mAttachInfo first. If it is not empty, delegate will handle it to the Handler of attachInfo.

Do not call these methods too early (mAttachInfo has not been initialized). runnable will not be executed in earlier Android versions. Refer to this question:

Http://stackoverflow.com/questions/4083787/runnable-is-posted-successfully-but-not-run

I am analyzing the source code of Android4.4. What is it? I still cannot verify it at home. I will wait for Monday to verify it at the company and then update it, of course, you can search for view post runnable not run in google or verify it yourself. However, according to the current Code, even if mAttachInfo is null, ViewRootImpl will be executed. getRunQueue (). postDelayed (action, delayMillis); therefore, it may not be a problem on newer platforms (to be verified ). At present, I have not had time to analyze its source code (which will be written later ).

Let's get started with a lot of things. At the beginning, I selected the simplest method for analysis today. Hey, it's the Message. java file.

To put it bluntly, Message is a data class that holds data. I will not introduce the basic data fields. Let's take a look at several fields that I think are necessary:

                            Object sPoolSync =               sPoolSize = 0          MAX_POOL_SIZE = 50;

Targetis the message handler. msg.tar get. dispatchMessage (msg) will be used when messageis obtained from messagequeuein looper.loop(publish messages );

Callback is the action to be executed by the message. Here, the dispatchMessage method of Handler is inserted in advance:

            (msg.callback !=           }               (mCallback !=                                                }

We can see that when Handler sends messages, the callback priority of the Message itself is high. If it is not empty, it is called first (the callback run method is called directly ).

Next indicates the next Message in the Message queue, similar to the concept of a single-chain table.

The remaining pool-related fields are all the variables required for reuse (reuse) introduced by Message. sPoolSync is the object lock, because the Message. obtain method will

Thread call; sPool indicates the Message object to be reused next; sPoolSize indicates the number of reusable objects; MAX_POOL_SIZE is obviously the upper limit of the pool,

Hardcode is 50. Here I want to analyze two methods,

The code for obtain and recycle is as follows:

                                      (sPool !=                  Message m =                 sPool =                 m.next =                  sPoolSize--                                                                        (sPoolSize <                 next =                 sPool =                  sPoolSize++       }

First, let's take a look at the obtain method. The first call means that nothing can be reused. In this case, sPool is null and a new Message object is returned. After the Message object is used up (

In logoff. the loop method has msg at the end. recycle (); such code), its recycle will be called. In recycle, The clearForRecycle method will be called first, but it only sets the fields to null or empty.

Next, sPoolSize does not reach the upper limit. next, save the old sPool value (that is, the previous object to be recycled before the current Message is recycled), and then the sPoolSize is updated to the new value, that is, the current Message, sPoolSize plus 1, indicates that another Message object can be reused. When obtain is called, a new Message is not directly returned, because we already have a Message object that can be reused. Set the sPool value to the Message m object to be returned, and then the sPool is updated to the previous Message object to be reused (reverse process compared to recycle ), finally, set the next field of m to null (m. next will be set to an appropriate value when the queue is re-entered.) The corresponding sPoolSize minus 1, indicating that one reusable object is missing, and finally the reusable object m is returned.

Based on such a recycling mechanism, Android recommends that we call the Message obtain method to obtain a Message object, instead of calling the ctor, because it may save the overhead of allocating a new object.

The analysis of the Message class is now available. Later, we will analyze the classes that are common in Android development... (I am welcome to criticize and correct my skills)

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.