blob: 68a71881b898d0013e529cdab856f56f5135f9b3 [file] [log] [blame]
Wale Ogunwale59507092018-10-29 09:00:30 -07001package com.android.server.wm;
Filip Gruszczynski77d94482015-12-11 13:59:52 -08002
Jorim Jaggi3878ca32017-02-02 17:13:05 -08003import static android.app.ActivityManager.START_SUCCESS;
4import static android.app.ActivityManager.START_TASK_TO_FRONT;
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005import static android.app.ActivityManager.processStateAmToProto;
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -08006import static android.app.WaitResult.LAUNCH_STATE_COLD;
7import static android.app.WaitResult.LAUNCH_STATE_HOT;
8import static android.app.WaitResult.LAUNCH_STATE_WARM;
Bryce Lee6c605092017-10-12 11:14:49 -07009import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
Wale Ogunwale3382ab12017-07-27 08:55:03 -070010import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale194435b2019-12-23 12:56:51 -080011import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
Wale Ogunwale3382ab12017-07-27 08:55:03 -070012import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
Vishnu Nair132ee832018-09-28 15:00:05 -070013import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale926aade2017-08-29 11:24:37 -070014import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
15import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Vishnu Nair132ee832018-09-28 15:00:05 -070016
Michal Karpinski201bc0c2018-07-20 15:32:00 +010017import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_ACTIVITY_START;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080018import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION;
Jorim Jaggi515dd682017-05-05 15:05:07 +020019import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_BIND_APPLICATION_DELAY_MS;
Todd Kennedy50d946c12017-03-17 13:55:38 -070020import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_CALLING_PACKAGE_NAME;
Jorim Jaggi172e99f2017-10-20 14:33:18 +020021import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_CANCELLED;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080022import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_DELAY_MS;
23import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_DEVICE_UPTIME_SECONDS;
Todd Kennedy50d946c12017-03-17 13:55:38 -070024import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_IS_EPHEMERAL;
Jorim Jaggi4d27b842017-08-17 17:22:26 +020025import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_PROCESS_RUNNING;
26import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_REPORTED_DRAWN;
27import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_REPORTED_DRAWN_MS;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080028import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_STARTING_WINDOW_DELAY_MS;
29import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_WINDOWS_DRAWN_DELAY_MS;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010030import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_PACKAGE_NAME;
31import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_UID;
32import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_UID_HAS_ANY_VISIBLE_WINDOW;
33import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_UID_PROC_STATE;
Jorim Jaggicdfc04e2017-04-28 19:06:24 +020034import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CLASS_NAME;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010035import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_COMING_FROM_PENDING_INTENT;
Todd Kennedy50d946c12017-03-17 13:55:38 -070036import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_INSTANT_APP_LAUNCH_TOKEN;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010037import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_INTENT_ACTION;
38import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_CUR_PROC_STATE;
39import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_CLIENT_ACTIVITIES;
40import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_FOREGROUND_ACTIVITIES;
41import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_FOREGROUND_SERVICES;
42import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_OVERLAY_UI;
43import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_TOP_UI;
44import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_MILLIS_SINCE_FG_INTERACTION;
45import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_MILLIS_SINCE_LAST_INTERACTION_EVENT;
46import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_MILLIS_SINCE_UNIMPORTANT;
47import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_PENDING_UI_CLEAN;
48import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_PROCESS_NAME;
49import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_REAL_CALLING_UID;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010050import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_REAL_CALLING_UID_HAS_ANY_VISIBLE_WINDOW;
Vishnu Nair132ee832018-09-28 15:00:05 -070051import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_REAL_CALLING_UID_PROC_STATE;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010052import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TARGET_SHORT_COMPONENT_NAME;
Calin Juravle759fbda2018-02-20 19:52:30 +000053import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PACKAGE_OPTIMIZATION_COMPILATION_FILTER;
Vishnu Nair132ee832018-09-28 15:00:05 -070054import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PACKAGE_OPTIMIZATION_COMPILATION_REASON;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080055import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_COLD_LAUNCH;
56import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_HOT_LAUNCH;
Jorim Jaggi4d27b842017-08-17 17:22:26 +020057import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_REPORTED_DRAWN_NO_BUNDLE;
58import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_REPORTED_DRAWN_WITH_BUNDLE;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080059import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_WARM_LAUNCH;
Ng Zhi Anbbefdec2018-01-30 17:12:39 -080060import static com.android.server.am.MemoryStatUtil.MemoryStat;
Rajeev Kumarbfcd9202018-03-02 22:42:13 +000061import static com.android.server.am.MemoryStatUtil.readMemoryStatFromFilesystem;
Vishnu Naira62534b2018-11-09 09:13:22 -080062import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_METRICS;
63import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
64import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Vishnu Nair132ee832018-09-28 15:00:05 -070065import static com.android.server.wm.ActivityTaskManagerInternal.APP_TRANSITION_TIMEOUT;
Jeff Changd136e772019-11-05 20:33:52 +080066import static com.android.server.wm.EventLogTags.WM_ACTIVITY_LAUNCH_TIME;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080067
Riddle Hsufd66d4d2019-11-14 10:35:55 +080068import android.annotation.NonNull;
69import android.annotation.Nullable;
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -080070import android.app.WaitResult;
Igor Murashkin212d06c2018-10-22 16:34:39 -070071import android.app.WindowConfiguration.WindowingMode;
Michal Karpinski319069b2019-03-27 15:46:50 +000072import android.content.ComponentName;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010073import android.content.Intent;
Calin Juravle759fbda2018-02-20 19:52:30 +000074import android.content.pm.ApplicationInfo;
75import android.content.pm.dex.ArtManagerInternal;
76import android.content.pm.dex.PackageOptimizationInfo;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080077import android.metrics.LogMaker;
Riddle Hsufd66d4d2019-11-14 10:35:55 +080078import android.os.Binder;
Jorim Jaggi172e99f2017-10-20 14:33:18 +020079import android.os.Looper;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080080import android.os.SystemClock;
Vishnu Nair132ee832018-09-28 15:00:05 -070081import android.os.Trace;
Riddle Hsufd66d4d2019-11-14 10:35:55 +080082import android.util.ArrayMap;
Vishnu Nair132ee832018-09-28 15:00:05 -070083import android.util.EventLog;
84import android.util.Log;
Jorim Jaggi172e99f2017-10-20 14:33:18 +020085import android.util.Slog;
Vishnu Nair132ee832018-09-28 15:00:05 -070086import android.util.TimeUtils;
Igor Murashkinc0b47e42018-11-07 15:54:18 -080087import android.util.proto.ProtoOutputStream;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080088
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -080089import com.android.internal.annotations.VisibleForTesting;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080090import com.android.internal.logging.MetricsLogger;
Ng Zhi An83473542018-02-20 09:02:14 -080091import com.android.internal.os.BackgroundThread;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -080092import com.android.internal.util.FrameworkStatsLog;
Riddle Hsufd66d4d2019-11-14 10:35:55 +080093import com.android.internal.util.function.pooled.PooledLambda;
Calin Juravle759fbda2018-02-20 19:52:30 +000094import com.android.server.LocalServices;
Louis Changcdec0802019-11-11 11:45:07 +080095
Riddle Hsufd66d4d2019-11-14 10:35:55 +080096import java.util.ArrayList;
97import java.util.LinkedList;
Yan Wang9eac5ec2019-09-30 15:42:18 -070098import java.util.concurrent.TimeUnit;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080099
100/**
Vishnu Nair132ee832018-09-28 15:00:05 -0700101 * Listens to activity launches, transitions, visibility changes and window drawn callbacks to
102 * determine app launch times and draw delays. Source of truth for activity metrics and provides
103 * data for Tron, logcat, event logs and {@link android.app.WaitResult}.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800104 * <p>
105 * A typical sequence of a launch event could be:
106 * {@link #notifyActivityLaunching}, {@link #notifyActivityLaunched},
107 * {@link #notifyStartingWindowDrawn} (optional), {@link #notifyTransitionStarting}
108 * {@link #notifyWindowsDrawn}.
109 * <p>
Vishnu Nair132ee832018-09-28 15:00:05 -0700110 * Tests:
Tadashi G. Takaoka28bc3702019-04-23 11:01:48 +0900111 * atest CtsWindowManagerDeviceTestCases:ActivityMetricsLoggerTests
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800112 */
113class ActivityMetricsLogger {
Jorim Jaggif9704102016-05-05 19:14:22 -0700114
Wale Ogunwale98875612018-10-12 07:53:02 -0700115 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityMetricsLogger" : TAG_ATM;
Jorim Jaggif9704102016-05-05 19:14:22 -0700116
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800117 // Window modes we are interested in logging. If we ever introduce a new type, we need to add
118 // a value here and increase the {@link #TRON_WINDOW_STATE_VARZ_STRINGS} array.
119 private static final int WINDOW_STATE_STANDARD = 0;
120 private static final int WINDOW_STATE_SIDE_BY_SIDE = 1;
121 private static final int WINDOW_STATE_FREEFORM = 2;
Winson Chung83471632016-12-13 11:02:12 -0800122 private static final int WINDOW_STATE_ASSISTANT = 3;
Wale Ogunwale194435b2019-12-23 12:56:51 -0800123 private static final int WINDOW_STATE_MULTI_WINDOW = 4;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800124 private static final int WINDOW_STATE_INVALID = -1;
125
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800126 /**
127 * The flag for {@link #notifyActivityLaunching} to skip associating a new launch with an active
128 * transition, in the case the launch is standalone (e.g. from recents).
129 */
130 private static final int IGNORE_CALLER = -1;
Vishnu Nair132ee832018-09-28 15:00:05 -0700131 private static final int INVALID_DELAY = -1;
132 private static final int INVALID_TRANSITION_TYPE = -1;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500133
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800134 // Preallocated strings we are sending to tron, so we don't have to allocate a new one every
135 // time we log.
136 private static final String[] TRON_WINDOW_STATE_VARZ_STRINGS = {
Winson Chung83471632016-12-13 11:02:12 -0800137 "window_time_0", "window_time_1", "window_time_2", "window_time_3"};
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800138
139 private int mWindowState = WINDOW_STATE_STANDARD;
140 private long mLastLogTimeSecs;
141 private final ActivityStackSupervisor mSupervisor;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800142 private final MetricsLogger mMetricsLogger = new MetricsLogger();
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800143
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800144 /** All active transitions. */
145 private final ArrayList<TransitionInfo> mTransitionInfoList = new ArrayList<>();
146 /** Map : Last launched activity => {@link TransitionInfo} */
147 private final ArrayMap<ActivityRecord, TransitionInfo> mLastTransitionInfo = new ArrayMap<>();
Calin Juravle759fbda2018-02-20 19:52:30 +0000148
149 private ArtManagerInternal mArtManagerInternal;
Vishnu Nair132ee832018-09-28 15:00:05 -0700150 private final StringBuilder mStringBuilder = new StringBuilder();
Calin Juravle759fbda2018-02-20 19:52:30 +0000151
Igor Murashkin212d06c2018-10-22 16:34:39 -0700152 /**
153 * Due to the global single concurrent launch sequence, all calls to this observer must be made
154 * in-order on the same thread to fulfill the "happens-before" guarantee in LaunchObserver.
155 */
Igor Murashkinc0b47e42018-11-07 15:54:18 -0800156 private final LaunchObserverRegistryImpl mLaunchObserver;
157 @VisibleForTesting static final int LAUNCH_OBSERVER_ACTIVITY_RECORD_PROTO_CHUNK_SIZE = 512;
Igor Murashkin212d06c2018-10-22 16:34:39 -0700158
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800159 /**
160 * The information created when an intent is incoming but we do not yet know whether it will be
161 * launched successfully.
162 */
163 static final class LaunchingState {
164 /** The timestamp of {@link #notifyActivityLaunching}. */
165 private long mCurrentTransitionStartTimeNs;
166 /** Non-null when a {@link TransitionInfo} is created for this state. */
167 private TransitionInfo mAssociatedTransitionInfo;
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200168
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800169 @VisibleForTesting
170 boolean allDrawn() {
171 return mAssociatedTransitionInfo != null && mAssociatedTransitionInfo.allDrawn();
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200172 }
Calin Juravle759fbda2018-02-20 19:52:30 +0000173 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800174
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800175 /** The information created when an activity is confirmed to be launched. */
176 private static final class TransitionInfo {
177 /**
178 * The field to lookup and update an existing transition efficiently between
179 * {@link #notifyActivityLaunching} and {@link #notifyActivityLaunched}.
180 *
181 * @see LaunchingState#mAssociatedTransitionInfo
182 */
183 final LaunchingState mLaunchingState;
184 /**
185 * The timestamp of the first {@link #notifyActivityLaunching}. It can be used as a key for
186 * observer to identify which callbacks belong to a launch event.
187 */
188 final long mTransitionStartTimeNs;
189 /** The device uptime in seconds when this transition info is created. */
190 final int mCurrentTransitionDeviceUptime;
191 /** The type can be cold (new process), warm (new activity), or hot (bring to front). */
192 final int mTransitionType;
193 /** Whether the process was already running when the transition started. */
194 final boolean mProcessRunning;
Riddle Hsue8d3d192019-11-26 18:56:39 +0800195 /** whether the process of the launching activity didn't have any active activity. */
196 final boolean mProcessSwitch;
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800197 /** The activities that should be drawn. */
198 final LinkedList<ActivityRecord> mPendingDrawActivities = new LinkedList<>();
Igor Murashkin212d06c2018-10-22 16:34:39 -0700199 /** The latest activity to have been launched. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800200 @NonNull ActivityRecord mLastLaunchedActivity;
201
202 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyTransitionStarting}. */
203 int mCurrentTransitionDelayMs;
204 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyStartingWindowDrawn}. */
205 int mStartingWindowDelayMs = INVALID_DELAY;
206 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyBindApplication}. */
207 int mBindApplicationDelayMs = INVALID_DELAY;
Vishnu Nair132ee832018-09-28 15:00:05 -0700208 /** Elapsed time from when we launch an activity to when its windows are drawn. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800209 int mWindowsDrawnDelayMs;
210 /** The reason why the transition started (see ActivityManagerInternal.APP_TRANSITION_*). */
211 int mReason = APP_TRANSITION_TIMEOUT;
212 /** The flag ensures that {@link #mStartingWindowDelayMs} is only set once. */
213 boolean mLoggedStartingWindowDrawn;
214 /** If the any app transitions have been logged as starting. */
215 boolean mLoggedTransitionStarting;
216
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800217 /** Non-null if the application has reported drawn but its window hasn't. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800218 @Nullable Runnable mPendingFullyDrawn;
219 /** Non-null if the trace is active. */
220 @Nullable String mLaunchTraceName;
221
222 /** @return Non-null if there will be a window drawn event for the launch. */
223 @Nullable
224 static TransitionInfo create(@NonNull ActivityRecord r,
Riddle Hsue8d3d192019-11-26 18:56:39 +0800225 @NonNull LaunchingState launchingState, boolean processRunning,
226 boolean processSwitch, int startResult) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800227 int transitionType = INVALID_TRANSITION_TYPE;
228 if (processRunning) {
229 if (startResult == START_SUCCESS) {
230 transitionType = TYPE_TRANSITION_WARM_LAUNCH;
231 } else if (startResult == START_TASK_TO_FRONT) {
232 transitionType = TYPE_TRANSITION_HOT_LAUNCH;
233 }
234 } else if (startResult == START_SUCCESS || startResult == START_TASK_TO_FRONT) {
235 // Task may still exist when cold launching an activity and the start result will be
236 // set to START_TASK_TO_FRONT. Treat this as a COLD launch.
237 transitionType = TYPE_TRANSITION_COLD_LAUNCH;
238 }
239 if (transitionType == INVALID_TRANSITION_TYPE) {
240 // That means the startResult is neither START_SUCCESS nor START_TASK_TO_FRONT.
241 return null;
242 }
Riddle Hsue8d3d192019-11-26 18:56:39 +0800243 return new TransitionInfo(r, launchingState, transitionType, processRunning,
244 processSwitch);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800245 }
246
247 /** Use {@link TransitionInfo#create} instead to ensure the transition type is valid. */
248 private TransitionInfo(ActivityRecord r, LaunchingState launchingState, int transitionType,
Riddle Hsue8d3d192019-11-26 18:56:39 +0800249 boolean processRunning, boolean processSwitch) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800250 mLaunchingState = launchingState;
251 mTransitionStartTimeNs = launchingState.mCurrentTransitionStartTimeNs;
252 mTransitionType = transitionType;
253 mProcessRunning = processRunning;
Riddle Hsue8d3d192019-11-26 18:56:39 +0800254 mProcessSwitch = processSwitch;
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800255 mCurrentTransitionDeviceUptime =
256 (int) TimeUnit.MILLISECONDS.toSeconds(SystemClock.uptimeMillis());
257 setLatestLaunchedActivity(r);
258 launchingState.mAssociatedTransitionInfo = this;
259 }
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800260
261 /**
262 * Remembers the latest launched activity to represent the final transition. This also
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800263 * tracks the activities that should be drawn, so a consecutive launching sequence can be
264 * coalesced as one event.
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800265 */
266 void setLatestLaunchedActivity(ActivityRecord r) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800267 if (mLastLaunchedActivity == r) {
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800268 return;
269 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800270 mLastLaunchedActivity = r;
271 if (!r.noDisplay) {
272 if (DEBUG_METRICS) Slog.i(TAG, "Add pending draw " + r);
273 mPendingDrawActivities.add(r);
274 }
275 }
276
277 /** @return {@code true} if the activity matches a launched activity in this transition. */
278 boolean contains(ActivityRecord r) {
279 return r == mLastLaunchedActivity || mPendingDrawActivities.contains(r);
280 }
281
282 /** Called when the activity is drawn or won't be drawn. */
283 void removePendingDrawActivity(ActivityRecord r) {
284 if (DEBUG_METRICS) Slog.i(TAG, "Remove pending draw " + r);
285 mPendingDrawActivities.remove(r);
286 }
287
288 boolean allDrawn() {
289 return mPendingDrawActivities.isEmpty();
290 }
291
Riddle Hsue8d3d192019-11-26 18:56:39 +0800292 /**
293 * @return {@code true} if the transition info should be sent to MetricsLogger, StatsLog, or
294 * LaunchObserver.
295 */
296 boolean isInterestingToLoggerAndObserver() {
297 return mProcessSwitch;
298 }
299
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800300 int calculateCurrentDelay() {
301 return calculateDelay(SystemClock.elapsedRealtimeNanos());
302 }
303
304 int calculateDelay(long timestampNs) {
305 // Shouldn't take more than 25 days to launch an app, so int is fine here.
306 return (int) TimeUnit.NANOSECONDS.toMillis(timestampNs - mTransitionStartTimeNs);
307 }
308
309 @Override
310 public String toString() {
311 return "TransitionInfo{" + Integer.toHexString(System.identityHashCode(this))
312 + " a=" + mLastLaunchedActivity + " ua=" + mPendingDrawActivities + "}";
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800313 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800314 }
315
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800316 static final class TransitionInfoSnapshot {
Calin Juravle759fbda2018-02-20 19:52:30 +0000317 final private ApplicationInfo applicationInfo;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700318 final private WindowProcessController processRecord;
Vishnu Nair132ee832018-09-28 15:00:05 -0700319 final String packageName;
320 final String launchedActivityName;
Calin Juravle759fbda2018-02-20 19:52:30 +0000321 final private String launchedActivityLaunchedFromPackage;
322 final private String launchedActivityLaunchToken;
323 final private String launchedActivityAppRecordRequiredAbi;
Vishnu Nair132ee832018-09-28 15:00:05 -0700324 final String launchedActivityShortComponentName;
Ng Zhi An83473542018-02-20 09:02:14 -0800325 final private String processName;
Calin Juravle759fbda2018-02-20 19:52:30 +0000326 final private int reason;
327 final private int startingWindowDelayMs;
328 final private int bindApplicationDelayMs;
Vishnu Nair132ee832018-09-28 15:00:05 -0700329 final int windowsDrawnDelayMs;
330 final int type;
331 final int userId;
332 /**
333 * Elapsed time from when we launch an activity to when the app reported it was
334 * fully drawn. If this is not reported then the value is set to INVALID_DELAY.
335 */
336 final int windowsFullyDrawnDelayMs;
337 final int activityRecordIdHashCode;
Calin Juravle759fbda2018-02-20 19:52:30 +0000338
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800339 private TransitionInfoSnapshot(TransitionInfo info) {
340 this(info, info.mLastLaunchedActivity, INVALID_DELAY);
Vishnu Nair132ee832018-09-28 15:00:05 -0700341 }
342
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800343 private TransitionInfoSnapshot(TransitionInfo info, ActivityRecord launchedActivity,
344 int windowsFullyDrawnDelayMs) {
Andrii Kulianeceebbf2019-06-26 17:36:51 -0700345 applicationInfo = launchedActivity.info.applicationInfo;
Vishnu Nair132ee832018-09-28 15:00:05 -0700346 packageName = launchedActivity.packageName;
347 launchedActivityName = launchedActivity.info.name;
348 launchedActivityLaunchedFromPackage = launchedActivity.launchedFromPackage;
349 launchedActivityLaunchToken = launchedActivity.info.launchToken;
350 launchedActivityAppRecordRequiredAbi = launchedActivity.app == null
Calin Juravle759fbda2018-02-20 19:52:30 +0000351 ? null
Vishnu Nairaf0ea312018-10-15 16:23:55 -0700352 : launchedActivity.app.getRequiredAbi();
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800353 reason = info.mReason;
354 startingWindowDelayMs = info.mStartingWindowDelayMs;
355 bindApplicationDelayMs = info.mBindApplicationDelayMs;
356 windowsDrawnDelayMs = info.mWindowsDrawnDelayMs;
357 type = info.mTransitionType;
358 processRecord = launchedActivity.app;
Vishnu Nairaf0ea312018-10-15 16:23:55 -0700359 processName = launchedActivity.processName;
Wale Ogunwale8b19de92018-11-29 19:58:26 -0800360 userId = launchedActivity.mUserId;
Vishnu Nair132ee832018-09-28 15:00:05 -0700361 launchedActivityShortComponentName = launchedActivity.shortComponentName;
362 activityRecordIdHashCode = System.identityHashCode(launchedActivity);
363 this.windowsFullyDrawnDelayMs = windowsFullyDrawnDelayMs;
Calin Juravle759fbda2018-02-20 19:52:30 +0000364 }
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -0800365
366 @WaitResult.LaunchState int getLaunchState() {
367 switch (type) {
368 case TYPE_TRANSITION_WARM_LAUNCH:
369 return LAUNCH_STATE_WARM;
370 case TYPE_TRANSITION_HOT_LAUNCH:
371 return LAUNCH_STATE_HOT;
372 case TYPE_TRANSITION_COLD_LAUNCH:
373 return LAUNCH_STATE_COLD;
374 default:
375 return -1;
376 }
377 }
Calin Juravle759fbda2018-02-20 19:52:30 +0000378 }
379
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800380 ActivityMetricsLogger(ActivityStackSupervisor supervisor, Looper looper) {
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800381 mLastLogTimeSecs = SystemClock.elapsedRealtime() / 1000;
382 mSupervisor = supervisor;
Igor Murashkinc0b47e42018-11-07 15:54:18 -0800383 mLaunchObserver = new LaunchObserverRegistryImpl(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800384 }
385
386 void logWindowState() {
387 final long now = SystemClock.elapsedRealtime() / 1000;
388 if (mWindowState != WINDOW_STATE_INVALID) {
389 // We log even if the window state hasn't changed, because the user might remain in
390 // home/fullscreen move forever and we would like to track this kind of behavior
391 // too.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800392 mMetricsLogger.count(TRON_WINDOW_STATE_VARZ_STRINGS[mWindowState],
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800393 (int) (now - mLastLogTimeSecs));
394 }
395 mLastLogTimeSecs = now;
396
Wale Ogunwale926aade2017-08-29 11:24:37 -0700397 mWindowState = WINDOW_STATE_INVALID;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800398 ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +0800399 mSupervisor.mRootWindowContainer.getTopDisplayFocusedStack();
lumarkf6c4a982018-06-15 15:43:12 +0800400 if (stack == null) {
401 return;
402 }
403
Wale Ogunwale926aade2017-08-29 11:24:37 -0700404 if (stack.isActivityTypeAssistant()) {
405 mWindowState = WINDOW_STATE_ASSISTANT;
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -0800406 return;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800407 }
Wale Ogunwale926aade2017-08-29 11:24:37 -0700408
Igor Murashkin212d06c2018-10-22 16:34:39 -0700409 @WindowingMode int windowingMode = stack.getWindowingMode();
Wale Ogunwale3382ab12017-07-27 08:55:03 -0700410 if (windowingMode == WINDOWING_MODE_PINNED) {
Louis Chang149d5c82019-12-30 09:47:39 +0800411 stack = mSupervisor.mRootWindowContainer.findStackBehind(stack);
Wale Ogunwale3382ab12017-07-27 08:55:03 -0700412 windowingMode = stack.getWindowingMode();
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -0800413 }
Wale Ogunwale926aade2017-08-29 11:24:37 -0700414 switch (windowingMode) {
415 case WINDOWING_MODE_FULLSCREEN:
416 mWindowState = WINDOW_STATE_STANDARD;
417 break;
418 case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
419 case WINDOWING_MODE_SPLIT_SCREEN_SECONDARY:
420 mWindowState = WINDOW_STATE_SIDE_BY_SIDE;
421 break;
Bryce Lee6c605092017-10-12 11:14:49 -0700422 case WINDOWING_MODE_FREEFORM:
Wale Ogunwale926aade2017-08-29 11:24:37 -0700423 mWindowState = WINDOW_STATE_FREEFORM;
424 break;
Wale Ogunwale194435b2019-12-23 12:56:51 -0800425 case WINDOWING_MODE_MULTI_WINDOW:
426 mWindowState = WINDOW_STATE_MULTI_WINDOW;
427 break;
Wale Ogunwale926aade2017-08-29 11:24:37 -0700428 default:
429 if (windowingMode != WINDOWING_MODE_UNDEFINED) {
430 throw new IllegalStateException("Unknown windowing mode for stack=" + stack
431 + " windowingMode=" + windowingMode);
432 }
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800433 }
434 }
Jorim Jaggi275561a2016-02-23 10:11:02 -0500435
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800436 /** @return Non-null {@link TransitionInfo} if the activity is found in an active transition. */
437 @Nullable
438 private TransitionInfo getActiveTransitionInfo(ActivityRecord r) {
439 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
440 final TransitionInfo info = mTransitionInfoList.get(i);
441 if (info.contains(r)) {
442 return info;
443 }
444 }
445 return null;
446 }
447
448 /**
449 * This method should be only used by starting recents and starting from recents, or internal
450 * tests. Because it doesn't lookup caller and always creates a new launching state.
451 *
452 * @see #notifyActivityLaunching(Intent, ActivityRecord, int)
453 */
454 LaunchingState notifyActivityLaunching(Intent intent) {
455 return notifyActivityLaunching(intent, null /* caller */, IGNORE_CALLER);
456 }
457
458 /**
459 * If the caller is found in an active transition, it will be considered as consecutive launch
460 * and coalesced into the active transition.
461 *
462 * @see #notifyActivityLaunching(Intent, ActivityRecord, int)
463 */
464 LaunchingState notifyActivityLaunching(Intent intent, @Nullable ActivityRecord caller) {
465 return notifyActivityLaunching(intent, caller, Binder.getCallingUid());
466 }
467
Jorim Jaggi275561a2016-02-23 10:11:02 -0500468 /**
469 * Notifies the tracker at the earliest possible point when we are starting to launch an
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800470 * activity. The caller must ensure that {@link #notifyActivityLaunched} will be called later
471 * with the returned {@link LaunchingState}.
Jorim Jaggi275561a2016-02-23 10:11:02 -0500472 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800473 private LaunchingState notifyActivityLaunching(Intent intent, @Nullable ActivityRecord caller,
474 int callingUid) {
475 final long transitionStartTimeNs = SystemClock.elapsedRealtimeNanos();
476 TransitionInfo existingInfo = null;
477 if (callingUid != IGNORE_CALLER) {
478 // Associate the launching event to an active transition if the caller is found in its
479 // launched activities.
480 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
481 final TransitionInfo info = mTransitionInfoList.get(i);
482 if (caller != null && info.contains(caller)) {
483 existingInfo = info;
484 break;
485 }
486 if (existingInfo == null && callingUid == info.mLastLaunchedActivity.getUid()) {
487 // Fallback to check the most recent matched uid for the case that the caller is
488 // not an activity.
489 existingInfo = info;
490 }
491 }
492 }
Igor Murashkin212d06c2018-10-22 16:34:39 -0700493 if (DEBUG_METRICS) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800494 Slog.i(TAG, "notifyActivityLaunching intent=" + intent
495 + " existingInfo=" + existingInfo);
Igor Murashkin212d06c2018-10-22 16:34:39 -0700496 }
497
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800498 if (existingInfo == null) {
499 // Only notify the observer for a new launching event.
500 launchObserverNotifyIntentStarted(intent, transitionStartTimeNs);
501 final LaunchingState launchingState = new LaunchingState();
502 launchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs;
503 return launchingState;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800504 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800505 existingInfo.mLaunchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs;
506 return existingInfo.mLaunchingState;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500507 }
508
509 /**
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700510 * Notifies the tracker that the activity is actually launching.
511 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800512 * @param launchingState The launching state to track the new or active transition.
513 * @param resultCode One of the {@link android.app.ActivityManager}.START_* flags, indicating
514 * the result of the launch.
515 * @param launchedActivity The activity that is being launched
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700516 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800517 void notifyActivityLaunched(@NonNull LaunchingState launchingState, int resultCode,
518 @Nullable ActivityRecord launchedActivity) {
519 if (launchedActivity == null) {
520 // The launch is aborted, e.g. intent not resolved, class not found.
521 abort(null /* info */, "nothing launched");
522 return;
523 }
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700524
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800525 final WindowProcessController processRecord = launchedActivity.app != null
526 ? launchedActivity.app
527 : mSupervisor.mService.getProcessController(
528 launchedActivity.processName, launchedActivity.info.applicationInfo.uid);
529 // Whether the process that will contains the activity is already running.
530 final boolean processRunning = processRecord != null;
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700531 // We consider this a "process switch" if the process of the activity that gets launched
532 // didn't have an activity that was in started state. In this case, we assume that lot
533 // of caches might be purged so the time until it produces the first frame is very
534 // interesting.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800535 final boolean processSwitch = !processRunning
Wale Ogunwalef6733932018-06-27 05:14:34 -0700536 || !processRecord.hasStartedActivity(launchedActivity);
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700537
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800538 final TransitionInfo info = launchingState.mAssociatedTransitionInfo;
539 if (DEBUG_METRICS) {
540 Slog.i(TAG, "notifyActivityLaunched" + " resultCode=" + resultCode
541 + " launchedActivity=" + launchedActivity + " processRunning=" + processRunning
542 + " processSwitch=" + processSwitch + " info=" + info);
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200543 }
544
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800545 if (launchedActivity.mDrawn) {
Vishnu Nairf8accc52018-10-11 10:19:54 -0700546 // Launched activity is already visible. We cannot measure windows drawn delay.
Riddle Hsu1063b512019-10-22 21:12:23 +0800547 abort(info, "launched activity already visible");
Vishnu Nairf8accc52018-10-11 10:19:54 -0700548 return;
549 }
550
Riddle Hsu20cf2bc2019-11-27 18:57:50 +0800551 if (info != null
552 && info.mLastLaunchedActivity.mDisplayContent == launchedActivity.mDisplayContent) {
553 // If we are already in an existing transition on the same display, only update the
554 // activity name, but not the other attributes.
Igor Murashkin212d06c2018-10-22 16:34:39 -0700555
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800556 if (DEBUG_METRICS) Slog.i(TAG, "notifyActivityLaunched update launched activity");
Igor Murashkin212d06c2018-10-22 16:34:39 -0700557 // Coalesce multiple (trampoline) activities from a single sequence together.
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800558 info.setLatestLaunchedActivity(launchedActivity);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500559 return;
560 }
561
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800562 final TransitionInfo newInfo = TransitionInfo.create(launchedActivity, launchingState,
Riddle Hsue8d3d192019-11-26 18:56:39 +0800563 processRunning, processSwitch, resultCode);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800564 if (newInfo == null) {
565 abort(info, "unrecognized launch");
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800566 return;
567 }
568
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200569 if (DEBUG_METRICS) Slog.i(TAG, "notifyActivityLaunched successful");
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800570 // A new launch sequence has begun. Start tracking it.
571 mTransitionInfoList.add(newInfo);
572 mLastTransitionInfo.put(launchedActivity, newInfo);
573 startLaunchTrace(newInfo);
Riddle Hsue8d3d192019-11-26 18:56:39 +0800574 if (newInfo.isInterestingToLoggerAndObserver()) {
575 launchObserverNotifyActivityLaunched(newInfo);
576 } else {
577 // As abort for no process switch.
578 launchObserverNotifyIntentFailed();
579 }
Jorim Jaggi275561a2016-02-23 10:11:02 -0500580 }
581
582 /**
583 * Notifies the tracker that all windows of the app have been drawn.
Riddle Hsueb628a52020-02-14 00:48:51 +0800584 *
585 * @return Non-null info if the activity was pending to draw, otherwise it might have been set
586 * to invisible (removed from active transition) or it was already drawn.
Jorim Jaggi275561a2016-02-23 10:11:02 -0500587 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800588 @Nullable
589 TransitionInfoSnapshot notifyWindowsDrawn(@NonNull ActivityRecord r, long timestampNs) {
590 if (DEBUG_METRICS) Slog.i(TAG, "notifyWindowsDrawn " + r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200591
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800592 final TransitionInfo info = getActiveTransitionInfo(r);
593 if (info == null || info.allDrawn()) {
594 if (DEBUG_METRICS) Slog.i(TAG, "notifyWindowsDrawn no activity to be drawn");
Vishnu Nair132ee832018-09-28 15:00:05 -0700595 return null;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500596 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800597 // Always calculate the delay because the caller may need to know the individual drawn time.
598 info.mWindowsDrawnDelayMs = info.calculateDelay(timestampNs);
599 info.removePendingDrawActivity(r);
600 final TransitionInfoSnapshot infoSnapshot = new TransitionInfoSnapshot(info);
601 if (info.mLoggedTransitionStarting && info.allDrawn()) {
602 done(false /* abort */, info, "notifyWindowsDrawn - all windows drawn", timestampNs);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500603 }
Vishnu Nair132ee832018-09-28 15:00:05 -0700604 return infoSnapshot;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500605 }
606
607 /**
608 * Notifies the tracker that the starting window was drawn.
609 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800610 void notifyStartingWindowDrawn(@NonNull ActivityRecord r) {
611 final TransitionInfo info = getActiveTransitionInfo(r);
612 if (info == null || info.mLoggedStartingWindowDrawn) {
Jorim Jaggi275561a2016-02-23 10:11:02 -0500613 return;
614 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800615 if (DEBUG_METRICS) Slog.i(TAG, "notifyStartingWindowDrawn " + r);
616 info.mLoggedStartingWindowDrawn = true;
617 info.mStartingWindowDelayMs = info.calculateDelay(SystemClock.elapsedRealtimeNanos());
Jorim Jaggi275561a2016-02-23 10:11:02 -0500618 }
619
620 /**
621 * Notifies the tracker that the app transition is starting.
622 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800623 * @param activityToReason A map from activity to a reason integer, which must be on of
624 * ActivityTaskManagerInternal.APP_TRANSITION_* reasons.
Jorim Jaggi275561a2016-02-23 10:11:02 -0500625 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800626 void notifyTransitionStarting(ArrayMap<ActivityRecord, Integer> activityToReason) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200627 if (DEBUG_METRICS) Slog.i(TAG, "notifyTransitionStarting");
Igor Murashkin212d06c2018-10-22 16:34:39 -0700628
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800629 final long timestampNs = SystemClock.elapsedRealtimeNanos();
630 for (int index = activityToReason.size() - 1; index >= 0; index--) {
631 final ActivityRecord r = activityToReason.keyAt(index);
632 final TransitionInfo info = getActiveTransitionInfo(r);
633 if (info == null || info.mLoggedTransitionStarting) {
634 // Ignore any subsequent notifyTransitionStarting.
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800635 continue;
636 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800637 if (DEBUG_METRICS) {
638 Slog.i(TAG, "notifyTransitionStarting activity=" + r + " info=" + info);
639 }
640
641 info.mCurrentTransitionDelayMs = info.calculateDelay(timestampNs);
642 info.mReason = activityToReason.valueAt(index);
643 info.mLoggedTransitionStarting = true;
644 if (info.allDrawn()) {
645 done(false /* abort */, info, "notifyTransitionStarting - all windows drawn",
646 timestampNs);
647 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800648 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800649 }
650
651 /** Makes sure that the reference to the removed activity is cleared. */
652 void notifyActivityRemoved(@NonNull ActivityRecord r) {
653 mLastTransitionInfo.remove(r);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500654 }
655
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200656 /**
657 * Notifies the tracker that the visibility of an app is changing.
658 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800659 * @param r the app that is changing its visibility
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200660 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800661 void notifyVisibilityChanged(@NonNull ActivityRecord r) {
662 final TransitionInfo info = getActiveTransitionInfo(r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200663 if (info == null) {
664 return;
665 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800666 if (DEBUG_METRICS) {
667 Slog.i(TAG, "notifyVisibilityChanged " + r + " visible=" + r.mVisibleRequested
668 + " state=" + r.getState() + " finishing=" + r.finishing);
669 }
670 if (!r.mVisibleRequested || r.finishing) {
671 info.removePendingDrawActivity(r);
672 }
673 if (info.mLastLaunchedActivity != r) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200674 return;
675 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800676 // The activity and its task are passed separately because the activity may be removed from
677 // the task later.
678 r.mAtmService.mH.sendMessage(PooledLambda.obtainMessage(
679 ActivityMetricsLogger::checkVisibility, this, r.getTask(), r));
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200680 }
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200681
Riddle Hsu1063b512019-10-22 21:12:23 +0800682 /** @return {@code true} if the given task has an activity will be drawn. */
Louis Changcdec0802019-11-11 11:45:07 +0800683 private static boolean hasActivityToBeDrawn(Task t) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800684 return t.forAllActivities((r) -> r.mVisibleRequested && !r.mDrawn && !r.finishing);
Vishnu Nairb1de42d2019-01-28 09:49:51 -0800685 }
686
Louis Changcdec0802019-11-11 11:45:07 +0800687 private void checkVisibility(Task t, ActivityRecord r) {
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700688 synchronized (mSupervisor.mService.mGlobalLock) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200689
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800690 final TransitionInfo info = getActiveTransitionInfo(r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200691
692 // If we have an active transition that's waiting on a certain activity that will be
693 // invisible now, we'll never get onWindowsDrawn, so abort the transition if necessary.
Vishnu Naird15063b2019-06-11 08:08:25 -0700694
695 // We have no active transitions.
696 if (info == null) {
697 return;
698 }
699
700 // The notified activity whose visibility changed is no longer the launched activity.
701 // We can still wait to get onWindowsDrawn.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800702 if (info.mLastLaunchedActivity != r) {
Vishnu Naird15063b2019-06-11 08:08:25 -0700703 return;
704 }
705
Riddle Hsu1063b512019-10-22 21:12:23 +0800706 // If the task of the launched activity contains any activity to be drawn, then the
707 // window drawn event should report later to complete the transition. Otherwise all
708 // activities in this task may be finished, invisible or drawn, so the transition event
709 // should be cancelled.
710 if (hasActivityToBeDrawn(t)) {
Vishnu Naird15063b2019-06-11 08:08:25 -0700711 return;
712 }
713
714 if (DEBUG_METRICS) Slog.i(TAG, "notifyVisibilityChanged to invisible activity=" + r);
715 logAppTransitionCancel(info);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800716 abort(info, "notifyVisibilityChanged to invisible");
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200717 }
718 }
719
Jorim Jaggi515dd682017-05-05 15:05:07 +0200720 /**
721 * Notifies the tracker that we called immediately before we call bindApplication on the client.
722 *
Wale Ogunwale31913b52018-10-13 08:29:31 -0700723 * @param appInfo The client into which we'll call bindApplication.
Jorim Jaggi515dd682017-05-05 15:05:07 +0200724 */
Wale Ogunwale31913b52018-10-13 08:29:31 -0700725 void notifyBindApplication(ApplicationInfo appInfo) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800726 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
727 final TransitionInfo info = mTransitionInfoList.get(i);
Jorim Jaggi515dd682017-05-05 15:05:07 +0200728
729 // App isn't attached to record yet, so match with info.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800730 if (info.mLastLaunchedActivity.info.applicationInfo == appInfo) {
731 info.mBindApplicationDelayMs = info.calculateCurrentDelay();
Jorim Jaggi515dd682017-05-05 15:05:07 +0200732 }
733 }
734 }
735
Riddle Hsu1063b512019-10-22 21:12:23 +0800736 /** Aborts tracking of current launch metrics. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800737 private void abort(TransitionInfo info, String cause) {
738 done(true /* abort */, info, cause, 0L /* timestampNs */);
Riddle Hsu1063b512019-10-22 21:12:23 +0800739 }
740
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800741 /** Called when the given transition (info) is no longer active. */
742 private void done(boolean abort, @Nullable TransitionInfo info, String cause,
Riddle Hsu1063b512019-10-22 21:12:23 +0800743 long timestampNs) {
Yan Wangd47f90b2019-10-03 19:17:15 -0700744 if (DEBUG_METRICS) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800745 Slog.i(TAG, "done abort=" + abort + " cause=" + cause + " timestamp=" + timestampNs
746 + " info=" + info);
Yan Wangd47f90b2019-10-03 19:17:15 -0700747 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800748 if (info == null) {
Igor Murashkin212d06c2018-10-22 16:34:39 -0700749 launchObserverNotifyIntentFailed();
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200750 return;
751 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800752
753 stopLaunchTrace(info);
754 if (abort) {
755 launchObserverNotifyActivityLaunchCancelled(info);
756 } else {
Riddle Hsue8d3d192019-11-26 18:56:39 +0800757 if (info.isInterestingToLoggerAndObserver()) {
758 launchObserverNotifyActivityLaunchFinished(info, timestampNs);
759 }
Yan Wang6f0b47d2020-01-02 16:09:30 -0800760 logAppTransitionFinished(info);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800761 }
762 info.mPendingDrawActivities.clear();
763 mTransitionInfoList.remove(info);
764 }
765
766 private void logAppTransitionCancel(TransitionInfo info) {
767 final int type = info.mTransitionType;
768 final ActivityRecord activity = info.mLastLaunchedActivity;
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200769 final LogMaker builder = new LogMaker(APP_TRANSITION_CANCELLED);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800770 builder.setPackageName(activity.packageName);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200771 builder.setType(type);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800772 builder.addTaggedData(FIELD_CLASS_NAME, activity.info.name);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200773 mMetricsLogger.write(builder);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800774 FrameworkStatsLog.write(
775 FrameworkStatsLog.APP_START_CANCELED,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800776 activity.info.applicationInfo.uid,
777 activity.packageName,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000778 convertAppStartTransitionType(type),
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800779 activity.info.name);
Igor Murashkin212d06c2018-10-22 16:34:39 -0700780 if (DEBUG_METRICS) {
781 Slog.i(TAG, String.format("APP_START_CANCELED(%s, %s, %s, %s)",
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800782 activity.info.applicationInfo.uid,
783 activity.packageName,
Igor Murashkin212d06c2018-10-22 16:34:39 -0700784 convertAppStartTransitionType(type),
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800785 activity.info.name));
Igor Murashkin212d06c2018-10-22 16:34:39 -0700786 }
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200787 }
788
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800789 private void logAppTransitionFinished(@NonNull TransitionInfo info) {
790 if (DEBUG_METRICS) Slog.i(TAG, "logging finished transition " + info);
Calin Juravle759fbda2018-02-20 19:52:30 +0000791
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800792 // Take a snapshot of the transition info before sending it to the handler for logging.
793 // This will avoid any races with other operations that modify the ActivityRecord.
794 final TransitionInfoSnapshot infoSnapshot = new TransitionInfoSnapshot(info);
Riddle Hsue8d3d192019-11-26 18:56:39 +0800795 if (info.isInterestingToLoggerAndObserver()) {
796 BackgroundThread.getHandler().post(() -> logAppTransition(
797 info.mCurrentTransitionDeviceUptime, info.mCurrentTransitionDelayMs,
798 infoSnapshot));
799 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800800 BackgroundThread.getHandler().post(() -> logAppDisplayed(infoSnapshot));
801 if (info.mPendingFullyDrawn != null) {
802 info.mPendingFullyDrawn.run();
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800803 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800804
805 info.mLastLaunchedActivity.info.launchToken = null;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800806 }
807
Ng Zhi An83473542018-02-20 09:02:14 -0800808 // This gets called on a background thread without holding the activity manager lock.
Calin Juravle759fbda2018-02-20 19:52:30 +0000809 private void logAppTransition(int currentTransitionDeviceUptime, int currentTransitionDelayMs,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800810 TransitionInfoSnapshot info) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000811 final LogMaker builder = new LogMaker(APP_TRANSITION);
812 builder.setPackageName(info.packageName);
813 builder.setType(info.type);
814 builder.addTaggedData(FIELD_CLASS_NAME, info.launchedActivityName);
815 final boolean isInstantApp = info.applicationInfo.isInstantApp();
816 if (info.launchedActivityLaunchedFromPackage != null) {
817 builder.addTaggedData(APP_TRANSITION_CALLING_PACKAGE_NAME,
818 info.launchedActivityLaunchedFromPackage);
819 }
820 String launchToken = info.launchedActivityLaunchToken;
821 if (launchToken != null) {
822 builder.addTaggedData(FIELD_INSTANT_APP_LAUNCH_TOKEN, launchToken);
823 }
824 builder.addTaggedData(APP_TRANSITION_IS_EPHEMERAL, isInstantApp ? 1 : 0);
825 builder.addTaggedData(APP_TRANSITION_DEVICE_UPTIME_SECONDS,
826 currentTransitionDeviceUptime);
827 builder.addTaggedData(APP_TRANSITION_DELAY_MS, currentTransitionDelayMs);
828 builder.setSubtype(info.reason);
Vishnu Nair132ee832018-09-28 15:00:05 -0700829 if (info.startingWindowDelayMs != INVALID_DELAY) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000830 builder.addTaggedData(APP_TRANSITION_STARTING_WINDOW_DELAY_MS,
831 info.startingWindowDelayMs);
832 }
Vishnu Nair132ee832018-09-28 15:00:05 -0700833 if (info.bindApplicationDelayMs != INVALID_DELAY) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000834 builder.addTaggedData(APP_TRANSITION_BIND_APPLICATION_DELAY_MS,
835 info.bindApplicationDelayMs);
836 }
837 builder.addTaggedData(APP_TRANSITION_WINDOWS_DRAWN_DELAY_MS, info.windowsDrawnDelayMs);
838 final ArtManagerInternal artManagerInternal = getArtManagerInternal();
839 final PackageOptimizationInfo packageOptimizationInfo =
840 (artManagerInternal == null) || (info.launchedActivityAppRecordRequiredAbi == null)
841 ? PackageOptimizationInfo.createWithNoInfo()
842 : artManagerInternal.getPackageOptimizationInfo(
843 info.applicationInfo,
844 info.launchedActivityAppRecordRequiredAbi);
845 builder.addTaggedData(PACKAGE_OPTIMIZATION_COMPILATION_REASON,
846 packageOptimizationInfo.getCompilationReason());
847 builder.addTaggedData(PACKAGE_OPTIMIZATION_COMPILATION_FILTER,
848 packageOptimizationInfo.getCompilationFilter());
849 mMetricsLogger.write(builder);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800850 FrameworkStatsLog.write(
851 FrameworkStatsLog.APP_START_OCCURRED,
Calin Juravle759fbda2018-02-20 19:52:30 +0000852 info.applicationInfo.uid,
853 info.packageName,
854 convertAppStartTransitionType(info.type),
855 info.launchedActivityName,
856 info.launchedActivityLaunchedFromPackage,
857 isInstantApp,
858 currentTransitionDeviceUptime * 1000,
859 info.reason,
860 currentTransitionDelayMs,
861 info.startingWindowDelayMs,
862 info.bindApplicationDelayMs,
863 info.windowsDrawnDelayMs,
864 launchToken,
865 packageOptimizationInfo.getCompilationReason(),
866 packageOptimizationInfo.getCompilationFilter());
Igor Murashkin212d06c2018-10-22 16:34:39 -0700867
868 if (DEBUG_METRICS) {
869 Slog.i(TAG, String.format("APP_START_OCCURRED(%s, %s, %s, %s, %s)",
870 info.applicationInfo.uid,
871 info.packageName,
872 convertAppStartTransitionType(info.type),
873 info.launchedActivityName,
874 info.launchedActivityLaunchedFromPackage));
875 }
876
877
Ng Zhi An83473542018-02-20 09:02:14 -0800878 logAppStartMemoryStateCapture(info);
Calin Juravle759fbda2018-02-20 19:52:30 +0000879 }
880
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800881 private void logAppDisplayed(TransitionInfoSnapshot info) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700882 if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
883 return;
884 }
885
Jeff Changd136e772019-11-05 20:33:52 +0800886 EventLog.writeEvent(WM_ACTIVITY_LAUNCH_TIME,
Vishnu Nair132ee832018-09-28 15:00:05 -0700887 info.userId, info.activityRecordIdHashCode, info.launchedActivityShortComponentName,
888 info.windowsDrawnDelayMs);
889
890 StringBuilder sb = mStringBuilder;
891 sb.setLength(0);
892 sb.append("Displayed ");
893 sb.append(info.launchedActivityShortComponentName);
894 sb.append(": ");
895 TimeUtils.formatDuration(info.windowsDrawnDelayMs, sb);
896 Log.i(TAG, sb.toString());
897 }
898
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000899 private int convertAppStartTransitionType(int tronType) {
900 if (tronType == TYPE_TRANSITION_COLD_LAUNCH) {
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800901 return FrameworkStatsLog.APP_START_OCCURRED__TYPE__COLD;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000902 }
903 if (tronType == TYPE_TRANSITION_WARM_LAUNCH) {
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800904 return FrameworkStatsLog.APP_START_OCCURRED__TYPE__WARM;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000905 }
906 if (tronType == TYPE_TRANSITION_HOT_LAUNCH) {
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800907 return FrameworkStatsLog.APP_START_OCCURRED__TYPE__HOT;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000908 }
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800909 return FrameworkStatsLog.APP_START_OCCURRED__TYPE__UNKNOWN;
Riddle Hsuc48c8912019-10-31 13:34:27 +0800910 }
911
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800912 /** @return the last known window drawn delay of the given activity. */
913 int getLastDrawnDelayMs(ActivityRecord r) {
914 final TransitionInfo info = mLastTransitionInfo.get(r);
915 return info != null ? info.mWindowsDrawnDelayMs : INVALID_DELAY;
Riddle Hsuc48c8912019-10-31 13:34:27 +0800916 }
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000917
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800918 /** @see android.app.Activity#reportFullyDrawn */
919 TransitionInfoSnapshot logAppTransitionReportedDrawn(ActivityRecord r,
Vishnu Nair132ee832018-09-28 15:00:05 -0700920 boolean restoredFromBundle) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800921 final TransitionInfo info = mLastTransitionInfo.get(r);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200922 if (info == null) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700923 return null;
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200924 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800925 if (!info.allDrawn() && info.mPendingFullyDrawn == null) {
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800926 // There are still undrawn activities, postpone reporting fully drawn until all of its
927 // windows are drawn. So that is closer to an usable state.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800928 info.mPendingFullyDrawn = () -> {
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800929 logAppTransitionReportedDrawn(r, restoredFromBundle);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800930 info.mPendingFullyDrawn = null;
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800931 };
932 return null;
933 }
Chris Wailes35c193c2018-10-09 18:12:00 -0700934
Riddle Hsue8d3d192019-11-26 18:56:39 +0800935 final long currentTimestampNs = SystemClock.elapsedRealtimeNanos();
936 final long startupTimeMs = info.mPendingFullyDrawn != null
937 ? info.mWindowsDrawnDelayMs
938 : TimeUnit.NANOSECONDS.toMillis(currentTimestampNs - info.mTransitionStartTimeNs);
939 final TransitionInfoSnapshot infoSnapshot =
940 new TransitionInfoSnapshot(info, r, (int) startupTimeMs);
941 BackgroundThread.getHandler().post(() -> logAppFullyDrawn(infoSnapshot));
942
943 if (!info.isInterestingToLoggerAndObserver()) {
944 return infoSnapshot;
945 }
946
Chris Wailes35c193c2018-10-09 18:12:00 -0700947 // Record the handling of the reportFullyDrawn callback in the trace system. This is not
948 // actually used to trace this function, but instead the logical task that this function
949 // fullfils (handling reportFullyDrawn() callbacks).
950 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800951 "ActivityManager:ReportingFullyDrawn " + info.mLastLaunchedActivity.packageName);
Chris Wailes35c193c2018-10-09 18:12:00 -0700952
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200953 final LogMaker builder = new LogMaker(APP_TRANSITION_REPORTED_DRAWN);
954 builder.setPackageName(r.packageName);
955 builder.addTaggedData(FIELD_CLASS_NAME, r.info.name);
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000956 builder.addTaggedData(APP_TRANSITION_REPORTED_DRAWN_MS, startupTimeMs);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200957 builder.setType(restoredFromBundle
958 ? TYPE_TRANSITION_REPORTED_DRAWN_WITH_BUNDLE
959 : TYPE_TRANSITION_REPORTED_DRAWN_NO_BUNDLE);
960 builder.addTaggedData(APP_TRANSITION_PROCESS_RUNNING,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800961 info.mProcessRunning ? 1 : 0);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200962 mMetricsLogger.write(builder);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800963 FrameworkStatsLog.write(
964 FrameworkStatsLog.APP_START_FULLY_DRAWN,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800965 info.mLastLaunchedActivity.info.applicationInfo.uid,
966 info.mLastLaunchedActivity.packageName,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000967 restoredFromBundle
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800968 ? FrameworkStatsLog.APP_START_FULLY_DRAWN__TYPE__WITH_BUNDLE
969 : FrameworkStatsLog.APP_START_FULLY_DRAWN__TYPE__WITHOUT_BUNDLE,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800970 info.mLastLaunchedActivity.info.name,
971 info.mProcessRunning,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000972 startupTimeMs);
Chris Wailes35c193c2018-10-09 18:12:00 -0700973
974 // Ends the trace started at the beginning of this function. This is located here to allow
975 // the trace slice to have a noticable duration.
976 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
977
Yan Wang9eac5ec2019-09-30 15:42:18 -0700978 // Notify reportFullyDrawn event.
979 launchObserverNotifyReportFullyDrawn(r, currentTimestampNs);
980
Vishnu Nair132ee832018-09-28 15:00:05 -0700981 return infoSnapshot;
982 }
983
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800984 private void logAppFullyDrawn(TransitionInfoSnapshot info) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700985 if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
986 return;
987 }
988
989 StringBuilder sb = mStringBuilder;
990 sb.setLength(0);
991 sb.append("Fully drawn ");
992 sb.append(info.launchedActivityShortComponentName);
993 sb.append(": ");
994 TimeUtils.formatDuration(info.windowsFullyDrawnDelayMs, sb);
995 Log.i(TAG, sb.toString());
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200996 }
997
Michal Karpinski4fd5b842019-01-28 15:13:32 +0000998 void logAbortedBgActivityStart(Intent intent, WindowProcessController callerApp,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100999 int callingUid, String callingPackage, int callingUidProcState,
1000 boolean callingUidHasAnyVisibleWindow,
1001 int realCallingUid, int realCallingUidProcState,
1002 boolean realCallingUidHasAnyVisibleWindow,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001003 boolean comingFromPendingIntent) {
1004
1005 final long nowElapsed = SystemClock.elapsedRealtime();
1006 final long nowUptime = SystemClock.uptimeMillis();
1007 final LogMaker builder = new LogMaker(ACTION_ACTIVITY_START);
1008 builder.setTimestamp(System.currentTimeMillis());
1009 builder.addTaggedData(FIELD_CALLING_UID, callingUid);
1010 builder.addTaggedData(FIELD_CALLING_PACKAGE_NAME, callingPackage);
1011 builder.addTaggedData(FIELD_CALLING_UID_PROC_STATE,
1012 processStateAmToProto(callingUidProcState));
1013 builder.addTaggedData(FIELD_CALLING_UID_HAS_ANY_VISIBLE_WINDOW,
1014 callingUidHasAnyVisibleWindow ? 1 : 0);
1015 builder.addTaggedData(FIELD_REAL_CALLING_UID, realCallingUid);
1016 builder.addTaggedData(FIELD_REAL_CALLING_UID_PROC_STATE,
1017 processStateAmToProto(realCallingUidProcState));
1018 builder.addTaggedData(FIELD_REAL_CALLING_UID_HAS_ANY_VISIBLE_WINDOW,
1019 realCallingUidHasAnyVisibleWindow ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001020 builder.addTaggedData(FIELD_COMING_FROM_PENDING_INTENT, comingFromPendingIntent ? 1 : 0);
Michal Karpinski8596ded2018-11-14 14:43:48 +00001021 if (intent != null) {
1022 builder.addTaggedData(FIELD_INTENT_ACTION, intent.getAction());
Michal Karpinski319069b2019-03-27 15:46:50 +00001023 ComponentName component = intent.getComponent();
1024 if (component != null) {
1025 builder.addTaggedData(FIELD_TARGET_SHORT_COMPONENT_NAME,
1026 component.flattenToShortString());
1027 }
Michal Karpinski8596ded2018-11-14 14:43:48 +00001028 }
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001029 if (callerApp != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001030 builder.addTaggedData(FIELD_PROCESS_RECORD_PROCESS_NAME, callerApp.mName);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001031 builder.addTaggedData(FIELD_PROCESS_RECORD_CUR_PROC_STATE,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001032 processStateAmToProto(callerApp.getCurrentProcState()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001033 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_CLIENT_ACTIVITIES,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001034 callerApp.hasClientActivities() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001035 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_FOREGROUND_SERVICES,
1036 callerApp.hasForegroundServices() ? 1 : 0);
1037 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_FOREGROUND_ACTIVITIES,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001038 callerApp.hasForegroundActivities() ? 1 : 0);
1039 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_TOP_UI, callerApp.hasTopUi() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001040 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_OVERLAY_UI,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001041 callerApp.hasOverlayUi() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001042 builder.addTaggedData(FIELD_PROCESS_RECORD_PENDING_UI_CLEAN,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001043 callerApp.hasPendingUiClean() ? 1 : 0);
1044 if (callerApp.getInteractionEventTime() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001045 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_LAST_INTERACTION_EVENT,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001046 (nowElapsed - callerApp.getInteractionEventTime()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001047 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001048 if (callerApp.getFgInteractionTime() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001049 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_FG_INTERACTION,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001050 (nowElapsed - callerApp.getFgInteractionTime()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001051 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001052 if (callerApp.getWhenUnimportant() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001053 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_UNIMPORTANT,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001054 (nowUptime - callerApp.getWhenUnimportant()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001055 }
1056 }
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001057 mMetricsLogger.write(builder);
1058 }
1059
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001060 private void logAppStartMemoryStateCapture(TransitionInfoSnapshot info) {
Ng Zhi An83473542018-02-20 09:02:14 -08001061 if (info.processRecord == null) {
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001062 if (DEBUG_METRICS) Slog.i(TAG, "logAppStartMemoryStateCapture processRecord null");
1063 return;
1064 }
1065
Wale Ogunwalef6733932018-06-27 05:14:34 -07001066 final int pid = info.processRecord.getPid();
Ng Zhi An83473542018-02-20 09:02:14 -08001067 final int uid = info.applicationInfo.uid;
Rajeev Kumarbfcd9202018-03-02 22:42:13 +00001068 final MemoryStat memoryStat = readMemoryStatFromFilesystem(uid, pid);
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001069 if (memoryStat == null) {
1070 if (DEBUG_METRICS) Slog.i(TAG, "logAppStartMemoryStateCapture memoryStat null");
1071 return;
1072 }
1073
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08001074 FrameworkStatsLog.write(
1075 FrameworkStatsLog.APP_START_MEMORY_STATE_CAPTURED,
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001076 uid,
Ng Zhi An83473542018-02-20 09:02:14 -08001077 info.processName,
1078 info.launchedActivityName,
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001079 memoryStat.pgfault,
1080 memoryStat.pgmajfault,
1081 memoryStat.rssInBytes,
1082 memoryStat.cacheInBytes,
1083 memoryStat.swapInBytes);
1084 }
1085
Calin Juravle759fbda2018-02-20 19:52:30 +00001086 private ArtManagerInternal getArtManagerInternal() {
1087 if (mArtManagerInternal == null) {
1088 // Note that this may be null.
1089 // ArtManagerInternal is registered during PackageManagerService
1090 // initialization which happens after ActivityManagerService.
1091 mArtManagerInternal = LocalServices.getService(ArtManagerInternal.class);
1092 }
1093 return mArtManagerInternal;
1094 }
Vishnu Nair132ee832018-09-28 15:00:05 -07001095
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001096 /** Starts trace for an activity is actually launching. */
1097 private void startLaunchTrace(@NonNull TransitionInfo info) {
1098 if (DEBUG_METRICS) Slog.i(TAG, "startLaunchTrace " + info);
1099 if (!Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
Vishnu Nair132ee832018-09-28 15:00:05 -07001100 return;
1101 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001102 info.mLaunchTraceName = "launching: " + info.mLastLaunchedActivity.packageName;
Riddle Hsue8d3d192019-11-26 18:56:39 +08001103 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName,
1104 (int) info.mTransitionStartTimeNs /* cookie */);
Vishnu Nair132ee832018-09-28 15:00:05 -07001105 }
1106
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001107 /** Stops trace for the launch is completed or cancelled. */
1108 private void stopLaunchTrace(@NonNull TransitionInfo info) {
1109 if (DEBUG_METRICS) Slog.i(TAG, "stopLaunchTrace " + info);
1110 if (info.mLaunchTraceName == null) {
Vishnu Nair132ee832018-09-28 15:00:05 -07001111 return;
1112 }
Riddle Hsue8d3d192019-11-26 18:56:39 +08001113 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName,
1114 (int) info.mTransitionStartTimeNs /* cookie */);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001115 info.mLaunchTraceName = null;
Vishnu Nair132ee832018-09-28 15:00:05 -07001116 }
Igor Murashkin212d06c2018-10-22 16:34:39 -07001117
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001118 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
1119 return mLaunchObserver;
1120 }
1121
Igor Murashkin212d06c2018-10-22 16:34:39 -07001122 /** Notify the {@link ActivityMetricsLaunchObserver} that a new launch sequence has begun. */
Yan Wangd47f90b2019-10-03 19:17:15 -07001123 private void launchObserverNotifyIntentStarted(Intent intent, long timestampNs) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001124 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1125 "MetricsLogger:launchObserverNotifyIntentStarted");
1126
1127 // Beginning a launch is timing sensitive and so should be observed as soon as possible.
Yan Wangd47f90b2019-10-03 19:17:15 -07001128 mLaunchObserver.onIntentStarted(intent, timestampNs);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001129
1130 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001131 }
1132
1133 /**
1134 * Notify the {@link ActivityMetricsLaunchObserver} that the previous launch sequence has
1135 * aborted due to intent failure (e.g. intent resolve failed or security error, etc) or
1136 * intent being delivered to the top running activity.
1137 */
1138 private void launchObserverNotifyIntentFailed() {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001139 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1140 "MetricsLogger:launchObserverNotifyIntentFailed");
1141
1142 mLaunchObserver.onIntentFailed();
1143
1144 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001145 }
1146
1147 /**
1148 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence's activity
1149 * has started.
1150 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001151 private void launchObserverNotifyActivityLaunched(TransitionInfo info) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001152 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1153 "MetricsLogger:launchObserverNotifyActivityLaunched");
1154
Igor Murashkin212d06c2018-10-22 16:34:39 -07001155 @ActivityMetricsLaunchObserver.Temperature int temperature =
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001156 convertTransitionTypeToLaunchObserverTemperature(info.mTransitionType);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001157
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001158 // Beginning a launch is timing sensitive and so should be observed as soon as possible.
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001159 mLaunchObserver.onActivityLaunched(convertActivityRecordToProto(info.mLastLaunchedActivity),
1160 temperature);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001161
1162 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001163 }
1164
1165 /**
Yan Wang9eac5ec2019-09-30 15:42:18 -07001166 * Notifies the {@link ActivityMetricsLaunchObserver} the reportFullDrawn event.
1167 */
Yan Wangd47f90b2019-10-03 19:17:15 -07001168 private void launchObserverNotifyReportFullyDrawn(ActivityRecord r, long timestampNs) {
Yan Wang9eac5ec2019-09-30 15:42:18 -07001169 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1170 "MetricsLogger:launchObserverNotifyReportFullyDrawn");
Yan Wangd47f90b2019-10-03 19:17:15 -07001171 mLaunchObserver.onReportFullyDrawn(convertActivityRecordToProto(r), timestampNs);
Yan Wang9eac5ec2019-09-30 15:42:18 -07001172 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1173 }
1174
1175 /**
Igor Murashkin212d06c2018-10-22 16:34:39 -07001176 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence is
1177 * cancelled.
1178 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001179 private void launchObserverNotifyActivityLaunchCancelled(TransitionInfo info) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001180 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1181 "MetricsLogger:launchObserverNotifyActivityLaunchCancelled");
Igor Murashkin212d06c2018-10-22 16:34:39 -07001182
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001183 final @ActivityMetricsLaunchObserver.ActivityRecordProto byte[] activityRecordProto =
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001184 info != null ? convertActivityRecordToProto(info.mLastLaunchedActivity) : null;
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001185
1186 mLaunchObserver.onActivityLaunchCancelled(activityRecordProto);
1187
1188 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001189 }
1190
1191 /**
1192 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence's activity
1193 * has fully finished (successfully).
1194 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001195 private void launchObserverNotifyActivityLaunchFinished(TransitionInfo info, long timestampNs) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001196 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1197 "MetricsLogger:launchObserverNotifyActivityLaunchFinished");
Igor Murashkin212d06c2018-10-22 16:34:39 -07001198
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001199 mLaunchObserver.onActivityLaunchFinished(
1200 convertActivityRecordToProto(info.mLastLaunchedActivity), timestampNs);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001201
1202 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1203 }
1204
1205 @VisibleForTesting
1206 static @ActivityMetricsLaunchObserver.ActivityRecordProto byte[]
1207 convertActivityRecordToProto(ActivityRecord record) {
1208 // May take non-negligible amount of time to convert ActivityRecord into a proto,
1209 // so track the time.
1210 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1211 "MetricsLogger:convertActivityRecordToProto");
1212
1213 // There does not appear to be a way to 'reset' a ProtoOutputBuffer stream,
1214 // so create a new one every time.
1215 final ProtoOutputStream protoOutputStream =
1216 new ProtoOutputStream(LAUNCH_OBSERVER_ACTIVITY_RECORD_PROTO_CHUNK_SIZE);
1217 // Write this data out as the top-most ActivityRecordProto (i.e. it is not a sub-object).
Wale Ogunwalef342f062020-01-27 07:34:13 -08001218 record.dumpDebug(protoOutputStream, WindowTraceLogLevel.ALL);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001219 final byte[] bytes = protoOutputStream.getBytes();
1220
1221 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1222
1223 return bytes;
Igor Murashkin212d06c2018-10-22 16:34:39 -07001224 }
1225
1226 private static @ActivityMetricsLaunchObserver.Temperature int
1227 convertTransitionTypeToLaunchObserverTemperature(int transitionType) {
1228 switch (transitionType) {
1229 case TYPE_TRANSITION_WARM_LAUNCH:
1230 return ActivityMetricsLaunchObserver.TEMPERATURE_WARM;
1231 case TYPE_TRANSITION_HOT_LAUNCH:
1232 return ActivityMetricsLaunchObserver.TEMPERATURE_HOT;
1233 case TYPE_TRANSITION_COLD_LAUNCH:
1234 return ActivityMetricsLaunchObserver.TEMPERATURE_COLD;
1235 default:
1236 return -1;
1237 }
1238 }
Filip Gruszczynski77d94482015-12-11 13:59:52 -08001239}