美文网首页
Window,WindowManager详解

Window,WindowManager详解

作者: 刘佳阔 | 来源:发表于2017-09-13 22:02 被阅读0次

    先上一张uml关系图,自己制作的哦

    QQ拼音截图20170915211245.png
    1. WindowManager是Android中一个重要的服务(Service )。WindowManager Service 是全局的,是唯一的。它将用户的操作,翻译成为指令,发送给呈现在界面上的各个Window。Activity会将顶级的控件注册到 Window Manager 中.
      WindowManager 继承自ViewManager,ViewManager是一个接口,代码如下
      public interface ViewManager{
          public void addView(View view, ViewGroup.LayoutParams params);
          public void updateViewLayout(View view, ViewGroup.LayoutParams params);
          public void removeView(View view);
      }
    
    1. windowManager 里一个重要的内部类就是 LayoutParams , LayoutParams 继承 ViewGroup.LayoutParams
      实现了 Parcelable接口
      layoutParams 里边定义了window的层级关系.代码如下
        public static final int TYPE_BASE_APPLICATION   = 1;
        public static final int TYPE_APPLICATION        = 2;
        public static final int LAST_APPLICATION_WINDOW = 99;
        public static final int LAST_SUB_WINDOW         = 1999;
        public static final int FIRST_SYSTEM_WINDOW     = 2000;
    

    其中.应用Window的层级范围是1-99,子Window的层级是1000-1999,系统Window的层级是2000-2999.想让window位于所有window的最顶层,采用较大的层级就可以.使用系统层级的window需要在权限中声名对应的window权限如
    <user-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    3.window 是一个抽象概念.每个window都对应着一个View和ViewRootImpl,Window和View通过ViewRootImpl来建立联系.下边分别讲解

    • window的添加过程
      window的add,remove,update过程都有WindowManager来实现,WindowManager是一个接口,具体实现类是WindowManagerImpl类.

        WindowManagerImpl 代码
       private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
      @Override
      public void addView(View view, ViewGroup.LayoutParams params) {
        mGlobal.addView(view, params, mDisplay, mParentWindow);
      }
      @Override
      public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
          mGlobal.updateViewLayout(view, params);
      }
      @Override
      public void removeView(View view) {
            mGlobal.removeView(view, false);
      }
      @Override
      public void removeViewImmediate(View view) {
        mGlobal.removeView(view, true);
      }
      

    1.WindowManagerImpl 通过 WindowManagerGlobal 来对View进行操作. WindowManagerGlobal通过单例模式提供他自己的对象.

    //WindowManagerGlobal 代码
     public static WindowManagerGlobal getInstance() {
        synchronized (WindowManagerGlobal.class) {
            if (sDefaultWindowManager == null) {
                sDefaultWindowManager = new WindowManagerGlobal();
            }
            return sDefaultWindowManager;
        }
    }
    

    2.接下来讲解 WindowManagerGlobal,他里边有几个重要参数先列出来

    //  WindowManagerGlobal 代码     
    private static IWindowManager sWindowManagerService;
    private static IWindowSession sWindowSession; //前两个先不看
    private final Object mLock = new Object(); //线程的锁
    //所有Window对应的view的集合
    private final ArrayList<View> mViews = new ArrayList<View>();
    //所有window对应的ViewRootImpl 的集合
    private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();
    //所有Window对应的布局参数集合
    private final ArrayList<WindowManager.LayoutParams> mParams =
            new ArrayList<WindowManager.LayoutParams>();
    //所有调用removeView方法但删除操作还没完成的View集合
    private final ArraySet<View> mDyingViews = new ArraySet<View>();
    

    3.看WindowManagerGolbal的addView方法

     //WindowManagerGolbal 代码
    public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        // ------- 1.先检查参数是否合法,
        if (view == null) {
            throw new IllegalArgumentException("view must not be null");
        }
        if (display == null) {
            throw new IllegalArgumentException("display must not be null");
        }
        if (!(params instanceof WindowManager.LayoutParams)) {
            throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
        }
    
        final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;
        if (parentWindow != null) { //调整parentWindow的param参数
            parentWindow.adjustLayoutParamsForSubWindow(wparams);
        } else {
            // If there's no parent and we're running on L or above (or in the
            // system context), assume we want hardware acceleration.
            final Context context = view.getContext();
            if (context != null //开启硬件加速
                    && context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
                wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
            }
        }
    
        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();//ViewRootImpl 加载系统属性
                            }
                        }
                    }
                };
                SystemProperties.addChangeCallback(mSystemPropertyUpdater);//监听系统属性变化
            }
    
            int index = findViewLocked(view, false);//看这个view是否存在于mViews里
            if (index >= 0) {
                if (mDyingViews.contains(view)) { //如果已经添加到mViews里,看看是否是在待删的mDyingViews里,是的话直接删除
     ,不是的话,就抛出异常.
                    // 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.
            //如果是面板view,就找到他第一次attach的window,以备以后查询.
            if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
                    wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
                final int count = mViews.size();
                for (int i = 0; i < count; i++) {
                    if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
                        panelParentView = mViews.get(i);
                    }
                }
            }
            //------- 2.生成一个新的viewRootImpl,并且把 view. viewrootImpl, param 都保存起来.
            root = new ViewRootImpl(view.getContext(), display);
            view.setLayoutParams(wparams);
            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
        }
    
        // do this last because it fires off messages to start doing things
        try {
          //------- 3.调用ViewRoomImpl来更新界面并完成Window的添加过程
            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;
        }
    }
         -------4.在 ViewRootImpl的setview方法里主要是一些对LayoutParams的处理,也看不太懂.不过其中重要是调用了requestLayout();
    进行重新绘制.然后调用 mWindowSession完成view的添加过程.
          //ViewRoomImpl内部成员
         final IWindowSession mWindowSession;
    
        //VewRoomImpl 的 setView 方法
       try {
                    mOrigWindowType = mWindowAttributes.type;
                    mAttachInfo.mRecomputeGlobalAttributes = true;
                    collectViewAttributes();
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mInputChannel);
                }
    

    其实,mWindowSession的类型是IWindowSession,他是一个Binder对象,真正的实现类是Session.也就是Window的一次添加过程是一次IPC调用

    //Session代码
    final WindowManagerService mService;
    @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);
    }
    

    这样,Window的一次添加过程就由WindowManagerService去处理了,而WindowManagerService内部会为每一个应用并保留一个单独的session

    • Window的删除过程
      从 WindowManager的实现类WindowManagerImpl 看起

        //windowManagerImpl代码
        private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
       @Override
      public void removeView(View view) {
          mGlobal.removeView(view, false);
      }
      

    接着看 WindowManagerGlobal

    //WindowManagerGlobal 代码 为了方便.把之前列出的WindowManagerGlobal 几个成员写下
    
      private static IWindowManager sWindowManagerService;
      private static IWindowSession sWindowSession; //前两个先不看
      private final Object mLock = new Object(); //线程的锁
      //所有Window对应的view的集合
      private final ArrayList<View> mViews = new ArrayList<View>();
      //所有window对应的ViewRootImpl 的集合
      private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();
      //所有Window对应的布局参数集合
      private final ArrayList<WindowManager.LayoutParams> mParams =
        new ArrayList<WindowManager.LayoutParams>();
      //所有调用removeView方法但删除操作还没完成的View集合
      private final ArraySet<View> mDyingViews = new ArraySet<View>();
       //  WindowManagerGlobal 主要代码
      public void removeView(View view, boolean immediate) {
          if (view == null) {
            throw new IllegalArgumentException("view must not be null");
          }
        synchronized (mLock) {
            int index = findViewLocked(view, true);//在 mViews集合里查找这个view的index.
            View curView = mRoots.get(index).getView();//找到这个所以的ViewRootImpl对应的view
            removeViewLocked(index, immediate); //这是主要的删除办法
            if (curView == view) {  //两个view相同,代表数据是正确的.结束方法.否则就抛出异常
                return;
            }
            throw new IllegalStateException("Calling with view " + view
                    + " but the ViewAncestor is attached to " + curView);
        }
    }
    

    // 接着看 removeViewLocked

        //WindowManagerGlobal 方法 ,immediate 标识是否立即删除.
       private void removeViewLocked(int index, boolean immediate) {
           ViewRootImpl root = mRoots.get(index);
            View view = root.getView();
        if (view != null) {
            InputMethodManager imm = InputMethodManager.getInstance();
            if (imm != null) {
                imm.windowDismissed(mViews.get(index).getWindowToken()); //这是一个调用InputManagerService的ipc的过程
            }
        }
        boolean deferred = root.die(immediate); //通过ViewRootImpl 完成view的删除
        if (view != null) {
            view.assignParent(null);
            if (deferred) {  //如果是延时的remove view,则把view 添加到mDyingViews里
                mDyingViews.add(view);
            }
        }
    }
    

    接下来追中到ViewRootImpl里的die方法

     //ViewRootImpl代码 immediate      
    boolean die(boolean immediate) {
            // Make sure we do execute immediately if we are in the middle of a traversal or the damage
            // done by dispatchDetachedFromWindow will cause havoc on return.
            if (immediate && !mIsInTraversal) {
                doDie(); //直接执行
                return false;
            }
    
        if (!mIsDrawing) {
            destroyHardwareRenderer();
        } else {
            Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
                    "  window=" + this + ", title=" + mWindowAttributes.getTitle());
        }
        mHandler.sendEmptyMessage(MSG_DIE); //其实就是在handler在处理消息时会调用 dodie方法
        return true;
    }
    //继续看dodie方法 ViewRootImpl代码
      void doDie() {
        checkThread(); //确保mThread=Thread.currentThread() //其实mThread初始化就是他
        if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
        synchronized (this) {
            if (mRemoved) { //标记变量.标识view是否被删除
                return;
            }
            mRemoved = true;
            if (mAdded) {
                dispatchDetachedFromWindow();//这是主要的删除方法
            }
    
            if (mAdded && !mFirst) {
                destroyHardwareRenderer(); //销毁硬件渲染器
    
                if (mView != null) {
                    int viewVisibility = mView.getVisibility();
                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
                    if (mWindowAttributesChanged || viewVisibilityChanged) {
                        // If layout params have been changed, first give them
                        // to the window manager to make sure it has the correct
                        // animation info.
                        try {
                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
                                    & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
                                mWindowSession.finishDrawing(mWindow); //用来更新window的layoutparams
                            }
                        } catch (RemoteException e) {
                        }
                    }
                    mSurface.release();
                }
            }
    
            mAdded = false;
        }
        //这句代码主要是通过本ViewRoomImpl在WindowManagerGlobal mRoots中的index.
        //分别在mRoots,mParams,mDyingViews 把这个index对应的不同数据都删除
        WindowManagerGlobal.getInstance().doRemoveView(this);
    }
    

    最后 ViewRootImpl中注意做了以下的事
    1.垃圾回收相关,清楚数据,和消息,移除回调
    2.通过Session的remove方法删除Window,其实是通过IPC调用WindowManagerService的removeWindow方 法.
    3.调用View的diapatchDetachedfromWindow 方法,内部会回调View的onDetachedFromWindow及onDetachedFromWindowInternal(),
    到此.remove过程完毕

    相关文章

      网友评论

          本文标题:Window,WindowManager详解

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