Android 由setContentView探究Activity界面加載流程及Activity、Window和DecorView的關系

前言

當我們打開一個activity需要顯示內容的時候,只需要在onCreate方法中執行setContentView方法,一行代碼搞定,很簡單,有么有。但是,有沒有想過setConentView方法內部,執行了那些操作,Window、DecorView、ViewRootImpl是怎么回事,本文就來一步步分析其內部工作流程。源碼基于Android API 21。

Activity#setContentView

    public void setContentView(int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

    ...

    public Window getWindow() {
        return mWindow;
    }

可以看到,Activity#setContentView內部調用了mWindow中的setContentView方法,那這個mWindow是什么呢?可以看出它是Window類型的。先來看看mWindow是在哪里創建的,通過源碼可以發現在Activity#attach中對其進行了賦值操作(注:在Activity啟動過程中,會執行ActivityThread#performLaunchActivity方法,在這個方法中會調用Activity#attach方法)。

    final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, IVoiceInteractor voiceInteractor) {

        ...
        //在這里創建Activity所屬的Window對象并賦值給mWindow
        mWindow = PolicyManager.makeNewWindow(this);
        mWindow.setCallback(this);//Activity實現了Window的Callback接口,這里給Window注冊監聽
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            mWindow.setSoftInputMode(info.softInputMode);
        }
        if (info.uiOptions != 0) {
            mWindow.setUiOptions(info.uiOptions);
        }
        ...

創建Window并初始化DecorView

接著上文看下PolicyManager#makeNewWindow

    public static Window makeNewWindow(Context context) {
        // this will likely crash somewhere beyond so we log it.
        Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
                "Call to PolicyManager.makeNewWindow is not supported", null);
        return null;
    }

發現PolicyManager#makeNewWindow方法并沒有具體實現,并且PolicyManager中的方法全在接口IPolicy中聲明了。

public interface IPolicy {
    public Window makeNewWindow(Context context);

    public LayoutInflater makeNewLayoutInflater(Context context);

    public WindowManagerPolicy makeNewWindowManager();

    public FallbackEventHandler makeNewFallbackEventHandler(Context context);
}

其真正的實現是在Policy類中,如下:

    public Window makeNewWindow(Context context) {
        return new PhoneWindow(context);
    }

可以看到,最終是實例化了PhoneWindow,PhoneWindow是Window的唯一子類。
至此,Window的創建過程就結束了,接著看PhoneWindow#setContentView方法。

    @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.

        //重點在這里,mContentParent為null,執行installDecor方法。
        if (mContentParent == null) {
            installDecor();//初始化DecorView
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
            //這個方法內部會把我們的布局文件的內容添加mContentParent中。
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();//執行回調
        }
    }

這個方法中主要兩個工作:1. 如果mContentParent為null,則執行installDecor方法,即初始化DecorView;2. 通過mLayoutInflater.inflate(layoutResID, mContentParent將我們的布局內部添加到mContentParent;3. 當屏幕的內容發生改變時,執行回調方法onContentChanged。那么這個mContentParent是指什么呢?這里先保留疑問,我們接下來就會解釋。來看下installDecor方法做了什么工作。

private void installDecor() {
        //如果DecorView為null,則創建DecorView
        if (mDecor == null) {
            mDecor = generateDecor();
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        }

        ...

        if (mContentParent == null) {
            初始化DecorView的布局結構,獲取mContentParent并返回。
            mContentParent = generateLayout(mDecor);
            ...
        } 

        ...

    }
    protected DecorView generateDecor() {
        return new DecorView(getContext(), -1);
    }
protected ViewGroup generateLayout(DecorView decor) {
        // Apply data from current theme.
      
        TypedArray a = getWindowStyle();
        ...
        //獲取一堆主題中設置的屬性進行相關設置(好長一堆~~)
        if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
            requestFeature(FEATURE_NO_TITLE);
        } else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
            // Don't allow an action bar if there is no title.
            requestFeature(FEATURE_ACTION_BAR);
        }

        if (...) {
            ...
        }
        ...
     
        // Inflate the window decor.
        //根據不同的窗口特征,layoutResource對應不同的布局文件,用來填充DecorView(又是很長一堆~~)。
        int layoutResource;
        int features = getLocalFeatures();
        // System.out.println("Features: 0x" + Integer.toHexString(features));
        if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
            layoutResource = R.layout.screen_swipe_dismiss;
        } else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogTitleIconsDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else {
                layoutResource = R.layout.screen_title_icons;
            }
            // XXX Remove this once action bar supports these features.
            removeFeature(FEATURE_ACTION_BAR);
            // System.out.println("Title Icons!");
        } 
        
        ...
        
        //重點在這里
        //把對應的布局文件填充并加載到DecorView,初始化DecorView的結構
        View in = mLayoutInflater.inflate(layoutResource, null);
        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        mContentRoot = (ViewGroup) in;
        //看到contentParent了吧,它對應了DecorView中id為com.android.internal.R.id.content的ViewGroup。
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        if (contentParent == null) {
            throw new RuntimeException("Window couldn't find content container view");
        }
        ...

        return contentParent;
    }

