转载请声明出处: https://blog.csdn.net/AndrExpert/article/details/81349343
在从Android 6.0源码的角度剖析UI界面架构的文章中,我们了解到每个Activity都对应着一个Window,Window是一个抽象的概念,它的具体表现形式是View。每一个Window都对应着一个View和一个ViewRootImpl,Window和View通过ViewRootImpl来建立联系。对于Window来说,WindowManager是外界访问Window的入口,Window的具体实现位于WindowManagerService中,WindowManager和WindowManagerService是一个交互是一个IPC过程。总之,Android中所有的视图(Activity、Dialog或Toast等)都是依附在Window来呈现的,Window实际是View的直接管理者。
WindowManager
是用于与Window管理器交互的接口,它继承于接口ViewManager,可通过Context.getSystemService(Context.WINDOW_SERVICE)
方式获取WindowManager的实例。ViewManager
提供了三个操作Window的方法,即addView()、updateViewLayout()、removeView(),它们分别实现Window内容的添加、更新、删除操作。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的源码发现,WindowManager并没有实现上述三个方法,根据以往的开发经验,源码中应该有个WindowManager的继承类,用于实现上述三个方法。因此,我们在…\frameworks\base\core\java\android\view目录下找到了WindowManagerImpl
,它虽然实现了addView()、removeView()、updateViewLayout()三个方法,但是却并没有真正实现相关功能逻辑,而是直接”委托”WindowManagerGlobal
并调用其相关方法实现具体的功能逻辑。WindowManagerImpl 源码如下:
public final class WindowManagerImpl implements WindowManager {
// 操作view逻辑具体实现类
private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
private final Display mDisplay;
// mParentWindow在Activity被创建时调用Activity的attach方法实例化
private final Window mParentWindow;
private IBinder mDefaultToken;
public WindowManagerImpl(Display display) {
this(display, null);
}
private WindowManagerImpl(Display display, Window parentWindow) {
mDisplay = display;
mParentWindow = parentWindow;
}
public WindowManagerImpl createLocalWindowManager(Window parentWindow) {
return new WindowManagerImpl(mDisplay, parentWindow);
}
// 实例化WindowManagerImpl
public WindowManagerImpl createPresentationWindowManager(Display display) {
return new WindowManagerImpl(display, mParentWindow);
}
// 添加view到Window
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mDisplay, mParentWindow);
}
// 更新window中的view
@Override
public void updateViewLayout(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.updateViewLayout(view, params);
}
// 从Window中删除view
@Override
public void removeView(View view) {
mGlobal.removeView(view, false);
}
@Override
public void removeViewImmediate(View view) {
mGlobal.removeView(view, true);
}
@Override
public Display getDefaultDisplay() {
return mDisplay;
}
...
}
由上述分析可知,当我们需要将一个View添加到Activity对应的Window中时,调用WindowManager的addView()方法,该方法最终会调用WindowManagerGlobal的addView()方法来实现具体的功能逻辑。在开始分析之前,我们先看下WindowManagerGlobal的几个重要的成员变量:
// 存放所有要添加到窗口的view
private final ArrayList mViews = new ArrayList();
// 存放绘制view的viewRootImpl,每一个view对应一个ViewRootImpl
private final ArrayList mRoots = new ArrayList();
// 存放所有view对应的LayoutParams
private final ArrayList mParams =
new ArrayList();
// 存放将要被移除的view
private final ArraySet mDyingViews = new ArraySet();
其中,mViews为存储所有要添加到Window中View的集合;mRoots为存储View相对应的具体实现类ViewRootImpl的集合;mParams为存储View相对应参数类WindowManager.LayoutParams的集合;mDyingViews 为存储将要被移除View的集合。WindowManagerGlobal的addView()具体执行流程如下:
首先,addView()方法会对传入的参数进行相关的边界检查;其次,通过findViewLocked()方法遍历查找mViews(View集合)中是否存在这个需要被add的view,如果存在(index>=0)即表明该View被重复则要么执行从Window移除该View的操作或抛出异常"View .. has already been added to the window manager."
(很熟悉吧^_^);接着,创建view的实现类ViewRootImpl的实例root,为view设置布局参数wparams,并将view、root、wparams添加到相关的集合中。由此可知,每一个View都对应着一个ViewRootImpl、LayoutParams
,其中前者为View的具体实现类,LayoutParams为View的布局参数;最后,调用ViewRootImpl的setView()方法
完成后面的绘制过程,setView内部会通过requetLayout来完成异步刷新请求。
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
// (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);
} 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);
}
// (2) 获取view在集合中的下标
// 如果index>=0说明该view已经被添加到window中
int index = findViewLocked(view, false);
if (index >= 0) {
// 如果打算移除该view,如果是执行ViewRootImpl的doDie
// 无需等待MSG_DIE消息,直接从view队列中移除
if (mDyingViews.contains(view)) {
// Don't wait for MSG_DIE to make it's way through root's queue.
mRoots.get(index).doDie();
} else {
// 重复添加,抛出"has already been added to the window manager"异常
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);
}
}
}
// (3) 实例化view对应的ViewRootImpl
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
// 将与view相关添加到集合中
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
}
// do this last because it fires off messages to start doing things
// (4) 最后,执行ViewRootImpl的setView方法完成add view任务
// // 执行绘制流程重新布局
// requestLayout();
try {
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
// BadTokenException or InvalidDisplayException, clean up.
synchronized (mLock) {
final int index = findViewLocked(view, false);
if (index >= 0) {
removeViewLocked(index, true);
}
}
throw e;
}
}
从上面的分析可知,addView执行到root.setView(…)后,setView()内部首先会通过requetLayout()来完成异步刷新请求
,该方法会调用scheduleTraversals()方法执行绘制View流程,也就是说,scheduleTraversals()方法实际是View绘制的入口
。(View的绘制流程请参考:从Android 6.0源码的角度剖析View的绘制流程);然后调用IWindowSession的addToDisplay方法将view添加到Window中。相关源码如下:
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
...
// 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.
// 执行绘制流程重新布局
// 调用scheduleTraversals()
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
mInputChannel = new InputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
// 执行IWindowSession的addToDisplay方法实现view添加
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();
}
}
...
}
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
// View绘制入口
scheduleTraversals();
}
}
IWindowSession是一个抽象接口,它的addToDisplay方法具体的逻辑必定实在IWindowSession的子类中实现,根据IWindowSession的命名可推得,这个子类就是Session,Session类继承于IWindowSession.Stub,是一个final类,每个应用通常有一个Session对象与窗口管理器(Window Manager)交互
。通过查看源码可知,addToDisplay()方法并没有实现相关的view添加逻辑,而是交给WindowManagerService的addWindow()方法来实现。有过跨进程通信(IPC)开发的朋友应该看到IWindowSession、Session以及WindowManagerService的代码结构应该很熟悉,实际上IWindowSession是一个Binder对象,Session、WindowManagerService均继承于IWindowSession.Stub,只是Session对象位于你开发的应用进程中,而WindowManagerService在系统进程中,即addView()操作实质上是一次跨进程调用(IPC)
。addToDisplay()源码如下:
@Override
public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
int viewVisibility, int displayId, Rect outContentInsets, Rect outStableInsets,
Rect outOutsets, InputChannel outInputChannel) {
// mService为WindowManagerService的实例
return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId,
outContentInsets, outStableInsets, outOutsets, outInputChannel);
}
至此,通过WindowManager的addView()方法将view添加到Window中的工作原理大概就剖析完毕了,至于WindowManagerService是如何实现真正的添加逻辑的,我们在Activity的Window创建过程章节再详谈。下图为源码中执行流程:
与调用WindowManager的addView()类似,WindowManager调用removeView()方法从Window中删除指定view是从WindowManagerGlobal的removeView()方法开始的。首先,该方法会调用findViewLocked()方法
获取被删除view在mViews集合中的下标,并根据下标从获取缓存在ViewRootImpl中的View实例,以便后面判断View对象是否为同一个;然后,调用removeViewLocked方法
执行具体的删除逻辑。WindowManagerGlobal的removeView()方法、removeViewLocked()方法源码如下:
public void removeView(View view, boolean immediate) {
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
// (1)获取要删除view位于mViews集合中的下标
// 然后根据下标取出view实例
synchronized (mLock) {
int index = findViewLocked(view, true);
View curView = mRoots.get(index).getView();
// (2) 执行删除逻辑
removeViewLocked(index, immediate);
if (curView == view) {
return;
}
throw new IllegalStateException("Calling with view " + view
+ " but the ViewAncestor is attached to " + curView);
}
}
private void removeViewLocked(int index, boolean immediate) {
// 根据下标获取ViewRootImpl对象
ViewRootImpl root = mRoots.get(index);
// 获取缓存在ViewRootImpl的View对象
View view = root.getView();
if (view != null) {
InputMethodManager imm = InputMethodManager.getInstance();
if (imm != null) {
imm.windowDismissed(mViews.get(index).getWindowToken());
}
}
// mGlobal.removeView(view, false);
// 即immediate=false
boolean deferred = root.die(immediate);
if (view != null) {
view.assignParent(null);
if (deferred) {
mDyingViews.add(view);
}
}
}
removeViewLocked(index, immediate)方法主要做2件事情:
(1) 根据Index下标获取存储在mRoots缓存中的ViewRootImpl对象,同时获取缓存在ViewRootImpl的View实例;
(2) 调用ViewRootImpl对象的die(immediate)方法,该方法会根据传入的immediate参数决定删除view的方式,即如果immediate && !mIsInTraversal为真,则调用doDie()方法执行立即执行删除操作(同步删除
),否则,只是使用Handler发送发送一个MSG_DIE消息,然后将要删除的view添加到mDyingViews集合中表示待删除。Handler收到该消息后再在handleMessage()方法中调用doDie()执行删除操作(异步删除
)。ViewRootImpl的die()方法源码如下:
boolean die(boolean immediate) {
// 同步删除
if (immediate && !mIsInTraversal) {
doDie();
return false;
}
if (!mIsDrawing) {
destroyHardwareRenderer();
} else {
Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
" window=" + this + ", title=" + mWindowAttributes.getTitle());
}
// 异步删除,使用Handler发送一个MSG_DIE消息
mHandler.sendEmptyMessage(MSG_DIE);
return true;
}
接下来,我们详细分析下ViewRootImpl的doDie()方法,该方法完成最终删除的逻辑。首先,检查当前线程是否为UI线程,否则抛出异常”Only the original thread that created a view hierarchy can touch its views”,也就是说,我们调用WindowManager的removeView()方法必须在UI线程(主线程)中进行;其次,调用dispatchDetachedFromWindow()方法完成真正删除View的逻辑
,包括三个部分:(1)做一些垃圾回收工作(比如清楚数据和消除、移除回调);(2)调用View的dispatchDetachedFromWindow()和onDetachedFromWindow()方法,以通知View从Window中移除事件;(3)调用Session的remove(mWindow)方法删除Window,该方法最终会调用WindowManagerService的removeWindow(this,window)方法
。由此可见,执行WindowManager的removeView()方法同样是一个IPC过程
。最后,调用WindowManagerGlobal的doRemoveView方法刷新数据,包括mRoots、mParams和mDyingViews,以实现将当前Window所关联的对象从缓存中删除。ViewRootImpl的doDie()源码如下:
void doDie() {
// 检查当前线程是否为主线程,即UI线程
// 否则抛出Only the original thread that created a view hierarchy can touch its views.
checkThread();
if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
synchronized (this) {
if (mRemoved) {
return;
}
mRemoved = true;
// 执行view删除逻辑
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) {
// IPC操作,结束绘制
mWindowSession.finishDrawing(mWindow);
}
} catch (RemoteException e) {
}
}
mSurface.release();
}
}
mAdded = false;
}
// 执行WindowManagerGlobal的doRemoveView方法完成移除
// 只是删除缓存中的数据
WindowManagerGlobal.getInstance().doRemoveView(this);
}
与调用WindowManager的addView()类似,WindowManager调用updateViewLayout()方法更新Window中指定的view是从WindowManagerGlobal的updateViewLayout()方法开始的。 updateViewLayout()方法比较简单,首先它需要更新View的LayoutParams并替换老的LayoutParams,接着再通过ViewRootImpl的setLayoutParams()方法
更新ViewRootImpl中的LayoutParams,该方法最终会调用ViewRootImpl的scheduleTraversals()方法
重新对View进行布局,包括测量、布局、重绘这三个过程。WindowManagerGlobal的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");
}
// 更新View的布局参数
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;
view.setLayoutParams(wparams);
synchronized (mLock) {
// 获取view对应的ViewRootImpl对象
int index = findViewLocked(view, true);
ViewRootImpl root = mRoots.get(index);
// 更新mParams集合中的wparams
mParams.remove(index);
mParams.add(index, wparams);
// 执行
root.setLayoutParams(wparams, false);
}
}
由从Android 6.0源码的角度剖析View的绘制流程可知,除了View本身的重绘以外,ViewRootImpl还会通过Session的relayout()方法来更新Window的视图,这个过程最终由WindowManagerService的relayoutWindow()来实现。由此可见,WindowManager的updateViewLayout()也是一次IPC操作。updateViewLayout源码执行流程如下: