Activity的resume
上次在Activity的启动流程中,我们知道了Activity的生命周期都是通过Handler发送消息来执行的,而View的绘制就是在onResume之后:
// H();
case RESUME_ACTIVITY:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
SomeArgs args = (SomeArgs) msg.obj;
handleResumeActivity((IBinder) args.arg1, true, args.argi1 != 0, true,
args.argi3, "RESUME_ACTIVITY");
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
// 调用onResume方法
r = performResumeActivity(token, clearHide, reason);
// 将decorView添加到屏幕中
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
wm.addView(decor, l);
}
// WindowManagerImpl.java
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}
-
handleResumeActivity
方法首先调用performResumeActivity
也就是我们Activity中的onResume方法。 - 在通过获取到decorView,我们的布局其实已经加载到decorView中了,在通过wm的addView方法将decorView传递出去。
- wm其实就是
WindowManagerImpl
,而在WindowManagerImpl
中又调用了WindowManagerGlobal
的addView
方法。
// WindowManagerGlobal.java
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
ViewRootImpl root;
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
root.setView(view, wparams, panelParentView);
}
// ViewRootImpl.java
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
requestLayout();
}
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
void scheduleTraversals() {
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
}
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
final class TraversalRunnable implements Runnable {
@Override
public void run() {
doTraversal();
}
}
在addView方法中首先构建了ViewRootImpl
这个非常关键的类,这个类就是操作View的绘制流程的类,在通过setView
方法设置View。
而在setView方法中我们又看到了非常熟悉的一个方法requestLayout
,我们在自定义ViewGroup的时候,如果要更新布局就会调用这个方法刷新界面,其实就是调用了View的重新绘制流程。
经过一系列的调用之后,最终调用了doTraversal
方法。
measure
void doTraversal() {
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
}
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
onMeasure(widthMeasureSpec, heightMeasureSpec);
}
在doTraversal
中调用了performMeasure
,而performMeasure
又调用了View的onMeasure方法,这个才开始真正的测量。
我们以LinearLayout的VERTICAL
来分析:
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
heightMeasureSpec, usedHeight);
}
if (useLargestChild &&
(heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED)) {
mTotalLength = 0;
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
if (child == null) {
mTotalLength += measureNullChild(i);
continue;
}
if (child.getVisibility() == GONE) {
i += getChildrenSkipCount(child, i);
continue;
}
final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)
child.getLayoutParams();
// Account for negative margins
final int totalLength = mTotalLength;
mTotalLength = Math.max(totalLength, totalLength + largestChildHeight +
lp.topMargin + lp.bottomMargin + getNextLocationOffset(child));
}
}
// Add in our padding
mTotalLength += mPaddingTop + mPaddingBottom;
int heightSize = mTotalLength;
int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
}
void measureChildBeforeLayout(View child, int childIndex,
int widthMeasureSpec, int totalWidth, int heightMeasureSpec,
int totalHeight) {
measureChildWithMargins(child, widthMeasureSpec, totalWidth,
heightMeasureSpec, totalHeight);
}
protected void measureChildWithMargins(View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
+ heightUsed, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
首先遍历所有的子View,然后通过子View的measure方法来继续测量,如果子View是ViewGroup则继续遍历,如果是View则直接可以测量子View的宽高。而在View的measure中调用了onMeasure方法,这个方法就是我们平时写的自定义View的时候覆盖的方法,来指定我们自定义View的宽高。
通过深入优先遍历的算法,从最里层的View开始测量,最终测量到最外层的ViewGroup。
当测量到最外层的时候,会再次遍历自己的子View将子View的宽高计算。
最终调用setMeasuredDimension将宽高设置好。
layout
void doTraversal() {
performLayout(lp, mWidth, mHeight);
}
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
}
public void layout(int l, int t, int r, int b) {
onLayout(changed, l, t, r, b);
}
当performMeasure方法执行完之后,doTraversal
又调用了performLayout
来进行确定子View的位置。而performLayout
则继续调用View的layout方法,在这里我们又见到了熟悉的onLayout
。
同样以LinearLayout的VERTICAL
来分析
void layoutVertical(int left, int top, int right, int bottom) {
for (int i = 0; i < count; i++) {
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
layoutVertical会遍历所有的子View并调用setChildFrame来为子View指定对应的位置。
这个时候layout和measure的计算方式又有所区别,measure是通过深度优先遍历的方式,首先获取子View的宽高,而layout指定View的位置的时候,是从外向内,依次遍历指定View的位置。
draw
void doTraversal() {
performDraw();
}
private void performDraw() {
try {
// 调用绘制函数
draw(fullRedrawNeeded);
} finally {
mIsDrawing = false;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
private void draw(boolean fullRedrawNeeded) {
// 获取surface
Surface surface = mSurface;
if (!surface.isValid()) {
return;
}
// 绘制需要更新
if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
// 使用硬件加速
if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
// 使用硬件渲染绘制
mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
} else {
// 使用cpu绘制
if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
return;
}
}
}
if (animating) {
mFullRedrawNeeded = true;
scheduleTraversals();
}
}
当performMeasure方法执行完之后,doTraversal
又调用了performDraw
开始绘制视图。
在draw函数中获取需要绘制的区域,再判断是否使用硬件加速。
通常情况下都是使用cpu绘制,也就是直接调用drawSoftware:
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
boolean scalingRequired, Rect dirty) {
// Draw with software renderer.
final Canvas canvas;
try {
final int left = dirty.left;
final int top = dirty.top;
final int right = dirty.right;
final int bottom = dirty.bottom;
// 获取canvas对象,用于framework层绘制
canvas = mSurface.lockCanvas(dirty);
} catch (Surface.OutOfResourcesException e) {
return false;
}
try {
// 开始绘制,从decorView开始绘制
mView.draw(canvas);
} finally {
// 释放canvas锁,并通知SurfaceFlinger更新
// private static native void nHwuiDraw(long renderer); 调用native方法
surface.unlockCanvasAndPost(canvas);
}
return true;
}
从上面的函数可以看出绘制的过程:
- 判断使用gpu还是cpu渲染
- 获取绘制的surface对象
- 通过surface获取并锁住canvas对象
- 从DecorView开始发起整个view树的绘制
- 解锁canvas对象,并通知surfaceFlinger对象更新视图,调用native方法。
我们来看View的draw函数:
public void draw(Canvas canvas) {
drawBackground(canvas);
if (!verticalEdges && !horizontalEdges) {
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Overlay is part of the content and draws beneath Foreground
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
// we're done...
return;
}
}
View的draw方法会调用dispatchDraw(canvas)
来传递绘制过程,dispatchDraw会遍历调用所有子元素的draw方法,这样draw就会一层一层的传递下去,知道最后一个View绘制完成。
这个时候View的整个绘制流程就完成了。