美文网首页
创建应用窗口过程

创建应用窗口过程

作者: 刘佳阔 | 来源:发表于2017-12-22 21:55 被阅读0次
    window类关系图

    1.每个窗口都对应一个Activity对象,所以创建应用窗口首先是创建Activity.而启动Activity的任务由ActivityThread完成,本质是构造一个Activity对象.当ActivityThread接受到Ams发送的启动Activity通知时,会创建指定的Activity对象,Activity创建PhoneWindow类--DecorView类--创建相应的View或ViewGroup.创建完成后,Activity把创建好的界面显示到屏幕上,于是调用WindowManager类,WindowManager创建ViewRoot类和ViewRoot的内部类W.之后WindowManager在调用Wms提供的远程接口完成窗口的添加并显示在屏幕上

    1. 代码入口是ActivityThread.performLaunchActivity
      private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
    
        Activity activity = null;
        try { //1.创建activity的对象,用classLoader从程序中装载指定Activity对应的Class文件
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
        } 
             //2.创建 系统application,appContext appContext本质是ContextImpl
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
             Context appContext = createBaseContextForActivity(r, activity);
             //3.为activity 配置内部变量.同时创建Window对象. this变量使Activity对象持有ActivityThread的引用.r 是ActivityClientRecord对象.
    r.token是一个Binder,是Ams中的一个HistoryRecord对象. r.parent是一个父Activity,这种理念是为了允许把Activity嵌入到另一个Activity内部执行,
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.voiceInteractor);
    
                int theme = r.activityInfo.getThemeResource(); //activity使用的主题
                if (theme != 0) {
                    activity.setTheme(theme);
                }
    
              //4 这里会调用Activity的onCreate方法.
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
    
                //调用 onstart
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
                //调用 onRestoreInstanceState
                if (!r.activity.mFinished) {
                    if (r.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                    r.persistentState);
                        }
                    } else if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
                //调用 onPostCreate
                if (!r.activity.mFinished) {
                    activity.mCalled = false;
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state, r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state);
                    }
                  
                }
            }
    
            //ArrayMap<IBinder, ActivityClientRecord>结构
            mActivities.put(r.token, r);
        return activity;
    }
    

    //2.接着看步骤1.3的Actdivity 的attacth方法

      //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, IVoiceInteractor voiceInteractor) {
        attachBaseContext(context); //新建的contextImpl赋值给mBase.
    
    
        //1.创建Window.其实是创建了Window的子类PhoneWindow
        mWindow = PolicyManager.makeNewWindow(this);
        mWindow.setCallback(this); //表示Activity实现的Window的所有回调函数
    
    
          //activity配置重要变量
        mUiThread = Thread.currentThread();
        mMainThread = aThread;  
        mInstrumentation = instr;
        mToken = token;   //Binder HistoryRecord类
        mApplication = application;
        mIntent = intent;
        mComponent = intent.getComponent();
        mActivityInfo = info;
        mTitle = title;
        mParent = parent; //activity
         
        //2.给每个window分配WindowManager,其实是WindowManagerImpl.每个Window都对应一个WindowManagerImpl对象,
    但WindowManger是一个重量级的类.他的真正实现是WindowManagerGlobal,而WindowManagerImpl只是一个装饰类,只是
    把功能交给WindowManagerGlobal来实现
        mWindow.setWindowManager(
                (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                mToken, mComponent.flattenToString(),
                (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
        if (mParent != null) {//如果有父activity,就把父acitivty的window赋值给本Activity的window的container变量.
            mWindow.setContainer(mParent.getWindow());
        }
        //activity 也持有WindowManager变量
        mWindowManager = mWindow.getWindowManager();
    }
    

    //3.接下来是步骤1.4的 mInstrumentation.callActivityOnCreate(activity, r.state);

    //1.Instrumentation类 他又调用Activity的performCreate方法
    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    } 
      //2.Activity 类 此时走到了onCreate ,我们会在onCreate中调用setContentView方法.接着看
    final void performCreate(Bundle icicle) {
        onCreate(icicle);
        mActivityTransitionState.readState(icicle);
        performCreateCommon();
      }
     //3.主要还是调用    getWindow().setContentView().而   getWindow()就是我们第一步生的Window类PhoneWindow对象.
     public void setContentView(View view, ViewGroup.LayoutParams params) {
        getWindow().setContentView(view, params);
        initWindowDecorActionBar();
      }
      //4.phoneWindow类
     @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
    
        if (mContentParent == null) {
            installDecor(); //5.初始化Decor,为Window创建界面.
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews(); 
        }
          //6.把要添加的view放在 mContentParent中.下边一个是有位移的添加方法,一个是直接添加.
      mContentParnet其实就是我们setcontView是的那个view.他的id就是R.id.content.
      我们平时定义的lauout.xml就成了mContentParnet 的子View
        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            view.setLayoutParams(params);
            final Scene newScene = new Scene(mContentParent, view);
            transitionTo(newScene);
        } else {
            mContentParent.addView(view, params);
        }
        //7.此时的callback就是2.1时创建Window时设置的回调.既Activity自己.
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged(); //调用activity的onContentChanged回调方法.
        }
    }
    

    //4.看3.5的installDecor()方法

     private void installDecor() {
        if (mDecor == null) {
            mDecor = generateDecor(); //1.创建一个DecorView.继承自FrameLayout,是窗口的最顶层View.
        }
        if (mContentParent == null) {
            //2.这是我们自定义View的父View.
            mContentParent = generateLayout(mDecor);
        }
            // Set up decor part of UI to ignore fitsSystemWindows if appropriate.
            mDecor.makeOptionalFitsSystemWindows();//设置view适配系统窗口
            //下边是根据设定的主题来设置标题栏样式.先不关注
            ...
     }
    

    //5.接着看 generateLayout()方法.

     protected ViewGroup generateLayout(DecorView decor) {//decor是刚创建的DecorView
        TypedArray a = getWindowStyle(); //1.指定Window样式
    
        //2.requestFeature()启用窗体的扩展特性,用户可调用这个方法更改window样式
        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);
        }
          ...
         //3.得到最终要使用的resource文件id.这个文件肯定包含一个id=content的FrameLayout,
        int layoutResource;
        int features = getLocalFeatures();
        mDecor.startChanging();
        //4.把该resource文件添加到Decorview里.它是DevorView的唯一view,同时赋值给变量mContentRoot
        View in = mLayoutInflater.inflate(layoutResource, null);
        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        mContentRoot = (ViewGroup) in;
        //5.contentParent是mContentRoot的子view
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        if (contentParent == null) {
            throw new RuntimeException("Window couldn't find content container view");
        }
        mDecor.finishChanging();
    
        return contentParent; 
    }
    

    //6.这样.window的窗口元素就设置完成,接下来通知Wms创建窗口.首先是Activity通知Ams,Ams处理完后调用Activity的makeVisible()方法,该方法和后续操作将把窗口真正添加进Wms中.

    //Activity类
     void makeVisible() {
        if (!mWindowAdded) {
            ViewManager wm = getWindowManager();//1.这里就是Activity内部的WindowManager类,具体其实是
    WindowManagerImpl类,然后会调用WindowManagerGlobal的addView方法.
            wm.addView(mDecor, getWindow().getAttributes());
            mWindowAdded = true;
        }
        mDecor.setVisibility(View.VISIBLE);
    }
    //2.接着看WindowManagerGlobal的addView
    //1.WindowMangerGlobal有三个变量.ArrayList<View> mViews 每个View都将成为Wms所认为的一个窗口.
    ArrayList<ViewRootImpl> mRoots 每个View都对应的一个ViewRootImpl对象,
    ArrayList<WindowManager.LayoutParams> mParams 每个View对应的参数,
    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) {
            // Start watching for system property changes.
            if (mSystemPropertyUpdater == null) {
                mSystemPropertyUpdater = new Runnable() {
                    @Override public void run() {
                        synchronized (mLock) {
                            for (int i = mRoots.size() - 1; i >= 0; --i) {
                                mRoots.get(i).loadSystemProperties(); //加载系统属性
                            }
                        }
                    }
                };
                SystemProperties.addChangeCallback(mSystemPropertyUpdater);
            }
    
            int index = findViewLocked(view, false); //2.如果该View已经添加过了.就不允许重复添加
            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.
            }
    
            // If this is a panel window, then find the window it is being
            // attached to for future reference.
            if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
                    wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
     //3.1000-1999之间,是子窗口,需要找他的父窗口保存在panelParentView变量中
                final int count = mViews.size();
                for (int i = 0; i < count; i++) {
                    if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
                        panelParentView = mViews.get(i);
                    }
                }
            }
         //4.生成ViewRootImpl.用来沟通Wms和View,
            root = new ViewRootImpl(view.getContext(), display);
            view.setLayoutParams(wparams);
         //5.把该view对应的变量添加到WindowManagerGlobal的三个对象中.
            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
        }
    
        // do this last because it fires off messages to start doing things
        try {
        //6.完成最后的真正意义的添加动作 view是要添加的窗口 wParams是窗口的参数LayoutParams,panelParentView表示该窗口的父窗口,可以为空
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
            throw e;
        }
    }
    

    //接下来看ViewRootImpl的setView方法

    public void setView(View view, WindowManager.LayoutParams attrs, View       panelParentView) {
        synchronized (this) {
            if (mView == null) {
                mView = view;
              //1.赋值attrs
              mWindowAttributes.copyFrom(attrs);
                if (mWindowAttributes.packageName == null) {
                    mWindowAttributes.packageName = mBasePackageName;
                }
                attrs = mWindowAttributes;
                //2.配置参数
                mSoftInputMode = attrs.softInputMode;
                mWindowAttributesChanged = true;
                mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED;
                mAttachInfo.mRootView = view;
                mAttachInfo.mScalingRequired = mTranslator != null;
                mAttachInfo.mApplicationScale =
                        mTranslator == null ? 1.0f : mTranslator.applicationScale;
            //3.如果有父窗口,把父窗口的token赋值给mAttachInfo
                if (panelParentView != null) {
                    mAttachInfo.mPanelParentWindowToken
                            = panelParentView.getApplicationWindowToken();
                }
                mAdded = true;
                int res; /* = WindowManagerImpl.ADD_OKAY; */
    
                // 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.
            //4.发出重绘请求,仅是发出一个异步请求,使Ui线程的下一个消息处理是界面重绘,使窗口在相应其他消息之前
            先变得可见
                requestLayout();
     
                try { //5.通知Wms添加窗口,mWindowSession是WindowManagerGlobla的一个镜头变量,每个应用程序仅有一个mWindowSession对象,类型为IWindowSession,是一个Binder引用,对应Wms中的Session子类,Wms为每个应用程序分配一个Session对象.
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mInputChannel);
                } catch (RemoteException {
                    throw new RuntimeException("Adding window failed", e);
                } 
        }
    

    至此,窗口的创建过程全部结束.
    最后总结一下.第一步.是在ActivityThread的performLaunchActivity方法通过反射创建Activity启动的对象,同时为Activity创建添加一个ContextImpl对象,调用Activity.attach方法,然后执行Activity的onCreate,onStart.第二步Activity.attach中,为该Acitivity创建一个PhoneWindow(继承自Window)对象,这是一个轻量的对象,其实内部是由WindowManagerGlobal实现具体操作.第三步.在执行Activity的onCreate过程中,为activity创建DecorView,这是每个activity的顶层view.他里边包含一个id为content的view.就是我们调用setContentView的父view,第四部,Activity的view设置完成后.Activity通知Ams,Ams处理完后调用Activity的makeVisible()方法,该方法和后续操作将把窗口真正添加进Wms中.此时wms为创建一个ViewRootImpl类,用来沟通wms和view.最后.ViewRootImpl在把view进行一些处理后,通知Wms添加窗口

    相关文章

      网友评论

          本文标题:创建应用窗口过程

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