[034]Activity启动时间

前言

我相信大家肯定遇到过Activity启动慢的BUG,在优化问题之前,我们都会自我测试一下Activity启动耗时是不是和测试给的数值一样,在我们没有高速相机的情况下,我们如何获得Activity启动时间。
我一般都用这个指令:

adb logcat -b all | grep am_activity_launch_time

注意结果最后的数字297,代表Activity启动的时长297ms。

am_activity_launch_time: [0,44198042,com.kobe.jankblock/.MainActivity,297]

一、am_activity_launch_time计算的截止时间

一般对于一个Activity显示到屏幕上,有三个重要时间点,请问am_activity_launch_time计算的截止时间是以下哪个事件完成之后的。
onCreate
onResume
doTraversal-View.onDraw

二、Demo时间

写个demo试试看。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            Thread.sleep(100);//休眠100ms
        }catch (Exception e) {

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            Thread.sleep(200);//休眠200ms
        }catch (Exception e) {

        }
    }
}
public class MyTextView extends TextView {
    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        try {
            Thread.sleep(400);//休眠100ms
        }catch (Exception e) {

        }
    }
}

上述代码非常简单,我分别在三个阶段block了100ms,200ms,400ms
这几个数值选取还是很有讲究的,我们可以通过一次测试就可以得到结论。
测试结果:1008 - 297 = 711 约等于 700ms。

am_activity_launch_time: [0,44198042,com.kobe.jankblock/.MainActivity,1008]
答案:am_activity_launch_time是以第一次doTraversal-View.onDraw完成为截止时间的,也就是Activity的第一帧绘制完成的时间(当然这句话不准确,因为真正的绘制还需要通过RenderThread去绘制)。

三、源码分析

我们就看看这个am_activity_launch_time是怎么计算的。

3.1 logAppDisplayed

/frameworks/base/services/core/java/com/android/server/wm/ActivityMetricsLogger.java

    private void logAppDisplayed(WindowingModeTransitionInfoSnapshot info) {
        if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
            return;
        }

        EventLog.writeEvent(AM_ACTIVITY_LAUNCH_TIME,
                info.userId, info.activityRecordIdHashCode, info.launchedActivityShortComponentName,
                info.windowsDrawnDelayMs);//注意这个windowsDrawnDelayMs的值

        StringBuilder sb = mStringBuilder;
        sb.setLength(0);
        sb.append("Displayed ");
        sb.append(info.launchedActivityShortComponentName);
        sb.append(": ");
        TimeUtils.formatDuration(info.windowsDrawnDelayMs, sb);
        Log.i(TAG, sb.toString());
    }

我们需要找到windowsDrawnDelayMs赋值的地方

3.2 notifyWindowsDrawn

/frameworks/base/services/core/java/com/android/server/wm/ActivityMetricsLogger.java

     /**
     * Notifies the tracker that all windows of the app have been drawn.
     */
    WindowingModeTransitionInfoSnapshot notifyWindowsDrawn(@WindowingMode int windowingMode,
                                                           long timestamp) {
        if (DEBUG_METRICS) Slog.i(TAG, "notifyWindowsDrawn windowingMode=" + windowingMode);

        final WindowingModeTransitionInfo info = mWindowingModeTransitionInfo.get(windowingMode);
        if (info == null || info.loggedWindowsDrawn) {
            return null;
        }
        info.windowsDrawnDelayMs = calculateDelay(timestamp);//调用3.2.1
        info.loggedWindowsDrawn = true;
        final WindowingModeTransitionInfoSnapshot infoSnapshot =
                new WindowingModeTransitionInfoSnapshot(info);
        if (allWindowsDrawn() && mLoggedTransitionStarting) {
            reset(false /* abort */, info, "notifyWindowsDrawn - all windows drawn");
        }
        return infoSnapshot;
    }

    //3.2.1
    private int calculateDelay(long timestamp) {
        // Shouldn't take more than 25 days to launch an app, so int is fine here.
        return (int) (timestamp - mCurrentTransitionStartTime);
    }

info.windowsDrawnDelayMs = timestamp - mCurrentTransitionStartTime,所以我们需要找到调用notifyWindowsDrawn的地方。

3.3 onWindowsDrawn

/frameworks/base/services/core/java/com/android/server/wm/ActivityRecord.java

    /** Called when the windows associated app window container are drawn. */
    public void onWindowsDrawn(boolean drawn, long timestamp) {
        synchronized (mAtmService.mGlobalLock) {
            mDrawn = drawn;
            if (!drawn) {
                return;
            }
            final WindowingModeTransitionInfoSnapshot info = mStackSupervisor
                    .getActivityMetricsLogger().notifyWindowsDrawn(getWindowingMode(), timestamp);
            final int windowsDrawnDelayMs = info != null ? info.windowsDrawnDelayMs : INVALID_DELAY;
            final @LaunchState int launchState = info != null ? info.getLaunchState() : -1;
            mStackSupervisor.reportActivityLaunchedLocked(false /* timeout */, this,
                    windowsDrawnDelayMs, launchState);
            mStackSupervisor.stopWaitingForActivityVisible(this);
            finishLaunchTickingLocked();
            if (task != null) {
                task.hasBeenVisible = true;
            }
        }
    }

我们只要找对到onWindowsDrawn被调用的地方就可以了,我就不继续逆向分析,直接给出调用关系。

3.4 调用关系

3.4.1 App绘制完成如何通知WindowManagerService

有兴趣的朋友可以去看reportDrawFinished是什么时候被回调的,我就不深入讲了,不想研究的,只要记住第一帧绘制结束就会调用reportDrawFinished。
最后WindowSurfacePlacer中post(mPerformSurfacePlacement)
异步执行mPerformSurfacePlacement.run()

