Window顾名思义就是窗口,Android Window的实现类是PhoneWindow。WindowManager是访问Window的入口,通过它可以创建Window,WindowManager的具体实现在WindowService中,Window与WindowService之间的交互是一种IPC过程。Android中的界面都是通过Window来呈现的,比如Activity、Dialog和Toast等,他们的界面都是附加在Window上的,因此View的实际管理者是Window。
1.Window与WindowManager
在了解Window的工作机制之前我们先来看下如何使用WindowManager添加一个Window。
WindowManager windowManager = getWindowManager();
Button btAdd = new Button(this);
btAdd.setText("手动添加按钮");
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat.TRANSPARENT);
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
layoutParams.gravity = Gravity.LEFT;
layoutParams.x = 100;
layoutParams.y = 200;
windowManager.addView(btAdd,layoutParams);
上面代码是将一个Button添加到坐标(100,200)的位置。下面简单介绍下WindowManager.LayoutParams中的flags与type这两个参数。
flags表示的是Window的属性,有很多选择项,简单介绍几种。
FLAG_NOT_FOCUSABLE:
表示Window不需要获取焦点,又不需要接受任何输入事件,次标记还会同时启用FLAG_NOT_TOUCH_MODAL,最终事件会传递给下层有焦点的Window。
FLAG_NOT_TOUCH_MODAL:
此模式下系统会将当前Window区域以外的单击事件传递给底层的Window,当前区域以内的单击事件则自己处理。
FLAG_SHOW_WHEN_LOCKED:
开启当前模式,可以让Window显示在锁屏界面上。
如果了解其他的属性,建议还是看下源码:
/** Window flag: as long as this window is visible to the user, allow
* the lock screen to activate while the screen is on.
* This can be used independently, or in combination with
* {@link #FLAG_KEEP_SCREEN_ON} and/or {@link #FLAG_SHOW_WHEN_LOCKED} */
public static final int FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001;
/** Window flag: everything behind this window will be dimmed.
* Use {@link #dimAmount} to control the amount of dim. */
public static final int FLAG_DIM_BEHIND = 0x00000002;
/** Window flag: blur everything behind this window.
* @deprecated Blurring is no longer supported. */
@Deprecated
public static final int FLAG_BLUR_BEHIND = 0x00000004;
type表示Window的类型,一般Window有三种类型:应用Window、子Window和系统Window。应用类的Window对应着一个Activity。子Window是不能单独存在的,他需要在特定的父Window之中,比如常见的Dialog就是一个子Window。系统Window需要声明特殊的权限才能创建,比如Toast跟系统状态栏等。
Window是分层的,每个Window都有对应的z-ordered,层级大的会覆盖在层级小的Window的上面,这和HTML中的z-index的概念是完全一致的。在三类Window中,应用Window的层级范围是1~99,子Window的层级范围是1000~1999,系统Window的层级范围是2000~2999,这些层级范围对应着WindowManager.LayoutParams的type参数。如果想要Window位于所有Window的最顶层,那么采用较大的层级即可。很显然系统Window的层级是最大的,而且系统层级有很多值,一般我们可以选用TYPE_SYSTEM_OVERLAY或者TYPE_SYSTEM_ERROR,如果采用TYPE_SYSTEM_ERROR,只需要为type参数指定这个层级即可:mLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR;同时声明权限:<uses-permissionandroid: name= “android.permission .SYSTEM_ALERT_WINDOW”/>。因为系统类型的Window是需要检查权限的,如果不在AndroidManifest 中使用相应的权限,那么创建Window的时候就会报错。
WindowManager的功能比较简单,常用的就是三个方法:addView、updateViewLayout和removeView,这三个方法都定义在ViewManager中,WindowManager继承了ViewManager。
/** Interface to let you add and remove child views to an Activity. To get an instance
* of this class, call {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
*/
public interface ViewManager
{
/**
* Assign the passed LayoutParams to the passed View and add the view to the window.
* <p>Throws {@link android.view.WindowManager.BadTokenException} for certain programming
* errors, such as adding a second view to a window without removing the first view.
* <p>Throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a
* secondary {@link Display} and the specified display can't be found
* (see {@link android.app.Presentation}).
* @param view The view to be added to this window.
* @param params The LayoutParams to assign to view.
*/
public void addView(View view, ViewGroup.LayoutParams params);
public void updateViewLayout(View view, ViewGroup.LayoutParams params);
public void removeView(View view);
}
对于我们开发者来说,WindowManager常用的就只有这三个功能,当然这三个方法也就足够用了。WindowManager操作Window其实就是在操作里面的View。通过这些方法,我们可以实现诸如随意拖拽位置的Window等效果。
2.Window的内部机制
Window是一个抽象类,每个Window都对应一个View跟一个ViewRootImpl,Window跟View是通过ViewRootImpl建立联系的,因此Window并不实际存在,它是以View的形式存在的。从WindowManager的定义跟主要方法也能看出,View是Window存在的实体。下面就具体介绍下Window的addView、updateViewLayout和removeView。
2.1Window的添加过程。
Window的添加过程需要通过WindowManager的addView来实现,不过WindowManager是一个接口,真正实现是在WindowManagerImpl中,三个主要操作,先上源码:
@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);
}
上面的源码很明显,WindowManagerImpl也没有直接实现Window的三大操作,而是由WindowManagerGlobal来处理的,代码段:private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance(); 可以看出,WindowManagerGlobal以工厂的形式向外提供自己的实例。WindowManagerImpl这种工作模式是典型的桥接模式,将所有的操作委托给WindowManagerGlobal来实现。具体看下addView的源码:
1.检查参数是否合法,子Window还需要调整布局:
......
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;
}
}
......
2.创建ViewRootImpl并将View添加到列表中
WindowManagerGlobal中的几个重要列表:
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则是对应的布局。mDyingViews存储的是正在被删除的View。
......
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
......
上面源码表示了addView添加View的过程。
3.通过ViewRootImpl来更新界面,完成Window的添加过程
......
// do this last because it fires off messages to start doing things
try {
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
// BadTokenException or InvalidDisplayException, clean up.
if (index >= 0) {
removeViewLocked(index, true);
}
throw e;
}
......
ViewRootImpl的setView方法在界面View的时候有说到,在setView内部,通过requestLayout方法实现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();
......
接着通过WindowSession来完成Window的添加过程。下面的源码中,mWindowSession是IWindowSession的实例,这是一个Binder对象,真正的实现类是Session,也就是说Window的添加过程是一次IPC调用。
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();
}
}
Session内部会通过WindowManagerService来实现Window的添加过程。
介绍到这里,各位就发现,Window的添加请求是交给WindowManagerService去处理的,WindowManagerService内部会为每一个应用保留一个单独的Session。具体的代码的逻辑大家看下源码,这里主要介绍部分源码,还是以流程为主。
2.2Window的删除过程
Window的删除过程与添加过程一样,都是先通过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);
}
}
removeView的过程还是比较简洁的,先findViewLocked找到待删除的View的索引,这个索引是上面说的ArrayList mViews的index,然后删除掉这个就可以了。
private int findViewLocked(View view, boolean required) {
final int index = mViews.indexOf(view);
if (required && index < 0) {
throw new IllegalArgumentException("View=" + view + " not attached to window manager");
}
return index;
}
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);
}
}
}
在WindowManager中提供了两种删除的接口:removeView跟removeViewImmediate,他们分别表示异步跟同步删除,removeViewImmediate方法一般不会使用,以免删除Window发生意外错误。我们重点看下异步删除的情况。代码段6可以看到,删除操作是通过ViewRootImpl的die方法完成的,具体看下这个方法:
/**
* @param immediate True, do now if not in traversal. False, put on queue and do later.
* @return True, request has been queued. False, request has been completed.
*/
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方法只是发了一个请求,然后就返回了,再看代码段6,View被加到mDyingViews中了。异步删除可以看到发送了一个message,MSG_DIE,然后ViewRootImpl的handler会处理此消息然后调用die方法,同步的话就直接删除了。这也是这两种删除方式的区别。真正删除View的逻辑在doDie方法的dispatchDetachedFromWindow方法中。
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);
}
void dispatchDetachedFromWindow() {
if (mView != null && mView.mAttachInfo != null) {
mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
mView.dispatchDetachedFromWindow();
}
mAccessibilityInteractionConnectionManager.ensureNoConnection();
mAccessibilityManager.removeAccessibilityStateChangeListener(
mAccessibilityInteractionConnectionManager);
mAccessibilityManager.removeHighTextContrastStateChangeListener(
mHighContrastTextManager);
removeSendWindowContentChangedCallback();
destroyHardwareRenderer();
setAccessibilityFocus(null, null);
mView.assignParent(null);
mView = null;
mAttachInfo.mRootView = null;
mSurface.release();
if (mInputQueueCallback != null && mInputQueue != null) {
mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
mInputQueue.dispose();
mInputQueueCallback = null;
mInputQueue = null;
}
if (mInputEventReceiver != null) {
mInputEventReceiver.dispose();
mInputEventReceiver = null;
}
try {
mWindowSession.remove(mWindow);
} catch (RemoteException e) {
}
// Dispose the input channel after removing the window so the Window Manager
// doesn't interpret the input channel being closed as an abnormal termination.
if (mInputChannel != null) {
mInputChannel.dispose();
mInputChannel = null;
}
mDisplayManager.unregisterDisplayListener(mDisplayListener);
unscheduleTraversals();
}
从上面的源码可以看到,dispatchDetachedFromWindow主要做了3件事:
(1)垃圾回收相关工作
(2)通过Session的remove方法删除Window
(3)调用View的dispatchDetachedFromWindow方法,内部调用View的onDetachedFromWindow方法,这个也是做一些资源回收比较合适的时机,比如终止动画、停止线程等。
最终doDie方法调用WindowManagerGlobal的doRemoveView刷新数据。
2.3Window的更新过程
介绍完Window的删除,Window的更新过程直接上源码:
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);
}
}
看源码还是很简单的,首先更新LayoutParams,然后通过ViewRootImpl的setLayoutParams更新ViewRootImpl中的LayoutParams,然后ViewRootImpl通过scheduleTraversals对View重新布局,包括测量,布局,绘制这三个过程。除了View本身重绘之外,ViewRootImpl会通过Session来更新Window视图,同样也是有WindowManagerService的relayoutWindow来实现的,也是一个IPC过程。