一.概述
Window表示一个窗口的概念,通过源码我们可以知道,Window是一个抽象类,那么到底Window的实现类是什么呢?其实是PhoneWindow。创建一个Window是一件很简单的事,只需要通过WindowManager即可完成。WindowManager是外界访问Window的入口,Window的具体实现位于WindowManagerService中,WindowManager和WindowManagerService的交互是一个IPC过程。
Android所有的视图都是通过Window来呈现的,不管是Activity、Dialog还是Toast,他们的视图实际上都是附加在Window上的,因此Window实际上是View的直接管理者。Activity的设置视图的方法setContentView在底层也是通过Window来实现的。
**二. Window和WindowManager
2.1WindowManager**
要分析Window的工作机制,我们先了解如何使用WindowManager添加一个Window。
例如将一个Button添加到屏幕当中的某个坐标上,都需要使用到WindowManager.LaoutParams(这里就不贴详细添加流程了)
查看下LayoutParams的源码
public static class LayoutParams extends ViewGroup.LayoutParams implements Parcelable {
……}
public LayoutParams() {
super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
type = TYPE_APPLICATION;
format = PixelFormat.OPAQUE;
}
public LayoutParams(int _type) {
super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
type = _type;
format = PixelFormat.OPAQUE;
}
public LayoutParams(int _type, int _flags) {
super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
type = _type;
flags = _flags;
format = PixelFormat.OPAQUE;
}
……
通过上述部分源码,我们可以看到LayoutParams继承的ViewGroup.LayoutParams,并实现了序列化(因为WindowManager和WindowManagerService的交互是一个IPC过程需要序列化)。
我们可以看到LayoutParams的构造函数中有两个比较重要的参数:flags和type。
Flags参数表示Window的属性,他有很多选项,介绍几个比较常用的
FLAG_NOT_FOCUSABLE
窗口标志:这个窗口永远不会得到关键的输入焦点,所以用户不能将密钥或其他按钮事件发送给它。那些将去聚焦窗口后面是什么。这个标志也将使 flag_not_touch_modal 是否显式设置。设置此标志也意味着窗口不需要互动。
FLAG_NOT_TOUCH_MODAL
允许任何指针事件。系统会将当前Window区域以外的单击事件传递给底层的Window。否则它将消耗所有指针事件本身,而不管它们是否在窗户里面。
FLAG_SHOW_WHEN_LOCKED
开启此模式可以让Window显示在锁屏的界面上。(special flag to let windows be shown when the screen is locked. This will let application windows take precedence over key guard or any other lock screens.)
Type参数表示Window的类型,Window有三种类型,分别是应用Window、子Window和系统Window。应用类Window对应这一个Activity。子Window不能单独存在,它需要附属在特定的父Window之中,比如常见的一些Dialog就是一个子Window。系统Window是需要声明权限才能创建的Window,比如Toast和状态栏这些都是系统Window。
Window是分层的,层级大的会覆盖在层级小的上面,层级从大到小(系统Window>子Window>应用Window)
小总结下,WindowManager所提供的功能很简单,即添加View,更新View和删除View.
public interface ViewManager
{// WindowManager继承ViewManager
public void addView(View view, ViewGroup.LayoutParams params);
public void updateViewLayout(View view, ViewGroup.LayoutParams params);
public void removeView(View view);
}
我们时常见到那种可以拖动的Window效果,只需要根据手指的位置来设定LayoutParams中的x和y的值即可改变Window的位置,首先个View设置监听,然后在onTouch方法中不断更新View的设置。
2.2Window的内部机制
Window是一个抽象的概念(The only existing implementation of this abstract class is android.view.PhoneWindow, which you should instantiate when needing a Window.),每一个Window都对应着一个View和一个ViewRootImpl,Window并不是实际存在的,无论是从上述源码的英语解释中或者WindowManager的定义也可以看出,它提供的三个接口方法addView、updateViewLayout、removeView都是针对View的,这说明View才是Window存在的载体。
我们已知WindowManager是一个接口,需要一个具体的类来实现这个接口,所以真的的实现类是WindowManagerImpl类,但是WindowManagerImpl全部交给了WindowManagerGlobal来处理,WindowManagerGlobal以工厂的形式向外提供自己的实例。WindowManagerImpl这种工作模式是典型的桥接模式,将所有的操作全部委托给WindowManagerGlobal。
public final class WindowManagerImpl implements WindowManager {
private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
…………
@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);
}
可以发现,WindowManagerImpl并没有直接实现Window的三大操作,而是全部交给了WindowManagerGlobal来处理,WindowManagerGlobal以工厂的形式向外提供自己的实例。
WindowManagerImpl这种工作模式是典型的桥接模式,将所有操作委托给WindowManagerGlobal来实现。
接下来依次分析Window的添加、删除、更新过程。
**2.2.1
Window的添加过程**
1.首先判断参数是否合法,如果是子Window还需要调整一些布局参数
在后半段
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);
} else {
// If there's no parent, then hardware acceleration for this view is
// set from the application's hardware acceleration setting.
2.创建ViewRootlmpl并将View添加到列表中
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
可以看到有三个参数需要添加view,root,wparams;
private final ArrayList<View> mViews = new ArrayList<View>();
private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();
private final ArrayList<WindowManager.LayoutParams> mParams =
new ArrayList<WindowManager.LayoutParams>();
private final ArraySet<View> mDyingViews = new ArraySet<View>();
通过以上代码
mViews存储的是所有Window对应的View;
mRoots存储的是所有Window所对应的ViewRootImpl;
mParams存储的是所有Window所对应的布局参数;
mDyingViews则存储了那些正在被删除的View对象,或者说是那些已经调用removeView方法但是删除操作还未完成的Window对象。
3.通过ViewRootImpl来更新界面并完成Window的添加过程
经过添加到列表中,接下来步骤由ViewRootImpl的setView方法来完成,
所以接下来在看看ViewRootImpl的setView方法。
ViewRootImpl root;
try {
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
// BadTokenException or InvalidDisplayException, clean up.
if (index >= 0) {
removeViewLocked(index, true);
}
throw e;
}
setView内部通过requestLayout()方法来完成异步刷新要求
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
接着会通过WindowSession最终来完成Window的添加过程。
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
……
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);
} finally {
if (restore) {
attrs.restore();
}
}
……
}
mWindowSession的类型是IWindowSession,它是一个Binder对象,真正的实现类是Session,也就是Window的添加过程是一次IPC调用。最终在Session内部会通过WindowManagerService来实现Window的添加。
所以,Window的添加请求就交给WindowManagerService去处理了,在WindowManagerService内部会为每一个应用保留一个单独的Session。
**2.2.2
Window的删除过程**
Window的删除过程和添加过程一样,都是先通过WindowManagerImpl后,在进一步通过WindowManagerGlobal来实现。
先查找View再删除View
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);
//首先通过findViewLocked来查找待删除View的索引,
// 这个查找过程就是数组遍历
View curView = mRoots.get(index).getView();
//然后再调用 removeViewLocked来做进一步删除
removeViewLocked(index, immediate);
if (curView == view) {
return;
}
throw new IllegalStateException("Calling with view " + view
+ " but the ViewAncestor is attached to " + curView);
}
}
同样也是调用ViewRootImpl来完成删除操作。在WindowManager中提供了两种删除接口removeView(异步删除),removeViewImmediate(同步删除)。
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);
}
}
}
接下来看root.die方法,在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);
//如果是异步删除,那么就发送一个MSG_DIE
return true;
}
****2.2.3
Window的更新过程**
同样的,还是先看WindowManagerGlobal的updateViewLayout,它需要更新View的LayoutParams并替换掉老的LayoutParams,接着还是更新ViewRootImpl的LayoutParams。
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);
//ViewRootImpl的LayoutParams
}
}
在ViewRootImpl中会通过scheduleTraversals方法对View重新布局,包括测量、布局、重绘这三个过程。
涉及到Window的改变,在ViewRootImpl中还会通过WindowSession来更新Window视图(由WindowManagerService—-都是一个IPC过程)
小结:
对于这个的分析步骤
1.WindowManagerImpl(交给别人是桥接)交给WindowManagerGlobal(这个是工厂)来处理,
2.WindowManagerGlobal内部涉及Window的变化就交由ViewManagerImpl来处理
3.ViewManagerImpl会通过WindowSession来完成剩余操作,这个WindowSession的类型是一个Bidner对象,整个操作是一个IPC调用
顺着艺术与探索的思路理一理
参考:《Android艺术与探索》