Android 中Activity、Window和View之间的关系

转载至http://blog.csdn.net/chujidiy/article/details/7820451

这篇文章主要会从源码的角度去分析,解析它们之间的关系。

我想大多数人,对于这3个东西的概念能区分,但是具体区别在哪却很难说出来。

我这里根据我个人的理解来讲讲我个人对这3个概念的理解。当然这里设计到通用的事件窗口模型等通用GUI设计,我这里就不打算讲了,纯粹从概念上来进行区分。

ActivityAndroid应用程序的载体,允许用户在其上创建一个用户界面,并且提供用户处理事件的API,如onKeyEventonTouchEvent等。并维护应用程序的生命周期(由于android应用程序的运行环境和其他操作系统不同,android的应用程序是运行在框架之内,所以他的应用程序不能当当从进程的级别去考虑,而更多是从概念上去考虑。android应用程序是由多个活动堆积而成,而各个活动又有其独立的生命周期)。Activity本身是个庞大的载体,可以理解成是应用程序的载体,如果没有Activityandroid应用程序将无法运行。也可以理解成android应用程序的入口。Acivity的实例对象由系统维护。系统服务ActivityManager负责维护Activity的实例对象,并根据运行状态维护其状态信息。

但在用户级别,程序员可能很愿意理解成为一个界面的载体。但仅仅是个载体,它本身并不负责任何绘制Activity的内部实现,实际上是创建了一个Window对象。Window是一个抽象类,它的具体是在
android_src_home/framework/policies/base/phone/com/android/internal/policy/impl目录下的PhoneWindow.java

当我们调用AcitivitysetContentView方法的时候实际上是调用的Window对象的setContentView方法,所以我们可以看出Activity中关于界面的绘制实际上全是交给Window对象来做的。绘制类图的话,可以看出Activity聚合了一个Window对象。

下面是PhoneWindow中的setContentView方法的实现:

@Override  

    public void setContentView(View view,    ViewGroup.LayoutParams params) {    //setContentView

        if (mContentParent == null) {  

            installDecor();  

        } else {  

            mContentParent.removeAllViews();  

        }  

        mContentParent.addView(view, params);  

        final Callback cb = getCallback();  

        if (cb != null) {  

            cb.onContentChanged();  

        }  

    }  

Window内部首先判断mContentParent是否为空,然后调用installDecor方法(安装装饰器),我们看看这个方法如何实现的

private void installDecor() {  

        if (mDecor == null) {  

            mDecor = generateDecor();  

            mDecor.setIsRootNamespace(true);  

        }  

        if (mContentParent == null) {  

            mContentParent = generateLayout(mDecor);  

            mTitleView = (TextView)findViewById(com.android.internal.R.id.title);  

            if (mTitleView != null) {  

                if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {  

                    View titleContainer = findViewById(com.android.internal.R.id.title_container);  

                    if (titleContainer != null) {  

                        titleContainer.setVisibility(View.GONE);  

                    } else {  

                        mTitleView.setVisibility(View.GONE);  

                    }  

                    if (mContentParent instanceof FrameLayout) {  

                        ((FrameLayout)mContentParent).setForeground(null);  

                    }  

                } else {  

                    mTitleView.setText(mTitle);  

                }  

            }  

        }  

    }  

在该方法中,首先创建一个DecorView,DecorView是一个扩张FrameLayout的类,是所有窗口的根View。我们在Activity中调用的setConctentView就是放到DecorView中了。这是我们类图的聚合关系如下:

Activity—>Window—>DecorView

这是我们得出这3个类之间最直接的一个关系。

我们详细分析一下,类对象是如何被创建的。

先不考虑Activity的创建(因为 Acitivity的实例由ActivityManager维护,是在另一个进程设计到IPC的通信,后面会讲到),而考虑WindowView的创建。

Activity被创建后,系统会调用它的attach方法来将Activity添加到ActivityThread(ui线程)当中。我们找到Activityattach方法如下:

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,  

            Object lastNonConfigurationInstance,  

            HashMap<String,Object> lastNonConfigurationChildInstances,  

            Configuration config) {  

        attachBaseContext(context);  

       mWindow= PolicyManager.makeNewWindow(this);  //创建Window

        mWindow.setCallback(this);  

        if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {  

            mWindow.setSoftInputMode(info.softInputMode);  

        }  

        mUiThread = Thread.currentThread();  

        mMainThread = aThread;  

        mInstrumentation = instr;  

        mToken = token;  

        mIdent = ident;  

        mApplication = application;  

        mIntent = intent;  

        mComponent = intent.getComponent();  

        mActivityInfo = info;  

        mTitle = title;  

        mParent = parent;  

        mEmbeddedID = id;  

        mLastNonConfigurationInstance = lastNonConfigurationInstance;  

        mLastNonConfigurationChildInstances = lastNonConfigurationChildInstances;  

        mWindow.setWindowManager(null, mToken, mComponent.flattenToString());  

        if (mParent != null) {  

            mWindow.setContainer(mParent.getWindow());  

        }  

        mWindowManager = mWindow.getWindowManager();  

        mCurrentConfig = config;  

    }  

