Window, WindowManager, WindowManagerService 的简单梳理(三)- Activiy 的 Window 的创建过程

Window, WindowManager, WindowManagerService 的简单梳理(一)

Window, WindowManager, WindowManagerService 的简单梳理(二)- Window 的添加过程

相比前面两篇,Activiy 的 Window 的创建过程要简单多了。大致有下面几个步骤:

  • PhoneWindow 的创建
    在 Activity 启动时,会通过 ActivityThread 的 performLaunchActivity() 启动对应 Activity。其中,就会调用 Activity 的 attach()方法。
    在 Activity 的 attach() 方法里面,可以看到创建了 PhoneWindow 对象。当然,PhoneWindow 并不是 WindowManagerService 添加的 Window,不是一个概念。关于 Window 的概念,见上面两篇文章。

     // Activity
     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,
             Window window) {
         attachBaseContext(context);
    
         mFragments.attachHost(null /*parent*/);
    
         mWindow = new PhoneWindow(this, window);
         mWindow.setWindowControllerCallback(this);
         mWindow.setCallback(this);
         mWindow.setOnWindowDismissedCallback(this);
         mWindow.getLayoutInflater().setPrivateFactory(this);
    
         ...
         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;
     }
    

    顺便一提,Activity 实现了 Window.Callback 接口。

    // Window
     public interface Callback {
         public boolean dispatchKeyEvent(KeyEvent event);
         public boolean dispatchKeyShortcutEvent(KeyEvent event);
         public boolean dispatchTouchEvent(MotionEvent event);
         public boolean dispatchTrackballEvent(MotionEvent event);
         public boolean dispatchGenericMotionEvent(MotionEvent event);
         public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event);
         public View onCreatePanelView(int featureId);
         public boolean onCreatePanelMenu(int featureId, Menu menu);
         public boolean onPreparePanel(int featureId, View view, Menu menu);
         public boolean onMenuOpened(int featureId, Menu menu);
         public boolean onMenuItemSelected(int featureId, MenuItem item);
         public void onWindowAttributesChanged(WindowManager.LayoutParams attrs);
         public void onContentChanged();
         public void onWindowFocusChanged(boolean hasFocus);
         public void onAttachedToWindow();
         public void onDetachedFromWindow();
         public void onPanelClosed(int featureId, Menu menu);
         public boolean onSearchRequested();
         public boolean onSearchRequested(SearchEvent searchEvent);
         public ActionMode onWindowStartingActionMode(ActionMode.Callback callback);
         public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type);
         public void onActionModeStarted(ActionMode mode);
         public void onActionModeFinished(ActionMode mode);
         default public void onProvideKeyboardShortcuts(
                 List<KeyboardShortcutGroup> data, @Nullable Menu menu, int deviceId) { };
    }
    
  • DecorView 的创建
    ActivityThread 的 performLaunchActivity() 调用 attach() 之后,会调用到 Activity 的 onCreate。众所周知,我们是在 onCreate 里面 setContentView 的。

    // Activity
     public void setContentView(@LayoutRes int layoutResID) {
         getWindow().setContentView(layoutResID);
         initWindowDecorActionBar();
     }
    

    还是进入了 PhoneWindow。
    然后在 PhoneWindow 的 installDecor 中,用 generateDecor 中创建了 DecorView mDecor;用 generateLayout 创建了 mContentParent。我们设置的 Activity 的布局就是最终加入 mContentParent 中进行显示。

    // PhoneWindow
        // This is the top-level view of the window, containing the window decor.
        private DecorView mDecor;
    
        // This is the view in which the window contents are placed. It is either
        // mDecor itself, or a child of mDecor where the contents go.
        ViewGroup mContentParent;
    
        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) {
             // 内部会初始化 mDecor 和 mContentParent
             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 {
             // 将设置的 Activity 的 Layout 添加到 mContentParent 上面
             mLayoutInflater.inflate(layoutResID, mContentParent);
         }
         mContentParent.requestApplyInsets();
         // 这里的 cb 就是 Activity attach() 的时候传入的 Activity 对象
         final Callback cb = getCallback();
         if (cb != null && !isDestroyed()) {
             cb.onContentChanged();
         }
         mContentParentExplicitlySet = true;
     }
    
        private void installDecor() {
            mForceDecorInstall = false;
            if (mDecor == null) {
                // 生成 mDecor
                mDecor = generateDecor(-1);
                mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
                mDecor.setIsRootNamespace(true);
                if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                    mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
                }
            } else {
                mDecor.setWindow(this);
            }
            if (mContentParent == null) {
                // 生成 mContentParent 
                mContentParent = generateLayout(mDecor);
    
                // Set up decor part of UI to ignore fitsSystemWindows if appropriate.
                mDecor.makeOptionalFitsSystemWindows();
    
                final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
                     R.id.decor_content_parent);
                ...
            }
        }
    
        protected DecorView generateDecor(int featureId) {
            // System process doesn't have application context and in that case we need to directly use
            // the context we have. Otherwise we want the application context, so we don't cling to the
            // activity.
            Context context;
            ...
            return new DecorView(context, featureId, this, getAttributes());
         }
    
        public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
    
        protected ViewGroup generateLayout(DecorView decor) {
            // Apply data from current theme.
            ...
            ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
            ...
            return contentParent;
        }
    
  • 添加 DecorView 到 WindowManager
    《Android 开发艺术探索》对于这个阶段说的很有道理,这个时候 DecorView 还没有被 WindowManager 识别,所以这个时候 Window 还无法提供具体功能,因为它还无法接收外界的输入信息。
    DecorView 是在 Activity 的 onResume 阶段添加到 WindowManager 的
    具体是在 ActivityThread 的 handleResumeActivity() 方法中触发了添加 DecorView 到 WindowManager 的代码调用,并且是在调用了 onResume() 方法之后
    所以我在 Activity 的 onStart() 和 onResume() 中做了测试:可以 get 到 DecorView,但是 DecorView 的 isAttachedToWindow() 返回的是 false。

    // ActivityThread 
        final void handleResumeActivity(IBinder token,
                boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
            ActivityClientRecord r = mActivities.get(token);
            if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) {
                return;
            }
            ...
            // TODO Push resumeArgs into the activity for consideration
            // performResumeActivity 会触发 Activity onResume 的调用
            r = performResumeActivity(token, clearHide, reason);
    
            if (r != null) {
                final Activity a = r.activity;
                ...
                // 下面这段代码就是将 DecorView 添加到 WindowManager
                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;
                    l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                    l.softInputMode |= forwardBit;
                    ...
                    if (a.mVisibleFromClient && !a.mWindowAdded) {
                        a.mWindowAdded = true;
                        wm.addView(decor, l);
                    }
    
                // If the window has already been added, but during resume
                // we started another activity, then don't yet make the
                // window visible.
                } else if (!willBeVisible) {
                    if (localLOGV) Slog.v(
                        TAG, "Launch " + r + " mStartedActivity set");
                    r.hideForNow = true;
                }
    
                ...
                // 代码中还有一个分支会调用到 Activity 的 makeVisible(),这里我就直接省略掉了。
               // 但是我们可以看一下 Activity 的 makeVisible() 方法的实现
        }
    
    // Activity
        void makeVisible() {
            if (!mWindowAdded) {
                ViewManager wm = getWindowManager();
                wm.addView(mDecor, getWindow().getAttributes());
                mWindowAdded = true;
            }
            mDecor.setVisibility(View.VISIBLE);
        }
    

可见,Activity 的显示,最终也是将一个 View 添加到 WindowManager 之中。只不过这里是 DecorView,但是接下来的方法和流程与 Window, WindowManager, WindowManagerService 的简单梳理(二)- Window 的添加过程 中介绍的相同。

不仅 Activity 如此,Dialog 和 Toast 最终也是将一个 View 添加到 WindowManager 中,最终实现自己的显示窗口的添加,以完成显示功能。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容