blob: 0502d0bfa9335de4974371eacf543fcf3ec2efbe [file] [log] [blame]
Wale Ogunwale59507092018-10-29 09:00:30 -07001package com.android.server.wm;
Filip Gruszczynski77d94482015-12-11 13:59:52 -08002
Jorim Jaggi3878ca32017-02-02 17:13:05 -08003import static android.app.ActivityManager.START_SUCCESS;
4import static android.app.ActivityManager.START_TASK_TO_FRONT;
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005import static android.app.ActivityManager.processStateAmToProto;
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -08006import static android.app.WaitResult.LAUNCH_STATE_COLD;
7import static android.app.WaitResult.LAUNCH_STATE_HOT;
8import static android.app.WaitResult.LAUNCH_STATE_WARM;
Bryce Lee6c605092017-10-12 11:14:49 -07009import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
Wale Ogunwale3382ab12017-07-27 08:55:03 -070010import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale194435b2019-12-23 12:56:51 -080011import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
Wale Ogunwale3382ab12017-07-27 08:55:03 -070012import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
Vishnu Nair132ee832018-09-28 15:00:05 -070013import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale926aade2017-08-29 11:24:37 -070014import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
15import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Vishnu Nair132ee832018-09-28 15:00:05 -070016
Michal Karpinski201bc0c2018-07-20 15:32:00 +010017import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_ACTIVITY_START;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080018import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION;
Jorim Jaggi515dd682017-05-05 15:05:07 +020019import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_BIND_APPLICATION_DELAY_MS;
Todd Kennedy50d946c12017-03-17 13:55:38 -070020import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_CALLING_PACKAGE_NAME;
Jorim Jaggi172e99f2017-10-20 14:33:18 +020021import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_CANCELLED;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080022import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_DELAY_MS;
23import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_DEVICE_UPTIME_SECONDS;
Todd Kennedy50d946c12017-03-17 13:55:38 -070024import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_IS_EPHEMERAL;
Jorim Jaggi4d27b842017-08-17 17:22:26 +020025import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_PROCESS_RUNNING;
26import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_REPORTED_DRAWN;
27import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_REPORTED_DRAWN_MS;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080028import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_STARTING_WINDOW_DELAY_MS;
29import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.APP_TRANSITION_WINDOWS_DRAWN_DELAY_MS;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010030import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_PACKAGE_NAME;
31import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_UID;
32import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_UID_HAS_ANY_VISIBLE_WINDOW;
33import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CALLING_UID_PROC_STATE;
Jorim Jaggicdfc04e2017-04-28 19:06:24 +020034import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_CLASS_NAME;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010035import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_COMING_FROM_PENDING_INTENT;
Todd Kennedy50d946c12017-03-17 13:55:38 -070036import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_INSTANT_APP_LAUNCH_TOKEN;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010037import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_INTENT_ACTION;
38import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_CUR_PROC_STATE;
39import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_CLIENT_ACTIVITIES;
40import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_FOREGROUND_ACTIVITIES;
41import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_FOREGROUND_SERVICES;
42import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_OVERLAY_UI;
43import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_HAS_TOP_UI;
44import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_MILLIS_SINCE_FG_INTERACTION;
45import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_MILLIS_SINCE_LAST_INTERACTION_EVENT;
46import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_MILLIS_SINCE_UNIMPORTANT;
47import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_PENDING_UI_CLEAN;
48import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_PROCESS_RECORD_PROCESS_NAME;
49import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_REAL_CALLING_UID;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010050import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_REAL_CALLING_UID_HAS_ANY_VISIBLE_WINDOW;
Vishnu Nair132ee832018-09-28 15:00:05 -070051import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_REAL_CALLING_UID_PROC_STATE;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010052import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TARGET_SHORT_COMPONENT_NAME;
Calin Juravle759fbda2018-02-20 19:52:30 +000053import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PACKAGE_OPTIMIZATION_COMPILATION_FILTER;
Vishnu Nair132ee832018-09-28 15:00:05 -070054import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PACKAGE_OPTIMIZATION_COMPILATION_REASON;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080055import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_COLD_LAUNCH;
56import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_HOT_LAUNCH;
Jorim Jaggi4d27b842017-08-17 17:22:26 +020057import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_REPORTED_DRAWN_NO_BUNDLE;
58import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_REPORTED_DRAWN_WITH_BUNDLE;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080059import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_WARM_LAUNCH;
Ng Zhi Anbbefdec2018-01-30 17:12:39 -080060import static com.android.server.am.MemoryStatUtil.MemoryStat;
Rajeev Kumarbfcd9202018-03-02 22:42:13 +000061import static com.android.server.am.MemoryStatUtil.readMemoryStatFromFilesystem;
Vishnu Naira62534b2018-11-09 09:13:22 -080062import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_METRICS;
63import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
64import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Vishnu Nair132ee832018-09-28 15:00:05 -070065import static com.android.server.wm.ActivityTaskManagerInternal.APP_TRANSITION_TIMEOUT;
Jeff Changd136e772019-11-05 20:33:52 +080066import static com.android.server.wm.EventLogTags.WM_ACTIVITY_LAUNCH_TIME;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080067
Riddle Hsufd66d4d2019-11-14 10:35:55 +080068import android.annotation.NonNull;
69import android.annotation.Nullable;
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -080070import android.app.WaitResult;
Igor Murashkin212d06c2018-10-22 16:34:39 -070071import android.app.WindowConfiguration.WindowingMode;
Michal Karpinski319069b2019-03-27 15:46:50 +000072import android.content.ComponentName;
Michal Karpinski201bc0c2018-07-20 15:32:00 +010073import android.content.Intent;
Calin Juravle759fbda2018-02-20 19:52:30 +000074import android.content.pm.ApplicationInfo;
75import android.content.pm.dex.ArtManagerInternal;
76import android.content.pm.dex.PackageOptimizationInfo;
Jorim Jaggi3878ca32017-02-02 17:13:05 -080077import android.metrics.LogMaker;
Riddle Hsufd66d4d2019-11-14 10:35:55 +080078import android.os.Binder;
Jorim Jaggi172e99f2017-10-20 14:33:18 +020079import android.os.Looper;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080080import android.os.SystemClock;
Vishnu Nair132ee832018-09-28 15:00:05 -070081import android.os.Trace;
Riddle Hsufd66d4d2019-11-14 10:35:55 +080082import android.util.ArrayMap;
Vishnu Nair132ee832018-09-28 15:00:05 -070083import android.util.EventLog;
84import android.util.Log;
Jorim Jaggi172e99f2017-10-20 14:33:18 +020085import android.util.Slog;
Vishnu Nair132ee832018-09-28 15:00:05 -070086import android.util.TimeUtils;
Igor Murashkinc0b47e42018-11-07 15:54:18 -080087import android.util.proto.ProtoOutputStream;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080088
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -080089import com.android.internal.annotations.VisibleForTesting;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080090import com.android.internal.logging.MetricsLogger;
Ng Zhi An83473542018-02-20 09:02:14 -080091import com.android.internal.os.BackgroundThread;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -080092import com.android.internal.util.FrameworkStatsLog;
Riddle Hsufd66d4d2019-11-14 10:35:55 +080093import com.android.internal.util.function.pooled.PooledLambda;
Calin Juravle759fbda2018-02-20 19:52:30 +000094import com.android.server.LocalServices;
Louis Changcdec0802019-11-11 11:45:07 +080095
Riddle Hsufd66d4d2019-11-14 10:35:55 +080096import java.util.ArrayList;
97import java.util.LinkedList;
Yan Wang9eac5ec2019-09-30 15:42:18 -070098import java.util.concurrent.TimeUnit;
Filip Gruszczynski77d94482015-12-11 13:59:52 -080099
100/**
Vishnu Nair132ee832018-09-28 15:00:05 -0700101 * Listens to activity launches, transitions, visibility changes and window drawn callbacks to
102 * determine app launch times and draw delays. Source of truth for activity metrics and provides
103 * data for Tron, logcat, event logs and {@link android.app.WaitResult}.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800104 * <p>
105 * A typical sequence of a launch event could be:
106 * {@link #notifyActivityLaunching}, {@link #notifyActivityLaunched},
107 * {@link #notifyStartingWindowDrawn} (optional), {@link #notifyTransitionStarting}
108 * {@link #notifyWindowsDrawn}.
109 * <p>
Vishnu Nair132ee832018-09-28 15:00:05 -0700110 * Tests:
Tadashi G. Takaoka28bc3702019-04-23 11:01:48 +0900111 * atest CtsWindowManagerDeviceTestCases:ActivityMetricsLoggerTests
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800112 */
113class ActivityMetricsLogger {
Jorim Jaggif9704102016-05-05 19:14:22 -0700114
Wale Ogunwale98875612018-10-12 07:53:02 -0700115 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityMetricsLogger" : TAG_ATM;
Jorim Jaggif9704102016-05-05 19:14:22 -0700116
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800117 // Window modes we are interested in logging. If we ever introduce a new type, we need to add
118 // a value here and increase the {@link #TRON_WINDOW_STATE_VARZ_STRINGS} array.
119 private static final int WINDOW_STATE_STANDARD = 0;
120 private static final int WINDOW_STATE_SIDE_BY_SIDE = 1;
121 private static final int WINDOW_STATE_FREEFORM = 2;
Winson Chung83471632016-12-13 11:02:12 -0800122 private static final int WINDOW_STATE_ASSISTANT = 3;
Wale Ogunwale194435b2019-12-23 12:56:51 -0800123 private static final int WINDOW_STATE_MULTI_WINDOW = 4;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800124 private static final int WINDOW_STATE_INVALID = -1;
125
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800126 /**
127 * The flag for {@link #notifyActivityLaunching} to skip associating a new launch with an active
128 * transition, in the case the launch is standalone (e.g. from recents).
129 */
130 private static final int IGNORE_CALLER = -1;
Vishnu Nair132ee832018-09-28 15:00:05 -0700131 private static final int INVALID_DELAY = -1;
132 private static final int INVALID_TRANSITION_TYPE = -1;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500133
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800134 // Preallocated strings we are sending to tron, so we don't have to allocate a new one every
135 // time we log.
136 private static final String[] TRON_WINDOW_STATE_VARZ_STRINGS = {
Winson Chung83471632016-12-13 11:02:12 -0800137 "window_time_0", "window_time_1", "window_time_2", "window_time_3"};
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800138
139 private int mWindowState = WINDOW_STATE_STANDARD;
140 private long mLastLogTimeSecs;
141 private final ActivityStackSupervisor mSupervisor;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800142 private final MetricsLogger mMetricsLogger = new MetricsLogger();
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800143
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800144 /** All active transitions. */
145 private final ArrayList<TransitionInfo> mTransitionInfoList = new ArrayList<>();
146 /** Map : Last launched activity => {@link TransitionInfo} */
147 private final ArrayMap<ActivityRecord, TransitionInfo> mLastTransitionInfo = new ArrayMap<>();
Calin Juravle759fbda2018-02-20 19:52:30 +0000148
149 private ArtManagerInternal mArtManagerInternal;
Vishnu Nair132ee832018-09-28 15:00:05 -0700150 private final StringBuilder mStringBuilder = new StringBuilder();
Calin Juravle759fbda2018-02-20 19:52:30 +0000151
Igor Murashkin212d06c2018-10-22 16:34:39 -0700152 /**
153 * Due to the global single concurrent launch sequence, all calls to this observer must be made
154 * in-order on the same thread to fulfill the "happens-before" guarantee in LaunchObserver.
155 */
Igor Murashkinc0b47e42018-11-07 15:54:18 -0800156 private final LaunchObserverRegistryImpl mLaunchObserver;
157 @VisibleForTesting static final int LAUNCH_OBSERVER_ACTIVITY_RECORD_PROTO_CHUNK_SIZE = 512;
Igor Murashkin212d06c2018-10-22 16:34:39 -0700158
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800159 /**
160 * The information created when an intent is incoming but we do not yet know whether it will be
161 * launched successfully.
162 */
163 static final class LaunchingState {
164 /** The timestamp of {@link #notifyActivityLaunching}. */
165 private long mCurrentTransitionStartTimeNs;
166 /** Non-null when a {@link TransitionInfo} is created for this state. */
167 private TransitionInfo mAssociatedTransitionInfo;
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200168
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800169 @VisibleForTesting
170 boolean allDrawn() {
171 return mAssociatedTransitionInfo != null && mAssociatedTransitionInfo.allDrawn();
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200172 }
Calin Juravle759fbda2018-02-20 19:52:30 +0000173 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800174
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800175 /** The information created when an activity is confirmed to be launched. */
176 private static final class TransitionInfo {
177 /**
178 * The field to lookup and update an existing transition efficiently between
179 * {@link #notifyActivityLaunching} and {@link #notifyActivityLaunched}.
180 *
181 * @see LaunchingState#mAssociatedTransitionInfo
182 */
183 final LaunchingState mLaunchingState;
184 /**
185 * The timestamp of the first {@link #notifyActivityLaunching}. It can be used as a key for
186 * observer to identify which callbacks belong to a launch event.
187 */
188 final long mTransitionStartTimeNs;
189 /** The device uptime in seconds when this transition info is created. */
190 final int mCurrentTransitionDeviceUptime;
191 /** The type can be cold (new process), warm (new activity), or hot (bring to front). */
192 final int mTransitionType;
193 /** Whether the process was already running when the transition started. */
194 final boolean mProcessRunning;
Riddle Hsue8d3d192019-11-26 18:56:39 +0800195 /** whether the process of the launching activity didn't have any active activity. */
196 final boolean mProcessSwitch;
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800197 /** The activities that should be drawn. */
198 final LinkedList<ActivityRecord> mPendingDrawActivities = new LinkedList<>();
Igor Murashkin212d06c2018-10-22 16:34:39 -0700199 /** The latest activity to have been launched. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800200 @NonNull ActivityRecord mLastLaunchedActivity;
201
202 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyTransitionStarting}. */
203 int mCurrentTransitionDelayMs;
204 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyStartingWindowDrawn}. */
205 int mStartingWindowDelayMs = INVALID_DELAY;
206 /** The time from {@link #mTransitionStartTimeNs} to {@link #notifyBindApplication}. */
207 int mBindApplicationDelayMs = INVALID_DELAY;
Vishnu Nair132ee832018-09-28 15:00:05 -0700208 /** Elapsed time from when we launch an activity to when its windows are drawn. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800209 int mWindowsDrawnDelayMs;
210 /** The reason why the transition started (see ActivityManagerInternal.APP_TRANSITION_*). */
211 int mReason = APP_TRANSITION_TIMEOUT;
212 /** The flag ensures that {@link #mStartingWindowDelayMs} is only set once. */
213 boolean mLoggedStartingWindowDrawn;
214 /** If the any app transitions have been logged as starting. */
215 boolean mLoggedTransitionStarting;
216
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800217 /** Non-null if the application has reported drawn but its window hasn't. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800218 @Nullable Runnable mPendingFullyDrawn;
219 /** Non-null if the trace is active. */
220 @Nullable String mLaunchTraceName;
221
222 /** @return Non-null if there will be a window drawn event for the launch. */
223 @Nullable
224 static TransitionInfo create(@NonNull ActivityRecord r,
Riddle Hsue8d3d192019-11-26 18:56:39 +0800225 @NonNull LaunchingState launchingState, boolean processRunning,
226 boolean processSwitch, int startResult) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800227 int transitionType = INVALID_TRANSITION_TYPE;
228 if (processRunning) {
229 if (startResult == START_SUCCESS) {
230 transitionType = TYPE_TRANSITION_WARM_LAUNCH;
231 } else if (startResult == START_TASK_TO_FRONT) {
232 transitionType = TYPE_TRANSITION_HOT_LAUNCH;
233 }
234 } else if (startResult == START_SUCCESS || startResult == START_TASK_TO_FRONT) {
235 // Task may still exist when cold launching an activity and the start result will be
236 // set to START_TASK_TO_FRONT. Treat this as a COLD launch.
237 transitionType = TYPE_TRANSITION_COLD_LAUNCH;
238 }
239 if (transitionType == INVALID_TRANSITION_TYPE) {
240 // That means the startResult is neither START_SUCCESS nor START_TASK_TO_FRONT.
241 return null;
242 }
Riddle Hsue8d3d192019-11-26 18:56:39 +0800243 return new TransitionInfo(r, launchingState, transitionType, processRunning,
244 processSwitch);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800245 }
246
247 /** Use {@link TransitionInfo#create} instead to ensure the transition type is valid. */
248 private TransitionInfo(ActivityRecord r, LaunchingState launchingState, int transitionType,
Riddle Hsue8d3d192019-11-26 18:56:39 +0800249 boolean processRunning, boolean processSwitch) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800250 mLaunchingState = launchingState;
251 mTransitionStartTimeNs = launchingState.mCurrentTransitionStartTimeNs;
252 mTransitionType = transitionType;
253 mProcessRunning = processRunning;
Riddle Hsue8d3d192019-11-26 18:56:39 +0800254 mProcessSwitch = processSwitch;
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800255 mCurrentTransitionDeviceUptime =
256 (int) TimeUnit.MILLISECONDS.toSeconds(SystemClock.uptimeMillis());
257 setLatestLaunchedActivity(r);
258 launchingState.mAssociatedTransitionInfo = this;
259 }
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800260
261 /**
262 * Remembers the latest launched activity to represent the final transition. This also
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800263 * tracks the activities that should be drawn, so a consecutive launching sequence can be
264 * coalesced as one event.
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800265 */
266 void setLatestLaunchedActivity(ActivityRecord r) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800267 if (mLastLaunchedActivity == r) {
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800268 return;
269 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800270 mLastLaunchedActivity = r;
271 if (!r.noDisplay) {
272 if (DEBUG_METRICS) Slog.i(TAG, "Add pending draw " + r);
273 mPendingDrawActivities.add(r);
274 }
275 }
276
277 /** @return {@code true} if the activity matches a launched activity in this transition. */
278 boolean contains(ActivityRecord r) {
279 return r == mLastLaunchedActivity || mPendingDrawActivities.contains(r);
280 }
281
282 /** Called when the activity is drawn or won't be drawn. */
283 void removePendingDrawActivity(ActivityRecord r) {
284 if (DEBUG_METRICS) Slog.i(TAG, "Remove pending draw " + r);
285 mPendingDrawActivities.remove(r);
286 }
287
288 boolean allDrawn() {
289 return mPendingDrawActivities.isEmpty();
290 }
291
Riddle Hsue8d3d192019-11-26 18:56:39 +0800292 /**
293 * @return {@code true} if the transition info should be sent to MetricsLogger, StatsLog, or
294 * LaunchObserver.
295 */
296 boolean isInterestingToLoggerAndObserver() {
297 return mProcessSwitch;
298 }
299
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800300 int calculateCurrentDelay() {
301 return calculateDelay(SystemClock.elapsedRealtimeNanos());
302 }
303
304 int calculateDelay(long timestampNs) {
305 // Shouldn't take more than 25 days to launch an app, so int is fine here.
306 return (int) TimeUnit.NANOSECONDS.toMillis(timestampNs - mTransitionStartTimeNs);
307 }
308
309 @Override
310 public String toString() {
311 return "TransitionInfo{" + Integer.toHexString(System.identityHashCode(this))
312 + " a=" + mLastLaunchedActivity + " ua=" + mPendingDrawActivities + "}";
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800313 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800314 }
315
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800316 static final class TransitionInfoSnapshot {
Calin Juravle759fbda2018-02-20 19:52:30 +0000317 final private ApplicationInfo applicationInfo;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700318 final private WindowProcessController processRecord;
Vishnu Nair132ee832018-09-28 15:00:05 -0700319 final String packageName;
320 final String launchedActivityName;
Calin Juravle759fbda2018-02-20 19:52:30 +0000321 final private String launchedActivityLaunchedFromPackage;
322 final private String launchedActivityLaunchToken;
323 final private String launchedActivityAppRecordRequiredAbi;
Vishnu Nair132ee832018-09-28 15:00:05 -0700324 final String launchedActivityShortComponentName;
Ng Zhi An83473542018-02-20 09:02:14 -0800325 final private String processName;
Calin Juravle759fbda2018-02-20 19:52:30 +0000326 final private int reason;
327 final private int startingWindowDelayMs;
328 final private int bindApplicationDelayMs;
Vishnu Nair132ee832018-09-28 15:00:05 -0700329 final int windowsDrawnDelayMs;
330 final int type;
331 final int userId;
332 /**
333 * Elapsed time from when we launch an activity to when the app reported it was
334 * fully drawn. If this is not reported then the value is set to INVALID_DELAY.
335 */
336 final int windowsFullyDrawnDelayMs;
337 final int activityRecordIdHashCode;
Calin Juravle759fbda2018-02-20 19:52:30 +0000338
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800339 private TransitionInfoSnapshot(TransitionInfo info) {
340 this(info, info.mLastLaunchedActivity, INVALID_DELAY);
Vishnu Nair132ee832018-09-28 15:00:05 -0700341 }
342
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800343 private TransitionInfoSnapshot(TransitionInfo info, ActivityRecord launchedActivity,
344 int windowsFullyDrawnDelayMs) {
Andrii Kulianeceebbf2019-06-26 17:36:51 -0700345 applicationInfo = launchedActivity.info.applicationInfo;
Vishnu Nair132ee832018-09-28 15:00:05 -0700346 packageName = launchedActivity.packageName;
347 launchedActivityName = launchedActivity.info.name;
348 launchedActivityLaunchedFromPackage = launchedActivity.launchedFromPackage;
349 launchedActivityLaunchToken = launchedActivity.info.launchToken;
350 launchedActivityAppRecordRequiredAbi = launchedActivity.app == null
Calin Juravle759fbda2018-02-20 19:52:30 +0000351 ? null
Vishnu Nairaf0ea312018-10-15 16:23:55 -0700352 : launchedActivity.app.getRequiredAbi();
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800353 reason = info.mReason;
354 startingWindowDelayMs = info.mStartingWindowDelayMs;
355 bindApplicationDelayMs = info.mBindApplicationDelayMs;
356 windowsDrawnDelayMs = info.mWindowsDrawnDelayMs;
357 type = info.mTransitionType;
358 processRecord = launchedActivity.app;
Vishnu Nairaf0ea312018-10-15 16:23:55 -0700359 processName = launchedActivity.processName;
Wale Ogunwale8b19de92018-11-29 19:58:26 -0800360 userId = launchedActivity.mUserId;
Vishnu Nair132ee832018-09-28 15:00:05 -0700361 launchedActivityShortComponentName = launchedActivity.shortComponentName;
362 activityRecordIdHashCode = System.identityHashCode(launchedActivity);
363 this.windowsFullyDrawnDelayMs = windowsFullyDrawnDelayMs;
Calin Juravle759fbda2018-02-20 19:52:30 +0000364 }
Vishnu Nairbb9ab4b2018-12-13 10:29:46 -0800365
366 @WaitResult.LaunchState int getLaunchState() {
367 switch (type) {
368 case TYPE_TRANSITION_WARM_LAUNCH:
369 return LAUNCH_STATE_WARM;
370 case TYPE_TRANSITION_HOT_LAUNCH:
371 return LAUNCH_STATE_HOT;
372 case TYPE_TRANSITION_COLD_LAUNCH:
373 return LAUNCH_STATE_COLD;
374 default:
375 return -1;
376 }
377 }
Calin Juravle759fbda2018-02-20 19:52:30 +0000378 }
379
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800380 ActivityMetricsLogger(ActivityStackSupervisor supervisor, Looper looper) {
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800381 mLastLogTimeSecs = SystemClock.elapsedRealtime() / 1000;
382 mSupervisor = supervisor;
Igor Murashkinc0b47e42018-11-07 15:54:18 -0800383 mLaunchObserver = new LaunchObserverRegistryImpl(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800384 }
385
386 void logWindowState() {
387 final long now = SystemClock.elapsedRealtime() / 1000;
388 if (mWindowState != WINDOW_STATE_INVALID) {
389 // We log even if the window state hasn't changed, because the user might remain in
390 // home/fullscreen move forever and we would like to track this kind of behavior
391 // too.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800392 mMetricsLogger.count(TRON_WINDOW_STATE_VARZ_STRINGS[mWindowState],
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800393 (int) (now - mLastLogTimeSecs));
394 }
395 mLastLogTimeSecs = now;
396
Wale Ogunwale926aade2017-08-29 11:24:37 -0700397 mWindowState = WINDOW_STATE_INVALID;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800398 ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +0800399 mSupervisor.mRootWindowContainer.getTopDisplayFocusedStack();
lumarkf6c4a982018-06-15 15:43:12 +0800400 if (stack == null) {
401 return;
402 }
403
Wale Ogunwale926aade2017-08-29 11:24:37 -0700404 if (stack.isActivityTypeAssistant()) {
405 mWindowState = WINDOW_STATE_ASSISTANT;
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -0800406 return;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800407 }
Wale Ogunwale926aade2017-08-29 11:24:37 -0700408
Igor Murashkin212d06c2018-10-22 16:34:39 -0700409 @WindowingMode int windowingMode = stack.getWindowingMode();
Wale Ogunwale3382ab12017-07-27 08:55:03 -0700410 if (windowingMode == WINDOWING_MODE_PINNED) {
Louis Chang149d5c82019-12-30 09:47:39 +0800411 stack = mSupervisor.mRootWindowContainer.findStackBehind(stack);
Wale Ogunwale3382ab12017-07-27 08:55:03 -0700412 windowingMode = stack.getWindowingMode();
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -0800413 }
Wale Ogunwale926aade2017-08-29 11:24:37 -0700414 switch (windowingMode) {
415 case WINDOWING_MODE_FULLSCREEN:
416 mWindowState = WINDOW_STATE_STANDARD;
417 break;
418 case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
419 case WINDOWING_MODE_SPLIT_SCREEN_SECONDARY:
420 mWindowState = WINDOW_STATE_SIDE_BY_SIDE;
421 break;
Bryce Lee6c605092017-10-12 11:14:49 -0700422 case WINDOWING_MODE_FREEFORM:
Wale Ogunwale926aade2017-08-29 11:24:37 -0700423 mWindowState = WINDOW_STATE_FREEFORM;
424 break;
Wale Ogunwale194435b2019-12-23 12:56:51 -0800425 case WINDOWING_MODE_MULTI_WINDOW:
426 mWindowState = WINDOW_STATE_MULTI_WINDOW;
427 break;
Wale Ogunwale926aade2017-08-29 11:24:37 -0700428 default:
429 if (windowingMode != WINDOWING_MODE_UNDEFINED) {
430 throw new IllegalStateException("Unknown windowing mode for stack=" + stack
431 + " windowingMode=" + windowingMode);
432 }
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800433 }
434 }
Jorim Jaggi275561a2016-02-23 10:11:02 -0500435
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800436 /** @return Non-null {@link TransitionInfo} if the activity is found in an active transition. */
437 @Nullable
438 private TransitionInfo getActiveTransitionInfo(ActivityRecord r) {
439 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
440 final TransitionInfo info = mTransitionInfoList.get(i);
441 if (info.contains(r)) {
442 return info;
443 }
444 }
445 return null;
446 }
447
448 /**
449 * This method should be only used by starting recents and starting from recents, or internal
450 * tests. Because it doesn't lookup caller and always creates a new launching state.
451 *
452 * @see #notifyActivityLaunching(Intent, ActivityRecord, int)
453 */
454 LaunchingState notifyActivityLaunching(Intent intent) {
455 return notifyActivityLaunching(intent, null /* caller */, IGNORE_CALLER);
456 }
457
458 /**
459 * If the caller is found in an active transition, it will be considered as consecutive launch
460 * and coalesced into the active transition.
461 *
462 * @see #notifyActivityLaunching(Intent, ActivityRecord, int)
463 */
464 LaunchingState notifyActivityLaunching(Intent intent, @Nullable ActivityRecord caller) {
465 return notifyActivityLaunching(intent, caller, Binder.getCallingUid());
466 }
467
Jorim Jaggi275561a2016-02-23 10:11:02 -0500468 /**
469 * Notifies the tracker at the earliest possible point when we are starting to launch an
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800470 * activity. The caller must ensure that {@link #notifyActivityLaunched} will be called later
471 * with the returned {@link LaunchingState}.
Jorim Jaggi275561a2016-02-23 10:11:02 -0500472 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800473 private LaunchingState notifyActivityLaunching(Intent intent, @Nullable ActivityRecord caller,
474 int callingUid) {
475 final long transitionStartTimeNs = SystemClock.elapsedRealtimeNanos();
476 TransitionInfo existingInfo = null;
477 if (callingUid != IGNORE_CALLER) {
478 // Associate the launching event to an active transition if the caller is found in its
479 // launched activities.
480 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
481 final TransitionInfo info = mTransitionInfoList.get(i);
482 if (caller != null && info.contains(caller)) {
483 existingInfo = info;
484 break;
485 }
486 if (existingInfo == null && callingUid == info.mLastLaunchedActivity.getUid()) {
487 // Fallback to check the most recent matched uid for the case that the caller is
488 // not an activity.
489 existingInfo = info;
490 }
491 }
492 }
Igor Murashkin212d06c2018-10-22 16:34:39 -0700493 if (DEBUG_METRICS) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800494 Slog.i(TAG, "notifyActivityLaunching intent=" + intent
495 + " existingInfo=" + existingInfo);
Igor Murashkin212d06c2018-10-22 16:34:39 -0700496 }
497
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800498 if (existingInfo == null) {
499 // Only notify the observer for a new launching event.
500 launchObserverNotifyIntentStarted(intent, transitionStartTimeNs);
501 final LaunchingState launchingState = new LaunchingState();
502 launchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs;
503 return launchingState;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800504 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800505 existingInfo.mLaunchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs;
506 return existingInfo.mLaunchingState;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500507 }
508
509 /**
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700510 * Notifies the tracker that the activity is actually launching.
511 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800512 * @param launchingState The launching state to track the new or active transition.
513 * @param resultCode One of the {@link android.app.ActivityManager}.START_* flags, indicating
514 * the result of the launch.
515 * @param launchedActivity The activity that is being launched
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700516 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800517 void notifyActivityLaunched(@NonNull LaunchingState launchingState, int resultCode,
518 @Nullable ActivityRecord launchedActivity) {
519 if (launchedActivity == null) {
520 // The launch is aborted, e.g. intent not resolved, class not found.
521 abort(null /* info */, "nothing launched");
522 return;
523 }
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700524
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800525 final WindowProcessController processRecord = launchedActivity.app != null
526 ? launchedActivity.app
527 : mSupervisor.mService.getProcessController(
528 launchedActivity.processName, launchedActivity.info.applicationInfo.uid);
529 // Whether the process that will contains the activity is already running.
530 final boolean processRunning = processRecord != null;
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700531 // We consider this a "process switch" if the process of the activity that gets launched
532 // didn't have an activity that was in started state. In this case, we assume that lot
533 // of caches might be purged so the time until it produces the first frame is very
534 // interesting.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800535 final boolean processSwitch = !processRunning
Wale Ogunwalef6733932018-06-27 05:14:34 -0700536 || !processRecord.hasStartedActivity(launchedActivity);
Jorim Jaggi1e630c02016-05-16 12:13:13 -0700537
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800538 final TransitionInfo info = launchingState.mAssociatedTransitionInfo;
539 if (DEBUG_METRICS) {
540 Slog.i(TAG, "notifyActivityLaunched" + " resultCode=" + resultCode
541 + " launchedActivity=" + launchedActivity + " processRunning=" + processRunning
542 + " processSwitch=" + processSwitch + " info=" + info);
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200543 }
544
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800545 if (launchedActivity.mDrawn) {
Vishnu Nairf8accc52018-10-11 10:19:54 -0700546 // Launched activity is already visible. We cannot measure windows drawn delay.
Riddle Hsu1063b512019-10-22 21:12:23 +0800547 abort(info, "launched activity already visible");
Vishnu Nairf8accc52018-10-11 10:19:54 -0700548 return;
549 }
550
Riddle Hsu20cf2bc2019-11-27 18:57:50 +0800551 if (info != null
552 && info.mLastLaunchedActivity.mDisplayContent == launchedActivity.mDisplayContent) {
553 // If we are already in an existing transition on the same display, only update the
554 // activity name, but not the other attributes.
Igor Murashkin212d06c2018-10-22 16:34:39 -0700555
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800556 if (DEBUG_METRICS) Slog.i(TAG, "notifyActivityLaunched update launched activity");
Igor Murashkin212d06c2018-10-22 16:34:39 -0700557 // Coalesce multiple (trampoline) activities from a single sequence together.
Riddle Hsu1c5d72e2019-10-09 20:54:26 +0800558 info.setLatestLaunchedActivity(launchedActivity);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500559 return;
560 }
561
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800562 final TransitionInfo newInfo = TransitionInfo.create(launchedActivity, launchingState,
Riddle Hsue8d3d192019-11-26 18:56:39 +0800563 processRunning, processSwitch, resultCode);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800564 if (newInfo == null) {
565 abort(info, "unrecognized launch");
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800566 return;
567 }
568
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200569 if (DEBUG_METRICS) Slog.i(TAG, "notifyActivityLaunched successful");
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800570 // A new launch sequence has begun. Start tracking it.
571 mTransitionInfoList.add(newInfo);
572 mLastTransitionInfo.put(launchedActivity, newInfo);
573 startLaunchTrace(newInfo);
Riddle Hsue8d3d192019-11-26 18:56:39 +0800574 if (newInfo.isInterestingToLoggerAndObserver()) {
575 launchObserverNotifyActivityLaunched(newInfo);
576 } else {
577 // As abort for no process switch.
578 launchObserverNotifyIntentFailed();
579 }
Jorim Jaggi275561a2016-02-23 10:11:02 -0500580 }
581
582 /**
583 * Notifies the tracker that all windows of the app have been drawn.
584 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800585 @Nullable
586 TransitionInfoSnapshot notifyWindowsDrawn(@NonNull ActivityRecord r, long timestampNs) {
587 if (DEBUG_METRICS) Slog.i(TAG, "notifyWindowsDrawn " + r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200588
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800589 final TransitionInfo info = getActiveTransitionInfo(r);
590 if (info == null || info.allDrawn()) {
591 if (DEBUG_METRICS) Slog.i(TAG, "notifyWindowsDrawn no activity to be drawn");
Vishnu Nair132ee832018-09-28 15:00:05 -0700592 return null;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500593 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800594 // Always calculate the delay because the caller may need to know the individual drawn time.
595 info.mWindowsDrawnDelayMs = info.calculateDelay(timestampNs);
596 info.removePendingDrawActivity(r);
597 final TransitionInfoSnapshot infoSnapshot = new TransitionInfoSnapshot(info);
598 if (info.mLoggedTransitionStarting && info.allDrawn()) {
599 done(false /* abort */, info, "notifyWindowsDrawn - all windows drawn", timestampNs);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500600 }
Vishnu Nair132ee832018-09-28 15:00:05 -0700601 return infoSnapshot;
Jorim Jaggi275561a2016-02-23 10:11:02 -0500602 }
603
604 /**
605 * Notifies the tracker that the starting window was drawn.
606 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800607 void notifyStartingWindowDrawn(@NonNull ActivityRecord r) {
608 final TransitionInfo info = getActiveTransitionInfo(r);
609 if (info == null || info.mLoggedStartingWindowDrawn) {
Jorim Jaggi275561a2016-02-23 10:11:02 -0500610 return;
611 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800612 if (DEBUG_METRICS) Slog.i(TAG, "notifyStartingWindowDrawn " + r);
613 info.mLoggedStartingWindowDrawn = true;
614 info.mStartingWindowDelayMs = info.calculateDelay(SystemClock.elapsedRealtimeNanos());
Jorim Jaggi275561a2016-02-23 10:11:02 -0500615 }
616
617 /**
618 * Notifies the tracker that the app transition is starting.
619 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800620 * @param activityToReason A map from activity to a reason integer, which must be on of
621 * ActivityTaskManagerInternal.APP_TRANSITION_* reasons.
Jorim Jaggi275561a2016-02-23 10:11:02 -0500622 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800623 void notifyTransitionStarting(ArrayMap<ActivityRecord, Integer> activityToReason) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200624 if (DEBUG_METRICS) Slog.i(TAG, "notifyTransitionStarting");
Igor Murashkin212d06c2018-10-22 16:34:39 -0700625
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800626 final long timestampNs = SystemClock.elapsedRealtimeNanos();
627 for (int index = activityToReason.size() - 1; index >= 0; index--) {
628 final ActivityRecord r = activityToReason.keyAt(index);
629 final TransitionInfo info = getActiveTransitionInfo(r);
630 if (info == null || info.mLoggedTransitionStarting) {
631 // Ignore any subsequent notifyTransitionStarting.
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800632 continue;
633 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800634 if (DEBUG_METRICS) {
635 Slog.i(TAG, "notifyTransitionStarting activity=" + r + " info=" + info);
636 }
637
638 info.mCurrentTransitionDelayMs = info.calculateDelay(timestampNs);
639 info.mReason = activityToReason.valueAt(index);
640 info.mLoggedTransitionStarting = true;
641 if (info.allDrawn()) {
642 done(false /* abort */, info, "notifyTransitionStarting - all windows drawn",
643 timestampNs);
644 }
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800645 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800646 }
647
648 /** Makes sure that the reference to the removed activity is cleared. */
649 void notifyActivityRemoved(@NonNull ActivityRecord r) {
650 mLastTransitionInfo.remove(r);
Jorim Jaggi275561a2016-02-23 10:11:02 -0500651 }
652
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200653 /**
654 * Notifies the tracker that the visibility of an app is changing.
655 *
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800656 * @param r the app that is changing its visibility
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200657 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800658 void notifyVisibilityChanged(@NonNull ActivityRecord r) {
659 final TransitionInfo info = getActiveTransitionInfo(r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200660 if (info == null) {
661 return;
662 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800663 if (DEBUG_METRICS) {
664 Slog.i(TAG, "notifyVisibilityChanged " + r + " visible=" + r.mVisibleRequested
665 + " state=" + r.getState() + " finishing=" + r.finishing);
666 }
667 if (!r.mVisibleRequested || r.finishing) {
668 info.removePendingDrawActivity(r);
669 }
670 if (info.mLastLaunchedActivity != r) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200671 return;
672 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800673 // The activity and its task are passed separately because the activity may be removed from
674 // the task later.
675 r.mAtmService.mH.sendMessage(PooledLambda.obtainMessage(
676 ActivityMetricsLogger::checkVisibility, this, r.getTask(), r));
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200677 }
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200678
Riddle Hsu1063b512019-10-22 21:12:23 +0800679 /** @return {@code true} if the given task has an activity will be drawn. */
Louis Changcdec0802019-11-11 11:45:07 +0800680 private static boolean hasActivityToBeDrawn(Task t) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800681 return t.forAllActivities((r) -> r.mVisibleRequested && !r.mDrawn && !r.finishing);
Vishnu Nairb1de42d2019-01-28 09:49:51 -0800682 }
683
Louis Changcdec0802019-11-11 11:45:07 +0800684 private void checkVisibility(Task t, ActivityRecord r) {
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700685 synchronized (mSupervisor.mService.mGlobalLock) {
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200686
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800687 final TransitionInfo info = getActiveTransitionInfo(r);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200688
689 // If we have an active transition that's waiting on a certain activity that will be
690 // invisible now, we'll never get onWindowsDrawn, so abort the transition if necessary.
Vishnu Naird15063b2019-06-11 08:08:25 -0700691
692 // We have no active transitions.
693 if (info == null) {
694 return;
695 }
696
697 // The notified activity whose visibility changed is no longer the launched activity.
698 // We can still wait to get onWindowsDrawn.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800699 if (info.mLastLaunchedActivity != r) {
Vishnu Naird15063b2019-06-11 08:08:25 -0700700 return;
701 }
702
Riddle Hsu1063b512019-10-22 21:12:23 +0800703 // If the task of the launched activity contains any activity to be drawn, then the
704 // window drawn event should report later to complete the transition. Otherwise all
705 // activities in this task may be finished, invisible or drawn, so the transition event
706 // should be cancelled.
707 if (hasActivityToBeDrawn(t)) {
Vishnu Naird15063b2019-06-11 08:08:25 -0700708 return;
709 }
710
711 if (DEBUG_METRICS) Slog.i(TAG, "notifyVisibilityChanged to invisible activity=" + r);
712 logAppTransitionCancel(info);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800713 abort(info, "notifyVisibilityChanged to invisible");
Jorim Jaggicdfc04e2017-04-28 19:06:24 +0200714 }
715 }
716
Jorim Jaggi515dd682017-05-05 15:05:07 +0200717 /**
718 * Notifies the tracker that we called immediately before we call bindApplication on the client.
719 *
Wale Ogunwale31913b52018-10-13 08:29:31 -0700720 * @param appInfo The client into which we'll call bindApplication.
Jorim Jaggi515dd682017-05-05 15:05:07 +0200721 */
Wale Ogunwale31913b52018-10-13 08:29:31 -0700722 void notifyBindApplication(ApplicationInfo appInfo) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800723 for (int i = mTransitionInfoList.size() - 1; i >= 0; i--) {
724 final TransitionInfo info = mTransitionInfoList.get(i);
Jorim Jaggi515dd682017-05-05 15:05:07 +0200725
726 // App isn't attached to record yet, so match with info.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800727 if (info.mLastLaunchedActivity.info.applicationInfo == appInfo) {
728 info.mBindApplicationDelayMs = info.calculateCurrentDelay();
Jorim Jaggi515dd682017-05-05 15:05:07 +0200729 }
730 }
731 }
732
Riddle Hsu1063b512019-10-22 21:12:23 +0800733 /** Aborts tracking of current launch metrics. */
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800734 private void abort(TransitionInfo info, String cause) {
735 done(true /* abort */, info, cause, 0L /* timestampNs */);
Riddle Hsu1063b512019-10-22 21:12:23 +0800736 }
737
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800738 /** Called when the given transition (info) is no longer active. */
739 private void done(boolean abort, @Nullable TransitionInfo info, String cause,
Riddle Hsu1063b512019-10-22 21:12:23 +0800740 long timestampNs) {
Yan Wangd47f90b2019-10-03 19:17:15 -0700741 if (DEBUG_METRICS) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800742 Slog.i(TAG, "done abort=" + abort + " cause=" + cause + " timestamp=" + timestampNs
743 + " info=" + info);
Yan Wangd47f90b2019-10-03 19:17:15 -0700744 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800745 if (info == null) {
Igor Murashkin212d06c2018-10-22 16:34:39 -0700746 launchObserverNotifyIntentFailed();
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200747 return;
748 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800749
750 stopLaunchTrace(info);
751 if (abort) {
752 launchObserverNotifyActivityLaunchCancelled(info);
753 } else {
Riddle Hsue8d3d192019-11-26 18:56:39 +0800754 if (info.isInterestingToLoggerAndObserver()) {
755 launchObserverNotifyActivityLaunchFinished(info, timestampNs);
756 }
Yan Wang6f0b47d2020-01-02 16:09:30 -0800757 logAppTransitionFinished(info);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800758 }
759 info.mPendingDrawActivities.clear();
760 mTransitionInfoList.remove(info);
761 }
762
763 private void logAppTransitionCancel(TransitionInfo info) {
764 final int type = info.mTransitionType;
765 final ActivityRecord activity = info.mLastLaunchedActivity;
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200766 final LogMaker builder = new LogMaker(APP_TRANSITION_CANCELLED);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800767 builder.setPackageName(activity.packageName);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200768 builder.setType(type);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800769 builder.addTaggedData(FIELD_CLASS_NAME, activity.info.name);
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200770 mMetricsLogger.write(builder);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800771 FrameworkStatsLog.write(
772 FrameworkStatsLog.APP_START_CANCELED,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800773 activity.info.applicationInfo.uid,
774 activity.packageName,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000775 convertAppStartTransitionType(type),
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800776 activity.info.name);
Igor Murashkin212d06c2018-10-22 16:34:39 -0700777 if (DEBUG_METRICS) {
778 Slog.i(TAG, String.format("APP_START_CANCELED(%s, %s, %s, %s)",
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800779 activity.info.applicationInfo.uid,
780 activity.packageName,
Igor Murashkin212d06c2018-10-22 16:34:39 -0700781 convertAppStartTransitionType(type),
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800782 activity.info.name));
Igor Murashkin212d06c2018-10-22 16:34:39 -0700783 }
Jorim Jaggi172e99f2017-10-20 14:33:18 +0200784 }
785
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800786 private void logAppTransitionFinished(@NonNull TransitionInfo info) {
787 if (DEBUG_METRICS) Slog.i(TAG, "logging finished transition " + info);
Calin Juravle759fbda2018-02-20 19:52:30 +0000788
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800789 // Take a snapshot of the transition info before sending it to the handler for logging.
790 // This will avoid any races with other operations that modify the ActivityRecord.
791 final TransitionInfoSnapshot infoSnapshot = new TransitionInfoSnapshot(info);
Riddle Hsue8d3d192019-11-26 18:56:39 +0800792 if (info.isInterestingToLoggerAndObserver()) {
793 BackgroundThread.getHandler().post(() -> logAppTransition(
794 info.mCurrentTransitionDeviceUptime, info.mCurrentTransitionDelayMs,
795 infoSnapshot));
796 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800797 BackgroundThread.getHandler().post(() -> logAppDisplayed(infoSnapshot));
798 if (info.mPendingFullyDrawn != null) {
799 info.mPendingFullyDrawn.run();
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800800 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800801
802 info.mLastLaunchedActivity.info.launchToken = null;
Jorim Jaggi3878ca32017-02-02 17:13:05 -0800803 }
804
Ng Zhi An83473542018-02-20 09:02:14 -0800805 // This gets called on a background thread without holding the activity manager lock.
Calin Juravle759fbda2018-02-20 19:52:30 +0000806 private void logAppTransition(int currentTransitionDeviceUptime, int currentTransitionDelayMs,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800807 TransitionInfoSnapshot info) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000808 final LogMaker builder = new LogMaker(APP_TRANSITION);
809 builder.setPackageName(info.packageName);
810 builder.setType(info.type);
811 builder.addTaggedData(FIELD_CLASS_NAME, info.launchedActivityName);
812 final boolean isInstantApp = info.applicationInfo.isInstantApp();
813 if (info.launchedActivityLaunchedFromPackage != null) {
814 builder.addTaggedData(APP_TRANSITION_CALLING_PACKAGE_NAME,
815 info.launchedActivityLaunchedFromPackage);
816 }
817 String launchToken = info.launchedActivityLaunchToken;
818 if (launchToken != null) {
819 builder.addTaggedData(FIELD_INSTANT_APP_LAUNCH_TOKEN, launchToken);
820 }
821 builder.addTaggedData(APP_TRANSITION_IS_EPHEMERAL, isInstantApp ? 1 : 0);
822 builder.addTaggedData(APP_TRANSITION_DEVICE_UPTIME_SECONDS,
823 currentTransitionDeviceUptime);
824 builder.addTaggedData(APP_TRANSITION_DELAY_MS, currentTransitionDelayMs);
825 builder.setSubtype(info.reason);
Vishnu Nair132ee832018-09-28 15:00:05 -0700826 if (info.startingWindowDelayMs != INVALID_DELAY) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000827 builder.addTaggedData(APP_TRANSITION_STARTING_WINDOW_DELAY_MS,
828 info.startingWindowDelayMs);
829 }
Vishnu Nair132ee832018-09-28 15:00:05 -0700830 if (info.bindApplicationDelayMs != INVALID_DELAY) {
Calin Juravle759fbda2018-02-20 19:52:30 +0000831 builder.addTaggedData(APP_TRANSITION_BIND_APPLICATION_DELAY_MS,
832 info.bindApplicationDelayMs);
833 }
834 builder.addTaggedData(APP_TRANSITION_WINDOWS_DRAWN_DELAY_MS, info.windowsDrawnDelayMs);
835 final ArtManagerInternal artManagerInternal = getArtManagerInternal();
836 final PackageOptimizationInfo packageOptimizationInfo =
837 (artManagerInternal == null) || (info.launchedActivityAppRecordRequiredAbi == null)
838 ? PackageOptimizationInfo.createWithNoInfo()
839 : artManagerInternal.getPackageOptimizationInfo(
840 info.applicationInfo,
841 info.launchedActivityAppRecordRequiredAbi);
842 builder.addTaggedData(PACKAGE_OPTIMIZATION_COMPILATION_REASON,
843 packageOptimizationInfo.getCompilationReason());
844 builder.addTaggedData(PACKAGE_OPTIMIZATION_COMPILATION_FILTER,
845 packageOptimizationInfo.getCompilationFilter());
846 mMetricsLogger.write(builder);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800847 FrameworkStatsLog.write(
848 FrameworkStatsLog.APP_START_OCCURRED,
Calin Juravle759fbda2018-02-20 19:52:30 +0000849 info.applicationInfo.uid,
850 info.packageName,
851 convertAppStartTransitionType(info.type),
852 info.launchedActivityName,
853 info.launchedActivityLaunchedFromPackage,
854 isInstantApp,
855 currentTransitionDeviceUptime * 1000,
856 info.reason,
857 currentTransitionDelayMs,
858 info.startingWindowDelayMs,
859 info.bindApplicationDelayMs,
860 info.windowsDrawnDelayMs,
861 launchToken,
862 packageOptimizationInfo.getCompilationReason(),
863 packageOptimizationInfo.getCompilationFilter());
Igor Murashkin212d06c2018-10-22 16:34:39 -0700864
865 if (DEBUG_METRICS) {
866 Slog.i(TAG, String.format("APP_START_OCCURRED(%s, %s, %s, %s, %s)",
867 info.applicationInfo.uid,
868 info.packageName,
869 convertAppStartTransitionType(info.type),
870 info.launchedActivityName,
871 info.launchedActivityLaunchedFromPackage));
872 }
873
874
Ng Zhi An83473542018-02-20 09:02:14 -0800875 logAppStartMemoryStateCapture(info);
Calin Juravle759fbda2018-02-20 19:52:30 +0000876 }
877
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800878 private void logAppDisplayed(TransitionInfoSnapshot info) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700879 if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
880 return;
881 }
882
Jeff Changd136e772019-11-05 20:33:52 +0800883 EventLog.writeEvent(WM_ACTIVITY_LAUNCH_TIME,
Vishnu Nair132ee832018-09-28 15:00:05 -0700884 info.userId, info.activityRecordIdHashCode, info.launchedActivityShortComponentName,
885 info.windowsDrawnDelayMs);
886
887 StringBuilder sb = mStringBuilder;
888 sb.setLength(0);
889 sb.append("Displayed ");
890 sb.append(info.launchedActivityShortComponentName);
891 sb.append(": ");
892 TimeUtils.formatDuration(info.windowsDrawnDelayMs, sb);
893 Log.i(TAG, sb.toString());
894 }
895
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000896 private int convertAppStartTransitionType(int tronType) {
897 if (tronType == TYPE_TRANSITION_COLD_LAUNCH) {
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800898 return FrameworkStatsLog.APP_START_OCCURRED__TYPE__COLD;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000899 }
900 if (tronType == TYPE_TRANSITION_WARM_LAUNCH) {
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800901 return FrameworkStatsLog.APP_START_OCCURRED__TYPE__WARM;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000902 }
903 if (tronType == TYPE_TRANSITION_HOT_LAUNCH) {
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800904 return FrameworkStatsLog.APP_START_OCCURRED__TYPE__HOT;
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000905 }
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800906 return FrameworkStatsLog.APP_START_OCCURRED__TYPE__UNKNOWN;
Riddle Hsuc48c8912019-10-31 13:34:27 +0800907 }
908
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800909 /** @return the last known window drawn delay of the given activity. */
910 int getLastDrawnDelayMs(ActivityRecord r) {
911 final TransitionInfo info = mLastTransitionInfo.get(r);
912 return info != null ? info.mWindowsDrawnDelayMs : INVALID_DELAY;
Riddle Hsuc48c8912019-10-31 13:34:27 +0800913 }
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000914
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800915 /** @see android.app.Activity#reportFullyDrawn */
916 TransitionInfoSnapshot logAppTransitionReportedDrawn(ActivityRecord r,
Vishnu Nair132ee832018-09-28 15:00:05 -0700917 boolean restoredFromBundle) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800918 final TransitionInfo info = mLastTransitionInfo.get(r);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200919 if (info == null) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700920 return null;
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200921 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800922 if (!info.allDrawn() && info.mPendingFullyDrawn == null) {
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800923 // There are still undrawn activities, postpone reporting fully drawn until all of its
924 // windows are drawn. So that is closer to an usable state.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800925 info.mPendingFullyDrawn = () -> {
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800926 logAppTransitionReportedDrawn(r, restoredFromBundle);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800927 info.mPendingFullyDrawn = null;
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +0800928 };
929 return null;
930 }
Chris Wailes35c193c2018-10-09 18:12:00 -0700931
Riddle Hsue8d3d192019-11-26 18:56:39 +0800932 final long currentTimestampNs = SystemClock.elapsedRealtimeNanos();
933 final long startupTimeMs = info.mPendingFullyDrawn != null
934 ? info.mWindowsDrawnDelayMs
935 : TimeUnit.NANOSECONDS.toMillis(currentTimestampNs - info.mTransitionStartTimeNs);
936 final TransitionInfoSnapshot infoSnapshot =
937 new TransitionInfoSnapshot(info, r, (int) startupTimeMs);
938 BackgroundThread.getHandler().post(() -> logAppFullyDrawn(infoSnapshot));
939
940 if (!info.isInterestingToLoggerAndObserver()) {
941 return infoSnapshot;
942 }
943
Chris Wailes35c193c2018-10-09 18:12:00 -0700944 // Record the handling of the reportFullyDrawn callback in the trace system. This is not
945 // actually used to trace this function, but instead the logical task that this function
946 // fullfils (handling reportFullyDrawn() callbacks).
947 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800948 "ActivityManager:ReportingFullyDrawn " + info.mLastLaunchedActivity.packageName);
Chris Wailes35c193c2018-10-09 18:12:00 -0700949
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200950 final LogMaker builder = new LogMaker(APP_TRANSITION_REPORTED_DRAWN);
951 builder.setPackageName(r.packageName);
952 builder.addTaggedData(FIELD_CLASS_NAME, r.info.name);
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000953 builder.addTaggedData(APP_TRANSITION_REPORTED_DRAWN_MS, startupTimeMs);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200954 builder.setType(restoredFromBundle
955 ? TYPE_TRANSITION_REPORTED_DRAWN_WITH_BUNDLE
956 : TYPE_TRANSITION_REPORTED_DRAWN_NO_BUNDLE);
957 builder.addTaggedData(APP_TRANSITION_PROCESS_RUNNING,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800958 info.mProcessRunning ? 1 : 0);
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200959 mMetricsLogger.write(builder);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800960 FrameworkStatsLog.write(
961 FrameworkStatsLog.APP_START_FULLY_DRAWN,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800962 info.mLastLaunchedActivity.info.applicationInfo.uid,
963 info.mLastLaunchedActivity.packageName,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000964 restoredFromBundle
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800965 ? FrameworkStatsLog.APP_START_FULLY_DRAWN__TYPE__WITH_BUNDLE
966 : FrameworkStatsLog.APP_START_FULLY_DRAWN__TYPE__WITHOUT_BUNDLE,
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800967 info.mLastLaunchedActivity.info.name,
968 info.mProcessRunning,
Olivier Gaillardaed7f122017-12-12 14:26:22 +0000969 startupTimeMs);
Chris Wailes35c193c2018-10-09 18:12:00 -0700970
971 // Ends the trace started at the beginning of this function. This is located here to allow
972 // the trace slice to have a noticable duration.
973 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
974
Yan Wang9eac5ec2019-09-30 15:42:18 -0700975 // Notify reportFullyDrawn event.
976 launchObserverNotifyReportFullyDrawn(r, currentTimestampNs);
977
Vishnu Nair132ee832018-09-28 15:00:05 -0700978 return infoSnapshot;
979 }
980
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800981 private void logAppFullyDrawn(TransitionInfoSnapshot info) {
Vishnu Nair132ee832018-09-28 15:00:05 -0700982 if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
983 return;
984 }
985
986 StringBuilder sb = mStringBuilder;
987 sb.setLength(0);
988 sb.append("Fully drawn ");
989 sb.append(info.launchedActivityShortComponentName);
990 sb.append(": ");
991 TimeUtils.formatDuration(info.windowsFullyDrawnDelayMs, sb);
992 Log.i(TAG, sb.toString());
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200993 }
994
Michal Karpinski4fd5b842019-01-28 15:13:32 +0000995 void logAbortedBgActivityStart(Intent intent, WindowProcessController callerApp,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100996 int callingUid, String callingPackage, int callingUidProcState,
997 boolean callingUidHasAnyVisibleWindow,
998 int realCallingUid, int realCallingUidProcState,
999 boolean realCallingUidHasAnyVisibleWindow,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001000 boolean comingFromPendingIntent) {
1001
1002 final long nowElapsed = SystemClock.elapsedRealtime();
1003 final long nowUptime = SystemClock.uptimeMillis();
1004 final LogMaker builder = new LogMaker(ACTION_ACTIVITY_START);
1005 builder.setTimestamp(System.currentTimeMillis());
1006 builder.addTaggedData(FIELD_CALLING_UID, callingUid);
1007 builder.addTaggedData(FIELD_CALLING_PACKAGE_NAME, callingPackage);
1008 builder.addTaggedData(FIELD_CALLING_UID_PROC_STATE,
1009 processStateAmToProto(callingUidProcState));
1010 builder.addTaggedData(FIELD_CALLING_UID_HAS_ANY_VISIBLE_WINDOW,
1011 callingUidHasAnyVisibleWindow ? 1 : 0);
1012 builder.addTaggedData(FIELD_REAL_CALLING_UID, realCallingUid);
1013 builder.addTaggedData(FIELD_REAL_CALLING_UID_PROC_STATE,
1014 processStateAmToProto(realCallingUidProcState));
1015 builder.addTaggedData(FIELD_REAL_CALLING_UID_HAS_ANY_VISIBLE_WINDOW,
1016 realCallingUidHasAnyVisibleWindow ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001017 builder.addTaggedData(FIELD_COMING_FROM_PENDING_INTENT, comingFromPendingIntent ? 1 : 0);
Michal Karpinski8596ded2018-11-14 14:43:48 +00001018 if (intent != null) {
1019 builder.addTaggedData(FIELD_INTENT_ACTION, intent.getAction());
Michal Karpinski319069b2019-03-27 15:46:50 +00001020 ComponentName component = intent.getComponent();
1021 if (component != null) {
1022 builder.addTaggedData(FIELD_TARGET_SHORT_COMPONENT_NAME,
1023 component.flattenToShortString());
1024 }
Michal Karpinski8596ded2018-11-14 14:43:48 +00001025 }
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001026 if (callerApp != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001027 builder.addTaggedData(FIELD_PROCESS_RECORD_PROCESS_NAME, callerApp.mName);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001028 builder.addTaggedData(FIELD_PROCESS_RECORD_CUR_PROC_STATE,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001029 processStateAmToProto(callerApp.getCurrentProcState()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001030 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_CLIENT_ACTIVITIES,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001031 callerApp.hasClientActivities() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001032 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_FOREGROUND_SERVICES,
1033 callerApp.hasForegroundServices() ? 1 : 0);
1034 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_FOREGROUND_ACTIVITIES,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001035 callerApp.hasForegroundActivities() ? 1 : 0);
1036 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_TOP_UI, callerApp.hasTopUi() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001037 builder.addTaggedData(FIELD_PROCESS_RECORD_HAS_OVERLAY_UI,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001038 callerApp.hasOverlayUi() ? 1 : 0);
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001039 builder.addTaggedData(FIELD_PROCESS_RECORD_PENDING_UI_CLEAN,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001040 callerApp.hasPendingUiClean() ? 1 : 0);
1041 if (callerApp.getInteractionEventTime() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001042 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_LAST_INTERACTION_EVENT,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001043 (nowElapsed - callerApp.getInteractionEventTime()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001044 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001045 if (callerApp.getFgInteractionTime() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001046 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_FG_INTERACTION,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001047 (nowElapsed - callerApp.getFgInteractionTime()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001048 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001049 if (callerApp.getWhenUnimportant() != 0) {
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001050 builder.addTaggedData(FIELD_PROCESS_RECORD_MILLIS_SINCE_UNIMPORTANT,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001051 (nowUptime - callerApp.getWhenUnimportant()));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001052 }
1053 }
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001054 mMetricsLogger.write(builder);
1055 }
1056
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001057 private void logAppStartMemoryStateCapture(TransitionInfoSnapshot info) {
Ng Zhi An83473542018-02-20 09:02:14 -08001058 if (info.processRecord == null) {
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001059 if (DEBUG_METRICS) Slog.i(TAG, "logAppStartMemoryStateCapture processRecord null");
1060 return;
1061 }
1062
Wale Ogunwalef6733932018-06-27 05:14:34 -07001063 final int pid = info.processRecord.getPid();
Ng Zhi An83473542018-02-20 09:02:14 -08001064 final int uid = info.applicationInfo.uid;
Rajeev Kumarbfcd9202018-03-02 22:42:13 +00001065 final MemoryStat memoryStat = readMemoryStatFromFilesystem(uid, pid);
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001066 if (memoryStat == null) {
1067 if (DEBUG_METRICS) Slog.i(TAG, "logAppStartMemoryStateCapture memoryStat null");
1068 return;
1069 }
1070
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08001071 FrameworkStatsLog.write(
1072 FrameworkStatsLog.APP_START_MEMORY_STATE_CAPTURED,
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001073 uid,
Ng Zhi An83473542018-02-20 09:02:14 -08001074 info.processName,
1075 info.launchedActivityName,
Ng Zhi Anbbefdec2018-01-30 17:12:39 -08001076 memoryStat.pgfault,
1077 memoryStat.pgmajfault,
1078 memoryStat.rssInBytes,
1079 memoryStat.cacheInBytes,
1080 memoryStat.swapInBytes);
1081 }
1082
Calin Juravle759fbda2018-02-20 19:52:30 +00001083 private ArtManagerInternal getArtManagerInternal() {
1084 if (mArtManagerInternal == null) {
1085 // Note that this may be null.
1086 // ArtManagerInternal is registered during PackageManagerService
1087 // initialization which happens after ActivityManagerService.
1088 mArtManagerInternal = LocalServices.getService(ArtManagerInternal.class);
1089 }
1090 return mArtManagerInternal;
1091 }
Vishnu Nair132ee832018-09-28 15:00:05 -07001092
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001093 /** Starts trace for an activity is actually launching. */
1094 private void startLaunchTrace(@NonNull TransitionInfo info) {
1095 if (DEBUG_METRICS) Slog.i(TAG, "startLaunchTrace " + info);
1096 if (!Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
Vishnu Nair132ee832018-09-28 15:00:05 -07001097 return;
1098 }
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001099 info.mLaunchTraceName = "launching: " + info.mLastLaunchedActivity.packageName;
Riddle Hsue8d3d192019-11-26 18:56:39 +08001100 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName,
1101 (int) info.mTransitionStartTimeNs /* cookie */);
Vishnu Nair132ee832018-09-28 15:00:05 -07001102 }
1103
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001104 /** Stops trace for the launch is completed or cancelled. */
1105 private void stopLaunchTrace(@NonNull TransitionInfo info) {
1106 if (DEBUG_METRICS) Slog.i(TAG, "stopLaunchTrace " + info);
1107 if (info.mLaunchTraceName == null) {
Vishnu Nair132ee832018-09-28 15:00:05 -07001108 return;
1109 }
Riddle Hsue8d3d192019-11-26 18:56:39 +08001110 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName,
1111 (int) info.mTransitionStartTimeNs /* cookie */);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001112 info.mLaunchTraceName = null;
Vishnu Nair132ee832018-09-28 15:00:05 -07001113 }
Igor Murashkin212d06c2018-10-22 16:34:39 -07001114
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001115 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
1116 return mLaunchObserver;
1117 }
1118
Igor Murashkin212d06c2018-10-22 16:34:39 -07001119 /** Notify the {@link ActivityMetricsLaunchObserver} that a new launch sequence has begun. */
Yan Wangd47f90b2019-10-03 19:17:15 -07001120 private void launchObserverNotifyIntentStarted(Intent intent, long timestampNs) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001121 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1122 "MetricsLogger:launchObserverNotifyIntentStarted");
1123
1124 // Beginning a launch is timing sensitive and so should be observed as soon as possible.
Yan Wangd47f90b2019-10-03 19:17:15 -07001125 mLaunchObserver.onIntentStarted(intent, timestampNs);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001126
1127 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001128 }
1129
1130 /**
1131 * Notify the {@link ActivityMetricsLaunchObserver} that the previous launch sequence has
1132 * aborted due to intent failure (e.g. intent resolve failed or security error, etc) or
1133 * intent being delivered to the top running activity.
1134 */
1135 private void launchObserverNotifyIntentFailed() {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001136 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1137 "MetricsLogger:launchObserverNotifyIntentFailed");
1138
1139 mLaunchObserver.onIntentFailed();
1140
1141 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001142 }
1143
1144 /**
1145 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence's activity
1146 * has started.
1147 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001148 private void launchObserverNotifyActivityLaunched(TransitionInfo info) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001149 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1150 "MetricsLogger:launchObserverNotifyActivityLaunched");
1151
Igor Murashkin212d06c2018-10-22 16:34:39 -07001152 @ActivityMetricsLaunchObserver.Temperature int temperature =
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001153 convertTransitionTypeToLaunchObserverTemperature(info.mTransitionType);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001154
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001155 // Beginning a launch is timing sensitive and so should be observed as soon as possible.
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001156 mLaunchObserver.onActivityLaunched(convertActivityRecordToProto(info.mLastLaunchedActivity),
1157 temperature);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001158
1159 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001160 }
1161
1162 /**
Yan Wang9eac5ec2019-09-30 15:42:18 -07001163 * Notifies the {@link ActivityMetricsLaunchObserver} the reportFullDrawn event.
1164 */
Yan Wangd47f90b2019-10-03 19:17:15 -07001165 private void launchObserverNotifyReportFullyDrawn(ActivityRecord r, long timestampNs) {
Yan Wang9eac5ec2019-09-30 15:42:18 -07001166 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1167 "MetricsLogger:launchObserverNotifyReportFullyDrawn");
Yan Wangd47f90b2019-10-03 19:17:15 -07001168 mLaunchObserver.onReportFullyDrawn(convertActivityRecordToProto(r), timestampNs);
Yan Wang9eac5ec2019-09-30 15:42:18 -07001169 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1170 }
1171
1172 /**
Igor Murashkin212d06c2018-10-22 16:34:39 -07001173 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence is
1174 * cancelled.
1175 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001176 private void launchObserverNotifyActivityLaunchCancelled(TransitionInfo info) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001177 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1178 "MetricsLogger:launchObserverNotifyActivityLaunchCancelled");
Igor Murashkin212d06c2018-10-22 16:34:39 -07001179
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001180 final @ActivityMetricsLaunchObserver.ActivityRecordProto byte[] activityRecordProto =
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001181 info != null ? convertActivityRecordToProto(info.mLastLaunchedActivity) : null;
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001182
1183 mLaunchObserver.onActivityLaunchCancelled(activityRecordProto);
1184
1185 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Igor Murashkin212d06c2018-10-22 16:34:39 -07001186 }
1187
1188 /**
1189 * Notify the {@link ActivityMetricsLaunchObserver} that the current launch sequence's activity
1190 * has fully finished (successfully).
1191 */
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001192 private void launchObserverNotifyActivityLaunchFinished(TransitionInfo info, long timestampNs) {
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001193 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1194 "MetricsLogger:launchObserverNotifyActivityLaunchFinished");
Igor Murashkin212d06c2018-10-22 16:34:39 -07001195
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001196 mLaunchObserver.onActivityLaunchFinished(
1197 convertActivityRecordToProto(info.mLastLaunchedActivity), timestampNs);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001198
1199 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1200 }
1201
1202 @VisibleForTesting
1203 static @ActivityMetricsLaunchObserver.ActivityRecordProto byte[]
1204 convertActivityRecordToProto(ActivityRecord record) {
1205 // May take non-negligible amount of time to convert ActivityRecord into a proto,
1206 // so track the time.
1207 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1208 "MetricsLogger:convertActivityRecordToProto");
1209
1210 // There does not appear to be a way to 'reset' a ProtoOutputBuffer stream,
1211 // so create a new one every time.
1212 final ProtoOutputStream protoOutputStream =
1213 new ProtoOutputStream(LAUNCH_OBSERVER_ACTIVITY_RECORD_PROTO_CHUNK_SIZE);
1214 // Write this data out as the top-most ActivityRecordProto (i.e. it is not a sub-object).
Wale Ogunwalef342f062020-01-27 07:34:13 -08001215 record.dumpDebug(protoOutputStream, WindowTraceLogLevel.ALL);
Igor Murashkinc0b47e42018-11-07 15:54:18 -08001216 final byte[] bytes = protoOutputStream.getBytes();
1217
1218 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1219
1220 return bytes;
Igor Murashkin212d06c2018-10-22 16:34:39 -07001221 }
1222
1223 private static @ActivityMetricsLaunchObserver.Temperature int
1224 convertTransitionTypeToLaunchObserverTemperature(int transitionType) {
1225 switch (transitionType) {
1226 case TYPE_TRANSITION_WARM_LAUNCH:
1227 return ActivityMetricsLaunchObserver.TEMPERATURE_WARM;
1228 case TYPE_TRANSITION_HOT_LAUNCH:
1229 return ActivityMetricsLaunchObserver.TEMPERATURE_HOT;
1230 case TYPE_TRANSITION_COLD_LAUNCH:
1231 return ActivityMetricsLaunchObserver.TEMPERATURE_COLD;
1232 default:
1233 return -1;
1234 }
1235 }
Filip Gruszczynski77d94482015-12-11 13:59:52 -08001236}