這個主要做了三件事:1.根據主題中屬性進行一些相關設置2.根據不同的窗口特征,獲取對應的布局文件,用來初始化DecorView的布局結構。3.獲取contentParent,contentParent對應了DecorView布局文件中id為com.android.internal.R.id.content的ViewGroup,它其實是一個FrameLayout。如圖所示:

DecorView結構圖.png

再回到上文PhoneWindow#setContentView方法中,當獲取到mContentParent后,還會執行mLayoutInflater.inflate(layoutResID, mContentParent)將我們寫的xml布局文件加載到mContentParent,至于加載細節我們這里就不做分析了。

小結:至此,我們已經實例化了Window,初始化了DecorView布局結構,并且把我們布局文件加載到了mContentParent中。不過DecorView并沒有顯示出來,因為View并不能單獨存在,必須依附于Window。

在Activity在啟動流程中(Activity的啟動流程很復雜,我們這里不做具體分析),當執行了ActivityThread#performLaunchActivity方法后還會執行ActivityThread#handleResumeActivity方法,在這個方法中首先會調用Activity的onResume方法,接著調用Activity的makeVisible方法。

    void makeVisible() {
        if (!mWindowAdded) {
            ViewManager wm = getWindowManager();//獲取WindowManager
            wm.addView(mDecor, getWindow().getAttributes());//通過WindowManager完成Window的添加過程
            mWindowAdded = true;
        }
        mDecor.setVisibility(View.VISIBLE);//讓DecorView可見
    }

此方法將完成Window的添加過程,以及讓DecorView顯示出來,至此Activity界面加載流程就結束了

將DecorView添加到Window

接著上文,看看DecorView是如何添加到Window中的。Window其實是個抽象的概念,它并不是一個實體。我們可以把Window理解成一種抽象的功能集合,每個Window都關聯一個View和ViewRootImpl。

public interface ViewManager
{   
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}

發現ViewManager是一個接口,WindowManager繼承了ViewManager,也是一個接口。看它的實現類WindowManagerImpl中的addView方法。

    @Override
    public void addView(View view, ViewGroup.LayoutParams params) {
        mGlobal.addView(view, params, mDisplay, mParentWindow);
    }

發現WindowManagerImpl#addView并沒有實現具體細節,而是交給了WindowManagerGlobal中的addView去處理。

public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        ...

        ViewRootImpl root;

        synchronized (mLock) {
            ...
            //實例化ViewRootImpl,它是WindowManager和DecorView的紐帶
            root = new ViewRootImpl(view.getContext(), display);

            view.setLayoutParams(wparams);

            mViews.add(view);//保存所有Window對應的View
            mRoots.add(root);//保存所有Window對應的ViewRootImpl
            mParams.add(wparams);//保存所有Window對應的布局參數
        }

        // do this last because it fires off messages to start doing things
        try {
            //重點是這個方法 開始出發消息做事情
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
            // BadTokenException or InvalidDisplayException, clean up.
            synchronized (mLock) {
                final int index = findViewLocked(view, false);
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
            }
            throw e;
        }
    }

我們接著來看ViewRootImpl#setView方法

