blob: de51d4b267dfa7541072056908e59bab5020fe83 [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;
11import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
Vishnu Nair132ee832018-09-28 15:00:05 -070012import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale926aade2017-08-29 11:24:37 -070013import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
14import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Vishnu Nair132ee832018-09-28 15:00:05 -070015
Michal Karpinski201bc0c2018-07-20 15:32:00 +010016import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_ACTIVITY_START;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080017import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION;
Jorim Jaggi515dd682017-05-05 15:05:07 +020018import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_BIND_APPLICATION_DELAY_MS;
Todd Kennedy50d946c12017-03-17 13:55:38 -070019import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_CALLING_PACKAGE_NAME;
Jorim Jaggi172e99f2017-10-20 14:33:18 +020020import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_CANCELLED;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080021import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_DELAY_MS;
22import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_DEVICE_UPTIME_SECONDS;
Todd Kennedy50d946c12017-03-17 13:55:38 -070023import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_IS_EPHEMERAL;
Jorim Jaggi4d27b842017-08-17 17:22:26 +020024import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_PROCESS_RUNNING;
25import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_REPORTED_DRAWN;
26import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_REPORTED_DRAWN_MS;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080027import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_STARTING_WINDOW_DELAY_MS;
28import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_WINDOWS_DRAWN_DELAY_MS;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010029import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_PACKAGE_NAME;
30import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_UID;
31import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_UID_HAS_ANY_VISIBLE_WINDOW;
32import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_UID_PROC_STATE;
Jorim Jaggicdfc04e2017-04-28 19:06:24 +020033import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CLASS_NAME;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010034import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_COMING_FROM_PENDING_INTENT;
Todd Kennedy50d946c12017-03-17 13:55:38 -070035import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_INSTANT_APP_LAUNCH_TOKEN;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010036import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_INTENT_ACTION;
37import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_CUR_PROC_STATE;
38import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_CLIENT_ACTIVITIES;
39import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_FOREGROUND_ACTIVITIES;
40import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_FOREGROUND_SERVICES;
41import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_OVERLAY_UI;
42import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_TOP_UI;
43import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_MILLIS_SINCE_FG_INTERACTION;
44import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_MILLIS_SINCE_LAST_INTERACTION_EVENT;
45import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_MILLIS_SINCE_UNIMPORTANT;
46import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_PENDING_UI_CLEAN;
47import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_PROCESS_NAME;
48import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_REAL_CALLING_UID;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010049import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_REAL_CALLING_UID_HAS_ANY_VISIBLE_WINDOW;
Vishnu Nair132ee832018-09-28 15:00:05 -070050import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_REAL_CALLING_UID_PROC_STATE;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010051import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TARGET_SHORT_COMPONENT_NAME;
Calin Juravle759fbda2018-02-20 19:52:30 +000052import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PACKAGE_OPTIMIZATION_COMPILATION_FILTER;
Vishnu Nair132ee832018-09-28 15:00:05 -070053import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PACKAGE_OPTIMIZATION_COMPILATION_REASON;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080054import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_COLD_LAUNCH;
55import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_HOT_LAUNCH;
Jorim Jaggi4d27b842017-08-17 17:22:26 +020056import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_REPORTED_DRAWN_NO_BUNDLE;
57import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_REPORTED_DRAWN_WITH_BUNDLE;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080058import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_WARM_LAUNCH;
Ng Zhi Anbbefdec2018-01-30 17:12:39 -080059import static com.android.server.am.MemoryStatUtil.MemoryStat;
Rajeev Kumarbfcd9202018-03-02 22:42:13 +000060import static com.android.server.am.MemoryStatUtil.readMemoryStatFromFilesystem;
Vishnu Naira62534b2018-11-09 09:13:22 -080061import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_METRICS;
62import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
63import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Vishnu Nair132ee832018-09-28 15:00:05 -070064import static com.android.server.wm.ActivityTaskManagerInternal.APP_TRANSITION_TIMEOUT;
Jeff Changd136e772019-11-05 20:33:52 +080065import static com.android.server.wm.EventLogTags.WM_ACTIVITY_LAUNCH_TIME;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080066
Riddle Hsufd66d4d2019-11-14 10:35:55 +080067import android.annotation.NonNull;
68import android.annotation.Nullable;
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -080069import android.app.WaitResult;
Igor Murashkin212d06c2018-10-22 16:34:39 -070070import android.app.WindowConfiguration.WindowingMode;
Michal Karpinski319069b2019-03-27 15:46:50 +000071import android.content.ComponentName;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010072import android.content.Intent;
Calin Juravle759fbda2018-02-20 19:52:30 +000073import android.content.pm.ApplicationInfo;
74import android.content.pm.dex.ArtManagerInternal;
75import android.content.pm.dex.PackageOptimizationInfo;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080076import android.metrics.LogMaker;
Riddle Hsufd66d4d2019-11-14 10:35:55 +080077import android.os.Binder;
Jorim Jaggi172e99f2017-10-20 14:33:18 +020078import android.os.Looper;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080079import android.os.SystemClock;
Vishnu Nair132ee832018-09-28 15:00:05 -070080import android.os.Trace;
Riddle Hsufd66d4d2019-11-14 10:35:55 +080081import android.util.ArrayMap;
Vishnu Nair132ee832018-09-28 15:00:05 -070082import android.util.EventLog;
83import android.util.Log;
Jorim Jaggi172e99f2017-10-20 14:33:18 +020084import android.util.Slog;
Olivier Gaillardaed7f122017-12-12 14:26:22 +000085import android.util.StatsLog;
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;
Riddle Hsufd66d4d2019-11-14 10:35:55 +080092import com.android.internal.util.function.pooled.PooledLambda;
Calin Juravle759fbda2018-02-20 19:52:30 +000093import com.android.server.LocalServices;
Louis Changcdec0802019-11-11 11:45:07 +080094
Riddle Hsufd66d4d2019-11-14 10:35:55 +080095import java.util.ArrayList;
96import java.util.LinkedList;
Yan Wang9eac5ec2019-09-30 15:42:18 -070097import java.util.concurrent.TimeUnit;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080098
99/**
Vishnu Nair132ee832018-09-28 15:00:05 -0700100 * Listens to activity launches, transitions, visibility changes and window drawn callbacks to
101 * determine app launch times and draw delays. Source of truth for activity metrics and provides
102 * data for Tron, logcat, event logs and {@link android.app.WaitResult}.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800103 * <p>
104 * A typical sequence of a launch event could be:
105 * {@link #notifyActivityLaunching}, {@link #notifyActivityLaunched},
106 * {@link #notifyStartingWindowDrawn} (optional), {@link #notifyTransitionStarting}
107 * {@link #notifyWindowsDrawn}.
108 * <p>
Vishnu Nair132ee832018-09-28 15:00:05 -0700109 * Tests:
Tadashi G. Takaoka28bc3702019-04-23 11:01:48 +0900110 * atest CtsWindowManagerDeviceTestCases:ActivityMetricsLoggerTests
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800111 */
112class ActivityMetricsLogger {
Jorim Jaggif9704102016-05-05 19:14:22 -0700113
Wale Ogunwale98875612018-10-12 07:53:02 -0700114 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityMetricsLogger" : TAG_ATM;
Jorim Jaggif9704102016-05-05 19:14:22 -0700115
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800116 // Window modes we are interested in logging. If we ever introduce a new type, we need to add
117 // a value here and increase the {@link #TRON_WINDOW_STATE_VARZ_STRINGS} array.
118 private static final int WINDOW_STATE_STANDARD = 0;
119 private static final int WINDOW_STATE_SIDE_BY_SIDE = 1;
120 private static final int WINDOW_STATE_FREEFORM = 2;
Winson Chung83471632016-12-13 11:02:12 -0800121 private static final int WINDOW_STATE_ASSISTANT = 3;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800122 private static final int WINDOW_STATE_INVALID = -1;
123
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800124 /**
125 * The flag for {@link #notifyActivityLaunching} to skip associating a new launch with an active
126 * transition, in the case the launch is standalone (e.g. from recents).
127 */
128 private static final int IGNORE_CALLER = -1;
Vishnu Nair132ee832018-09-28 15:00:05 -0700129 private static final int INVALID_DELAY = -1;
130 private static final int INVALID_TRANSITION_TYPE = -1;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500131
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800132 // Preallocated strings we are sending to tron, so we don't have to allocate a new one every
133 // time we log.
134 private static final String[] TRON_WINDOW_STATE_VARZ_STRINGS = {
Winson Chung83471632016-12-13 11:02:12 -0800135 "window_time_0", "window_time_1", "window_time_2", "window_time_3"};
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800136
137 private int mWindowState = WINDOW_STATE_STANDARD;
138 private long mLastLogTimeSecs;
139 private final ActivityStackSupervisor mSupervisor;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800140 private final MetricsLogger mMetricsLogger = new MetricsLogger();
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800141
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800142 /** All active transitions. */
143 private final ArrayList<TransitionInfo> mTransitionInfoList = new ArrayList<>();
144 /** Map : Last launched activity => {@link TransitionInfo} */
145 private final ArrayMap<ActivityRecord, TransitionInfo> mLastTransitionInfo = new ArrayMap<>();
Calin Juravle759fbda2018-02-20 19:52:30 +0000146
147 private ArtManagerInternal mArtManagerInternal;
Vishnu Nair132ee832018-09-28 15:00:05 -0700148 private final StringBuilder mStringBuilder = new StringBuilder();
Calin Juravle759fbda2018-02-20 19:52:30 +0000149
Igor Murashkin212d06c2018-10-22 16:34:39 -0700150 /**
151 * Due to the global single concurrent launch sequence, all calls to this observer must be made
152 * in-order on the same thread to fulfill the "happens-before" guarantee in LaunchObserver.
153 */
Igor Murashkinc0b47e42018-11-07 15:54:18 -0800154 private final LaunchObserverRegistryImpl mLaunchObserver;
155 @VisibleForTesting static final int LAUNCH_OBSERVER_ACTIVITY_RECORD_PROTO_CHUNK_SIZE = 512;
Igor Murashkin212d06c2018-10-22 16:34:39 -0700156
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800157 /**
158 * The information created when an intent is incoming but we do not yet know whether it will be
159 * launched successfully.
160 */
161 static final class LaunchingState {
162 /** The timestamp of {@link #notifyActivityLaunching}. */
163 private long mCurrentTransitionStartTimeNs;
164 /** Non-null when a {@link TransitionInfo} is created for this state. */
165 private TransitionInfo mAssociatedTransitionInfo;
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200166
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800167 @VisibleForTesting
168 boolean allDrawn() {
169 return mAssociatedTransitionInfo != null && mAssociatedTransitionInfo.allDrawn();
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200170 }
Calin Juravle759fbda2018-02-20 19:52:30 +0000171 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800172
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800173 /** The information created when an activity is confirmed to be launched. */
174 private static final class TransitionInfo {
175 /**
176 * The field to lookup and update an existing transition efficiently between
177 * {@link #notifyActivityLaunching} and {@link #notifyActivityLaunched}.
178 *
179 * @see LaunchingState#mAssociatedTransitionInfo
180 */
181 final LaunchingState mLaunchingState;
182 /**
183 * The timestamp of the first {@link #notifyActivityLaunching}. It can be used as a key for
184 * observer to identify which callbacks belong to a launch event.
185 */
186 final long mTransitionStartTimeNs;
187 /** The device uptime in seconds when this transition info is created. */
188 final int mCurrentTransitionDeviceUptime;
189 /** The type can be cold (new process), warm (new activity), or hot (bring to front). */
190 final int mTransitionType;
191 /** Whether the process was already running when the transition started. */
192 final boolean mProcessRunning;
193 /** The activities that should be drawn. */
194 final LinkedList<ActivityRecord> mPendingDrawActivities = new LinkedList<>();
Igor Murashkin212d06c2018-10-22 16:34:39 -0700195 /** The latest activity to have been launched. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800196 @NonNull ActivityRecord mLastLaunchedActivity;
197
198 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyTransitionStarting}. */
199 int mCurrentTransitionDelayMs;
200 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyStartingWindowDrawn}. */
201 int mStartingWindowDelayMs = INVALID_DELAY;
202 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyBindApplication}. */
203 int mBindApplicationDelayMs = INVALID_DELAY;
Vishnu Nair132ee832018-09-28 15:00:05 -0700204 /** Elapsed time from when we launch an activity to when its windows are drawn. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800205 int mWindowsDrawnDelayMs;
206 /** The reason why the transition started (see ActivityManagerInternal.APP_TRANSITION_*). */
207 int mReason = APP_TRANSITION_TIMEOUT;
208 /** The flag ensures that {@link #mStartingWindowDelayMs} is only set once. */
209 boolean mLoggedStartingWindowDrawn;
210 /** If the any app transitions have been logged as starting. */
211 boolean mLoggedTransitionStarting;
212
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800213 /** Non-null if the application has reported drawn but its window hasn't. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800214 @Nullable Runnable mPendingFullyDrawn;
215 /** Non-null if the trace is active. */
216 @Nullable String mLaunchTraceName;
217
218 /** @return Non-null if there will be a window drawn event for the launch. */
219 @Nullable
220 static TransitionInfo create(@NonNull ActivityRecord r,
221 @NonNull LaunchingState launchingState, boolean processRunning, int startResult) {
222 int transitionType = INVALID_TRANSITION_TYPE;
223 if (processRunning) {
224 if (startResult == START_SUCCESS) {
225 transitionType = TYPE_TRANSITION_WARM_LAUNCH;
226 } else if (startResult == START_TASK_TO_FRONT) {
227 transitionType = TYPE_TRANSITION_HOT_LAUNCH;
228 }
229 } else if (startResult == START_SUCCESS || startResult == START_TASK_TO_FRONT) {
230 // Task may still exist when cold launching an activity and the start result will be
231 // set to START_TASK_TO_FRONT. Treat this as a COLD launch.
232 transitionType = TYPE_TRANSITION_COLD_LAUNCH;
233 }
234 if (transitionType == INVALID_TRANSITION_TYPE) {
235 // That means the startResult is neither START_SUCCESS nor START_TASK_TO_FRONT.
236 return null;
237 }
238 return new TransitionInfo(r, launchingState, transitionType, processRunning);
239 }
240
241 /** Use {@link TransitionInfo#create} instead to ensure the transition type is valid. */
242 private TransitionInfo(ActivityRecord r, LaunchingState launchingState, int transitionType,
243 boolean processRunning) {
244 mLaunchingState = launchingState;
245 mTransitionStartTimeNs = launchingState.mCurrentTransitionStartTimeNs;
246 mTransitionType = transitionType;
247 mProcessRunning = processRunning;
248 mCurrentTransitionDeviceUptime =
249 (int) TimeUnit.MILLISECONDS.toSeconds(SystemClock.uptimeMillis());
250 setLatestLaunchedActivity(r);
251 launchingState.mAssociatedTransitionInfo = this;
252 }
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800253
254 /**
255 * Remembers the latest launched activity to represent the final transition. This also
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800256 * tracks the activities that should be drawn, so a consecutive launching sequence can be
257 * coalesced as one event.
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800258 */
259 void setLatestLaunchedActivity(ActivityRecord r) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800260 if (mLastLaunchedActivity == r) {
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800261 return;
262 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800263 mLastLaunchedActivity = r;
264 if (!r.noDisplay) {
265 if (DEBUG_METRICS) Slog.i(TAG, "Add pending draw " + r);
266 mPendingDrawActivities.add(r);
267 }
268 }
269
270 /** @return {@code true} if the activity matches a launched activity in this transition. */
271 boolean contains(ActivityRecord r) {
272 return r == mLastLaunchedActivity || mPendingDrawActivities.contains(r);
273 }
274
275 /** Called when the activity is drawn or won't be drawn. */
276 void removePendingDrawActivity(ActivityRecord r) {
277 if (DEBUG_METRICS) Slog.i(TAG, "Remove pending draw " + r);
278 mPendingDrawActivities.remove(r);
279 }
280
281 boolean allDrawn() {
282 return mPendingDrawActivities.isEmpty();
283 }
284
285 int calculateCurrentDelay() {
286 return calculateDelay(SystemClock.elapsedRealtimeNanos());
287 }
288
289 int calculateDelay(long timestampNs) {
290 // Shouldn't take more than 25 days to launch an app, so int is fine here.
291 return (int) TimeUnit.NANOSECONDS.toMillis(timestampNs - mTransitionStartTimeNs);
292 }
293
294 @Override
295 public String toString() {
296 return "TransitionInfo{" + Integer.toHexString(System.identityHashCode(this))
297 + " a=" + mLastLaunchedActivity + " ua=" + mPendingDrawActivities + "}";
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800298 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800299 }
300
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800301 static final class TransitionInfoSnapshot {
Calin Juravle759fbda2018-02-20 19:52:30 +0000302 final private ApplicationInfo applicationInfo;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700303 final private WindowProcessController processRecord;
Vishnu Nair132ee832018-09-28 15:00:05 -0700304 final String packageName;
305 final String launchedActivityName;
Calin Juravle759fbda2018-02-20 19:52:30 +0000306 final private String launchedActivityLaunchedFromPackage;
307 final private String launchedActivityLaunchToken;
308 final private String launchedActivityAppRecordRequiredAbi;
Vishnu Nair132ee832018-09-28 15:00:05 -0700309 final String launchedActivityShortComponentName;
Ng Zhi An83473542018-02-20 09:02:14 -0800310 final private String processName;
Calin Juravle759fbda2018-02-20 19:52:30 +0000311 final private int reason;
312 final private int startingWindowDelayMs;
313 final private int bindApplicationDelayMs;
Vishnu Nair132ee832018-09-28 15:00:05 -0700314 final int windowsDrawnDelayMs;
315 final int type;
316 final int userId;
317 /**
318 * Elapsed time from when we launch an activity to when the app reported it was
319 * fully drawn. If this is not reported then the value is set to INVALID_DELAY.
320 */
321 final int windowsFullyDrawnDelayMs;
322 final int activityRecordIdHashCode;
Calin Juravle759fbda2018-02-20 19:52:30 +0000323
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800324 private TransitionInfoSnapshot(TransitionInfo info) {
325 this(info, info.mLastLaunchedActivity, INVALID_DELAY);
Vishnu Nair132ee832018-09-28 15:00:05 -0700326 }
327
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800328 private TransitionInfoSnapshot(TransitionInfo info, ActivityRecord launchedActivity,
329 int windowsFullyDrawnDelayMs) {
Andrii Kulianeceebbf2019-06-26 17:36:51 -0700330 applicationInfo = launchedActivity.info.applicationInfo;
Vishnu Nair132ee832018-09-28 15:00:05 -0700331 packageName = launchedActivity.packageName;
332 launchedActivityName = launchedActivity.info.name;
333 launchedActivityLaunchedFromPackage = launchedActivity.launchedFromPackage;
334 launchedActivityLaunchToken = launchedActivity.info.launchToken;
335 launchedActivityAppRecordRequiredAbi = launchedActivity.app == null
Calin Juravle759fbda2018-02-20 19:52:30 +0000336 ? null
Vishnu Nairaf0ea312018-10-15 16:23:55 -0700337 : launchedActivity.app.getRequiredAbi();
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800338 reason = info.mReason;
339 startingWindowDelayMs = info.mStartingWindowDelayMs;
340 bindApplicationDelayMs = info.mBindApplicationDelayMs;
341 windowsDrawnDelayMs = info.mWindowsDrawnDelayMs;
342 type = info.mTransitionType;
343 processRecord = launchedActivity.app;
Vishnu Nairaf0ea312018-10-15 16:23:55 -0700344 processName = launchedActivity.processName;
Wale Ogunwale8b19de92018-11-29 19:58:26 -0800345 userId = launchedActivity.mUserId;
Vishnu Nair132ee832018-09-28 15:00:05 -0700346 launchedActivityShortComponentName = launchedActivity.shortComponentName;
347 activityRecordIdHashCode = System.identityHashCode(launchedActivity);
348 this.windowsFullyDrawnDelayMs = windowsFullyDrawnDelayMs;
Calin Juravle759fbda2018-02-20 19:52:30 +0000349 }
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -0800350
351 @WaitResult.LaunchState int getLaunchState() {
352 switch (type) {
353 case TYPE_TRANSITION_WARM_LAUNCH:
354 return LAUNCH_STATE_WARM;
355 case TYPE_TRANSITION_HOT_LAUNCH:
356 return LAUNCH_STATE_HOT;
357 case TYPE_TRANSITION_COLD_LAUNCH:
358 return LAUNCH_STATE_COLD;
359 default:
360 return -1;
361 }
362 }
Calin Juravle759fbda2018-02-20 19:52:30 +0000363 }
364
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800365 ActivityMetricsLogger(ActivityStackSupervisor supervisor, Looper looper) {
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800366 mLastLogTimeSecs = SystemClock.elapsedRealtime() / 1000;
367 mSupervisor = supervisor;
Igor Murashkinc0b47e42018-11-07 15:54:18 -0800368 mLaunchObserver = new LaunchObserverRegistryImpl(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800369 }
370
371 void logWindowState() {
372 final long now = SystemClock.elapsedRealtime() / 1000;
373 if (mWindowState != WINDOW_STATE_INVALID) {
374 // We log even if the window state hasn't changed, because the user might remain in
375 // home/fullscreen move forever and we would like to track this kind of behavior
376 // too.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800377 mMetricsLogger.count(TRON_WINDOW_STATE_VARZ_STRINGS[mWindowState],
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800378 (int) (now - mLastLogTimeSecs));
379 }
380 mLastLogTimeSecs = now;
381
Wale Ogunwale926aade2017-08-29 11:24:37 -0700382 mWindowState = WINDOW_STATE_INVALID;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800383 ActivityStack stack =
384 mSupervisor.mRootActivityContainer.getTopDisplayFocusedStack();
lumarkf6c4a982018-06-15 15:43:12 +0800385 if (stack == null) {
386 return;
387 }
388
Wale Ogunwale926aade2017-08-29 11:24:37 -0700389 if (stack.isActivityTypeAssistant()) {
390 mWindowState = WINDOW_STATE_ASSISTANT;
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -0800391 return;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800392 }
Wale Ogunwale926aade2017-08-29 11:24:37 -0700393
Igor Murashkin212d06c2018-10-22 16:34:39 -0700394 @WindowingMode int windowingMode = stack.getWindowingMode();
Wale Ogunwale3382ab12017-07-27 08:55:03 -0700395 if (windowingMode == WINDOWING_MODE_PINNED) {
Wale Ogunwaled32da472018-11-16 07:19:28 -0800396 stack = mSupervisor.mRootActivityContainer.findStackBehind(stack);
Wale Ogunwale3382ab12017-07-27 08:55:03 -0700397 windowingMode = stack.getWindowingMode();
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -0800398 }
Wale Ogunwale926aade2017-08-29 11:24:37 -0700399 switch (windowingMode) {
400 case WINDOWING_MODE_FULLSCREEN:
401 mWindowState = WINDOW_STATE_STANDARD;
402 break;
403 case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
404 case WINDOWING_MODE_SPLIT_SCREEN_SECONDARY:
405 mWindowState = WINDOW_STATE_SIDE_BY_SIDE;
406 break;
Bryce Lee6c605092017-10-12 11:14:49 -0700407 case WINDOWING_MODE_FREEFORM:
Wale Ogunwale926aade2017-08-29 11:24:37 -0700408 mWindowState = WINDOW_STATE_FREEFORM;
409 break;
410 default:
411 if (windowingMode != WINDOWING_MODE_UNDEFINED) {
412 throw new IllegalStateException("Unknown windowing mode for stack=" + stack
413 + " windowingMode=" + windowingMode);
414 }
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800415 }
416 }
Jorim Jaggi275561a2016-02-23 10:11:02 -0500417
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800418 /** @return Non-null {@link TransitionInfo} if the activity is found in an active transition. */
419 @Nullable
420 private TransitionInfo getActiveTransitionInfo(ActivityRecord r) {
421 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
422 final TransitionInfo info = mTransitionInfoList.get(i);
423 if (info.contains(r)) {
424 return info;
425 }
426 }
427 return null;
428 }
429
430 /**
431 * This method should be only used by starting recents and starting from recents, or internal
432 * tests. Because it doesn't lookup caller and always creates a new launching state.
433 *
434 * @see #notifyActivityLaunching(Intent, ActivityRecord, int)
435 */
436 LaunchingState notifyActivityLaunching(Intent intent) {
437 return notifyActivityLaunching(intent, null /* caller */, IGNORE_CALLER);
438 }
439
440 /**
441 * If the caller is found in an active transition, it will be considered as consecutive launch
442 * and coalesced into the active transition.
443 *
444 * @see #notifyActivityLaunching(Intent, ActivityRecord, int)
445 */
446 LaunchingState notifyActivityLaunching(Intent intent, @Nullable ActivityRecord caller) {
447 return notifyActivityLaunching(intent, caller, Binder.getCallingUid());
448 }
449
Jorim Jaggi275561a2016-02-23 10:11:02 -0500450 /**
451 * Notifies the tracker at the earliest possible point when we are starting to launch an
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800452 * activity. The caller must ensure that {@link #notifyActivityLaunched} will be called later
453 * with the returned {@link LaunchingState}.
Jorim Jaggi275561a2016-02-23 10:11:02 -0500454 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800455 private LaunchingState notifyActivityLaunching(Intent intent, @Nullable ActivityRecord caller,
456 int callingUid) {
457 final long transitionStartTimeNs = SystemClock.elapsedRealtimeNanos();
458 TransitionInfo existingInfo = null;
459 if (callingUid != IGNORE_CALLER) {
460 // Associate the launching event to an active transition if the caller is found in its
461 // launched activities.
462 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
463 final TransitionInfo info = mTransitionInfoList.get(i);
464 if (caller != null && info.contains(caller)) {
465 existingInfo = info;
466 break;
467 }
468 if (existingInfo == null && callingUid == info.mLastLaunchedActivity.getUid()) {
469 // Fallback to check the most recent matched uid for the case that the caller is
470 // not an activity.
471 existingInfo = info;
472 }
473 }
474 }
Igor Murashkin212d06c2018-10-22 16:34:39 -0700475 if (DEBUG_METRICS) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800476 Slog.i(TAG, "notifyActivityLaunching intent=" + intent
477 + " existingInfo=" + existingInfo);
Igor Murashkin212d06c2018-10-22 16:34:39 -0700478 }
479
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800480 if (existingInfo == null) {
481 // Only notify the observer for a new launching event.
482 launchObserverNotifyIntentStarted(intent, transitionStartTimeNs);
483 final LaunchingState launchingState = new LaunchingState();
484 launchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs;
485 return launchingState;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800486 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800487 existingInfo.mLaunchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs;
488 return existingInfo.mLaunchingState;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500489 }
490
491 /**
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700492 * Notifies the tracker that the activity is actually launching.
493 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800494 * @param launchingState The launching state to track the new or active transition.
495 * @param resultCode One of the {@link android.app.ActivityManager}.START_* flags, indicating
496 * the result of the launch.
497 * @param launchedActivity The activity that is being launched
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700498 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800499 void notifyActivityLaunched(@NonNull LaunchingState launchingState, int resultCode,
500 @Nullable ActivityRecord launchedActivity) {
501 if (launchedActivity == null) {
502 // The launch is aborted, e.g. intent not resolved, class not found.
503 abort(null /* info */, "nothing launched");
504 return;
505 }
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700506
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800507 final WindowProcessController processRecord = launchedActivity.app != null
508 ? launchedActivity.app
509 : mSupervisor.mService.getProcessController(
510 launchedActivity.processName, launchedActivity.info.applicationInfo.uid);
511 // Whether the process that will contains the activity is already running.
512 final boolean processRunning = processRecord != null;
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700513 // We consider this a "process switch" if the process of the activity that gets launched
514 // didn't have an activity that was in started state. In this case, we assume that lot
515 // of caches might be purged so the time until it produces the first frame is very
516 // interesting.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800517 final boolean processSwitch = !processRunning
Wale Ogunwalef6733932018-06-27 05:14:34 -0700518 || !processRecord.hasStartedActivity(launchedActivity);
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700519
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800520 final TransitionInfo info = launchingState.mAssociatedTransitionInfo;
521 if (DEBUG_METRICS) {
522 Slog.i(TAG, "notifyActivityLaunched" + " resultCode=" + resultCode
523 + " launchedActivity=" + launchedActivity + " processRunning=" + processRunning
524 + " processSwitch=" + processSwitch + " info=" + info);
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200525 }
526
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800527 if (launchedActivity.mDrawn) {
Vishnu Nairf8accc52018-10-11 10:19:54 -0700528 // Launched activity is already visible. We cannot measure windows drawn delay.
Riddle Hsu1063b512019-10-22 21:12:23 +0800529 abort(info, "launched activity already visible");
Vishnu Nairf8accc52018-10-11 10:19:54 -0700530 return;
531 }
532
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800533 if (info != null) {
Vishnu Nairf8accc52018-10-11 10:19:54 -0700534 // If we are already in an existing transition, only update the activity name, but not
535 // the other attributes.
Igor Murashkin212d06c2018-10-22 16:34:39 -0700536
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800537 if (DEBUG_METRICS) Slog.i(TAG, "notifyActivityLaunched update launched activity");
Igor Murashkin212d06c2018-10-22 16:34:39 -0700538 // Coalesce multiple (trampoline) activities from a single sequence together.
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800539 info.setLatestLaunchedActivity(launchedActivity);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500540 return;
541 }
542
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800543 if (!processSwitch) {
544 abort(info, "not a process switch");
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800545 return;
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800546 }
547
548 final TransitionInfo newInfo = TransitionInfo.create(launchedActivity, launchingState,
549 processRunning, resultCode);
550 if (newInfo == null) {
551 abort(info, "unrecognized launch");
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800552 return;
553 }
554
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200555 if (DEBUG_METRICS) Slog.i(TAG, "notifyActivityLaunched successful");
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800556 // A new launch sequence has begun. Start tracking it.
557 mTransitionInfoList.add(newInfo);
558 mLastTransitionInfo.put(launchedActivity, newInfo);
559 startLaunchTrace(newInfo);
Igor Murashkin212d06c2018-10-22 16:34:39 -0700560 launchObserverNotifyActivityLaunched(newInfo);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500561 }
562
563 /**
564 * Notifies the tracker that all windows of the app have been drawn.
565 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800566 @Nullable
567 TransitionInfoSnapshot notifyWindowsDrawn(@NonNull ActivityRecord r, long timestampNs) {
568 if (DEBUG_METRICS) Slog.i(TAG, "notifyWindowsDrawn " + r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200569
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800570 final TransitionInfo info = getActiveTransitionInfo(r);
571 if (info == null || info.allDrawn()) {
572 if (DEBUG_METRICS) Slog.i(TAG, "notifyWindowsDrawn no activity to be drawn");
Vishnu Nair132ee832018-09-28 15:00:05 -0700573 return null;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500574 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800575 // Always calculate the delay because the caller may need to know the individual drawn time.
576 info.mWindowsDrawnDelayMs = info.calculateDelay(timestampNs);
577 info.removePendingDrawActivity(r);
578 final TransitionInfoSnapshot infoSnapshot = new TransitionInfoSnapshot(info);
579 if (info.mLoggedTransitionStarting && info.allDrawn()) {
580 done(false /* abort */, info, "notifyWindowsDrawn - all windows drawn", timestampNs);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500581 }
Vishnu Nair132ee832018-09-28 15:00:05 -0700582 return infoSnapshot;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500583 }
584
585 /**
586 * Notifies the tracker that the starting window was drawn.
587 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800588 void notifyStartingWindowDrawn(@NonNull ActivityRecord r) {
589 final TransitionInfo info = getActiveTransitionInfo(r);
590 if (info == null || info.mLoggedStartingWindowDrawn) {
Jorim Jaggi275561a2016-02-23 10:11:02 -0500591 return;
592 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800593 if (DEBUG_METRICS) Slog.i(TAG, "notifyStartingWindowDrawn " + r);
594 info.mLoggedStartingWindowDrawn = true;
595 info.mStartingWindowDelayMs = info.calculateDelay(SystemClock.elapsedRealtimeNanos());
Jorim Jaggi275561a2016-02-23 10:11:02 -0500596 }
597
598 /**
599 * Notifies the tracker that the app transition is starting.
600 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800601 * @param activityToReason A map from activity to a reason integer, which must be on of
602 * ActivityTaskManagerInternal.APP_TRANSITION_* reasons.
Jorim Jaggi275561a2016-02-23 10:11:02 -0500603 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800604 void notifyTransitionStarting(ArrayMap<ActivityRecord, Integer> activityToReason) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200605 if (DEBUG_METRICS) Slog.i(TAG, "notifyTransitionStarting");
Igor Murashkin212d06c2018-10-22 16:34:39 -0700606
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800607 final long timestampNs = SystemClock.elapsedRealtimeNanos();
608 for (int index = activityToReason.size() - 1; index >= 0; index--) {
609 final ActivityRecord r = activityToReason.keyAt(index);
610 final TransitionInfo info = getActiveTransitionInfo(r);
611 if (info == null || info.mLoggedTransitionStarting) {
612 // Ignore any subsequent notifyTransitionStarting.
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800613 continue;
614 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800615 if (DEBUG_METRICS) {
616 Slog.i(TAG, "notifyTransitionStarting activity=" + r + " info=" + info);
617 }
618
619 info.mCurrentTransitionDelayMs = info.calculateDelay(timestampNs);
620 info.mReason = activityToReason.valueAt(index);
621 info.mLoggedTransitionStarting = true;
622 if (info.allDrawn()) {
623 done(false /* abort */, info, "notifyTransitionStarting - all windows drawn",
624 timestampNs);
625 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800626 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800627 }
628
629 /** Makes sure that the reference to the removed activity is cleared. */
630 void notifyActivityRemoved(@NonNull ActivityRecord r) {
631 mLastTransitionInfo.remove(r);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500632 }
633
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200634 /**
635 * Notifies the tracker that the visibility of an app is changing.
636 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800637 * @param r the app that is changing its visibility
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200638 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800639 void notifyVisibilityChanged(@NonNull ActivityRecord r) {
640 final TransitionInfo info = getActiveTransitionInfo(r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200641 if (info == null) {
642 return;
643 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800644 if (DEBUG_METRICS) {
645 Slog.i(TAG, "notifyVisibilityChanged " + r + " visible=" + r.mVisibleRequested
646 + " state=" + r.getState() + " finishing=" + r.finishing);
647 }
648 if (!r.mVisibleRequested || r.finishing) {
649 info.removePendingDrawActivity(r);
650 }
651 if (info.mLastLaunchedActivity != r) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200652 return;
653 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800654 // The activity and its task are passed separately because the activity may be removed from
655 // the task later.
656 r.mAtmService.mH.sendMessage(PooledLambda.obtainMessage(
657 ActivityMetricsLogger::checkVisibility, this, r.getTask(), r));
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200658 }
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200659
Riddle Hsu1063b512019-10-22 21:12:23 +0800660 /** @return {@code true} if the given task has an activity will be drawn. */
Louis Changcdec0802019-11-11 11:45:07 +0800661 private static boolean hasActivityToBeDrawn(Task t) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800662 return t.forAllActivities((r) -> r.mVisibleRequested && !r.mDrawn && !r.finishing);
Vishnu Nairb1de42d2019-01-28 09:49:51 -0800663 }
664
Louis Changcdec0802019-11-11 11:45:07 +0800665 private void checkVisibility(Task t, ActivityRecord r) {
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700666 synchronized (mSupervisor.mService.mGlobalLock) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200667
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800668 final TransitionInfo info = getActiveTransitionInfo(r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200669
670 // If we have an active transition that's waiting on a certain activity that will be
671 // invisible now, we'll never get onWindowsDrawn, so abort the transition if necessary.
Vishnu Naird15063b2019-06-11 08:08:25 -0700672
673 // We have no active transitions.
674 if (info == null) {
675 return;
676 }
677
678 // The notified activity whose visibility changed is no longer the launched activity.
679 // We can still wait to get onWindowsDrawn.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800680 if (info.mLastLaunchedActivity != r) {
Vishnu Naird15063b2019-06-11 08:08:25 -0700681 return;
682 }
683
Riddle Hsu1063b512019-10-22 21:12:23 +0800684 // If the task of the launched activity contains any activity to be drawn, then the
685 // window drawn event should report later to complete the transition. Otherwise all
686 // activities in this task may be finished, invisible or drawn, so the transition event
687 // should be cancelled.
688 if (hasActivityToBeDrawn(t)) {
Vishnu Naird15063b2019-06-11 08:08:25 -0700689 return;
690 }
691
692 if (DEBUG_METRICS) Slog.i(TAG, "notifyVisibilityChanged to invisible activity=" + r);
693 logAppTransitionCancel(info);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800694 abort(info, "notifyVisibilityChanged to invisible");
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200695 }
696 }
697
Jorim Jaggi515dd682017-05-05 15:05:07 +0200698 /**
699 * Notifies the tracker that we called immediately before we call bindApplication on the client.
700 *
Wale Ogunwale31913b52018-10-13 08:29:31 -0700701 * @param appInfo The client into which we'll call bindApplication.
Jorim Jaggi515dd682017-05-05 15:05:07 +0200702 */
Wale Ogunwale31913b52018-10-13 08:29:31 -0700703 void notifyBindApplication(ApplicationInfo appInfo) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800704 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
705 final TransitionInfo info = mTransitionInfoList.get(i);
Jorim Jaggi515dd682017-05-05 15:05:07 +0200706
707 // App isn't attached to record yet, so match with info.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800708 if (info.mLastLaunchedActivity.info.applicationInfo == appInfo) {
709 info.mBindApplicationDelayMs = info.calculateCurrentDelay();
Jorim Jaggi515dd682017-05-05 15:05:07 +0200710 }
711 }
712 }
713
Riddle Hsu1063b512019-10-22 21:12:23 +0800714 /** Aborts tracking of current launch metrics. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800715 private void abort(TransitionInfo info, String cause) {
716 done(true /* abort */, info, cause, 0L /* timestampNs */);
Riddle Hsu1063b512019-10-22 21:12:23 +0800717 }
718
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800719 /** Called when the given transition (info) is no longer active. */
720 private void done(boolean abort, @Nullable TransitionInfo info, String cause,
Riddle Hsu1063b512019-10-22 21:12:23 +0800721 long timestampNs) {
Yan Wangd47f90b2019-10-03 19:17:15 -0700722 if (DEBUG_METRICS) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800723 Slog.i(TAG, "done abort=" + abort + " cause=" + cause + " timestamp=" + timestampNs
724 + " info=" + info);
Yan Wangd47f90b2019-10-03 19:17:15 -0700725 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800726 if (info == null) {
Igor Murashkin212d06c2018-10-22 16:34:39 -0700727 launchObserverNotifyIntentFailed();
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200728 return;
729 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800730
731 stopLaunchTrace(info);
732 if (abort) {
733 launchObserverNotifyActivityLaunchCancelled(info);
734 } else {
735 logAppTransitionFinished(info);
736 launchObserverNotifyActivityLaunchFinished(info, timestampNs);
737 }
738 info.mPendingDrawActivities.clear();
739 mTransitionInfoList.remove(info);
740 }
741
742 private void logAppTransitionCancel(TransitionInfo info) {
743 final int type = info.mTransitionType;
744 final ActivityRecord activity = info.mLastLaunchedActivity;
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200745 final LogMaker builder = new LogMaker(APP_TRANSITION_CANCELLED);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800746 builder.setPackageName(activity.packageName);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200747 builder.setType(type);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800748 builder.addTaggedData(FIELD_CLASS_NAME, activity.info.name);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200749 mMetricsLogger.write(builder);
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000750 StatsLog.write(
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800751 StatsLog.APP_START_CANCELED,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800752 activity.info.applicationInfo.uid,
753 activity.packageName,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000754 convertAppStartTransitionType(type),
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800755 activity.info.name);
Igor Murashkin212d06c2018-10-22 16:34:39 -0700756 if (DEBUG_METRICS) {
757 Slog.i(TAG, String.format("APP_START_CANCELED(%s, %s, %s, %s)",
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800758 activity.info.applicationInfo.uid,
759 activity.packageName,
Igor Murashkin212d06c2018-10-22 16:34:39 -0700760 convertAppStartTransitionType(type),
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800761 activity.info.name));
Igor Murashkin212d06c2018-10-22 16:34:39 -0700762 }
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200763 }
764
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800765 private void logAppTransitionFinished(@NonNull TransitionInfo info) {
766 if (DEBUG_METRICS) Slog.i(TAG, "logging finished transition " + info);
Calin Juravle759fbda2018-02-20 19:52:30 +0000767
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800768 // Take a snapshot of the transition info before sending it to the handler for logging.
769 // This will avoid any races with other operations that modify the ActivityRecord.
770 final TransitionInfoSnapshot infoSnapshot = new TransitionInfoSnapshot(info);
771 BackgroundThread.getHandler().post(() -> logAppTransition(
772 info.mCurrentTransitionDeviceUptime, info.mCurrentTransitionDelayMs, infoSnapshot));
773 BackgroundThread.getHandler().post(() -> logAppDisplayed(infoSnapshot));
774 if (info.mPendingFullyDrawn != null) {
775 info.mPendingFullyDrawn.run();
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800776 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800777
778 info.mLastLaunchedActivity.info.launchToken = null;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800779 }
780
Ng Zhi An83473542018-02-20 09:02:14 -0800781 // This gets called on a background thread without holding the activity manager lock.
Calin Juravle759fbda2018-02-20 19:52:30 +0000782 private void logAppTransition(int currentTransitionDeviceUptime, int currentTransitionDelayMs,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800783 TransitionInfoSnapshot info) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000784 final LogMaker builder = new LogMaker(APP_TRANSITION);
785 builder.setPackageName(info.packageName);
786 builder.setType(info.type);
787 builder.addTaggedData(FIELD_CLASS_NAME, info.launchedActivityName);
788 final boolean isInstantApp = info.applicationInfo.isInstantApp();
789 if (info.launchedActivityLaunchedFromPackage != null) {
790 builder.addTaggedData(APP_TRANSITION_CALLING_PACKAGE_NAME,
791 info.launchedActivityLaunchedFromPackage);
792 }
793 String launchToken = info.launchedActivityLaunchToken;
794 if (launchToken != null) {
795 builder.addTaggedData(FIELD_INSTANT_APP_LAUNCH_TOKEN, launchToken);
796 }
797 builder.addTaggedData(APP_TRANSITION_IS_EPHEMERAL, isInstantApp ? 1 : 0);
798 builder.addTaggedData(APP_TRANSITION_DEVICE_UPTIME_SECONDS,
799 currentTransitionDeviceUptime);
800 builder.addTaggedData(APP_TRANSITION_DELAY_MS, currentTransitionDelayMs);
801 builder.setSubtype(info.reason);
Vishnu Nair132ee832018-09-28 15:00:05 -0700802 if (info.startingWindowDelayMs != INVALID_DELAY) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000803 builder.addTaggedData(APP_TRANSITION_STARTING_WINDOW_DELAY_MS,
804 info.startingWindowDelayMs);
805 }
Vishnu Nair132ee832018-09-28 15:00:05 -0700806 if (info.bindApplicationDelayMs != INVALID_DELAY) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000807 builder.addTaggedData(APP_TRANSITION_BIND_APPLICATION_DELAY_MS,
808 info.bindApplicationDelayMs);
809 }
810 builder.addTaggedData(APP_TRANSITION_WINDOWS_DRAWN_DELAY_MS, info.windowsDrawnDelayMs);
811 final ArtManagerInternal artManagerInternal = getArtManagerInternal();
812 final PackageOptimizationInfo packageOptimizationInfo =
813 (artManagerInternal == null) || (info.launchedActivityAppRecordRequiredAbi == null)
814 ? PackageOptimizationInfo.createWithNoInfo()
815 : artManagerInternal.getPackageOptimizationInfo(
816 info.applicationInfo,
817 info.launchedActivityAppRecordRequiredAbi);
818 builder.addTaggedData(PACKAGE_OPTIMIZATION_COMPILATION_REASON,
819 packageOptimizationInfo.getCompilationReason());
820 builder.addTaggedData(PACKAGE_OPTIMIZATION_COMPILATION_FILTER,
821 packageOptimizationInfo.getCompilationFilter());
822 mMetricsLogger.write(builder);
823 StatsLog.write(
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800824 StatsLog.APP_START_OCCURRED,
Calin Juravle759fbda2018-02-20 19:52:30 +0000825 info.applicationInfo.uid,
826 info.packageName,
827 convertAppStartTransitionType(info.type),
828 info.launchedActivityName,
829 info.launchedActivityLaunchedFromPackage,
830 isInstantApp,
831 currentTransitionDeviceUptime * 1000,
832 info.reason,
833 currentTransitionDelayMs,
834 info.startingWindowDelayMs,
835 info.bindApplicationDelayMs,
836 info.windowsDrawnDelayMs,
837 launchToken,
838 packageOptimizationInfo.getCompilationReason(),
839 packageOptimizationInfo.getCompilationFilter());
Igor Murashkin212d06c2018-10-22 16:34:39 -0700840
841 if (DEBUG_METRICS) {
842 Slog.i(TAG, String.format("APP_START_OCCURRED(%s, %s, %s, %s, %s)",
843 info.applicationInfo.uid,
844 info.packageName,
845 convertAppStartTransitionType(info.type),
846 info.launchedActivityName,
847 info.launchedActivityLaunchedFromPackage));
848 }
849
850
Ng Zhi An83473542018-02-20 09:02:14 -0800851 logAppStartMemoryStateCapture(info);
Calin Juravle759fbda2018-02-20 19:52:30 +0000852 }
853
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800854 private void logAppDisplayed(TransitionInfoSnapshot info) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700855 if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
856 return;
857 }
858
Jeff Changd136e772019-11-05 20:33:52 +0800859 EventLog.writeEvent(WM_ACTIVITY_LAUNCH_TIME,
Vishnu Nair132ee832018-09-28 15:00:05 -0700860 info.userId, info.activityRecordIdHashCode, info.launchedActivityShortComponentName,
861 info.windowsDrawnDelayMs);
862
863 StringBuilder sb = mStringBuilder;
864 sb.setLength(0);
865 sb.append("Displayed ");
866 sb.append(info.launchedActivityShortComponentName);
867 sb.append(": ");
868 TimeUtils.formatDuration(info.windowsDrawnDelayMs, sb);
869 Log.i(TAG, sb.toString());
870 }
871
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000872 private int convertAppStartTransitionType(int tronType) {
873 if (tronType == TYPE_TRANSITION_COLD_LAUNCH) {
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800874 return StatsLog.APP_START_OCCURRED__TYPE__COLD;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000875 }
876 if (tronType == TYPE_TRANSITION_WARM_LAUNCH) {
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800877 return StatsLog.APP_START_OCCURRED__TYPE__WARM;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000878 }
879 if (tronType == TYPE_TRANSITION_HOT_LAUNCH) {
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800880 return StatsLog.APP_START_OCCURRED__TYPE__HOT;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000881 }
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800882 return StatsLog.APP_START_OCCURRED__TYPE__UNKNOWN;
Riddle Hsuc48c8912019-10-31 13:34:27 +0800883 }
884
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800885 /** @return the last known window drawn delay of the given activity. */
886 int getLastDrawnDelayMs(ActivityRecord r) {
887 final TransitionInfo info = mLastTransitionInfo.get(r);
888 return info != null ? info.mWindowsDrawnDelayMs : INVALID_DELAY;
Riddle Hsuc48c8912019-10-31 13:34:27 +0800889 }
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000890
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800891 /** @see android.app.Activity#reportFullyDrawn */
892 TransitionInfoSnapshot logAppTransitionReportedDrawn(ActivityRecord r,
Vishnu Nair132ee832018-09-28 15:00:05 -0700893 boolean restoredFromBundle) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800894 final TransitionInfo info = mLastTransitionInfo.get(r);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200895 if (info == null) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700896 return null;
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200897 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800898 if (!info.allDrawn() && info.mPendingFullyDrawn == null) {
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800899 // There are still undrawn activities, postpone reporting fully drawn until all of its
900 // windows are drawn. So that is closer to an usable state.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800901 info.mPendingFullyDrawn = () -> {
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800902 logAppTransitionReportedDrawn(r, restoredFromBundle);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800903 info.mPendingFullyDrawn = null;
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800904 };
905 return null;
906 }
Chris Wailes35c193c2018-10-09 18:12:00 -0700907
908 // Record the handling of the reportFullyDrawn callback in the trace system. This is not
909 // actually used to trace this function, but instead the logical task that this function
910 // fullfils (handling reportFullyDrawn() callbacks).
911 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800912 "ActivityManager:ReportingFullyDrawn " + info.mLastLaunchedActivity.packageName);
Chris Wailes35c193c2018-10-09 18:12:00 -0700913
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200914 final LogMaker builder = new LogMaker(APP_TRANSITION_REPORTED_DRAWN);
915 builder.setPackageName(r.packageName);
916 builder.addTaggedData(FIELD_CLASS_NAME, r.info.name);
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800917 final long currentTimestampNs = SystemClock.elapsedRealtimeNanos();
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800918 final long startupTimeMs = info.mPendingFullyDrawn != null
919 ? info.mWindowsDrawnDelayMs
920 : TimeUnit.NANOSECONDS.toMillis(currentTimestampNs - info.mTransitionStartTimeNs);
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000921 builder.addTaggedData(APP_TRANSITION_REPORTED_DRAWN_MS, startupTimeMs);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200922 builder.setType(restoredFromBundle
923 ? TYPE_TRANSITION_REPORTED_DRAWN_WITH_BUNDLE
924 : TYPE_TRANSITION_REPORTED_DRAWN_NO_BUNDLE);
925 builder.addTaggedData(APP_TRANSITION_PROCESS_RUNNING,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800926 info.mProcessRunning ? 1 : 0);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200927 mMetricsLogger.write(builder);
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000928 StatsLog.write(
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800929 StatsLog.APP_START_FULLY_DRAWN,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800930 info.mLastLaunchedActivity.info.applicationInfo.uid,
931 info.mLastLaunchedActivity.packageName,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000932 restoredFromBundle
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800933 ? StatsLog.APP_START_FULLY_DRAWN__TYPE__WITH_BUNDLE
934 : StatsLog.APP_START_FULLY_DRAWN__TYPE__WITHOUT_BUNDLE,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800935 info.mLastLaunchedActivity.info.name,
936 info.mProcessRunning,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000937 startupTimeMs);
Chris Wailes35c193c2018-10-09 18:12:00 -0700938
939 // Ends the trace started at the beginning of this function. This is located here to allow
940 // the trace slice to have a noticable duration.
941 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
942
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800943 final TransitionInfoSnapshot infoSnapshot =
944 new TransitionInfoSnapshot(info, r, (int) startupTimeMs);
Vishnu Nair132ee832018-09-28 15:00:05 -0700945 BackgroundThread.getHandler().post(() -> logAppFullyDrawn(infoSnapshot));
Yan Wang9eac5ec2019-09-30 15:42:18 -0700946
947 // Notify reportFullyDrawn event.
948 launchObserverNotifyReportFullyDrawn(r, currentTimestampNs);
949
Vishnu Nair132ee832018-09-28 15:00:05 -0700950 return infoSnapshot;
951 }
952
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800953 private void logAppFullyDrawn(TransitionInfoSnapshot info) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700954 if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
955 return;
956 }
957
958 StringBuilder sb = mStringBuilder;
959 sb.setLength(0);
960 sb.append("Fully drawn ");
961 sb.append(info.launchedActivityShortComponentName);
962 sb.append(": ");
963 TimeUtils.formatDuration(info.windowsFullyDrawnDelayMs, sb);
964 Log.i(TAG, sb.toString());
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200965 }
966
Michal Karpinski4fd5b842019-01-28 15:13:32 +0000967 void logAbortedBgActivityStart(Intent intent, WindowProcessController callerApp,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100968 int callingUid, String callingPackage, int callingUidProcState,
969 boolean callingUidHasAnyVisibleWindow,
970 int realCallingUid, int realCallingUidProcState,
971 boolean realCallingUidHasAnyVisibleWindow,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100972 boolean comingFromPendingIntent) {
973
974 final long nowElapsed = SystemClock.elapsedRealtime();
975 final long nowUptime = SystemClock.uptimeMillis();
976 final LogMaker builder = new LogMaker(ACTION_ACTIVITY_START);
977 builder.setTimestamp(System.currentTimeMillis());
978 builder.addTaggedData(FIELD_CALLING_UID, callingUid);
979 builder.addTaggedData(FIELD_CALLING_PACKAGE_NAME, callingPackage);
980 builder.addTaggedData(FIELD_CALLING_UID_PROC_STATE,
981 processStateAmToProto(callingUidProcState));
982 builder.addTaggedData(FIELD_CALLING_UID_HAS_ANY_VISIBLE_WINDOW,
983 callingUidHasAnyVisibleWindow ? 1 : 0);
984 builder.addTaggedData(FIELD_REAL_CALLING_UID, realCallingUid);
985 builder.addTaggedData(FIELD_REAL_CALLING_UID_PROC_STATE,
986 processStateAmToProto(realCallingUidProcState));
987 builder.addTaggedData(FIELD_REAL_CALLING_UID_HAS_ANY_VISIBLE_WINDOW,
988 realCallingUidHasAnyVisibleWindow ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100989 builder.addTaggedData(FIELD_COMING_FROM_PENDING_INTENT, comingFromPendingIntent ? 1 : 0);
Michal Karpinski8596ded2018-11-14 14:43:48 +0000990 if (intent != null) {
991 builder.addTaggedData(FIELD_INTENT_ACTION, intent.getAction());
Michal Karpinski319069b2019-03-27 15:46:50 +0000992 ComponentName component = intent.getComponent();
993 if (component != null) {
994 builder.addTaggedData(FIELD_TARGET_SHORT_COMPONENT_NAME,
995 component.flattenToShortString());
996 }
Michal Karpinski8596ded2018-11-14 14:43:48 +0000997 }
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100998 if (callerApp != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700999 builder.addTaggedData(FIELD_PROCESS_RECORD_PROCESS_NAME, callerApp.mName);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001000 builder.addTaggedData(FIELD_PROCESS_RECORD_CUR_PROC_STATE,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001001 processStateAmToProto(callerApp.getCurrentProcState()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001002 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_CLIENT_ACTIVITIES,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001003 callerApp.hasClientActivities() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001004 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_FOREGROUND_SERVICES,
1005 callerApp.hasForegroundServices() ? 1 : 0);
1006 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_FOREGROUND_ACTIVITIES,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001007 callerApp.hasForegroundActivities() ? 1 : 0);
1008 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_TOP_UI, callerApp.hasTopUi() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001009 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_OVERLAY_UI,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001010 callerApp.hasOverlayUi() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001011 builder.addTaggedData(FIELD_PROCESS_RECORD_PENDING_UI_CLEAN,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001012 callerApp.hasPendingUiClean() ? 1 : 0);
1013 if (callerApp.getInteractionEventTime() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001014 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_LAST_INTERACTION_EVENT,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001015 (nowElapsed - callerApp.getInteractionEventTime()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001016 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001017 if (callerApp.getFgInteractionTime() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001018 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_FG_INTERACTION,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001019 (nowElapsed - callerApp.getFgInteractionTime()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001020 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001021 if (callerApp.getWhenUnimportant() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001022 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_UNIMPORTANT,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001023 (nowUptime - callerApp.getWhenUnimportant()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001024 }
1025 }
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001026 mMetricsLogger.write(builder);
1027 }
1028
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001029 private void logAppStartMemoryStateCapture(TransitionInfoSnapshot info) {
Ng Zhi An83473542018-02-20 09:02:14 -08001030 if (info.processRecord == null) {
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001031 if (DEBUG_METRICS) Slog.i(TAG, "logAppStartMemoryStateCapture processRecord null");
1032 return;
1033 }
1034
Wale Ogunwalef6733932018-06-27 05:14:34 -07001035 final int pid = info.processRecord.getPid();
Ng Zhi An83473542018-02-20 09:02:14 -08001036 final int uid = info.applicationInfo.uid;
Rajeev Kumarbfcd9202018-03-02 22:42:13 +00001037 final MemoryStat memoryStat = readMemoryStatFromFilesystem(uid, pid);
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001038 if (memoryStat == null) {
1039 if (DEBUG_METRICS) Slog.i(TAG, "logAppStartMemoryStateCapture memoryStat null");
1040 return;
1041 }
1042
1043 StatsLog.write(
1044 StatsLog.APP_START_MEMORY_STATE_CAPTURED,
1045 uid,
Ng Zhi An83473542018-02-20 09:02:14 -08001046 info.processName,
1047 info.launchedActivityName,
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001048 memoryStat.pgfault,
1049 memoryStat.pgmajfault,
1050 memoryStat.rssInBytes,
1051 memoryStat.cacheInBytes,
1052 memoryStat.swapInBytes);
1053 }
1054
Calin Juravle759fbda2018-02-20 19:52:30 +00001055 private ArtManagerInternal getArtManagerInternal() {
1056 if (mArtManagerInternal == null) {
1057 // Note that this may be null.
1058 // ArtManagerInternal is registered during PackageManagerService
1059 // initialization which happens after ActivityManagerService.
1060 mArtManagerInternal = LocalServices.getService(ArtManagerInternal.class);
1061 }
1062 return mArtManagerInternal;
1063 }
Vishnu Nair132ee832018-09-28 15:00:05 -07001064
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001065 /** Starts trace for an activity is actually launching. */
1066 private void startLaunchTrace(@NonNull TransitionInfo info) {
1067 if (DEBUG_METRICS) Slog.i(TAG, "startLaunchTrace " + info);
1068 if (!Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
Vishnu Nair132ee832018-09-28 15:00:05 -07001069 return;
1070 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001071 info.mLaunchTraceName = "launching: " + info.mLastLaunchedActivity.packageName;
1072 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName, 0);
Vishnu Nair132ee832018-09-28 15:00:05 -07001073 }
1074
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001075 /** Stops trace for the launch is completed or cancelled. */
1076 private void stopLaunchTrace(@NonNull TransitionInfo info) {
1077 if (DEBUG_METRICS) Slog.i(TAG, "stopLaunchTrace " + info);
1078 if (info.mLaunchTraceName == null) {
Vishnu Nair132ee832018-09-28 15:00:05 -07001079 return;
1080 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001081 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName, 0);
1082 info.mLaunchTraceName = null;
Vishnu Nair132ee832018-09-28 15:00:05 -07001083 }
Igor Murashkin212d06c2018-10-22 16:34:39 -07001084
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001085 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
1086 return mLaunchObserver;
1087 }
1088
Igor Murashkin212d06c2018-10-22 16:34:39 -07001089 /** Notify the {@link ActivityMetricsLaunchObserver} that a new launch sequence has begun. */
Yan Wangd47f90b2019-10-03 19:17:15 -07001090 private void launchObserverNotifyIntentStarted(Intent intent, long timestampNs) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001091 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1092 "MetricsLogger:launchObserverNotifyIntentStarted");
1093
1094 // Beginning a launch is timing sensitive and so should be observed as soon as possible.
Yan Wangd47f90b2019-10-03 19:17:15 -07001095 mLaunchObserver.onIntentStarted(intent, timestampNs);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001096
1097 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001098 }
1099
1100 /**
1101 * Notify the {@link ActivityMetricsLaunchObserver} that the previous launch sequence has
1102 * aborted due to intent failure (e.g. intent resolve failed or security error, etc) or
1103 * intent being delivered to the top running activity.
1104 */
1105 private void launchObserverNotifyIntentFailed() {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001106 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1107 "MetricsLogger:launchObserverNotifyIntentFailed");
1108
1109 mLaunchObserver.onIntentFailed();
1110
1111 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001112 }
1113
1114 /**
1115 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence's activity
1116 * has started.
1117 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001118 private void launchObserverNotifyActivityLaunched(TransitionInfo info) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001119 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1120 "MetricsLogger:launchObserverNotifyActivityLaunched");
1121
Igor Murashkin212d06c2018-10-22 16:34:39 -07001122 @ActivityMetricsLaunchObserver.Temperature int temperature =
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001123 convertTransitionTypeToLaunchObserverTemperature(info.mTransitionType);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001124
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001125 // Beginning a launch is timing sensitive and so should be observed as soon as possible.
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001126 mLaunchObserver.onActivityLaunched(convertActivityRecordToProto(info.mLastLaunchedActivity),
1127 temperature);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001128
1129 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001130 }
1131
1132 /**
Yan Wang9eac5ec2019-09-30 15:42:18 -07001133 * Notifies the {@link ActivityMetricsLaunchObserver} the reportFullDrawn event.
1134 */
Yan Wangd47f90b2019-10-03 19:17:15 -07001135 private void launchObserverNotifyReportFullyDrawn(ActivityRecord r, long timestampNs) {
Yan Wang9eac5ec2019-09-30 15:42:18 -07001136 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1137 "MetricsLogger:launchObserverNotifyReportFullyDrawn");
Yan Wangd47f90b2019-10-03 19:17:15 -07001138 mLaunchObserver.onReportFullyDrawn(convertActivityRecordToProto(r), timestampNs);
Yan Wang9eac5ec2019-09-30 15:42:18 -07001139 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1140 }
1141
1142 /**
Igor Murashkin212d06c2018-10-22 16:34:39 -07001143 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence is
1144 * cancelled.
1145 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001146 private void launchObserverNotifyActivityLaunchCancelled(TransitionInfo info) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001147 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1148 "MetricsLogger:launchObserverNotifyActivityLaunchCancelled");
Igor Murashkin212d06c2018-10-22 16:34:39 -07001149
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001150 final @ActivityMetricsLaunchObserver.ActivityRecordProto byte[] activityRecordProto =
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001151 info != null ? convertActivityRecordToProto(info.mLastLaunchedActivity) : null;
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001152
1153 mLaunchObserver.onActivityLaunchCancelled(activityRecordProto);
1154
1155 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001156 }
1157
1158 /**
1159 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence's activity
1160 * has fully finished (successfully).
1161 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001162 private void launchObserverNotifyActivityLaunchFinished(TransitionInfo info, long timestampNs) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001163 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1164 "MetricsLogger:launchObserverNotifyActivityLaunchFinished");
Igor Murashkin212d06c2018-10-22 16:34:39 -07001165
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001166 mLaunchObserver.onActivityLaunchFinished(
1167 convertActivityRecordToProto(info.mLastLaunchedActivity), timestampNs);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001168
1169 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1170 }
1171
1172 @VisibleForTesting
1173 static @ActivityMetricsLaunchObserver.ActivityRecordProto byte[]
1174 convertActivityRecordToProto(ActivityRecord record) {
1175 // May take non-negligible amount of time to convert ActivityRecord into a proto,
1176 // so track the time.
1177 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1178 "MetricsLogger:convertActivityRecordToProto");
1179
1180 // There does not appear to be a way to 'reset' a ProtoOutputBuffer stream,
1181 // so create a new one every time.
1182 final ProtoOutputStream protoOutputStream =
1183 new ProtoOutputStream(LAUNCH_OBSERVER_ACTIVITY_RECORD_PROTO_CHUNK_SIZE);
1184 // Write this data out as the top-most ActivityRecordProto (i.e. it is not a sub-object).
1185 record.writeToProto(protoOutputStream);
1186 final byte[] bytes = protoOutputStream.getBytes();
1187
1188 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1189
1190 return bytes;
Igor Murashkin212d06c2018-10-22 16:34:39 -07001191 }
1192
1193 private static @ActivityMetricsLaunchObserver.Temperature int
1194 convertTransitionTypeToLaunchObserverTemperature(int transitionType) {
1195 switch (transitionType) {
1196 case TYPE_TRANSITION_WARM_LAUNCH:
1197 return ActivityMetricsLaunchObserver.TEMPERATURE_WARM;
1198 case TYPE_TRANSITION_HOT_LAUNCH:
1199 return ActivityMetricsLaunchObserver.TEMPERATURE_HOT;
1200 case TYPE_TRANSITION_COLD_LAUNCH:
1201 return ActivityMetricsLaunchObserver.TEMPERATURE_COLD;
1202 default:
1203 return -1;
1204 }
1205 }
Filip Gruszczynski77d94482015-12-11 13:59:52 -08001206}