Android版本:7.0(API27)
[TOC]
澄清几个概念
窗口(不是指的Window类):这是一个纯语义的说法,即程序员所看到的屏幕上的某个独立的界面,比如一个带有Title Bar的Activity界面、一个对话框、一个Menu菜单等,这些都称之为窗口。本书中所说的窗口管理一般也都泛指所有这些窗口,在Android的英文相关文章中则直接使用Window这个单词。而从WmS的角度来讲,窗口是接收用户消息的最小单元,WmS内部用特定的类表示一个窗口,以实现对窗口的管理。WmS接收到用户消息后,首先要判断这个消息属于哪个窗口,然后通过IPC调用把这个消息传递给客户端的ViewRoot类。
Window类:该类在android.view包中,是一个abstract类,该类抽象了“客户端窗口”的基本操作,并且定义了一组Callback接口,Activity类就是通过实现这个Callback接口以获得对消息处理的机会,因为消息最初是由WmS传递给View对象的。
ViewRoot类:该类在android.view包中,客户端申请创建窗口时需要一个客户端代理,用以和WmS进行交互,ViewRoot内部类W就是完成这个功能的。WmS所管理的每一个窗口都会对应一个ViewRoot类。
W类:该类是ViewRoot类的一个内部类,继承于Binder,用于向WmS提供一个IPC接口,从而让WmS控制窗口客户端的行为。
描述一个窗口之所以使用这么多类的原因在于,窗口的概念存在于客户端和服务端(WmS)之中,并且Framework又定义了一个Window类,这很容易让人产生混淆,实际上WmS所管理的窗口和Window类没有任何关系。
窗口工作原理
Activity、DecorView与Window、WindowMananger的关系如下图所示:
当ActivityThread接收到AmS发送start某个Activity后,就会创建指定的Activity对象。Activity又会创建PhoneWindow类→DecorView类→创建相应的View或者ViewGroup。创建完成后,Activity需要把创建好的界面显示到屏幕上,于是调用WindowManager类,后者于是创建一个ViewRootImpl对象,该对象实际上创建了ViewRootImpl类和W类,创建ViewRootImpl对象后,WindowManager再调用WmS提供的远程接口完成添加一个窗口并显示到屏幕上。
这其中ViewRootImpl非常重要,它具备如下几个核心功能:
- 它负责与WMS交互通信以调整窗口的位置大小,以及对来自WMS的事件(如窗口尺寸改变等)做出相应的处理;
- 触发控件树绘制(测量、布局、绘制);
- 接收并分发输入事件,触摸、按键等事件;
WindowManager使用
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mFloatingButton = new Button(this);
mFloatingButton.setText("click me");
mLayoutParams = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0,PixelFormat.TRANSPARENT);
mLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL| LayoutParams.FLAG_NOT_FOCUSABLE| LayoutParams.FLAG_SHOW_WHEN_LOCKED;
mLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR;
mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
mLayoutParams.x = 100;
mLayoutParams.y = 300;
mFloatingButton.setOnTouchListener(this);
mWindowManager.addView(mFloatingButton, mLayoutParams);
复制代码
上述代码将一个Button添加到频幕坐标(100,300)的位置上。其中WindowManager.LayoutParams的两个参数flags和type比较重要。
- flag
flag表示Window的属性,可以控制Window的显示特性,下面介绍比较常用的几个:
- FLAG_NOT_FOCUSABLE 设置之后Window不会获取焦点,也不会接收各种输入事件,最终事件会传递给在其下面的可获取焦点的Window,这个flag同时会启用 FLAG_NOT_TOUCH_MODAL flag。
- FLAG_NOT_TOUCH_MODAL 这个flag简而言之就是说,当前Window区域以外的点击事件传递给下层Window,当前Window区域以内的点击事件自己处理。
- FLAG_SHOW_WHEN_LOCKED 一个特殊的flag,使得Window可以在锁屏状态下显示,它使得Window比KeyGuard或其他锁屏界面具有更高的层级。
- type
type表示Window的类型,Window有三种类型,分别是应用Window,子Window和系统Window。
应用类Window对应着一个Activity。子Window不能单独存在,它需要附属在特定的父Window中,比如Dialog就是一个子Window。系统Window是需要声明权限才能创建的Window,比如Toast和系统状态栏这些都是系统Window。
Window是分层的,每个Window都有对应的z-ordered,层级大的会覆盖在层级小的Window上。在三类Window中,应用Window的层级范围是1~99,子Window的层级范围是1000~1999,系统Window的层级范围是2000~2999。很显然系统Window的层级是最大的,而且系统层级有很多值,一般我们可以选用TYPE_SYSTEM_ERROR或者TYPE_SYSTEM_OVERLAY,另外重要的是要记得在清单文件中声明权限。
WindowManager所提供的功能很简单,常用的只有三个方法,即添加View、更新View和删除View,这三个方法定义在ViewManager中,而WindowManager继承了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);
}
复制代码
WindowManager内部机制
Window是一个抽象的概念,每一个Window都对应着一个View和一个ViewRootImpl,Window和View通过ViewRootImpl来建立联系,因此Window并不是实际存在的,它是以View的形式存在,这点从WindowManager的定义可以看出,它提供的三个接口方法都是针对View的,这说明View才是WIndow存在的实体。在实际使用中无法直接访问Window,对WIndow的访问必须通过WindowManager。为了分析Window的内部机制,这里从Window的添加、删除以及更新去分析。
WindowManager的添加
WindowManager的实现类是WindowManagerImpl,所以我们直接看WindowManagerImpl.addView()方法:
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {applyDefaultToken(params);mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}
复制代码
addView内部借助mGlobal(WindowManagerGlobal)的addView,WindowManagerGlobal是一个单例,mGlobal.addView中用到了几个重要字段:
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:存储哪些正在被删除的对象; 从上面的分析我们能知道一个Window包含一个View、一个ViewRootImpl、一个布局参数,并且它们分别被存储在mViews、mRoots、mParams中。
public void addView(View view, ViewGroup.LayoutParams params,Display display, Window parentWindow) {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.final Context context = view.getContext();if (context != null&& (context.getApplicationInfo().flags& ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {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();}}}};SystemProperties.addChangeCallback(mSystemPropertyUpdater);}int index = findViewLocked(view, false);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) {final int count = mViews.size();for (int i = 0; i < count; i++) {if (mRoots.get(i).mWindow.asBinder() == wparams.token) {panelParentView = mViews.get(i);}}}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 thingstry {root.setView(view, wparams, panelParentView);} catch (RuntimeException e) {// BadTokenException or InvalidDisplayException, clean up.if (index >= 0) {removeViewLocked(index, true);}throw e;}}
}
复制代码
WindowManagerGlobal.addView方法的核心有两个作用:
- 建立上面我们说的联系(一个Window包含一个View、一个ViewRootImpl、一个布局参数,并且它们分别被存储在mViews、mRoots、mParams中),通过如下代码实现:
root = new ViewRootImpl(view.getContext(), display);view.setLayoutParams(wparams);mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
复制代码
- 通过ViewRootImpl显示View
root.setView(view, wparams, panelParentView);
复制代码
在“窗口工作原理”中我们已经说明的ViewRootImpl的重要作用,ViewRootImpl源码比较复杂还设计到Binder原理,所以为了不因深入细节而打乱我们的分析节奏,我们对ViewRootImpl的分析只看流程框架。下面我们继续看ViewRootImpl.setView:
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {.....mView = view;.....// 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.requestLayout();.....res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,getHostVisibility(), mDisplay.getDisplayId(),mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,mAttachInfo.mOutsets, mInputChannel);
}
复制代码
ViewRootImpl.setView的源码也很长,我们将关键的几个步骤罗列出来。
- 赋值mView,可以看出mView代表的是一个Window视图的根View,对Activity来说就是DecorView;这一点在这先记录一下,后续分析事件的分发都会使用到mView这个字段;
- 在显示Window前,通过调用requestLayout,开始视图的绘制流程(layout、measure、draw);
- 通过mWindowSession通知WMS显示Window,这个过程涉及到Binder、WMS等,细节不进行分析了;
在这里为后续“视图绘制”一文做个铺垫,进一步看一下requestLayout的源码
@Override
public void requestLayout() {if (!mHandlingLayoutInLayoutRequest) {checkThread();mLayoutRequested = true;scheduleTraversals();}
}
复制代码
调用scheduleTraversals开始绘制
void scheduleTraversals() {if (!mTraversalScheduled) {mTraversalScheduled = true;mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);if (!mUnbufferedInputDispatch) {scheduleConsumeBatchedInput();}notifyRendererOfFramePending();pokeDrawLockIfNeeded();}
}
复制代码
这里执行了一个异步任务mTraversalRunnable,继续看看mTraversalRunnable
final class TraversalRunnable implements Runnable {@Overridepublic void run() {doTraversal();}
}
复制代码
void doTraversal() {if (mTraversalScheduled) {mTraversalScheduled = false;mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);if (mProfile) {Debug.startMethodTracing("ViewAncestor");}performTraversals();if (mProfile) {Debug.stopMethodTracing();mProfile = false;}}
}
复制代码
看到performTraversals,它其实就是整个视图绘制的开始;在这里我们先对performTraversals有个印象,后面“视图绘制”一文会进一步分析performTraversals的。
WindowManager的删除
Window的删除过程和添加过程一样,通过WindowManagerImpl调用WindowManagerGlobal的removeView()来实现:
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);}
}
复制代码
首先通过findViewLocked()来查找待删除的View的索引,然后再调用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);}}
}
复制代码
removeViewLocked()是通过ViewRootImpl来完成删除操作的。WindowManager中提供了两种删除接口,removeView()和removeViewImmediate(),他们分表表示异步删除和同步删除。具体的删除操作由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;
}
复制代码
在异步删除的情况下,die()只是发送了一个请求删除的消息就返回了,这时候View还没有完成删除操作,所以最后将它添加到mDyingViews中,mDyingViews表示待删除的View的集合。如果是同步删除,不发送消息就直接调用dodie():
void doDie() {checkThread();if (LOCAL_LOGV) Log.v(mTag, "DIE in " + this + " of " + mSurface);synchronized (this) {if (mRemoved) {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);}} catch (RemoteException e) {}}mSurface.release();}}mAdded = false;}WindowManagerGlobal.getInstance().doRemoveView(this);
}
复制代码
在dodie()内部会调用dispatchDetachedFromWindow(),真正删除View的逻辑就在dispatchDetachedFromWindow()中:
void dispatchDetachedFromWindow() {if (mView != null && mView.mAttachInfo != null) {mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);mView.dispatchDetachedFromWindow();}.....try {mWindowSession.remove(mWindow);} catch (RemoteException e) {}
}
复制代码
dispatchDetachedFromWindow()主要做几件事情:
- 垃圾回收相关操作,比如清除数据和消息,移除回调;
- 通过Session的remove()删除Window,这同样是一个IPC过程,最终会调用WindowManagerService的removeWindow();
- 调用View的dispatchDetachedFromWindow(),进而调用View的onDetachedFromWindow(),onDetachedFromWindowInternal()。对于onDetachedFromWindow()对于大家来说一定不陌生,我们可以在这个方法内部做一些资源回收工作,比如终止动画、停止线程等;
- 最后再调用WindowManagerGlobal的doRemoveView()方法刷新数据,包括mRoots、mParams、mViews和mDyingViews,将当前Window所关联的对象从集合中删除。
WindowManager的更新
updateViewLayout()做的事情就比较简单了,首先先更新View的LayoutParams,接着更新ViewRootImpl的LayoutParams。ViewRootImpl会在setLayoutParams()中调用scheduleTraversals()来对View重新布局重绘。除此之外ViewRootImpl还会通过WindowSession来更新Window的视图,这个过程最终由WindowManagerService的relayoutWindow()来具体实现,这同样是一个IPC过程。具体代码执行逻辑大家可以自行查看一下。