我们看红色的代码部分,就是创建Window对象的代码。感兴趣的同学可以跟踪去看看具体是如何创建的。其实很简单,其内部实现调用了Policy对象的makeNewWindow方法,其方法直接new了一个PhoneWindow对象如下:

public PhoneWindow makeNewWindow(Context context) {

        returnnew PhoneWindow(context);

 }

这时我们已经可以把流程串起来,Activity创建后系统会调用其attach方法,将其添加到ActivityThread当中,在attach方法中创建了一个window对象。

下面分析View的创建。我们知道Window聚合了DocerView,当用户调用setContentView的时候会把一颗View树仍给DocerView.View树是已经创建好的实例对象了,所以我们研究的是DocerView是个什么东西,它是如何被创建的。

我们回头看看Window实现里边的setContentView方法,我们看上面代码的红色部分setContentView-> installDecor-> generateDecor

generateDecor直接new了一个DecorView对象:

protected DecorView generateDecor() {


        returnnew DecorView(getContext(), -1);

 }

我们可以去看看DecorView的实现,它是PhoneWindow的一个内部类。实现很简单,它默认会包含一个灰色的标题栏,然后在标题栏下边会包含一个空白区域用来当用户调用setContentView的时候放置用户View,并传递事件,这里不做详细分析,感兴趣同学可以自己研究研究。

DecorView创建好之后再回到Window中的setContentView方法中来,见下面代码部分,调用

 mContentParent.addView(view, params);

来将用户的View树添加到DecorView中。

到这时为止,我想我们已经很清晰的认识到它们3者之间的关系,并知道其创建流程。

现在总结一下:

ActivityonCreate之前调用attach方法,在attach方法中会创建window对象。window对象创建时并没有创建Decor对象对象。我们在Activity中调用setContentView,然后调用windowsetContentView,这时会检查DecorView是否存在,如果不存在则创建DecorView对象,然后把用户自己的View 添加到DecorView中。

上篇讲解了3个对象之间的关系和创建的时机。这篇讲解窗口是如何被绘制出来的。

首先,我们看一个概念。就是Viewdraw方法的doc:

Manually render this view (and all of its children) to the given Canvas.

意思是说把View绘制在画布上。个人觉得这个概念很重要,ViewCanvas 的关系,按常规的思维,肯定认为View聚合了Canvas对象,然后在ViewonDraw 方法中,在View中绘制图形。实际上恰恰相反,Canvas 是由系统提供,view通过draw方法来把自身绘制在画布上。如果这样来理解的话,很多东西理解起来就很自然了。系统在window中提供一个Canvas对象,DocerView通过调用draw方法来将自己绘制到canvas上。draw方法实际上是一个递归方法,他会循环调用孩子Viewdraw方法来完成整棵树的绘制。所以实际上一个界面的绘制所用的Cavans是同一个对象。Canvas内部聚合了Matrix对象来实现坐标系的变换。

下面回到系统如何来绘制一个窗口。

android 系统提供了WindowManager,WindowManager顾名思义窗口管理器。实际上它只是对WindowManager服务做了一个包装。其内部实现通过ISessionWindowIWindow接口来和WindowManager服务来通信,这里设计到IPC的概念。IPC即进程间的通讯,ANDROID通过IBinder接口来实现,IBinder通过transact方法来实现进程间的交互,这是一个使用很不友好的接口,好在android还提供了aidl的更人性化的接口,它使得IPC通信就像调用普通的JAVA方法那样便捷。不了解aidl的同学可以自行研究研究(其实我自己也是半桶水,了解概念,而用的不熟悉)

我来看Window是如何被添加到WindowManager的.

Activity有一个public的方法setVisible用来控制Activity的窗口是否显示。

我们看其内部实现发现其调用了makeVisible方法,该方法就是让Window显示在屏幕当中的方法,实现如下:

void makeVisible() {  

       if (!mWindowAdded) {  

           ViewManager wm = getWindowManager();  

           wm.addView(mDecor, getWindow().getAttributes());  

           mWindowAdded = true;  

       }  

       mDecor.setVisibility(View.VISIBLE);  

   }  

这时我们立马就明白了,Activity通过Context来获取WindowManager对象,然后把Window对象的DocerView添加到了WindowManager 服务中,所以android的窗口的创建和显示并不是在同一个进程中,而是把窗口的绘制和管理交给了专门的WindowManager服务,这也是android framework给我提供的基础服务。

我们看看mDeocr是在哪被创建的。

public void onWindowAttributesChanged(WindowManager.LayoutParams params) {  

      // Update window manager if: we have a view, that view is  

       // attached to its parent (which will be a RootView), and  

       // this activity is not embedded.  

        if (mParent == null) {  

            View decor = mDecor;  

            if (decor != null && decor.getParent() != null) {  

                getWindowManager().updateViewLayout(decor, params);  

            }  

        }  

    } 

这时我们已经知道,Activity创建好Window之后只要调用WindowManageraddView方法来将WindowDocerView添加进去即可是使Window显示出来。还方法Window其实是Activity中的概念,在WindowManager中是直接和View打交道的。

下面我们开始研究WindowManager对象,打开其源代码,发现它是一个接口,且只是简单的扩展了ViewManager接口.并增加了一个方法

getDefaultDisplay():Display. 内部还有一个继承自ViewGroup.LayoutParam的内部类。

我们在framework/base/core/java/android/view/WindowManagerImpl.java 中找到其实现类。

我们找到其核心的实现方法addView 方法,如下:

private void addView(View view, ViewGroup.LayoutParams params, boolean nest)  

    {  

        if (Config.LOGV) Log.v("WindowManager", "addView view=" + view);  

        if (!(params instanceof WindowManager.LayoutParams)) {  

            throw new IllegalArgumentException(  

                    "Params must be WindowManager.LayoutParams");  

        }  

        final WindowManager.LayoutParams wparams  

                = (WindowManager.LayoutParams)params;  



        ViewRoot root;  

        View panelParentView = null;  



        synchronized (this) {  

            // Here's an odd/questionable case: if someone tries to add a  

            // view multiple times, then we simply bump up a nesting count  

            // and they need to remove the view the corresponding number of  

            // times to have it actually removed from the window manager.  

            // This is useful specifically for the notification manager,  

            // which can continually add/remove the same view as a  

            // notification gets updated.  

            int index = findViewLocked(view, false);  

            if (index >= 0) {  

                if (!nest) {  

                    throw new IllegalStateException("View " + view  

                            + " has already been added to the window manager.");  

                }  

                root = mRoots[index];  

                root.mAddNesting++;  

                // Update layout parameters.  

                view.setLayoutParams(wparams);  

                root.setLayoutParams(wparams, true);  

                return;  

            }  



            // 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) {  

                final int count = mViews != null ? mViews.length : 0;  

                for (int i=0; i<count; i++) {  

                    if (mRoots[i].mWindow.asBinder() == wparams.token) {  

                        panelParentView = mViews[i];  

                    }  

                }  

            }  



           root =newViewRoot(view.getContext());  

            root.mAddNesting = 1;  

            view.setLayoutParams(wparams);  



            if (mViews == null) {  

                index = 1;  

                mViews = new View[1];  

                mRoots = new ViewRoot[1];  

                mParams = new WindowManager.LayoutParams[1];  

            } else {  

                index = mViews.length + 1;  

                Object[] old = mViews;  

                mViews = new View[index];  

                System.arraycopy(old, 0, mViews, 0, index-1);  

                old = mRoots;  

                mRoots = new ViewRoot[index];  

                System.arraycopy(old, 0, mRoots, 0, index-1);  

                old = mParams;  

                mParams = new WindowManager.LayoutParams[index];  

                System.arraycopy(old, 0, mParams, 0, index-1);  

            }  

            index--;  

            mViews[index] = view;  

            mRoots[index] = root;  

            mParams[index] = wparams;  

        }  

        // do this last because it fires off messages to start doing things  

       root.setView(view, wparams, panelParentView);  

    }  

我们来看看root =newViewRoot(view.getContext());root.setView(view, wparams, panelParentView);

创建了一个ViewRoot对象,然后把view添加到ViewRoot中。

ViewRoot对象是handler的一个实现,其聚合了ISessionWindowIWindow对象来和WindowManager服务进行IPC通信。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值