Activity的Window创建过程

来源:互联网 发布:淘宝卖家学院光云科技 编辑:程序博客网 时间:2024/05/01 11:29

Activity的Window创建过程

在 Adroid 中 Window 表示一个窗口的概念,任何能展示的视图都必须是挂载于 Window 上的,例如 Activity,Toast,Dialog,PopupWindow 等控件都有承载展示给用户的视图的 Window。而 Window 是一个抽线类,它的直接子类是 PhoneWindow。Window 可以接受事件,例如触摸事件,键盘的响应事件等。在事件传递机制就是将事件首先传递给 Window,然后再由 Window 传递给挂载在 Window 中的 DecorView 中,之后再传递到对应的 View 上。除此之后,在 Activity#setContentView(layoutId) 内部也是去调用 PhoneWindow#setContentView(layoutId) 去实现。

1、 从 setContentView(layoutId)了解 Activity 中 window的创建

1.1、 setContentView(layoutId)

public void setContentView(@LayoutRes int layoutResID) {    //getWindow 就是 activity 对应的 Window 的子类 PhoneWindow    getWindow().setContentView(layoutResID);    initWindowDecorActionBar();}

1.2、 Window 是在哪里实例化?

getWindow() 就是 Activity 所依赖的 Window对象,而它是在哪里创建呢?查看源码,可以知道 PhoneWindow 就是在 Activity#attach() 中被调用的。在这个方法主要做的事是:(1)创建 PhoneWindow 对象 ;(2) 设置事件监听,接受触摸事件,键盘输入等事件;(3)给 activity 的成员变量赋值。而 attach() 方法它是在 ActivityThread#performLaunchActivity() 方法中调用,这里涉及到 Activity 的生命周期的分析 ,这里不是讨论的终重点,先行跳过。现在呢,我们就知道了 activity 中的 window 在哪里创建的了。

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, String referrer, IVoiceInteractor voiceInteractor) {        attachBaseContext(context);        mFragments.attachHost(null /*parent*/);        mWindow = new PhoneWindow(this);//(1)创建 PhoneWindow 对象        mWindow.setCallback(this);// (2)设置事件监听器        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);        }        // (3)activity 成员变量的赋值        mUiThread = Thread.currentThread();        mMainThread = aThread;        mInstrumentation = instr;        mToken = token;        mIdent = ident;        mApplication = application;        mIntent = intent;        mReferrer = referrer;        mComponent = intent.getComponent();        mActivityInfo = info;        mTitle = title;        mParent = parent;        mEmbeddedID = id;        mLastNonConfigurationInstances = lastNonConfigurationInstances;        if (voiceInteractor != null) {            if (lastNonConfigurationInstances != null) {                mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;            } else {                mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,                        Looper.myLooper());            }        }        mWindow.setWindowManager(                (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),                mToken, mComponent.flattenToString(),                (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);        if (mParent != null) {            mWindow.setContainer(mParent.getWindow());        }        mWindowManager = mWindow.getWindowManager();        mCurrentConfig = config;    }

1.2、 继续了解 PhoneWindow#setContentView(layoutId)

在浏览源码之前,需要了解几个概念

  • DecorView 就是 Activity 的根视图,它是一个 FrameLayout 视图。有标题栏和内容栏,不过不同版本可能有差异。
  • mParentContent 就是 DecorView 的直接子 View,它是 Decor 的内容栏。它有指定的 id :android.R.id.content,通过 setContentView(layoutId) 的 layoutId 对应的 View 就是挂载在 mContentParent 上的。

初次调用时先检测 mContentParent 是否为 null,当该值为 null 时,就去 generateDecor() 装载一个根视图 Decor。然后调用 mContentParent.addView(view, params) 往 mContentParent 挂载 setContentView(layoutId) 对应的 View。

@Overridepublic void setContentView(View view, ViewGroup.LayoutParams params) {    // 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) {//mContentParent 就是 DecorView 中的一级子View        installDecor();//装载一个 Activity 的根视图    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {        mContentParent.removeAllViews();    }    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {        view.setLayoutParams(params);        final Scene newScene = new Scene(mContentParent, view);        transitionTo(newScene);    } else {        mContentParent.addView(view, params);// 往 mContentParent 挂载 setContentView(layoutId) 对应的 View。    }    mContentParent.requestApplyInsets();}private void installDecor() {    if (mDecor == null) {        mDecor = generateDecor(); // 创建 Activity 的根视图        ...    }    if (mContentParent == null) {        mContentParent = generateLayout(mDecor); //给 mContentParent 赋值        ...    }}//将内容栏添加到 Decor 中protected ViewGroup generateLayout(DecorView decor) {    ...    View in = mLayoutInflater.inflate(layoutResource, null);    decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));    ...}

1.3、 Activity 中的 onContentChanged()方法通知 Activity 视图发生了改变

当 Decor 初始化完毕之后,会通过在 Callback#onContentChanged(),表示 Decor 已经完成初始化操作.这个 Callback 就是在 Activity#attach() 方法设置的,因为在 Activity 中实现了 Callback 接口,因此该方法会回调到 Activity 中的 onContentChanged()方法中,不过这个方法是空实现,用户可已重写该方法。

final Callback cb = getCallback();// 在 DecorView 初始化完毕之后的回调 onContentChanged()方法。if (cb != null && !isDestroyed()) {    cb.onContentChanged();}

1.4、 往 Window 添加 DecorView

现在 Window 创建好了,对应的 DecorView 也初始完毕了,接下来就是发挥 WindowManager 的作用了,那就是往 Window 中添加 DecorView了。在这个过程涉及到 Activity 的生命周期的回调,我们这里暂且跳过,直接切入 Window 添加 DecorView 的源码。

1.4.1、 ActivityThread#handleResumeActivity

Activity 的生命周期的回调是一个 IPC 过程,在 ActivityThread#handleResumeActivity() 就是负责 Activity#onResume() 生命周期的回调。在 handleResumeActivity 方法内部调用 wm.addView(decor, l); 将 DecorView 添加到 Activity 对应的 Window 中。这个过程实际上是有 WindowManager 去完成的,每一 Window 都会对应一个 WindowManager,通过 WindowManager 去往 Window 中 addView,removeView或者是 updateViewLayout 操作。

//#handleResumeActivity 代码片段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);//设置 DecorView 不可见    ViewManager wm = a.getWindowManager();    WindowManager.LayoutParams l = r.window.getAttributes();    a.mDecor = decor;    l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;    l.softInputMode |= forwardBit;    if (a.mVisibleFromClient) {        a.mWindowAdded = true;        wm.addView(decor, l);//往 Window 添加 View    }} 

1.4.2、 Wm.addView 的过程

WindowManager 是一个接口,因此 addView 的操作是有其子 View 去实现的,那么它的子 View 是谁呢?下面的代码可以看到 WindowManager 的实现类就是 WindowManagerImpl。

public final class WindowManagerImpl implements WindowManager {}

1.4.3、 WindowManagerImpl.addView 的过程

WindowManagerImpl#addView 的操作都是交给 WindowManagerGlobal 的类去执行。

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

1.4.4、 WindowManagerGlobal.addView 的过程

WindowManagerGlobal 是单例的方式提供对象的,内部维护了 mView,mRoots,mParams,mDyingViews 等集合。

  • mViews 保存的就是添加到 Window 中的 View 对象。
  • mRoots 保存的就是 每一个 Window 对应的 ViewRootImpl 对象。
  • mDyingViews 保存的是哪些调用了 removeView 但是删除操作还未完成的 Window 对象对应的 View。
  • mParams 保存的是每一个 Window 的布局参数。
// 懒汉式单例模式public static WindowManagerGlobal getInstance() {    synchronized (WindowManagerGlobal.class) {        if (sDefaultWindowManager == null) {            sDefaultWindowManager = new WindowManagerGlobal();        }        return sDefaultWindowManager;    }}

在 addView 中创建 Window 对应的 ViewRootImpl 对象。并且往mViews,mRoots,mParams,mDyingViews 中保存当前 View 的信息。
最后调用 root.setView(view, wparams, panelParentView);

public void addView(View view, ViewGroup.LayoutParams params,        Display display, Window parentWindow) {    //校验操作    final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;    ViewRootImpl root;    View panelParentView = null;    synchronized (mLock) {        int index = findViewLocked(view, false);        if (index >= 0) {            if (mDyingViews.contains(view)) {                // Don't wait for MSG_DIE to make it's way through root's queue.                mRoots.get(index).doDie();            } else {                throw new IllegalStateException("View " + view                        + " has already been added to the window manager.");            }            // The previous removeView() had not completed executing. Now it has.        }        //创建 ViewRootImpl 对象。        root = new ViewRootImpl(view.getContext(), display);        view.setLayoutParams(wparams);        //保存到集合中        mViews.add(view);        mRoots.add(root);        mParams.add(wparams);    }    // 调用 View 的绘制代码    root.setView(view, wparams, panelParentView);}

1.4.5、DecorView 真正显示过出来

现在 Window 对应的视图已经准备好了,但是该仍然是不可见的,接下来继续看ActivityThread#handleResumeActivity 代码。这时会去调用 Activity#makeVisible()方法。因为在 1.4.1、 ActivityThread#handleResumeActivity 中 DecorView 被设置为 invisible 因此在这时Decor 会被设置为 View.VISIBLE。至此 View 就真正的显示出来了。

//ActivityThread#handleResumeActivityr.activity.mVisibleFromServer = true;if (r.activity.mVisibleFromClient) {   r.activity.makeVisible();}//Activity#makeVisible()void makeVisible() {    if (!mWindowAdded) {//判断 DecorView 是否被添加到 Window 中        ViewManager wm = getWindowManager();        wm.addView(mDecor, getWindow().getAttributes());        mWindowAdded = true;    }    mDecor.setVisibility(View.VISIBLE);//让 View 设置为可见}
0 0