美文网首页Activity Android
从Activity的创建到View的测量绘制

从Activity的创建到View的测量绘制

作者: 慕尼黑凌晨四点 | 来源:发表于2022-02-25 23:19 被阅读0次

    Activityの生成

    ActivityThread类中有个handleLaunchActivity方法。

    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent){
        ...
        final Activity a = performLaunchActivity(r, customIntent);
        return a;
    } 
    

    Activity对象便是在这个方法中通过反射创建了。该方法内部紧接着又调用了activity.attach方法,以及callActivityOnCreate方法

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            // 内部实现
            // Class.forName(className, false, cl).asSubclass(Activity.class)
            //       .getDeclaredConstructor().newInstance();
            activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
            //
        }
        ...
        activity.attach(appContext, this, getInstrumentation(), r.token,
                            r.ident, app, r.intent, r.activityInfo, title, r.parent,
                            r.embeddedID, r.lastNonConfigurationInstances, config,
                            r.referrer, r.voiceInteractor, window, r.configCallback,
                            r.assistToken);
        ...
        //显然下面这个方法是奔着activity.onCreate()去的。
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
        } else {
            mInstrumentation.callActivityOnCreate(activity, r.state);
        }
        return activity;
    }
    

    Activity.attach()中创建了mWindow和mWindowManager两个对象。其中mWindow是PhoneWindow()。

    final void attach(Context context, ...){
        mWindow = new PhoneWindow(this, window, activityConfigCallback);
        mWindow.setCallback(this);
        ...
        mWindow.setWindowManager(
                    (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                    mToken, mComponent.flattenToString(),
                    (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
        mWindowManager = mWindow.getWindowManager();
        ...
    }
    

    SetWindowManager的中告诉我们mWindowManager实现类是WindowManagerImpl

    public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
            boolean hardwareAccelerated) {
        mAppToken = appToken;
        mAppName = appName;
        mHardwareAccelerated = hardwareAccelerated;
        if (wm == null) {
            wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        }
        mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
    }
    

    Activity关联布局

    在onCreate的方法中,我们一般会setContentView。而setContentView内部是用的window.setContentView()。所以可以直接看PhoneWindow的setContentView方法;

    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }
    
    @Override
    public void setContentView(int layoutResID) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        if (mContentParent == null) {
            //内部做了3件事:
            //new DecorView()并添加布局
            //mContentParent = findViewById(R.id.content)
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }
    
        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
            //把layoutResId inflate到mContentParent上去
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }
    

    installDecor中为我们生成了一个DecorView,也就是所有Activity的顶层Veiw。【DecorView继承自FramLayout】

    private void installDecor() {
        if (mDecor == null) {
            mDecor = generateDecor(-1);
        } else {
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {
            //generateLayout中为mDecor选定一个布局(根据feature)并addView上去
            //并返回这个布局的ID为R.id.content的ViewGroup--findViewById(ID_ANDROID_CONTENT)
            mContentParent = generateLayout(mDecor);
        }
        ...
    }
    

    为顶层Decor添加parent

    然后跟着生命周期走到了ActivityThread.handleResumeActivity()方法:

    public void handleResumeActivity(...){
        //间接调用Activity.onResume
        final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        ...
        final Activity a = r.activity;
        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            decor.setVisibility(View.INVISIBLE);
            ViewManager wm = a.getWindowManager();
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            ...
            //重点在这
            wm.addView(decor, l);
        }
        ...
    }
    

    windowManager就是第一步里面我加粗了的那个对象。windowManagerImpl

    private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
    @Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow,
                mContext.getUserId());
    }
    

    所以直接开WindowManagerGlobal.addView():这里传入的view就是decorView,也就是Activity顶层View。

    public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow, int userId) {
        ViewRootImpl root =  new ViewRootImpl(view.getContext(), display);
        ...
        //decor成了root(ViewRootImpl)的子view;
        //想点进去看的话可以进去后找 view.assignParent(this);方法
        root.setView(view, wparams, panelParentView, userId);
    }
    

    至此,ViewRootImpl就成了所有view的祖宗view了。

    view绘制三部曲(之旅)

    如果读者还有兴致,可以点开root.setView方法,方法中在assignParent之前有一行:

    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView,
                int userId) {
        synchronized (this) {
            ...
            requestLayout();
            ...
            view.assignParent(this);
            ...  
        } 
    }
    
    @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }
    
    void checkThread() {
        //著名的线程检查的地方,流传多年的名句“子线程不能更新UI”的判断就在这里。
        //其实按上面的逻辑,root(也就是ViewRootImpl)在resume之前还未成为decorView的parent,所以可以推理出:
        //在onResume之前,其实是可以子线程更新UI的,感兴趣的可以试一试。
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                "Only the original thread that created a view hierarchy can touch its views.");
        }
    }
    

    这里的requestLayout就是整个View Tree第一次开始绘制的地方了。scheduleTraversals方法也在ViewRootImpl类中:

    
    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }
    
    final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
    
    void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
    
            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }
    
            performTraversals();
    
            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }
    
    //默认的super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    public final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
    private void performTraversals() {
        ...
        WindowManager.LayoutParams lp = mWindowAttributes;
        int desiredWindowWidth;
        int desiredWindowHeight;
        ...
        Rect frame = mWinFrame;//屏幕大小
        if (mFirst) {
            ...
            if (...) {
                ...
            } else {
                //宽高默认为屏幕大小
                desiredWindowWidth = frame.width();
                desiredWindowHeight = frame.height();
            }
            ...
            //把mAttachInfo向下传个子view,所以子view中的mAttachInfo,都是ViewRootImpl中的mAttachInfo。
            //view.post()中其实就是用到的mAttachInfo.mHandler,这个mHandler就是ViewRootImpl构造时new的。
            host.dispatchAttachedToWindow(mAttachInfo, 0);
            mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
            //状态栏和导航栏在下面这个方法设置
            dispatchApplyInsets(host);
        }
        ...
        //view.post如果在resume之前执行,由于viewRootImpl还未成为decor的parent,所以拿不到mHandler,所以就会存到队列中,此时再执行
        getRunQueue().executeActions(mAttachInfo.mHandler);
        if (layoutRequested) {
            ...
            // Ask host how big it wants to be
            windowSizeMayChange |= measureHierarchy(host, lp, res,
                  desiredWindowWidth, desiredWindowHeight);
        }
        ...
        performLayout(lp, mWidth, mHeight);
        mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
        ...
        boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() || !isViewVisible;
        performDraw()
        
    }
    

    measureHierarchy也在该类下:

    private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
                final Resources res, final int desiredWindowWidth, final int desiredWindowHeight){
        boolean goodMeasure = false;
        if (!goodMeasure) {
            childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
            childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
            if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
                windowSizeMayChange = true;
            }
        }    
        ...
    }
    
    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {
    
            case ViewGroup.LayoutParams.MATCH_PARENT:
                // Window can't resize. Force root view to be windowSize.
                measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
                break;
            case ViewGroup.LayoutParams.WRAP_CONTENT:
                // Window can resize. Set max size for root view.
                measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
                break;
            default:
                // Window wants to be an exact size. Force root view to be that size.
                measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
                break;
        }
        return measureSpec;
    }
    
    
    private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
        if (mView == null) {
            return;
        }
        //mview也就是viewRootImpl
        mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }
    

    到这里,decor开始它的测量,由此遍历整颗view Tree。

    相关文章

      网友评论

        本文标题:从Activity的创建到View的测量绘制

        本文链接:https://www.haomeiwen.com/subject/fawfrrtx.html