/**
     * We have one child
     */
    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
                mView = view;
                ...//省略一大波代碼
                // Schedule the first layout -before- adding to the window
                // manager, to make sure we do the relayout before receiving
                // any other events from the system.
                //內部最終會調用performTraversals方法開啟View的繪制流程。
                requestLayout();
                if ((mWindowAttributes.inputFeatures
                        & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
                    mInputChannel = new InputChannel();
                }
                try {
                    mOrigWindowType = mWindowAttributes.type;
                    mAttachInfo.mRecomputeGlobalAttributes = true;
                    collectViewAttributes();
                    //通過IWindowSession來完成Window的添加過程
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mInputChannel);
                } catch (RemoteException e) {
                    mAdded = false;
                    mView = null;
                    mAttachInfo.mRootView = null;
                    mInputChannel = null;
                    mFallbackEventHandler.setView(null);
                    unscheduleTraversals();
                    setAccessibilityFocus(null, null);
                    throw new RuntimeException("Adding window failed", e);
                } finally {
                    if (restore) {
                        attrs.restore();
                    }
                }
                ...//省略一大波代碼
         }

這個方法很長,我們只看與本文主流程相關部分。有兩個重要的地方。

  1. 通過requestLayout方法開啟頂級View的測繪。
    @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }
    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
        }
    }

    final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
    void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);

            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }

            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals");
            try {
                performTraversals();
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }
    private void performTraversals() {
            ...
            //執行測量
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
            ...
            //執行布局
            performLayout(lp, desiredWindowWidth, desiredWindowHeight);
            ...
            //執行繪制
            performDraw();
    }

performTraversals方法依次會執行performMeasureperformLayout以及performDraw來完成對頂級View的測量、布局、繪制。performMeasure方法中會調用measure方法,measure方法中又會調用onMeasure方法,在onMeasure方法中會完成子View的measure過程,measure過程就從父View傳到了子View。子View又會重復父View的動作,如此反復,就完成了整個View樹的測量過程。performLayout以及performDraw方法與performMeasure類似。可以說View的三大工作流程是performTraversals開始的

  1. 通過WindowSession完成window的添加過程。

先來看下mWindowSession的創建過程

   public ViewRootImpl(Context context, Display display) {
        mWindowSession = WindowManagerGlobal.getWindowSession();//獲取WindowSession
   }
public static IWindowSession getWindowSession() {
        synchronized (WindowManagerGlobal.class) {
            if (sWindowSession == null) {
                try {
                    InputMethodManager imm = InputMethodManager.getInstance();
                    IWindowManager windowManager = getWindowManagerService();
                    sWindowSession = windowManager.openSession(
                            new IWindowSessionCallback.Stub() {
                                @Override
                                public void onAnimatorScaleChanged(float scale) {
                                    ValueAnimator.setDurationScale(scale);
                                }
                            },
                            imm.getClient(), imm.getInputContext());
                    ValueAnimator.setDurationScale(windowManager.getCurrentAnimatorScale());
                } catch (RemoteException e) {
                    Log.e(TAG, "Failed to open window session", e);
                }
            }
            return sWindowSession;
        }
    }

    public static IWindowManager getWindowManagerService() {
        synchronized (WindowManagerGlobal.class) {
            if (sWindowManagerService == null) {
                sWindowManagerService = IWindowManager.Stub.asInterface(
                        ServiceManager.getService("window"));
            }
            return sWindowManagerService;
        }
    }

mWindowSession類型是IWindowManager,它是一個Binder對象,可見Window的添加過程是個IPC過程。

openSession方法是在WindowManagerService具體實現的

    public IWindowSession openSession(IWindowSessionCallback callback, IInputMethodClient client,
            IInputContext inputContext) {
        if (client == null) throw new IllegalArgumentException("null client");
        if (inputContext == null) throw new IllegalArgumentException("null inputContext");
        Session session = new Session(this, callback, client, inputContext);
        return session;
    }

在WindowManagerService#openSession實例化了Session并返回。Session是IWindowSession的實現類。addToDisplay方法也是在Session中具體實現的。

    @Override
    public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
            int viewVisibility, int displayId, Rect outContentInsets,
            InputChannel outInputChannel) {
        return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId,
                outContentInsets, outInputChannel);
    }

在這個方法內部又調用了WindowManagerService#addWindow方法,最終完成了Window的添加過程。其具體細節不再說了。。。

希望能對您有所幫助,若文中有錯誤或表述不當的地方還望指出,互相交流,共同成長!

相關文章:
Android View 測量流程(Measure)源碼解析
Android View 布局流程(Layout)源碼解析
Android View 繪制流程(Draw)源碼解析

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容