3.4.2 mPerformSurfacePlacement.run()如何调用到3.3 onWindowsDrawn

因为整个代码调用关系比较长,我就不画时序图了,直接给出调用堆栈。

V kobe    : java.lang.Exception: kobe
V kobe    :     at com.android.server.wm.ActivityRecord.onWindowsDrawn(ActivityRecord.java:2458)
V kobe    :     at com.android.server.wm.AppWindowToken.updateReportedVisibilityLocked(AppWindowToken.java:432)
V kobe    :     at com.android.server.wm.AppWindowToken.onFirstWindowDrawn(AppWindowToken.java:394)
V kobe    :     at com.android.server.wm.WindowState.performShowLocked(WindowState.java:3955)
V kobe    :     at com.android.server.wm.WindowStateAnimator.commitFinishDrawingLocked(WindowStateAnimator.java:349)
V kobe    :     at com.android.server.wm.DisplayContent.lambda$new$8$DisplayContent(DisplayContent.java:859)
V kobe    :     at com.android.server.wm.-$$Lambda$DisplayContent$qxt4izS31fb0LF2uo_OF9DMa7gc.accept(Unknown Source:4)
V kobe    :     at com.android.server.wm.WindowContainer$ForAllWindowsConsumerWrapper.apply(WindowContainer.java:1178)
V kobe    :     at com.android.server.wm.WindowContainer$ForAllWindowsConsumerWrapper.apply(WindowContainer.java:1168)
V kobe    :     at com.android.server.wm.WindowState.applyInOrderWithImeWindows(WindowState.java:4168)
V kobe    :     at com.android.server.wm.WindowState.forAllWindows(WindowState.java:4067)
V kobe    :     at com.android.server.wm.WindowContainer.forAllWindows(WindowContainer.java:877)
V kobe    :     at com.android.server.wm.AppWindowToken.forAllWindowsUnchecked(AppWindowToken.java:2061)
V kobe    :     at com.android.server.wm.AppWindowToken.forAllWindows(AppWindowToken.java:2051)
V kobe    :     at com.android.server.wm.WindowContainer.forAllWindows(WindowContainer.java:877)
V kobe    :     at com.android.server.wm.WindowContainer.forAllWindows(WindowContainer.java:877)
V kobe    :     at com.android.server.wm.WindowContainer.forAllWindows(WindowContainer.java:877)
V kobe    :     at com.android.server.wm.DisplayContent$TaskStackContainers.forAllWindows(DisplayContent.java:4447)
V kobe    :     at com.android.server.wm.DisplayContent.forAllWindows(DisplayContent.java:2224)
V kobe    :     at com.android.server.wm.WindowContainer.forAllWindows(WindowContainer.java:894)
V kobe    :     at com.android.server.wm.DisplayContent.applySurfaceChangesTransaction(DisplayContent.java:3838)
V kobe    :     at com.android.server.wm.RootWindowContainer.applySurfaceChangesTransaction(RootWindowContainer.java:864)
V kobe    :     at com.android.server.wm.RootWindowContainer.performSurfacePlacementNoTrace(RootWindowContainer.java:641)
V kobe    :     at com.android.server.wm.RootWindowContainer.performSurfacePlacement(RootWindowContainer.java:598)
V kobe    :     at com.android.server.wm.WindowSurfacePlacer.performSurfacePlacementLoop(WindowSurfacePlacer.java:159)
V kobe    :     at com.android.server.wm.WindowSurfacePlacer.performSurfacePlacement(WindowSurfacePlacer.java:105)
V kobe    :     at com.android.server.wm.WindowSurfacePlacer.performSurfacePlacement(WindowSurfacePlacer.java:95)
V kobe    :     at com.android.server.wm.WindowSurfacePlacer.lambda$new$0$WindowSurfacePlacer(WindowSurfacePlacer.java:62)
V kobe    :     at com.android.server.wm.-$$Lambda$WindowSurfacePlacer$4Hbamt-LFcbu8AoZBoOZN_LveKQ.run(Unknown Source:2)
V kobe    :     at android.os.Handler.handleCallback(Handler.java:883)
V kobe    :     at android.os.Handler.dispatchMessage(Handler.java:100)
V kobe    :     at android.os.Looper.loop(Looper.java:214)
V kobe    :     at android.os.HandlerThread.run(HandlerThread.java:67)
V kobe    :     at com.android.server.ServiceThread.run(ServiceThread.java:44)

四、总结

am_activity_launch_time是截止到activity的第一帧绘制完成的时间,整个时间包含onCreate,onResume,doTraversal,一般情况下am_activity_launch_time还是很客观地展现出一个activity启动时间。

但是有时候测试标准不一样,测试标准可能要求是整个界面完全显示出来,尤其是需要异步网络请求数据,后面几帧展现更多UI,对于这个情况,Activity启动时间就要远远大于am_activity_launch_time。

但是通过am_activity_launch_time来衡量一个Activity启动时间还是很科学的。

五、尾巴

我主要是跟踪了这个timestamp是怎么来的,你们自己可以跟一下mCurrentTransitionStartTime

    private int calculateDelay(long timestamp) {
        // Shouldn't take more than 25 days to launch an app, so int is fine here.
        return (int) (timestamp - mCurrentTransitionStartTime);
    }

如何跟踪Android的源码,最要的是记住关键的跨进程Binder调用点,跨线程的Handler异步调用点。我上面跟踪代码中就有一处跨进程Binder调用点和跨线程的Handler异步调用点,欢迎留言回答。

你可能感兴趣的:([034]Activity启动时间)