Window和WindowManager

了解:

  • Window表示一个窗口的概念
  • 它是一个抽象类
  • 具体实现类为PhoneWindow
  • 外界访问Window的入口是WindowManager
  • 具体实现位于WindowManagerService
  • WindowManager和WindowManagerService的交互是一个IPC(进程间的通信)过程

    使用WindowManager添加一个Window

 Button floatingButton=new Button(this);
        floatingButton.setText("I am floatingButton");
        WindowManager.LayoutParams mLayoutParams=new WindowManager.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                ViewGroup.LayoutParams.WRAP_CONTENT,0,0, PixelFormat.TRANSPARENT);
        mLayoutParams.flags= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
        mLayoutParams.gravity= Gravity.LEFT | Gravity.TOP;
        mLayoutParams.x=200;
        mLayoutParams.y=200;
        WindowManager mWindowManager=getWindowManager();
        mWindowManager.addView(floatingButton,mLayoutParams);

这样便将一个Button添加到了屏幕坐标为(200,200)的位置上。
Flags参数:

  • FLAG_NOT_FOCUSABLE:表示Window不需要获取焦点,也不需要接入各种输入事件,同时会启动FLAG_NOT_TOUCH_MODAL,最终事件会传递给下层具有焦点的Window。
  • FLAG_NOT_TOUCH_MODAL:当前Window区域意外的事件会传递给下层Window,当前的Window区域会自己处理单击事件。一般需要开启此标记
  • FLAG_SHOW_WHEN_LOCKED:让Window在锁屏的界面上
    Type参数:
  • 系统Window:需要声明权限再创建,如Toast、系统状态栏等;层级为2000~2999
  • 子Window:不能单独存在,需要附属在特定的父Window上,如Dialog;层级为1000~1999
  • 应用Window:对应着一个Activity;层级为1~99
    如果选用系统Window,比如
    mLayoutParams.type=WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
    那么需要声明权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

WindowManager继承了ViewManager,在ViewManger中提供了三个方法:

public interface ViewManager
{
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}

根据名字可以知道:

  • addView:创建一个Window并添加View
  • updateViewLayout:更新Window中的View
  • removeView:移除View

    Window的内部机制

    每一个Window对应着一个View和ViewRootImpl。Window和View是通过ViewRootImpl来建立联系的,因此Window并不是实际存在的,它是以View的形式存在的,这在上面的几个方法可知,都是针对View的操作。

  • 添加过程:
    WindowManagerImpl实现了WindowManager,正在实现了上面的方法。

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

    @Override
    public void updateViewLayout(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.updateViewLayout(view, params);
    }
    @Override
    public void removeView(View view) {
        mGlobal.removeView(view, false);
    }

从源码可知:以上三个操作都交给了WindowManagerGlobal去处理。

  • addView

    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.adjustLayoutParamsForSubWindow(wparams);
        } 
2.将View添加到相关列表中
            mViews.add(view);//Window所对应的View
            mRoots.add(root);//Window所对应的ViewRootImpl
            mParams.add(wparams);//Window所对应的布局参数
3.通过ViewRootImpl来更新界面并完成Window的添加过程:
root.setView(view, wparams, panelParentView);

在setView中有requestLayout方法,用来完成异步刷新请求

@Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }
scheduleTraversals方法为View的绘制入口,并刷新;

在setView中,有一段代码

try {
                    mOrigWindowType = mWindowAttributes.type;
                    mAttachInfo.mRecomputeGlobalAttributes = true;
                    collectViewAttributes();
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mInputChannel);
                } catch (RemoteException e) {
                    mAdded = false;
                    mView = null;
                    mAttachInfo.mRootView = null;
                    mInputChannel = null;
                    mFallbackEventHandler.setView(null);
                    unscheduleTraversals();
                    setAccessibilityFocus(null, null);
                    throw new RuntimeException("Adding window failed", e);
                } 

IWindowSession对象调用了addToDisplay方法,这是一个IPC调用。
IWindowSession的真正实现类是Session,走到Session中的addToDisplay方法:

@Override
    public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
            int viewVisibility, int displayId, Rect outContentInsets, Rect outStableInsets,
            Rect outOutsets, InputChannel outInputChannel) {
        return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId,
                outContentInsets, outStableInsets, outOutsets, outInputChannel);
    }

mService是WindowManagerService类型。在addWindow方法中,根据type返回不同的 LayoutParams.type,这样就把添加View交由WindowManagerService处理。

  • removeView

    与添加过程一样,通过WIndowManagerImpl寄托给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);
            View curView = mRoots.get(index).getView();
            removeViewLocked(index, immediate);
            if (curView == view) {
                return;
            }

            throw new IllegalStateException("Calling with view " + view
                    + " but the ViewAncestor is attached to " + curView);
        }
    }

其中removeViewLocked的方法源码为

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());
            }
        }
        boolean deferred = root.die(immediate);
        if (view != null) {
            view.assignParent(null);
            if (deferred) {
                mDyingViews.add(view);
            }
        }
    }

其中由ViewRootImpl的die方法来完成删除操作,源码如下

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(mTag, "Attempting to destroy the window while drawing!\n" +
                    "  window=" + this + ", title=" + mWindowAttributes.getTitle());
        }
        mHandler.sendEmptyMessage(MSG_DIE);
        return true;
    }

此方法中,如果是同步的话,则不发送消息而直接调用doDie方法,如果是异步的话,则发送消息,然后Handler会处理此消息并调用doDie方法。
doDie方法中,调用了dispatchDetachedFromWindow,dispatchDetachedFromWindow中做了四件事:

  1. 垃圾回收,清除数据、移除回调等
  2. 通过Session的remove方法移除Window,这同样是一个IPC过程,最终会调用WindowManagerService的removeWindow方法
  3. 调用View的dispatchDetachedFromWindow()方法,这个方法内部做一些资源回收的工作,比如停止动画、线程等
  4. 调用WindowManagerGlobal的doRemoveView,刷新数据,将与当前Window所关联的三类对象从列表删除。

    • updateViewLayout
public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
        if (view == null) {
            throw new IllegalArgumentException("view must not be null");
        }
        if (!(params instanceof WindowManager.LayoutParams)) {
            throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
        }

        final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;

        view.setLayoutParams(wparams);

        synchronized (mLock) {
            int index = findViewLocked(view, true);
            ViewRootImpl root = mRoots.get(index);
            mParams.remove(index);
            mParams.add(index, wparams);
            root.setLayoutParams(wparams, false);
        }
    }

updateViewLayout方法里面将新的WindowManager.LayoutParams替换老的WindowManager.LayoutParams,然后通过scheduleTraversals()方法绘制,在绘制的同时,线程 mTraversalRunnable会被开启,然后接下来的方法执行顺序:doTraversal()方法->performTraversals()方法->relayoutWindow方法,最后在relayoutWindow方法中调用了Session的relayout方法,进而调用WindowManagerService的relayoutWindow来具体实现更新,是一个IPC过程。
以上分析顺序,有什么差错麻烦请指出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值