Android版本:7.0(API27)android
[TOC]程序员
窗口(不是指的Window类):这是一个纯语义的说法,即程序员所看到的屏幕上的某个独立的界面,好比一个带有Title Bar的Activity界面、一个对话框、一个Menu菜单等,这些都称之为窗口。本书中所说的窗口管理通常也都泛指全部这些窗口,在Android的英文相关文章中则直接使用Window这个单词。而从WmS的角度来说,窗口是接收用户消息的最小单元,WmS内部用特定的类表示一个窗口,以实现对窗口的管理。WmS接收到用户消息后,首先要判断这个消息属于哪一个窗口,而后经过IPC调用把这个消息传递给客户端的ViewRoot类。bash
Window类:该类在android.view包中,是一个abstract类,该类抽象了“客户端窗口”的基本操做,而且定义了一组Callback接口,Activity类就是经过实现这个Callback接口以得到对消息处理的机会,由于消息最初是由WmS传递给View对象的。app
ViewRoot类:该类在android.view包中,客户端申请建立窗口时须要一个客户端代理,用以和WmS进行交互,ViewRoot内部类W就是完成这个功能的。WmS所管理的每个窗口都会对应一个ViewRoot类。框架
W类:该类是ViewRoot类的一个内部类,继承于Binder,用于向WmS提供一个IPC接口,从而让WmS控制窗口客户端的行为。异步
描述一个窗口之因此使用这么多类的缘由在于,窗口的概念存在于客户端和服务端(WmS)之中,而且Framework又定义了一个Window类,这很容易让人产生混淆,实际上WmS所管理的窗口和Window类没有任何关系。ide
Activity、DecorView与Window、WindowMananger的关系以下图所示:oop
当ActivityThread接收到AmS发送start某个Activity后,就会建立指定的Activity对象。Activity又会建立PhoneWindow类→DecorView类→建立相应的View或者ViewGroup。建立完成后,Activity须要把建立好的界面显示到屏幕上,因而调用WindowManager类,后者因而建立一个ViewRootImpl对象,该对象实际上建立了ViewRootImpl类和W类,建立ViewRootImpl对象后,WindowManager再调用WmS提供的远程接口完成添加一个窗口并显示到屏幕上。
这其中ViewRootImpl很是重要,它具有以下几个核心功能:布局
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比较重要。post
应用类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);
}
复制代码
Window是一个抽象的概念,每个Window都对应着一个View和一个ViewRootImpl,Window和View经过ViewRootImpl来创建联系,所以Window并非实际存在的,它是以View的形式存在,这点从WindowManager的定义能够看出,它提供的三个接口方法都是针对View的,这说明View才是WIndow存在的实体。在实际使用中没法直接访问Window,对WIndow的访问必须经过WindowManager。为了分析Window的内部机制,这里从Window的添加、删除以及更新去分析。
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>();
复制代码
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 things try { root.setView(view, wparams, panelParentView); } catch (RuntimeException e) { // BadTokenException or InvalidDisplayException, clean up. if (index >= 0) { removeViewLocked(index, true); } throw e; } } } 复制代码
WindowManagerGlobal.addView方法的核心有两个做用:
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
复制代码
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的源码也很长,咱们将关键的几个步骤罗列出来。
在这里为后续“视图绘制”一文作个铺垫,进一步看一下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 {
@Override
public 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的。
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()主要作几件事情:
updateViewLayout()作的事情就比较简单了,首先先更新View的LayoutParams,接着更新ViewRootImpl的LayoutParams。ViewRootImpl会在setLayoutParams()中调用scheduleTraversals()来对View从新布局重绘。除此以外ViewRootImpl还会经过WindowSession来更新Window的视图,这个过程最终由WindowManagerService的relayoutWindow()来具体实现,这一样是一个IPC过程。具体代码执行逻辑你们能够自行查看一下。