blob: 72665c84b970d057696cf98602f6990140fcebae [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;
Riddle Hsue8d3d192019-11-26 18:56:39 +0800193 /** whether the process of the launching activity didn't have any active activity. */
194 final boolean mProcessSwitch;
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800195 /** The activities that should be drawn. */
196 final LinkedList<ActivityRecord> mPendingDrawActivities = new LinkedList<>();
Igor Murashkin212d06c2018-10-22 16:34:39 -0700197 /** The latest activity to have been launched. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800198 @NonNull ActivityRecord mLastLaunchedActivity;
199
200 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyTransitionStarting}. */
201 int mCurrentTransitionDelayMs;
202 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyStartingWindowDrawn}. */
203 int mStartingWindowDelayMs = INVALID_DELAY;
204 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyBindApplication}. */
205 int mBindApplicationDelayMs = INVALID_DELAY;
Vishnu Nair132ee832018-09-28 15:00:05 -0700206 /** Elapsed time from when we launch an activity to when its windows are drawn. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800207 int mWindowsDrawnDelayMs;
208 /** The reason why the transition started (see ActivityManagerInternal.APP_TRANSITION_*). */
209 int mReason = APP_TRANSITION_TIMEOUT;
210 /** The flag ensures that {@link #mStartingWindowDelayMs} is only set once. */
211 boolean mLoggedStartingWindowDrawn;
212 /** If the any app transitions have been logged as starting. */
213 boolean mLoggedTransitionStarting;
214
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800215 /** Non-null if the application has reported drawn but its window hasn't. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800216 @Nullable Runnable mPendingFullyDrawn;
217 /** Non-null if the trace is active. */
218 @Nullable String mLaunchTraceName;
219
220 /** @return Non-null if there will be a window drawn event for the launch. */
221 @Nullable
222 static TransitionInfo create(@NonNull ActivityRecord r,
Riddle Hsue8d3d192019-11-26 18:56:39 +0800223 @NonNull LaunchingState launchingState, boolean processRunning,
224 boolean processSwitch, int startResult) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800225 int transitionType = INVALID_TRANSITION_TYPE;
226 if (processRunning) {
227 if (startResult == START_SUCCESS) {
228 transitionType = TYPE_TRANSITION_WARM_LAUNCH;
229 } else if (startResult == START_TASK_TO_FRONT) {
230 transitionType = TYPE_TRANSITION_HOT_LAUNCH;
231 }
232 } else if (startResult == START_SUCCESS || startResult == START_TASK_TO_FRONT) {
233 // Task may still exist when cold launching an activity and the start result will be
234 // set to START_TASK_TO_FRONT. Treat this as a COLD launch.
235 transitionType = TYPE_TRANSITION_COLD_LAUNCH;
236 }
237 if (transitionType == INVALID_TRANSITION_TYPE) {
238 // That means the startResult is neither START_SUCCESS nor START_TASK_TO_FRONT.
239 return null;
240 }
Riddle Hsue8d3d192019-11-26 18:56:39 +0800241 return new TransitionInfo(r, launchingState, transitionType, processRunning,
242 processSwitch);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800243 }
244
245 /** Use {@link TransitionInfo#create} instead to ensure the transition type is valid. */
246 private TransitionInfo(ActivityRecord r, LaunchingState launchingState, int transitionType,
Riddle Hsue8d3d192019-11-26 18:56:39 +0800247 boolean processRunning, boolean processSwitch) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800248 mLaunchingState = launchingState;
249 mTransitionStartTimeNs = launchingState.mCurrentTransitionStartTimeNs;
250 mTransitionType = transitionType;
251 mProcessRunning = processRunning;
Riddle Hsue8d3d192019-11-26 18:56:39 +0800252 mProcessSwitch = processSwitch;
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800253 mCurrentTransitionDeviceUptime =
254 (int) TimeUnit.MILLISECONDS.toSeconds(SystemClock.uptimeMillis());
255 setLatestLaunchedActivity(r);
256 launchingState.mAssociatedTransitionInfo = this;
257 }
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800258
259 /**
260 * Remembers the latest launched activity to represent the final transition. This also
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800261 * tracks the activities that should be drawn, so a consecutive launching sequence can be
262 * coalesced as one event.
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800263 */
264 void setLatestLaunchedActivity(ActivityRecord r) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800265 if (mLastLaunchedActivity == r) {
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800266 return;
267 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800268 mLastLaunchedActivity = r;
269 if (!r.noDisplay) {
270 if (DEBUG_METRICS) Slog.i(TAG, "Add pending draw " + r);
271 mPendingDrawActivities.add(r);
272 }
273 }
274
275 /** @return {@code true} if the activity matches a launched activity in this transition. */
276 boolean contains(ActivityRecord r) {
277 return r == mLastLaunchedActivity || mPendingDrawActivities.contains(r);
278 }
279
280 /** Called when the activity is drawn or won't be drawn. */
281 void removePendingDrawActivity(ActivityRecord r) {
282 if (DEBUG_METRICS) Slog.i(TAG, "Remove pending draw " + r);
283 mPendingDrawActivities.remove(r);
284 }
285
286 boolean allDrawn() {
287 return mPendingDrawActivities.isEmpty();
288 }
289
Riddle Hsue8d3d192019-11-26 18:56:39 +0800290 /**
291 * @return {@code true} if the transition info should be sent to MetricsLogger, StatsLog, or
292 * LaunchObserver.
293 */
294 boolean isInterestingToLoggerAndObserver() {
295 return mProcessSwitch;
296 }
297
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800298 int calculateCurrentDelay() {
299 return calculateDelay(SystemClock.elapsedRealtimeNanos());
300 }
301
302 int calculateDelay(long timestampNs) {
303 // Shouldn't take more than 25 days to launch an app, so int is fine here.
304 return (int) TimeUnit.NANOSECONDS.toMillis(timestampNs - mTransitionStartTimeNs);
305 }
306
307 @Override
308 public String toString() {
309 return "TransitionInfo{" + Integer.toHexString(System.identityHashCode(this))
310 + " a=" + mLastLaunchedActivity + " ua=" + mPendingDrawActivities + "}";
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800311 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800312 }
313
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800314 static final class TransitionInfoSnapshot {
Calin Juravle759fbda2018-02-20 19:52:30 +0000315 final private ApplicationInfo applicationInfo;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700316 final private WindowProcessController processRecord;
Vishnu Nair132ee832018-09-28 15:00:05 -0700317 final String packageName;
318 final String launchedActivityName;
Calin Juravle759fbda2018-02-20 19:52:30 +0000319 final private String launchedActivityLaunchedFromPackage;
320 final private String launchedActivityLaunchToken;
321 final private String launchedActivityAppRecordRequiredAbi;
Vishnu Nair132ee832018-09-28 15:00:05 -0700322 final String launchedActivityShortComponentName;
Ng Zhi An83473542018-02-20 09:02:14 -0800323 final private String processName;
Calin Juravle759fbda2018-02-20 19:52:30 +0000324 final private int reason;
325 final private int startingWindowDelayMs;
326 final private int bindApplicationDelayMs;
Vishnu Nair132ee832018-09-28 15:00:05 -0700327 final int windowsDrawnDelayMs;
328 final int type;
329 final int userId;
330 /**
331 * Elapsed time from when we launch an activity to when the app reported it was
332 * fully drawn. If this is not reported then the value is set to INVALID_DELAY.
333 */
334 final int windowsFullyDrawnDelayMs;
335 final int activityRecordIdHashCode;
Calin Juravle759fbda2018-02-20 19:52:30 +0000336
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800337 private TransitionInfoSnapshot(TransitionInfo info) {
338 this(info, info.mLastLaunchedActivity, INVALID_DELAY);
Vishnu Nair132ee832018-09-28 15:00:05 -0700339 }
340
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800341 private TransitionInfoSnapshot(TransitionInfo info, ActivityRecord launchedActivity,
342 int windowsFullyDrawnDelayMs) {
Andrii Kulianeceebbf2019-06-26 17:36:51 -0700343 applicationInfo = launchedActivity.info.applicationInfo;
Vishnu Nair132ee832018-09-28 15:00:05 -0700344 packageName = launchedActivity.packageName;
345 launchedActivityName = launchedActivity.info.name;
346 launchedActivityLaunchedFromPackage = launchedActivity.launchedFromPackage;
347 launchedActivityLaunchToken = launchedActivity.info.launchToken;
348 launchedActivityAppRecordRequiredAbi = launchedActivity.app == null
Calin Juravle759fbda2018-02-20 19:52:30 +0000349 ? null
Vishnu Nairaf0ea312018-10-15 16:23:55 -0700350 : launchedActivity.app.getRequiredAbi();
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800351 reason = info.mReason;
352 startingWindowDelayMs = info.mStartingWindowDelayMs;
353 bindApplicationDelayMs = info.mBindApplicationDelayMs;
354 windowsDrawnDelayMs = info.mWindowsDrawnDelayMs;
355 type = info.mTransitionType;
356 processRecord = launchedActivity.app;
Vishnu Nairaf0ea312018-10-15 16:23:55 -0700357 processName = launchedActivity.processName;
Wale Ogunwale8b19de92018-11-29 19:58:26 -0800358 userId = launchedActivity.mUserId;
Vishnu Nair132ee832018-09-28 15:00:05 -0700359 launchedActivityShortComponentName = launchedActivity.shortComponentName;
360 activityRecordIdHashCode = System.identityHashCode(launchedActivity);
361 this.windowsFullyDrawnDelayMs = windowsFullyDrawnDelayMs;
Calin Juravle759fbda2018-02-20 19:52:30 +0000362 }
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -0800363
364 @WaitResult.LaunchState int getLaunchState() {
365 switch (type) {
366 case TYPE_TRANSITION_WARM_LAUNCH:
367 return LAUNCH_STATE_WARM;
368 case TYPE_TRANSITION_HOT_LAUNCH:
369 return LAUNCH_STATE_HOT;
370 case TYPE_TRANSITION_COLD_LAUNCH:
371 return LAUNCH_STATE_COLD;
372 default:
373 return -1;
374 }
375 }
Calin Juravle759fbda2018-02-20 19:52:30 +0000376 }
377
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800378 ActivityMetricsLogger(ActivityStackSupervisor supervisor, Looper looper) {
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800379 mLastLogTimeSecs = SystemClock.elapsedRealtime() / 1000;
380 mSupervisor = supervisor;
Igor Murashkinc0b47e42018-11-07 15:54:18 -0800381 mLaunchObserver = new LaunchObserverRegistryImpl(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800382 }
383
384 void logWindowState() {
385 final long now = SystemClock.elapsedRealtime() / 1000;
386 if (mWindowState != WINDOW_STATE_INVALID) {
387 // We log even if the window state hasn't changed, because the user might remain in
388 // home/fullscreen move forever and we would like to track this kind of behavior
389 // too.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800390 mMetricsLogger.count(TRON_WINDOW_STATE_VARZ_STRINGS[mWindowState],
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800391 (int) (now - mLastLogTimeSecs));
392 }
393 mLastLogTimeSecs = now;
394
Wale Ogunwale926aade2017-08-29 11:24:37 -0700395 mWindowState = WINDOW_STATE_INVALID;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800396 ActivityStack stack =
397 mSupervisor.mRootActivityContainer.getTopDisplayFocusedStack();
lumarkf6c4a982018-06-15 15:43:12 +0800398 if (stack == null) {
399 return;
400 }
401
Wale Ogunwale926aade2017-08-29 11:24:37 -0700402 if (stack.isActivityTypeAssistant()) {
403 mWindowState = WINDOW_STATE_ASSISTANT;
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -0800404 return;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800405 }
Wale Ogunwale926aade2017-08-29 11:24:37 -0700406
Igor Murashkin212d06c2018-10-22 16:34:39 -0700407 @WindowingMode int windowingMode = stack.getWindowingMode();
Wale Ogunwale3382ab12017-07-27 08:55:03 -0700408 if (windowingMode == WINDOWING_MODE_PINNED) {
Wale Ogunwaled32da472018-11-16 07:19:28 -0800409 stack = mSupervisor.mRootActivityContainer.findStackBehind(stack);
Wale Ogunwale3382ab12017-07-27 08:55:03 -0700410 windowingMode = stack.getWindowingMode();
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -0800411 }
Wale Ogunwale926aade2017-08-29 11:24:37 -0700412 switch (windowingMode) {
413 case WINDOWING_MODE_FULLSCREEN:
414 mWindowState = WINDOW_STATE_STANDARD;
415 break;
416 case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
417 case WINDOWING_MODE_SPLIT_SCREEN_SECONDARY:
418 mWindowState = WINDOW_STATE_SIDE_BY_SIDE;
419 break;
Bryce Lee6c605092017-10-12 11:14:49 -0700420 case WINDOWING_MODE_FREEFORM:
Wale Ogunwale926aade2017-08-29 11:24:37 -0700421 mWindowState = WINDOW_STATE_FREEFORM;
422 break;
423 default:
424 if (windowingMode != WINDOWING_MODE_UNDEFINED) {
425 throw new IllegalStateException("Unknown windowing mode for stack=" + stack
426 + " windowingMode=" + windowingMode);
427 }
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800428 }
429 }
Jorim Jaggi275561a2016-02-23 10:11:02 -0500430
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800431 /** @return Non-null {@link TransitionInfo} if the activity is found in an active transition. */
432 @Nullable
433 private TransitionInfo getActiveTransitionInfo(ActivityRecord r) {
434 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
435 final TransitionInfo info = mTransitionInfoList.get(i);
436 if (info.contains(r)) {
437 return info;
438 }
439 }
440 return null;
441 }
442
443 /**
444 * This method should be only used by starting recents and starting from recents, or internal
445 * tests. Because it doesn't lookup caller and always creates a new launching state.
446 *
447 * @see #notifyActivityLaunching(Intent, ActivityRecord, int)
448 */
449 LaunchingState notifyActivityLaunching(Intent intent) {
450 return notifyActivityLaunching(intent, null /* caller */, IGNORE_CALLER);
451 }
452
453 /**
454 * If the caller is found in an active transition, it will be considered as consecutive launch
455 * and coalesced into the active transition.
456 *
457 * @see #notifyActivityLaunching(Intent, ActivityRecord, int)
458 */
459 LaunchingState notifyActivityLaunching(Intent intent, @Nullable ActivityRecord caller) {
460 return notifyActivityLaunching(intent, caller, Binder.getCallingUid());
461 }
462
Jorim Jaggi275561a2016-02-23 10:11:02 -0500463 /**
464 * Notifies the tracker at the earliest possible point when we are starting to launch an
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800465 * activity. The caller must ensure that {@link #notifyActivityLaunched} will be called later
466 * with the returned {@link LaunchingState}.
Jorim Jaggi275561a2016-02-23 10:11:02 -0500467 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800468 private LaunchingState notifyActivityLaunching(Intent intent, @Nullable ActivityRecord caller,
469 int callingUid) {
470 final long transitionStartTimeNs = SystemClock.elapsedRealtimeNanos();
471 TransitionInfo existingInfo = null;
472 if (callingUid != IGNORE_CALLER) {
473 // Associate the launching event to an active transition if the caller is found in its
474 // launched activities.
475 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
476 final TransitionInfo info = mTransitionInfoList.get(i);
477 if (caller != null && info.contains(caller)) {
478 existingInfo = info;
479 break;
480 }
481 if (existingInfo == null && callingUid == info.mLastLaunchedActivity.getUid()) {
482 // Fallback to check the most recent matched uid for the case that the caller is
483 // not an activity.
484 existingInfo = info;
485 }
486 }
487 }
Igor Murashkin212d06c2018-10-22 16:34:39 -0700488 if (DEBUG_METRICS) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800489 Slog.i(TAG, "notifyActivityLaunching intent=" + intent
490 + " existingInfo=" + existingInfo);
Igor Murashkin212d06c2018-10-22 16:34:39 -0700491 }
492
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800493 if (existingInfo == null) {
494 // Only notify the observer for a new launching event.
495 launchObserverNotifyIntentStarted(intent, transitionStartTimeNs);
496 final LaunchingState launchingState = new LaunchingState();
497 launchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs;
498 return launchingState;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800499 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800500 existingInfo.mLaunchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs;
501 return existingInfo.mLaunchingState;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500502 }
503
504 /**
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700505 * Notifies the tracker that the activity is actually launching.
506 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800507 * @param launchingState The launching state to track the new or active transition.
508 * @param resultCode One of the {@link android.app.ActivityManager}.START_* flags, indicating
509 * the result of the launch.
510 * @param launchedActivity The activity that is being launched
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700511 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800512 void notifyActivityLaunched(@NonNull LaunchingState launchingState, int resultCode,
513 @Nullable ActivityRecord launchedActivity) {
514 if (launchedActivity == null) {
515 // The launch is aborted, e.g. intent not resolved, class not found.
516 abort(null /* info */, "nothing launched");
517 return;
518 }
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700519
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800520 final WindowProcessController processRecord = launchedActivity.app != null
521 ? launchedActivity.app
522 : mSupervisor.mService.getProcessController(
523 launchedActivity.processName, launchedActivity.info.applicationInfo.uid);
524 // Whether the process that will contains the activity is already running.
525 final boolean processRunning = processRecord != null;
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700526 // We consider this a "process switch" if the process of the activity that gets launched
527 // didn't have an activity that was in started state. In this case, we assume that lot
528 // of caches might be purged so the time until it produces the first frame is very
529 // interesting.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800530 final boolean processSwitch = !processRunning
Wale Ogunwalef6733932018-06-27 05:14:34 -0700531 || !processRecord.hasStartedActivity(launchedActivity);
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700532
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800533 final TransitionInfo info = launchingState.mAssociatedTransitionInfo;
534 if (DEBUG_METRICS) {
535 Slog.i(TAG, "notifyActivityLaunched" + " resultCode=" + resultCode
536 + " launchedActivity=" + launchedActivity + " processRunning=" + processRunning
537 + " processSwitch=" + processSwitch + " info=" + info);
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200538 }
539
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800540 if (launchedActivity.mDrawn) {
Vishnu Nairf8accc52018-10-11 10:19:54 -0700541 // Launched activity is already visible. We cannot measure windows drawn delay.
Riddle Hsu1063b512019-10-22 21:12:23 +0800542 abort(info, "launched activity already visible");
Vishnu Nairf8accc52018-10-11 10:19:54 -0700543 return;
544 }
545
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800546 if (info != null) {
Vishnu Nairf8accc52018-10-11 10:19:54 -0700547 // If we are already in an existing transition, only update the activity name, but not
548 // the other attributes.
Igor Murashkin212d06c2018-10-22 16:34:39 -0700549
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800550 if (DEBUG_METRICS) Slog.i(TAG, "notifyActivityLaunched update launched activity");
Igor Murashkin212d06c2018-10-22 16:34:39 -0700551 // Coalesce multiple (trampoline) activities from a single sequence together.
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800552 info.setLatestLaunchedActivity(launchedActivity);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500553 return;
554 }
555
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800556 final TransitionInfo newInfo = TransitionInfo.create(launchedActivity, launchingState,
Riddle Hsue8d3d192019-11-26 18:56:39 +0800557 processRunning, processSwitch, resultCode);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800558 if (newInfo == null) {
559 abort(info, "unrecognized launch");
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800560 return;
561 }
562
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200563 if (DEBUG_METRICS) Slog.i(TAG, "notifyActivityLaunched successful");
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800564 // A new launch sequence has begun. Start tracking it.
565 mTransitionInfoList.add(newInfo);
566 mLastTransitionInfo.put(launchedActivity, newInfo);
567 startLaunchTrace(newInfo);
Riddle Hsue8d3d192019-11-26 18:56:39 +0800568 if (newInfo.isInterestingToLoggerAndObserver()) {
569 launchObserverNotifyActivityLaunched(newInfo);
570 } else {
571 // As abort for no process switch.
572 launchObserverNotifyIntentFailed();
573 }
Jorim Jaggi275561a2016-02-23 10:11:02 -0500574 }
575
576 /**
577 * Notifies the tracker that all windows of the app have been drawn.
578 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800579 @Nullable
580 TransitionInfoSnapshot notifyWindowsDrawn(@NonNull ActivityRecord r, long timestampNs) {
581 if (DEBUG_METRICS) Slog.i(TAG, "notifyWindowsDrawn " + r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200582
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800583 final TransitionInfo info = getActiveTransitionInfo(r);
584 if (info == null || info.allDrawn()) {
585 if (DEBUG_METRICS) Slog.i(TAG, "notifyWindowsDrawn no activity to be drawn");
Vishnu Nair132ee832018-09-28 15:00:05 -0700586 return null;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500587 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800588 // Always calculate the delay because the caller may need to know the individual drawn time.
589 info.mWindowsDrawnDelayMs = info.calculateDelay(timestampNs);
590 info.removePendingDrawActivity(r);
591 final TransitionInfoSnapshot infoSnapshot = new TransitionInfoSnapshot(info);
592 if (info.mLoggedTransitionStarting && info.allDrawn()) {
593 done(false /* abort */, info, "notifyWindowsDrawn - all windows drawn", timestampNs);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500594 }
Vishnu Nair132ee832018-09-28 15:00:05 -0700595 return infoSnapshot;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500596 }
597
598 /**
599 * Notifies the tracker that the starting window was drawn.
600 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800601 void notifyStartingWindowDrawn(@NonNull ActivityRecord r) {
602 final TransitionInfo info = getActiveTransitionInfo(r);
603 if (info == null || info.mLoggedStartingWindowDrawn) {
Jorim Jaggi275561a2016-02-23 10:11:02 -0500604 return;
605 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800606 if (DEBUG_METRICS) Slog.i(TAG, "notifyStartingWindowDrawn " + r);
607 info.mLoggedStartingWindowDrawn = true;
608 info.mStartingWindowDelayMs = info.calculateDelay(SystemClock.elapsedRealtimeNanos());
Jorim Jaggi275561a2016-02-23 10:11:02 -0500609 }
610
611 /**
612 * Notifies the tracker that the app transition is starting.
613 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800614 * @param activityToReason A map from activity to a reason integer, which must be on of
615 * ActivityTaskManagerInternal.APP_TRANSITION_* reasons.
Jorim Jaggi275561a2016-02-23 10:11:02 -0500616 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800617 void notifyTransitionStarting(ArrayMap<ActivityRecord, Integer> activityToReason) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200618 if (DEBUG_METRICS) Slog.i(TAG, "notifyTransitionStarting");
Igor Murashkin212d06c2018-10-22 16:34:39 -0700619
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800620 final long timestampNs = SystemClock.elapsedRealtimeNanos();
621 for (int index = activityToReason.size() - 1; index >= 0; index--) {
622 final ActivityRecord r = activityToReason.keyAt(index);
623 final TransitionInfo info = getActiveTransitionInfo(r);
624 if (info == null || info.mLoggedTransitionStarting) {
625 // Ignore any subsequent notifyTransitionStarting.
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800626 continue;
627 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800628 if (DEBUG_METRICS) {
629 Slog.i(TAG, "notifyTransitionStarting activity=" + r + " info=" + info);
630 }
631
632 info.mCurrentTransitionDelayMs = info.calculateDelay(timestampNs);
633 info.mReason = activityToReason.valueAt(index);
634 info.mLoggedTransitionStarting = true;
635 if (info.allDrawn()) {
636 done(false /* abort */, info, "notifyTransitionStarting - all windows drawn",
637 timestampNs);
638 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800639 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800640 }
641
642 /** Makes sure that the reference to the removed activity is cleared. */
643 void notifyActivityRemoved(@NonNull ActivityRecord r) {
644 mLastTransitionInfo.remove(r);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500645 }
646
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200647 /**
648 * Notifies the tracker that the visibility of an app is changing.
649 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800650 * @param r the app that is changing its visibility
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200651 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800652 void notifyVisibilityChanged(@NonNull ActivityRecord r) {
653 final TransitionInfo info = getActiveTransitionInfo(r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200654 if (info == null) {
655 return;
656 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800657 if (DEBUG_METRICS) {
658 Slog.i(TAG, "notifyVisibilityChanged " + r + " visible=" + r.mVisibleRequested
659 + " state=" + r.getState() + " finishing=" + r.finishing);
660 }
661 if (!r.mVisibleRequested || r.finishing) {
662 info.removePendingDrawActivity(r);
663 }
664 if (info.mLastLaunchedActivity != r) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200665 return;
666 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800667 // The activity and its task are passed separately because the activity may be removed from
668 // the task later.
669 r.mAtmService.mH.sendMessage(PooledLambda.obtainMessage(
670 ActivityMetricsLogger::checkVisibility, this, r.getTask(), r));
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200671 }
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200672
Riddle Hsu1063b512019-10-22 21:12:23 +0800673 /** @return {@code true} if the given task has an activity will be drawn. */
Louis Changcdec0802019-11-11 11:45:07 +0800674 private static boolean hasActivityToBeDrawn(Task t) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800675 return t.forAllActivities((r) -> r.mVisibleRequested && !r.mDrawn && !r.finishing);
Vishnu Nairb1de42d2019-01-28 09:49:51 -0800676 }
677
Louis Changcdec0802019-11-11 11:45:07 +0800678 private void checkVisibility(Task t, ActivityRecord r) {
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700679 synchronized (mSupervisor.mService.mGlobalLock) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200680
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800681 final TransitionInfo info = getActiveTransitionInfo(r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200682
683 // If we have an active transition that's waiting on a certain activity that will be
684 // invisible now, we'll never get onWindowsDrawn, so abort the transition if necessary.
Vishnu Naird15063b2019-06-11 08:08:25 -0700685
686 // We have no active transitions.
687 if (info == null) {
688 return;
689 }
690
691 // The notified activity whose visibility changed is no longer the launched activity.
692 // We can still wait to get onWindowsDrawn.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800693 if (info.mLastLaunchedActivity != r) {
Vishnu Naird15063b2019-06-11 08:08:25 -0700694 return;
695 }
696
Riddle Hsu1063b512019-10-22 21:12:23 +0800697 // If the task of the launched activity contains any activity to be drawn, then the
698 // window drawn event should report later to complete the transition. Otherwise all
699 // activities in this task may be finished, invisible or drawn, so the transition event
700 // should be cancelled.
701 if (hasActivityToBeDrawn(t)) {
Vishnu Naird15063b2019-06-11 08:08:25 -0700702 return;
703 }
704
705 if (DEBUG_METRICS) Slog.i(TAG, "notifyVisibilityChanged to invisible activity=" + r);
706 logAppTransitionCancel(info);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800707 abort(info, "notifyVisibilityChanged to invisible");
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200708 }
709 }
710
Jorim Jaggi515dd682017-05-05 15:05:07 +0200711 /**
712 * Notifies the tracker that we called immediately before we call bindApplication on the client.
713 *
Wale Ogunwale31913b52018-10-13 08:29:31 -0700714 * @param appInfo The client into which we'll call bindApplication.
Jorim Jaggi515dd682017-05-05 15:05:07 +0200715 */
Wale Ogunwale31913b52018-10-13 08:29:31 -0700716 void notifyBindApplication(ApplicationInfo appInfo) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800717 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
718 final TransitionInfo info = mTransitionInfoList.get(i);
Jorim Jaggi515dd682017-05-05 15:05:07 +0200719
720 // App isn't attached to record yet, so match with info.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800721 if (info.mLastLaunchedActivity.info.applicationInfo == appInfo) {
722 info.mBindApplicationDelayMs = info.calculateCurrentDelay();
Jorim Jaggi515dd682017-05-05 15:05:07 +0200723 }
724 }
725 }
726
Riddle Hsu1063b512019-10-22 21:12:23 +0800727 /** Aborts tracking of current launch metrics. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800728 private void abort(TransitionInfo info, String cause) {
729 done(true /* abort */, info, cause, 0L /* timestampNs */);
Riddle Hsu1063b512019-10-22 21:12:23 +0800730 }
731
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800732 /** Called when the given transition (info) is no longer active. */
733 private void done(boolean abort, @Nullable TransitionInfo info, String cause,
Riddle Hsu1063b512019-10-22 21:12:23 +0800734 long timestampNs) {
Yan Wangd47f90b2019-10-03 19:17:15 -0700735 if (DEBUG_METRICS) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800736 Slog.i(TAG, "done abort=" + abort + " cause=" + cause + " timestamp=" + timestampNs
737 + " info=" + info);
Yan Wangd47f90b2019-10-03 19:17:15 -0700738 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800739 if (info == null) {
Igor Murashkin212d06c2018-10-22 16:34:39 -0700740 launchObserverNotifyIntentFailed();
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200741 return;
742 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800743
744 stopLaunchTrace(info);
745 if (abort) {
746 launchObserverNotifyActivityLaunchCancelled(info);
747 } else {
748 logAppTransitionFinished(info);
Riddle Hsue8d3d192019-11-26 18:56:39 +0800749 if (info.isInterestingToLoggerAndObserver()) {
750 launchObserverNotifyActivityLaunchFinished(info, timestampNs);
751 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800752 }
753 info.mPendingDrawActivities.clear();
754 mTransitionInfoList.remove(info);
755 }
756
757 private void logAppTransitionCancel(TransitionInfo info) {
758 final int type = info.mTransitionType;
759 final ActivityRecord activity = info.mLastLaunchedActivity;
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200760 final LogMaker builder = new LogMaker(APP_TRANSITION_CANCELLED);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800761 builder.setPackageName(activity.packageName);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200762 builder.setType(type);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800763 builder.addTaggedData(FIELD_CLASS_NAME, activity.info.name);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200764 mMetricsLogger.write(builder);
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000765 StatsLog.write(
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800766 StatsLog.APP_START_CANCELED,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800767 activity.info.applicationInfo.uid,
768 activity.packageName,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000769 convertAppStartTransitionType(type),
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800770 activity.info.name);
Igor Murashkin212d06c2018-10-22 16:34:39 -0700771 if (DEBUG_METRICS) {
772 Slog.i(TAG, String.format("APP_START_CANCELED(%s, %s, %s, %s)",
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800773 activity.info.applicationInfo.uid,
774 activity.packageName,
Igor Murashkin212d06c2018-10-22 16:34:39 -0700775 convertAppStartTransitionType(type),
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800776 activity.info.name));
Igor Murashkin212d06c2018-10-22 16:34:39 -0700777 }
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200778 }
779
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800780 private void logAppTransitionFinished(@NonNull TransitionInfo info) {
781 if (DEBUG_METRICS) Slog.i(TAG, "logging finished transition " + info);
Calin Juravle759fbda2018-02-20 19:52:30 +0000782
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800783 // Take a snapshot of the transition info before sending it to the handler for logging.
784 // This will avoid any races with other operations that modify the ActivityRecord.
785 final TransitionInfoSnapshot infoSnapshot = new TransitionInfoSnapshot(info);
Riddle Hsue8d3d192019-11-26 18:56:39 +0800786 if (info.isInterestingToLoggerAndObserver()) {
787 BackgroundThread.getHandler().post(() -> logAppTransition(
788 info.mCurrentTransitionDeviceUptime, info.mCurrentTransitionDelayMs,
789 infoSnapshot));
790 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800791 BackgroundThread.getHandler().post(() -> logAppDisplayed(infoSnapshot));
792 if (info.mPendingFullyDrawn != null) {
793 info.mPendingFullyDrawn.run();
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800794 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800795
796 info.mLastLaunchedActivity.info.launchToken = null;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800797 }
798
Ng Zhi An83473542018-02-20 09:02:14 -0800799 // This gets called on a background thread without holding the activity manager lock.
Calin Juravle759fbda2018-02-20 19:52:30 +0000800 private void logAppTransition(int currentTransitionDeviceUptime, int currentTransitionDelayMs,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800801 TransitionInfoSnapshot info) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000802 final LogMaker builder = new LogMaker(APP_TRANSITION);
803 builder.setPackageName(info.packageName);
804 builder.setType(info.type);
805 builder.addTaggedData(FIELD_CLASS_NAME, info.launchedActivityName);
806 final boolean isInstantApp = info.applicationInfo.isInstantApp();
807 if (info.launchedActivityLaunchedFromPackage != null) {
808 builder.addTaggedData(APP_TRANSITION_CALLING_PACKAGE_NAME,
809 info.launchedActivityLaunchedFromPackage);
810 }
811 String launchToken = info.launchedActivityLaunchToken;
812 if (launchToken != null) {
813 builder.addTaggedData(FIELD_INSTANT_APP_LAUNCH_TOKEN, launchToken);
814 }
815 builder.addTaggedData(APP_TRANSITION_IS_EPHEMERAL, isInstantApp ? 1 : 0);
816 builder.addTaggedData(APP_TRANSITION_DEVICE_UPTIME_SECONDS,
817 currentTransitionDeviceUptime);
818 builder.addTaggedData(APP_TRANSITION_DELAY_MS, currentTransitionDelayMs);
819 builder.setSubtype(info.reason);
Vishnu Nair132ee832018-09-28 15:00:05 -0700820 if (info.startingWindowDelayMs != INVALID_DELAY) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000821 builder.addTaggedData(APP_TRANSITION_STARTING_WINDOW_DELAY_MS,
822 info.startingWindowDelayMs);
823 }
Vishnu Nair132ee832018-09-28 15:00:05 -0700824 if (info.bindApplicationDelayMs != INVALID_DELAY) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000825 builder.addTaggedData(APP_TRANSITION_BIND_APPLICATION_DELAY_MS,
826 info.bindApplicationDelayMs);
827 }
828 builder.addTaggedData(APP_TRANSITION_WINDOWS_DRAWN_DELAY_MS, info.windowsDrawnDelayMs);
829 final ArtManagerInternal artManagerInternal = getArtManagerInternal();
830 final PackageOptimizationInfo packageOptimizationInfo =
831 (artManagerInternal == null) || (info.launchedActivityAppRecordRequiredAbi == null)
832 ? PackageOptimizationInfo.createWithNoInfo()
833 : artManagerInternal.getPackageOptimizationInfo(
834 info.applicationInfo,
835 info.launchedActivityAppRecordRequiredAbi);
836 builder.addTaggedData(PACKAGE_OPTIMIZATION_COMPILATION_REASON,
837 packageOptimizationInfo.getCompilationReason());
838 builder.addTaggedData(PACKAGE_OPTIMIZATION_COMPILATION_FILTER,
839 packageOptimizationInfo.getCompilationFilter());
840 mMetricsLogger.write(builder);
841 StatsLog.write(
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800842 StatsLog.APP_START_OCCURRED,
Calin Juravle759fbda2018-02-20 19:52:30 +0000843 info.applicationInfo.uid,
844 info.packageName,
845 convertAppStartTransitionType(info.type),
846 info.launchedActivityName,
847 info.launchedActivityLaunchedFromPackage,
848 isInstantApp,
849 currentTransitionDeviceUptime * 1000,
850 info.reason,
851 currentTransitionDelayMs,
852 info.startingWindowDelayMs,
853 info.bindApplicationDelayMs,
854 info.windowsDrawnDelayMs,
855 launchToken,
856 packageOptimizationInfo.getCompilationReason(),
857 packageOptimizationInfo.getCompilationFilter());
Igor Murashkin212d06c2018-10-22 16:34:39 -0700858
859 if (DEBUG_METRICS) {
860 Slog.i(TAG, String.format("APP_START_OCCURRED(%s, %s, %s, %s, %s)",
861 info.applicationInfo.uid,
862 info.packageName,
863 convertAppStartTransitionType(info.type),
864 info.launchedActivityName,
865 info.launchedActivityLaunchedFromPackage));
866 }
867
868
Ng Zhi An83473542018-02-20 09:02:14 -0800869 logAppStartMemoryStateCapture(info);
Calin Juravle759fbda2018-02-20 19:52:30 +0000870 }
871
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800872 private void logAppDisplayed(TransitionInfoSnapshot info) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700873 if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
874 return;
875 }
876
Jeff Changd136e772019-11-05 20:33:52 +0800877 EventLog.writeEvent(WM_ACTIVITY_LAUNCH_TIME,
Vishnu Nair132ee832018-09-28 15:00:05 -0700878 info.userId, info.activityRecordIdHashCode, info.launchedActivityShortComponentName,
879 info.windowsDrawnDelayMs);
880
881 StringBuilder sb = mStringBuilder;
882 sb.setLength(0);
883 sb.append("Displayed ");
884 sb.append(info.launchedActivityShortComponentName);
885 sb.append(": ");
886 TimeUtils.formatDuration(info.windowsDrawnDelayMs, sb);
887 Log.i(TAG, sb.toString());
888 }
889
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000890 private int convertAppStartTransitionType(int tronType) {
891 if (tronType == TYPE_TRANSITION_COLD_LAUNCH) {
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800892 return StatsLog.APP_START_OCCURRED__TYPE__COLD;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000893 }
894 if (tronType == TYPE_TRANSITION_WARM_LAUNCH) {
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800895 return StatsLog.APP_START_OCCURRED__TYPE__WARM;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000896 }
897 if (tronType == TYPE_TRANSITION_HOT_LAUNCH) {
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800898 return StatsLog.APP_START_OCCURRED__TYPE__HOT;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000899 }
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800900 return StatsLog.APP_START_OCCURRED__TYPE__UNKNOWN;
Riddle Hsuc48c8912019-10-31 13:34:27 +0800901 }
902
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800903 /** @return the last known window drawn delay of the given activity. */
904 int getLastDrawnDelayMs(ActivityRecord r) {
905 final TransitionInfo info = mLastTransitionInfo.get(r);
906 return info != null ? info.mWindowsDrawnDelayMs : INVALID_DELAY;
Riddle Hsuc48c8912019-10-31 13:34:27 +0800907 }
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000908
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800909 /** @see android.app.Activity#reportFullyDrawn */
910 TransitionInfoSnapshot logAppTransitionReportedDrawn(ActivityRecord r,
Vishnu Nair132ee832018-09-28 15:00:05 -0700911 boolean restoredFromBundle) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800912 final TransitionInfo info = mLastTransitionInfo.get(r);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200913 if (info == null) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700914 return null;
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200915 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800916 if (!info.allDrawn() && info.mPendingFullyDrawn == null) {
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800917 // There are still undrawn activities, postpone reporting fully drawn until all of its
918 // windows are drawn. So that is closer to an usable state.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800919 info.mPendingFullyDrawn = () -> {
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800920 logAppTransitionReportedDrawn(r, restoredFromBundle);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800921 info.mPendingFullyDrawn = null;
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800922 };
923 return null;
924 }
Chris Wailes35c193c2018-10-09 18:12:00 -0700925
Riddle Hsue8d3d192019-11-26 18:56:39 +0800926 final long currentTimestampNs = SystemClock.elapsedRealtimeNanos();
927 final long startupTimeMs = info.mPendingFullyDrawn != null
928 ? info.mWindowsDrawnDelayMs
929 : TimeUnit.NANOSECONDS.toMillis(currentTimestampNs - info.mTransitionStartTimeNs);
930 final TransitionInfoSnapshot infoSnapshot =
931 new TransitionInfoSnapshot(info, r, (int) startupTimeMs);
932 BackgroundThread.getHandler().post(() -> logAppFullyDrawn(infoSnapshot));
933
934 if (!info.isInterestingToLoggerAndObserver()) {
935 return infoSnapshot;
936 }
937
Chris Wailes35c193c2018-10-09 18:12:00 -0700938 // Record the handling of the reportFullyDrawn callback in the trace system. This is not
939 // actually used to trace this function, but instead the logical task that this function
940 // fullfils (handling reportFullyDrawn() callbacks).
941 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800942 "ActivityManager:ReportingFullyDrawn " + info.mLastLaunchedActivity.packageName);
Chris Wailes35c193c2018-10-09 18:12:00 -0700943
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200944 final LogMaker builder = new LogMaker(APP_TRANSITION_REPORTED_DRAWN);
945 builder.setPackageName(r.packageName);
946 builder.addTaggedData(FIELD_CLASS_NAME, r.info.name);
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000947 builder.addTaggedData(APP_TRANSITION_REPORTED_DRAWN_MS, startupTimeMs);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200948 builder.setType(restoredFromBundle
949 ? TYPE_TRANSITION_REPORTED_DRAWN_WITH_BUNDLE
950 : TYPE_TRANSITION_REPORTED_DRAWN_NO_BUNDLE);
951 builder.addTaggedData(APP_TRANSITION_PROCESS_RUNNING,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800952 info.mProcessRunning ? 1 : 0);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200953 mMetricsLogger.write(builder);
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000954 StatsLog.write(
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800955 StatsLog.APP_START_FULLY_DRAWN,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800956 info.mLastLaunchedActivity.info.applicationInfo.uid,
957 info.mLastLaunchedActivity.packageName,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000958 restoredFromBundle
Chenjie Yu5caaa9d2018-03-06 15:48:54 -0800959 ? StatsLog.APP_START_FULLY_DRAWN__TYPE__WITH_BUNDLE
960 : StatsLog.APP_START_FULLY_DRAWN__TYPE__WITHOUT_BUNDLE,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800961 info.mLastLaunchedActivity.info.name,
962 info.mProcessRunning,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000963 startupTimeMs);
Chris Wailes35c193c2018-10-09 18:12:00 -0700964
965 // Ends the trace started at the beginning of this function. This is located here to allow
966 // the trace slice to have a noticable duration.
967 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
968
Yan Wang9eac5ec2019-09-30 15:42:18 -0700969 // Notify reportFullyDrawn event.
970 launchObserverNotifyReportFullyDrawn(r, currentTimestampNs);
971
Vishnu Nair132ee832018-09-28 15:00:05 -0700972 return infoSnapshot;
973 }
974
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800975 private void logAppFullyDrawn(TransitionInfoSnapshot info) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700976 if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
977 return;
978 }
979
980 StringBuilder sb = mStringBuilder;
981 sb.setLength(0);
982 sb.append("Fully drawn ");
983 sb.append(info.launchedActivityShortComponentName);
984 sb.append(": ");
985 TimeUtils.formatDuration(info.windowsFullyDrawnDelayMs, sb);
986 Log.i(TAG, sb.toString());
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200987 }
988
Michal Karpinski4fd5b842019-01-28 15:13:32 +0000989 void logAbortedBgActivityStart(Intent intent, WindowProcessController callerApp,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100990 int callingUid, String callingPackage, int callingUidProcState,
991 boolean callingUidHasAnyVisibleWindow,
992 int realCallingUid, int realCallingUidProcState,
993 boolean realCallingUidHasAnyVisibleWindow,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100994 boolean comingFromPendingIntent) {
995
996 final long nowElapsed = SystemClock.elapsedRealtime();
997 final long nowUptime = SystemClock.uptimeMillis();
998 final LogMaker builder = new LogMaker(ACTION_ACTIVITY_START);
999 builder.setTimestamp(System.currentTimeMillis());
1000 builder.addTaggedData(FIELD_CALLING_UID, callingUid);
1001 builder.addTaggedData(FIELD_CALLING_PACKAGE_NAME, callingPackage);
1002 builder.addTaggedData(FIELD_CALLING_UID_PROC_STATE,
1003 processStateAmToProto(callingUidProcState));
1004 builder.addTaggedData(FIELD_CALLING_UID_HAS_ANY_VISIBLE_WINDOW,
1005 callingUidHasAnyVisibleWindow ? 1 : 0);
1006 builder.addTaggedData(FIELD_REAL_CALLING_UID, realCallingUid);
1007 builder.addTaggedData(FIELD_REAL_CALLING_UID_PROC_STATE,
1008 processStateAmToProto(realCallingUidProcState));
1009 builder.addTaggedData(FIELD_REAL_CALLING_UID_HAS_ANY_VISIBLE_WINDOW,
1010 realCallingUidHasAnyVisibleWindow ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001011 builder.addTaggedData(FIELD_COMING_FROM_PENDING_INTENT, comingFromPendingIntent ? 1 : 0);
Michal Karpinski8596ded2018-11-14 14:43:48 +00001012 if (intent != null) {
1013 builder.addTaggedData(FIELD_INTENT_ACTION, intent.getAction());
Michal Karpinski319069b2019-03-27 15:46:50 +00001014 ComponentName component = intent.getComponent();
1015 if (component != null) {
1016 builder.addTaggedData(FIELD_TARGET_SHORT_COMPONENT_NAME,
1017 component.flattenToShortString());
1018 }
Michal Karpinski8596ded2018-11-14 14:43:48 +00001019 }
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001020 if (callerApp != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001021 builder.addTaggedData(FIELD_PROCESS_RECORD_PROCESS_NAME, callerApp.mName);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001022 builder.addTaggedData(FIELD_PROCESS_RECORD_CUR_PROC_STATE,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001023 processStateAmToProto(callerApp.getCurrentProcState()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001024 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_CLIENT_ACTIVITIES,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001025 callerApp.hasClientActivities() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001026 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_FOREGROUND_SERVICES,
1027 callerApp.hasForegroundServices() ? 1 : 0);
1028 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_FOREGROUND_ACTIVITIES,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001029 callerApp.hasForegroundActivities() ? 1 : 0);
1030 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_TOP_UI, callerApp.hasTopUi() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001031 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_OVERLAY_UI,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001032 callerApp.hasOverlayUi() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001033 builder.addTaggedData(FIELD_PROCESS_RECORD_PENDING_UI_CLEAN,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001034 callerApp.hasPendingUiClean() ? 1 : 0);
1035 if (callerApp.getInteractionEventTime() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001036 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_LAST_INTERACTION_EVENT,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001037 (nowElapsed - callerApp.getInteractionEventTime()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001038 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001039 if (callerApp.getFgInteractionTime() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001040 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_FG_INTERACTION,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001041 (nowElapsed - callerApp.getFgInteractionTime()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001042 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001043 if (callerApp.getWhenUnimportant() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001044 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_UNIMPORTANT,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001045 (nowUptime - callerApp.getWhenUnimportant()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001046 }
1047 }
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001048 mMetricsLogger.write(builder);
1049 }
1050
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001051 private void logAppStartMemoryStateCapture(TransitionInfoSnapshot info) {
Ng Zhi An83473542018-02-20 09:02:14 -08001052 if (info.processRecord == null) {
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001053 if (DEBUG_METRICS) Slog.i(TAG, "logAppStartMemoryStateCapture processRecord null");
1054 return;
1055 }
1056
Wale Ogunwalef6733932018-06-27 05:14:34 -07001057 final int pid = info.processRecord.getPid();
Ng Zhi An83473542018-02-20 09:02:14 -08001058 final int uid = info.applicationInfo.uid;
Rajeev Kumarbfcd9202018-03-02 22:42:13 +00001059 final MemoryStat memoryStat = readMemoryStatFromFilesystem(uid, pid);
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001060 if (memoryStat == null) {
1061 if (DEBUG_METRICS) Slog.i(TAG, "logAppStartMemoryStateCapture memoryStat null");
1062 return;
1063 }
1064
1065 StatsLog.write(
1066 StatsLog.APP_START_MEMORY_STATE_CAPTURED,
1067 uid,
Ng Zhi An83473542018-02-20 09:02:14 -08001068 info.processName,
1069 info.launchedActivityName,
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001070 memoryStat.pgfault,
1071 memoryStat.pgmajfault,
1072 memoryStat.rssInBytes,
1073 memoryStat.cacheInBytes,
1074 memoryStat.swapInBytes);
1075 }
1076
Calin Juravle759fbda2018-02-20 19:52:30 +00001077 private ArtManagerInternal getArtManagerInternal() {
1078 if (mArtManagerInternal == null) {
1079 // Note that this may be null.
1080 // ArtManagerInternal is registered during PackageManagerService
1081 // initialization which happens after ActivityManagerService.
1082 mArtManagerInternal = LocalServices.getService(ArtManagerInternal.class);
1083 }
1084 return mArtManagerInternal;
1085 }
Vishnu Nair132ee832018-09-28 15:00:05 -07001086
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001087 /** Starts trace for an activity is actually launching. */
1088 private void startLaunchTrace(@NonNull TransitionInfo info) {
1089 if (DEBUG_METRICS) Slog.i(TAG, "startLaunchTrace " + info);
1090 if (!Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
Vishnu Nair132ee832018-09-28 15:00:05 -07001091 return;
1092 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001093 info.mLaunchTraceName = "launching: " + info.mLastLaunchedActivity.packageName;
Riddle Hsue8d3d192019-11-26 18:56:39 +08001094 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName,
1095 (int) info.mTransitionStartTimeNs /* cookie */);
Vishnu Nair132ee832018-09-28 15:00:05 -07001096 }
1097
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001098 /** Stops trace for the launch is completed or cancelled. */
1099 private void stopLaunchTrace(@NonNull TransitionInfo info) {
1100 if (DEBUG_METRICS) Slog.i(TAG, "stopLaunchTrace " + info);
1101 if (info.mLaunchTraceName == null) {
Vishnu Nair132ee832018-09-28 15:00:05 -07001102 return;
1103 }
Riddle Hsue8d3d192019-11-26 18:56:39 +08001104 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName,
1105 (int) info.mTransitionStartTimeNs /* cookie */);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001106 info.mLaunchTraceName = null;
Vishnu Nair132ee832018-09-28 15:00:05 -07001107 }
Igor Murashkin212d06c2018-10-22 16:34:39 -07001108
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001109 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
1110 return mLaunchObserver;
1111 }
1112
Igor Murashkin212d06c2018-10-22 16:34:39 -07001113 /** Notify the {@link ActivityMetricsLaunchObserver} that a new launch sequence has begun. */
Yan Wangd47f90b2019-10-03 19:17:15 -07001114 private void launchObserverNotifyIntentStarted(Intent intent, long timestampNs) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001115 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1116 "MetricsLogger:launchObserverNotifyIntentStarted");
1117
1118 // Beginning a launch is timing sensitive and so should be observed as soon as possible.
Yan Wangd47f90b2019-10-03 19:17:15 -07001119 mLaunchObserver.onIntentStarted(intent, timestampNs);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001120
1121 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001122 }
1123
1124 /**
1125 * Notify the {@link ActivityMetricsLaunchObserver} that the previous launch sequence has
1126 * aborted due to intent failure (e.g. intent resolve failed or security error, etc) or
1127 * intent being delivered to the top running activity.
1128 */
1129 private void launchObserverNotifyIntentFailed() {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001130 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1131 "MetricsLogger:launchObserverNotifyIntentFailed");
1132
1133 mLaunchObserver.onIntentFailed();
1134
1135 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001136 }
1137
1138 /**
1139 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence's activity
1140 * has started.
1141 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001142 private void launchObserverNotifyActivityLaunched(TransitionInfo info) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001143 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1144 "MetricsLogger:launchObserverNotifyActivityLaunched");
1145
Igor Murashkin212d06c2018-10-22 16:34:39 -07001146 @ActivityMetricsLaunchObserver.Temperature int temperature =
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001147 convertTransitionTypeToLaunchObserverTemperature(info.mTransitionType);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001148
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001149 // Beginning a launch is timing sensitive and so should be observed as soon as possible.
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001150 mLaunchObserver.onActivityLaunched(convertActivityRecordToProto(info.mLastLaunchedActivity),
1151 temperature);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001152
1153 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001154 }
1155
1156 /**
Yan Wang9eac5ec2019-09-30 15:42:18 -07001157 * Notifies the {@link ActivityMetricsLaunchObserver} the reportFullDrawn event.
1158 */
Yan Wangd47f90b2019-10-03 19:17:15 -07001159 private void launchObserverNotifyReportFullyDrawn(ActivityRecord r, long timestampNs) {
Yan Wang9eac5ec2019-09-30 15:42:18 -07001160 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1161 "MetricsLogger:launchObserverNotifyReportFullyDrawn");
Yan Wangd47f90b2019-10-03 19:17:15 -07001162 mLaunchObserver.onReportFullyDrawn(convertActivityRecordToProto(r), timestampNs);
Yan Wang9eac5ec2019-09-30 15:42:18 -07001163 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1164 }
1165
1166 /**
Igor Murashkin212d06c2018-10-22 16:34:39 -07001167 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence is
1168 * cancelled.
1169 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001170 private void launchObserverNotifyActivityLaunchCancelled(TransitionInfo info) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001171 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1172 "MetricsLogger:launchObserverNotifyActivityLaunchCancelled");
Igor Murashkin212d06c2018-10-22 16:34:39 -07001173
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001174 final @ActivityMetricsLaunchObserver.ActivityRecordProto byte[] activityRecordProto =
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001175 info != null ? convertActivityRecordToProto(info.mLastLaunchedActivity) : null;
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001176
1177 mLaunchObserver.onActivityLaunchCancelled(activityRecordProto);
1178
1179 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001180 }
1181
1182 /**
1183 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence's activity
1184 * has fully finished (successfully).
1185 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001186 private void launchObserverNotifyActivityLaunchFinished(TransitionInfo info, long timestampNs) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001187 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1188 "MetricsLogger:launchObserverNotifyActivityLaunchFinished");
Igor Murashkin212d06c2018-10-22 16:34:39 -07001189
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001190 mLaunchObserver.onActivityLaunchFinished(
1191 convertActivityRecordToProto(info.mLastLaunchedActivity), timestampNs);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001192
1193 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1194 }
1195
1196 @VisibleForTesting
1197 static @ActivityMetricsLaunchObserver.ActivityRecordProto byte[]
1198 convertActivityRecordToProto(ActivityRecord record) {
1199 // May take non-negligible amount of time to convert ActivityRecord into a proto,
1200 // so track the time.
1201 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1202 "MetricsLogger:convertActivityRecordToProto");
1203
1204 // There does not appear to be a way to 'reset' a ProtoOutputBuffer stream,
1205 // so create a new one every time.
1206 final ProtoOutputStream protoOutputStream =
1207 new ProtoOutputStream(LAUNCH_OBSERVER_ACTIVITY_RECORD_PROTO_CHUNK_SIZE);
1208 // Write this data out as the top-most ActivityRecordProto (i.e. it is not a sub-object).
1209 record.writeToProto(protoOutputStream);
1210 final byte[] bytes = protoOutputStream.getBytes();
1211
1212 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1213
1214 return bytes;
Igor Murashkin212d06c2018-10-22 16:34:39 -07001215 }
1216
1217 private static @ActivityMetricsLaunchObserver.Temperature int
1218 convertTransitionTypeToLaunchObserverTemperature(int transitionType) {
1219 switch (transitionType) {
1220 case TYPE_TRANSITION_WARM_LAUNCH:
1221 return ActivityMetricsLaunchObserver.TEMPERATURE_WARM;
1222 case TYPE_TRANSITION_HOT_LAUNCH:
1223 return ActivityMetricsLaunchObserver.TEMPERATURE_HOT;
1224 case TYPE_TRANSITION_COLD_LAUNCH:
1225 return ActivityMetricsLaunchObserver.TEMPERATURE_COLD;
1226 default:
1227 return -1;
1228 }
1229 }
Filip Gruszczynski77d94482015-12-11 13:59:52 -08001230}