I have a little time today to write a tip to share. Feel nonsense waste everyone’s time, direct stick code, I believe we can understand

public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo ! = null) {① return attachInfo.mHandler.post(action); } // Postpone the runnable until we know on which thread it needs to run. // Assume that the runnable will be Successfully placed after attach. ② getRunQueue(). Post (action); return true; }Copy the code

The View () method executes two ways: if the View is added to the window, execute ①, otherwise execute ②

final static class AttachInfo { ... final Handler mHandler; . }Copy the code

Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler Handler

private HandlerActionQueue getRunQueue() { if (mRunQueue == null) { mRunQueue = new HandlerActionQueue(); } (3) the return mRunQueue; }Copy the code

The next step is to execute ②, get a HandlerActionQueue object, and then post->postDelayed

public class HandlerActionQueue { private HandlerAction[] mActions; private int mCount; public void post(Runnable action) { postDelayed(action, 0); } public void postDelayed(Runnable action, long delayMillis) { final HandlerAction handlerAction = new HandlerAction(action, delayMillis); synchronized (this) { if (mActions == null) { mActions = new HandlerAction[4]; } mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction); mCount++; }} ④ Public void executeActions(Handler Handler) {synchronized (this) {final HandlerAction[] actions = mActions; for (int i = 0, count = mCount; i < count; i++) { final HandlerAction handlerAction = actions[i]; handler.postDelayed(handlerAction.action, handlerAction.delay); } mActions = null; mCount = 0; }}... }Copy the code

The postDelayed method stores the message into mActions, and the growingArrayUtils. append method is a system utility class that contains array expansion logic. Let’s take a look at where ③ is used and find that there is only one use, as follows

void dispatchAttachedToWindow(AttachInfo info, int visibility) {
    ...
    if (mRunQueue != null) {
        mRunQueue.executeActions(info.mHandler);
        mRunQueue = null;
    }
    ...
}
Copy the code

The dispatchAttachedToWindow method is called after the View is added, and mrunqueue.executeActions is called. Now let’s look at the executeActions method ④, Finally, the AttachInfo mHandler is called to execute the action, and the general flow of view.post is completed.

To sum up: