Android View.post()原理分析

2021-04-19  本文已影响0人  雷涛赛文

一.背景

       别人问:View.post() 为什么能够获取到 View 的宽高 ?
       别人答案:post()是在View绘制完成后执行;
       仔细一想:View必须在绘制完成后才能得到宽高,那么post()又是在View绘制完成后执行,那么post()内就能够获取到View的宽高。
       带着问题和答案,没有别的途径,只能通过源码来找到答案,下面就直接从View.post()执行开始:

二.View.post()

       通过源码,先看一下View内部post()执行逻辑:

a.View.java
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;
}

       我们看到,在post()内部有两个分支可能执行:
       1.attachInfo对象不为空,执行通过attachInfo内部的Handler执行Runnable;
       2.若attachInfo为空,则执行getRunQueue().post();
       分支1涉及到AttachInfo,该AttachInfo涉及到View的绘制流程,后面进行详细分析,先分析分支2中的getRunQueue():

private HandlerActionQueue getRunQueue() {
    if (mRunQueue == null) {
        mRunQueue = new HandlerActionQueue();
    }
    return mRunQueue;
}

       getRunQueue()内部创建了一个HandlerActionQueue对象,再看一下HandlerActionQueue这个类:

b.HandlerActionQueue.java
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;
        }
    }

   .......

    private static class HandlerAction {
        final Runnable action;
        final long delay;

        public HandlerAction(Runnable action, long delay) {
            this.action = action;
            this.delay = delay;
        }

        public boolean matches(Runnable otherAction) {
            return otherAction == null && action == null
                    || action != null && action.equals(otherAction);
        }
    }
}

       HandlerActionQueue是一个初始容量是4的 HandlerAction数组。HandlerAction有两个成员变量:需要执行的Runnable和延迟执行的时间。
       队列的执行逻辑在 executeActions(handler) 方法中,通过传入的handler进行任务分发。
       前面分析到:在View.java内的getRunQueue()内部创建了HandlerActionQueue对象mRunQueue,那么executeActions()的调用也应该是在View内部,通过搜索发现,在View.java内部有一处调用到了executeActions()方法,一起看一下dispatchAttachedToWindow():

void dispatchAttachedToWindow(AttachInfo info, int visibility) {
    mAttachInfo = info;
    if (mOverlay != null) {
        mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
    }
    .......
    // Transfer all pending runnables.
    if (mRunQueue != null) {
        mRunQueue.executeActions(info.mHandler);
        mRunQueue = null;
    }
    performCollectViewAttributes(mAttachInfo, visibility);
    onAttachedToWindow();

    ......
    ......
}

       在dispatchAttachedToWindow()内部主要执行了两件事:
       1.对mAttachInfo进行赋值,也就是说:如果没有执行dispatchAttachedToWindow(),那么mAttachInfo为空,post()内部也就不会执行分支1;
       2.执行HandlerActionQueue的executeActions()方法来执行runnable;
       那么接下来需要分析dispatchAttachedToWindow()是在什么地方被调用的?熟悉View绘制流程可以参考之前写的一篇文章Android Activity 显示详解,可以清楚的看到在ViewRootImpl内部会执行dispatchAttachedToWindow(),再一起看一下:

c.ViewRootImpl.java

       先看一下ViewRootImpl的创建,即ViewRootImpl的构造方法,此处只分析跟View.post()相关的知识点:

public ViewRootImpl(Context context, Display display) {
    .......
    .......
    mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this,
                context);
    .....
    mChoreographer = Choreographer.getInstance();
    ......
}

       可以看到,在ViewRootImpl的构造方法内部,创建了AttachInfo对象和Choreographer实例(执行绘制流程Runnable)。AttachInfo传入了mHandler,后续的任务执行都是通过该Handler,简单看一下mHandler的创建:

final ViewRootHandler mHandler = new ViewRootHandler();
final class ViewRootHandler extends Handler {
}

       该Handler是使用的是默认的Looper,即主线程的Looper,因此该Handler进行的消息处理是工作在主线程。
       然后根据绘制的流程,一步一步的最终执行到熟悉的performTraversals()方法:

private void performTraversals() {
    final View host = mView;
    ......
    ......
    host.dispatchAttachedToWindow(mAttachInfo, 0);
    ......
    //Measure()
    //Layout()
    //Draw()
    ......
}

       在performTraversals()内部执行了host的dispatchAttachedToWindow()方法,将创建的AttachInfo对象作为参数传入,该host是ViewGroup(setContentView加载的LayoutID),看一下ViewGroup内dispatchAttachedToWindow()的执行逻辑:

@Override
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
    .....
    super.dispatchAttachedToWindow(info, visibility);
    .....

    final int count = mChildrenCount;
    final View[] children = mChildren;
    for (int i = 0; i < count; i++) {
        final View child = children[i];
        child.dispatchAttachedToWindow(info,
                    combineVisibility(visibility, child.getVisibility()));
    }
    ......
}

       可以看到,在ViewGroup内部的dispatchAttachedToWindow()会遍历子View,来执行子View的dispatchAttachedToWindow()方法,前面分析到,在View的dispatchAttachedToWindow()内部执行了AttachInfo对象的赋值操作,所有的子View共用一个AttachInfo对象。
       开始看到这里有一点疑惑:明明是先调用的 dispatchAttachedToWindow() ,再进行的Measure()、Layout()、Draw(),为什么 dispatchAttachedToWindow() 中可以获取到View的宽高呢?
       performTraversals()是在主线程消息队列的一次消息处理过程中执行的,而dispatchAttachedToWindow()间接调用的mRunQueue.executeActions() 发送的任务也是通过Handler发送到主线程消息队列的,由于Handler执行的有序性,那么它的执行就一定在这次的performTraversals()方法执行完之后,因此在post()里面是可以获取View的宽高的。

简单总结

       执行View.post()后,根据AttachInfo是否为空,即ViewRootImpl是否已经创建,View.post() 会执行不同的逻辑:
       分支1:ViewRootImpl 已经创建,即mAttachInfo已经初始化,直接通过Handler发送消息来执行任务。
       分支2:ViewRootImpl 未创建,即View尚未开始绘制,会将任务保存为 HandlerAction,暂存在HandlerActionQueue 中,等到View开始绘制,执行 performTraversal() 方法时,在 dispatchAttachedToWindow() 方法中通过Handler分发执行HandlerActionQueue中暂存的任务。

流程图如下:
image.png

三. 问题延伸

       通过上面的分析,我们可以看到,在执行View.post()后,如果AttachInfo没有创建,则会先加入HandlerActionQueue中,不会立刻执行,需要等View绘制完成才能执行post(),结合View的绘制流程,会有以下延伸问题:

a.为什么onCreate()使用view.post()无法立刻执行任务?

       还是从View绘制原理出发,View的绘制是在onResume()后进行绘制的,在onCreate()时,View还未进行绘制,所以AttachInfo也就没有被创建,那么就只能将起放入队列里面,后续等绘制完成后才能执行任务。

b.若只是创建一个 View,调用它的post(),那么post的任务会不会被执行?
View view = new View(this);
view.post(new Runnable() {
    @Override
    public void run() {
        //...................
    }
});

       还是从View绘制原理出发,不会。每个View中post() 需执行的任务,必须得添加到窗口视图--->执行绘制流程,任务才会被post到消息队列里去等待执行,即依赖于dispatchAttachedToWindow ();
       若View未添加到窗口视图,那么就不会走绘制流程,post() 添加的任务最终不会被post到消息队列里,即得不到执行。(但会保存到HandlerAction数组里)
       上述例子,因为它没有被添加到窗口视图,所以不会走绘制流程,所以该任务最终不会被post到消息队列里执行,执行addView(view)就可以进行绘制然后post()任务就可以执行了。

c.View.pos()传入的任务被执行的有效期

       通过post()代码可以看到,只要attachInfo对象不为空,那么任务就会被执行,attachInfo赋值是在dispatchAttachedToWindow(),那么置空是在什么地方呢?

void dispatchDetachedFromWindow() {
    AttachInfo info = mAttachInfo;
    if (info != null) {
        int vis = info.mWindowVisibility;
        if (vis != GONE) {
            onWindowVisibilityChanged(GONE);
            ......
        }
    }

    onDetachedFromWindow();
    onDetachedFromWindowInternal();

    .......

    mAttachInfo = null;
    .....
}

       通过分析源码知道,Activity在执行Destroy()后的执行流程如下:


image.png

       通过以上可以看到:View.post() 任务被执行的有效期是在 Activity 生命周期 onDestory()后。

以上就是对View.post()执行原理及延伸问题的分析!

       感谢该文章https://www.jianshu.com/p/e2a8cd384eda作者的分析。

上一篇 下一篇

猜你喜欢

热点阅读