• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.wm;
18 
19 import static android.Manifest.permission.ACTIVITY_EMBEDDING;
20 import static android.Manifest.permission.CAMERA;
21 import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
22 import static android.Manifest.permission.MANAGE_ACTIVITY_TASKS;
23 import static android.Manifest.permission.START_ANY_ACTIVITY;
24 import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
25 import static android.app.ActivityManager.START_DELIVERED_TO_TOP;
26 import static android.app.ActivityManager.START_FLAG_DEBUG;
27 import static android.app.ActivityManager.START_FLAG_NATIVE_DEBUGGING;
28 import static android.app.ActivityManager.START_FLAG_TRACK_ALLOCATION;
29 import static android.app.ActivityManager.START_TASK_TO_FRONT;
30 import static android.app.ActivityOptions.ANIM_REMOTE_ANIMATION;
31 import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
32 import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
33 import static android.app.WaitResult.INVALID_DELAY;
34 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
35 import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
36 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
37 import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
38 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
39 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
40 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
41 import static android.content.pm.PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY;
42 import static android.content.pm.PackageManager.PERMISSION_DENIED;
43 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
44 import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
45 import static android.os.Process.INVALID_UID;
46 import static android.os.Process.SYSTEM_UID;
47 import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
48 import static android.view.Display.DEFAULT_DISPLAY;
49 import static android.view.WindowManager.TRANSIT_TO_FRONT;
50 
51 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_STATES;
52 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_TASKS;
53 import static com.android.server.wm.ActivityRecord.State.PAUSED;
54 import static com.android.server.wm.ActivityRecord.State.PAUSING;
55 import static com.android.server.wm.ActivityRecord.State.RESTARTING_PROCESS;
56 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
57 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
58 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IDLE;
59 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS;
60 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ROOT_TASK;
61 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
62 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IDLE;
63 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_PAUSE;
64 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS;
65 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_ROOT_TASK;
66 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
67 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
68 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
69 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
70 import static com.android.server.wm.ActivityTaskManagerService.ANIMATE;
71 import static com.android.server.wm.ActivityTaskManagerService.H.FIRST_SUPERVISOR_TASK_MSG;
72 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
73 import static com.android.server.wm.LockTaskController.LOCK_TASK_AUTH_ALLOWLISTED;
74 import static com.android.server.wm.LockTaskController.LOCK_TASK_AUTH_LAUNCHABLE;
75 import static com.android.server.wm.LockTaskController.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
76 import static com.android.server.wm.RootWindowContainer.MATCH_ATTACHED_TASK_OR_RECENT_TASKS;
77 import static com.android.server.wm.RootWindowContainer.MATCH_ATTACHED_TASK_OR_RECENT_TASKS_AND_RESTORE;
78 import static com.android.server.wm.Task.FLAG_FORCE_HIDDEN_FOR_PINNED_TASK;
79 import static com.android.server.wm.Task.REPARENT_KEEP_ROOT_TASK_AT_FRONT;
80 import static com.android.server.wm.Task.TAG_CLEANUP;
81 import static com.android.server.wm.WindowContainer.POSITION_TOP;
82 
83 import android.Manifest;
84 import android.annotation.Nullable;
85 import android.app.Activity;
86 import android.app.ActivityManager;
87 import android.app.ActivityManagerInternal;
88 import android.app.ActivityOptions;
89 import android.app.AppOpsManager;
90 import android.app.AppOpsManagerInternal;
91 import android.app.IActivityClientController;
92 import android.app.ProfilerInfo;
93 import android.app.ResultInfo;
94 import android.app.TaskInfo;
95 import android.app.WaitResult;
96 import android.app.servertransaction.ActivityLifecycleItem;
97 import android.app.servertransaction.ClientTransaction;
98 import android.app.servertransaction.LaunchActivityItem;
99 import android.app.servertransaction.PauseActivityItem;
100 import android.app.servertransaction.ResumeActivityItem;
101 import android.content.ComponentName;
102 import android.content.Intent;
103 import android.content.pm.ActivityInfo;
104 import android.content.pm.ApplicationInfo;
105 import android.content.pm.PackageInfo;
106 import android.content.pm.PackageManager;
107 import android.content.pm.PackageManagerInternal;
108 import android.content.pm.ResolveInfo;
109 import android.content.pm.UserInfo;
110 import android.content.res.Configuration;
111 import android.graphics.Rect;
112 import android.hardware.SensorPrivacyManager;
113 import android.hardware.SensorPrivacyManagerInternal;
114 import android.os.Binder;
115 import android.os.Build;
116 import android.os.Bundle;
117 import android.os.Debug;
118 import android.os.Handler;
119 import android.os.IBinder;
120 import android.os.Looper;
121 import android.os.Message;
122 import android.os.PowerManager;
123 import android.os.RemoteException;
124 import android.os.SystemClock;
125 import android.os.Trace;
126 import android.os.UserHandle;
127 import android.os.UserManager;
128 import android.os.WorkSource;
129 import android.provider.MediaStore;
130 import android.util.ArrayMap;
131 import android.util.MergedConfiguration;
132 import android.util.Slog;
133 import android.util.SparseArray;
134 import android.util.SparseIntArray;
135 import android.view.Display;
136 
137 import com.android.internal.R;
138 import com.android.internal.annotations.GuardedBy;
139 import com.android.internal.annotations.VisibleForTesting;
140 import com.android.internal.content.ReferrerIntent;
141 import com.android.internal.protolog.common.ProtoLog;
142 import com.android.internal.util.ArrayUtils;
143 import com.android.internal.util.function.pooled.PooledConsumer;
144 import com.android.internal.util.function.pooled.PooledLambda;
145 import com.android.server.LocalServices;
146 import com.android.server.am.ActivityManagerService;
147 import com.android.server.am.HostingRecord;
148 import com.android.server.am.UserState;
149 import com.android.server.pm.PackageManagerServiceUtils;
150 import com.android.server.utils.Slogf;
151 import com.android.server.wm.ActivityMetricsLogger.LaunchingState;
152 
153 import java.io.FileDescriptor;
154 import java.io.PrintWriter;
155 import java.util.ArrayList;
156 import java.util.List;
157 import java.util.function.Consumer;
158 
159 // TODO: This class has become a dumping ground. Let's
160 // - Move things relating to the hierarchy to RootWindowContainer
161 // - Move things relating to activity life cycles to maybe a new class called ActivityLifeCycler
162 // - Move interface things to ActivityTaskManagerService.
163 // - All other little things to other files.
164 public class ActivityTaskSupervisor implements RecentTasks.Callbacks {
165     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskSupervisor" : TAG_ATM;
166     private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
167     private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
168     private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
169     private static final String TAG_ROOT_TASK = TAG + POSTFIX_ROOT_TASK;
170     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
171     static final String TAG_TASKS = TAG + POSTFIX_TASKS;
172 
173     /** How long we wait until giving up on the last activity telling us it is idle. */
174     private static final int IDLE_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
175 
176     /** How long we can hold the sleep wake lock before giving up. */
177     private static final int SLEEP_TIMEOUT = 5 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
178 
179     // How long we can hold the launch wake lock before giving up.
180     private static final int LAUNCH_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
181 
182     /** How long we wait until giving up on the activity telling us it released the top state. */
183     private static final int TOP_RESUMED_STATE_LOSS_TIMEOUT = 500;
184 
185     private static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_TASK_MSG;
186     private static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_TASK_MSG + 1;
187     private static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_TASK_MSG + 2;
188     private static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_TASK_MSG + 3;
189     private static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_TASK_MSG + 4;
190     private static final int PROCESS_STOPPING_AND_FINISHING_MSG = FIRST_SUPERVISOR_TASK_MSG + 5;
191     private static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_TASK_MSG + 12;
192     private static final int RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG = FIRST_SUPERVISOR_TASK_MSG + 13;
193     private static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_TASK_MSG + 14;
194     private static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_TASK_MSG + 15;
195     private static final int START_HOME_MSG = FIRST_SUPERVISOR_TASK_MSG + 16;
196     private static final int TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG = FIRST_SUPERVISOR_TASK_MSG + 17;
197 
198     // Used to indicate that windows of activities should be preserved during the resize.
199     static final boolean PRESERVE_WINDOWS = true;
200 
201     // Used to indicate if an object (e.g. task) should be moved/created
202     // at the top of its container (e.g. root task).
203     static final boolean ON_TOP = true;
204 
205     // Don't execute any calls to resume.
206     static final boolean DEFER_RESUME = true;
207 
208     // Used to indicate that a task is removed it should also be removed from recents.
209     static final boolean REMOVE_FROM_RECENTS = true;
210 
211     /** True if the docked root task is currently being resized. */
212     private boolean mDockedRootTaskResizing;
213 
214     // Activity actions an app cannot start if it uses a permission which is not granted.
215     private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION =
216             new ArrayMap<>();
217 
218     static {
ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE, Manifest.permission.CAMERA)219         ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE,
220                 Manifest.permission.CAMERA);
ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE, Manifest.permission.CAMERA)221         ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE,
222                 Manifest.permission.CAMERA);
ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL, Manifest.permission.CALL_PHONE)223         ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL,
224                 Manifest.permission.CALL_PHONE);
225     }
226 
227     /** Action restriction: launching the activity is not restricted. */
228     private static final int ACTIVITY_RESTRICTION_NONE = 0;
229     /** Action restriction: launching the activity is restricted by a permission. */
230     private static final int ACTIVITY_RESTRICTION_PERMISSION = 1;
231     /** Action restriction: launching the activity is restricted by an app op. */
232     private static final int ACTIVITY_RESTRICTION_APPOP = 2;
233 
234     // For debugging to make sure the caller when acquiring/releasing our
235     // wake lock is the system process.
236     private static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
237     /** The number of distinct task ids that can be assigned to the tasks of a single user */
238     private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
239 
240     final ActivityTaskManagerService mService;
241     RootWindowContainer mRootWindowContainer;
242 
243     /** The historial list of recent tasks including inactive tasks */
244     RecentTasks mRecentTasks;
245 
246     /** Helper class to abstract out logic for fetching the set of currently running tasks */
247     private RunningTasks mRunningTasks;
248 
249     /** Helper for {@link Task#fillTaskInfo}. */
250     final TaskInfoHelper mTaskInfoHelper = new TaskInfoHelper();
251 
252     private final ActivityTaskSupervisorHandler mHandler;
253     final Looper mLooper;
254 
255     /** Short cut */
256     private WindowManagerService mWindowManager;
257 
258     private AppOpsManager mAppOpsManager;
259 
260     /** Common synchronization logic used to save things to disks. */
261     PersisterQueue mPersisterQueue;
262     LaunchParamsPersister mLaunchParamsPersister;
263     private LaunchParamsController mLaunchParamsController;
264 
265     /**
266      * The processes with changed states that should eventually call
267      * {@link WindowProcessController#computeProcessActivityState}.
268      */
269     private final ArrayList<WindowProcessController> mActivityStateChangedProcs = new ArrayList<>();
270 
271     /**
272      * Maps the task identifier that activities are currently being started in to the userId of the
273      * task. Each time a new task is created, the entry for the userId of the task is incremented
274      */
275     private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20);
276 
277     /** List of requests waiting for the target activity to be launched or visible. */
278     private final ArrayList<WaitInfo> mWaitingActivityLaunched = new ArrayList<>();
279 
280     /** List of activities that are ready to be stopped, but waiting for the next activity to
281      * settle down before doing so. */
282     final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>();
283 
284     /** List of activities that are ready to be finished, but waiting for the previous activity to
285      * settle down before doing so.  It contains ActivityRecord objects. */
286     final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>();
287 
288     /**
289      * Activities that specify No History must be removed once the user navigates away from them.
290      * If the device goes to sleep with such an activity in the paused state then we save it
291      * here and finish it later if another activity replaces it on wakeup.
292      */
293     final ArrayList<ActivityRecord> mNoHistoryActivities = new ArrayList<>();
294 
295     /** List of activities whose multi-window mode changed that we need to report to the
296      * application */
297     private final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
298 
299     /** List of activities whose picture-in-picture mode changed that we need to report to the
300      * application */
301     private final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
302 
303     /**
304      * Animations that for the current transition have requested not to
305      * be considered for the transition animation.
306      */
307     final ArrayList<ActivityRecord> mNoAnimActivities = new ArrayList<>();
308 
309     /**
310      * Cached value of the topmost resumed activity in the system. Updated when new activity is
311      * resumed.
312      */
313     private ActivityRecord mTopResumedActivity;
314 
315     /**
316      * Flag indicating whether we're currently waiting for the previous top activity to handle the
317      * loss of the state and report back before making new activity top resumed.
318      */
319     private boolean mTopResumedActivityWaitingForPrev;
320 
321     /** The target root task bounds for the picture-in-picture mode changed that we need to
322      * report to the application */
323     private Rect mPipModeChangedTargetRootTaskBounds;
324 
325     /** Used on user changes */
326     final ArrayList<UserState> mStartingUsers = new ArrayList<>();
327 
328     /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity
329      * is being brought in front of us. */
330     boolean mUserLeaving = false;
331 
332     /**
333      * The system chooser activity which worked as a delegate of
334      * {@link com.android.internal.app.ResolverActivity}.
335      */
336     private ComponentName mSystemChooserActivity;
337 
338     /**
339      * We don't want to allow the device to go to sleep while in the process
340      * of launching an activity.  This is primarily to allow alarm intent
341      * receivers to launch an activity and get that to run before the device
342      * goes back to sleep.
343      */
344     PowerManager.WakeLock mLaunchingActivityWakeLock;
345 
346     /**
347      * Set when the system is going to sleep, until we have
348      * successfully paused the current activity and released our wake lock.
349      * At that point the system is allowed to actually sleep.
350      */
351     PowerManager.WakeLock mGoingToSleepWakeLock;
352 
353     /**
354      * Used to keep {@link RootWindowContainer#ensureActivitiesVisible} from being entered
355      * recursively. And only update keyguard states once the nested updates are done.
356      */
357     private int mVisibilityTransactionDepth;
358 
359     /**
360      * Whether to the visibility updates that started from {@code RootWindowContainer} should be
361      * deferred.
362      */
363     private boolean mDeferRootVisibilityUpdate;
364 
365     private ActivityMetricsLogger mActivityMetricsLogger;
366 
367     /** Check if placing task or activity on specified display is allowed. */
canPlaceEntityOnDisplay(int displayId, int callingPid, int callingUid, ActivityInfo activityInfo)368     boolean canPlaceEntityOnDisplay(int displayId, int callingPid, int callingUid,
369             ActivityInfo activityInfo) {
370         return canPlaceEntityOnDisplay(displayId, callingPid, callingUid, null /* task */,
371                 activityInfo);
372     }
373 
canPlaceEntityOnDisplay(int displayId, int callingPid, int callingUid, Task task)374     boolean canPlaceEntityOnDisplay(int displayId, int callingPid, int callingUid, Task task) {
375         return canPlaceEntityOnDisplay(displayId, callingPid, callingUid, task,
376                 null /* activityInfo */);
377     }
378 
canPlaceEntityOnDisplay(int displayId, int callingPid, int callingUid, Task task, ActivityInfo activityInfo)379     private boolean canPlaceEntityOnDisplay(int displayId, int callingPid, int callingUid,
380             Task task, ActivityInfo activityInfo) {
381         if (displayId == DEFAULT_DISPLAY) {
382             // No restrictions for the default display.
383             return true;
384         }
385         if (!mService.mSupportsMultiDisplay) {
386             // Can't launch on secondary displays if feature is not supported.
387             return false;
388         }
389 
390         if (!isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, displayId, activityInfo)) {
391             // Can't place activities to a display that has restricted launch rules.
392             // In this case the request should be made by explicitly adding target display id and
393             // by caller with corresponding permissions. See #isCallerAllowedToLaunchOnDisplay().
394             return false;
395         }
396 
397         final DisplayContent displayContent =
398                 mRootWindowContainer.getDisplayContentOrCreate(displayId);
399         if (displayContent != null && displayContent.mDwpcHelper.hasController()) {
400             final ArrayList<ActivityInfo> activities = new ArrayList<>();
401             if (activityInfo != null) {
402                 activities.add(activityInfo);
403             }
404             if (task != null) {
405                 task.forAllActivities((r) -> {
406                     activities.add(r.info);
407                 });
408             }
409             if (!displayContent.mDwpcHelper.canContainActivities(activities,
410                     displayContent.getWindowingMode())) {
411                 return false;
412             }
413         }
414 
415         return true;
416     }
417 
418     /**
419      * Used to keep track whether app visibilities got changed since the last pause. Useful to
420      * determine whether to invoke the task stack change listener after pausing.
421      */
422     boolean mAppVisibilitiesChangedSinceLastPause;
423 
424     private KeyguardController mKeyguardController;
425 
426     private PowerManager mPowerManager;
427     private int mDeferResumeCount;
428 
429     private boolean mInitialized;
430 
ActivityTaskSupervisor(ActivityTaskManagerService service, Looper looper)431     public ActivityTaskSupervisor(ActivityTaskManagerService service, Looper looper) {
432         mService = service;
433         mLooper = looper;
434         mHandler = new ActivityTaskSupervisorHandler(looper);
435     }
436 
initialize()437     public void initialize() {
438         if (mInitialized) {
439             return;
440         }
441 
442         mInitialized = true;
443         setRunningTasks(new RunningTasks());
444 
445         mActivityMetricsLogger = new ActivityMetricsLogger(this, mHandler.getLooper());
446         mKeyguardController = new KeyguardController(mService, this);
447 
448         mPersisterQueue = new PersisterQueue();
449         mLaunchParamsPersister = new LaunchParamsPersister(mPersisterQueue, this);
450         mLaunchParamsController = new LaunchParamsController(mService, mLaunchParamsPersister);
451         mLaunchParamsController.registerDefaultModifiers(this);
452     }
453 
onSystemReady()454     void onSystemReady() {
455         mLaunchParamsPersister.onSystemReady();
456     }
457 
onUserUnlocked(int userId)458     void onUserUnlocked(int userId) {
459         // Only start persisting when the first user is unlocked. The method call is
460         // idempotent so there is no side effect to call it again when the second user is
461         // unlocked.
462         mPersisterQueue.startPersisting();
463         mLaunchParamsPersister.onUnlockUser(userId);
464 
465         // Need to launch home again for those displays that do not have encryption aware home app.
466         scheduleStartHome("userUnlocked");
467     }
468 
getActivityMetricsLogger()469     public ActivityMetricsLogger getActivityMetricsLogger() {
470         return mActivityMetricsLogger;
471     }
472 
getKeyguardController()473     public KeyguardController getKeyguardController() {
474         return mKeyguardController;
475     }
476 
getSystemChooserActivity()477     ComponentName getSystemChooserActivity() {
478         if (mSystemChooserActivity == null) {
479             mSystemChooserActivity = ComponentName.unflattenFromString(
480                     mService.mContext.getResources().getString(R.string.config_chooserActivity));
481         }
482         return mSystemChooserActivity;
483     }
484 
setRecentTasks(RecentTasks recentTasks)485     void setRecentTasks(RecentTasks recentTasks) {
486         if (mRecentTasks != null) {
487             mRecentTasks.unregisterCallback(this);
488         }
489         mRecentTasks = recentTasks;
490         mRecentTasks.registerCallback(this);
491     }
492 
493     @VisibleForTesting
setRunningTasks(RunningTasks runningTasks)494     void setRunningTasks(RunningTasks runningTasks) {
495         mRunningTasks = runningTasks;
496     }
497 
getRunningTasks()498     RunningTasks getRunningTasks() {
499         return mRunningTasks;
500     }
501 
502     /**
503      * At the time when the constructor runs, the power manager has not yet been
504      * initialized.  So we initialize our wakelocks afterwards.
505      */
initPowerManagement()506     void initPowerManagement() {
507         mPowerManager = mService.mContext.getSystemService(PowerManager.class);
508         mGoingToSleepWakeLock = mPowerManager
509                 .newWakeLock(PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
510         mLaunchingActivityWakeLock = mPowerManager.newWakeLock(PARTIAL_WAKE_LOCK, "*launch*");
511         mLaunchingActivityWakeLock.setReferenceCounted(false);
512     }
513 
setWindowManager(WindowManagerService wm)514     void setWindowManager(WindowManagerService wm) {
515         mWindowManager = wm;
516         getKeyguardController().setWindowManager(wm);
517     }
518 
moveRecentsRootTaskToFront(String reason)519     void moveRecentsRootTaskToFront(String reason) {
520         final Task recentsRootTask = mRootWindowContainer.getDefaultTaskDisplayArea()
521                 .getRootTask(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_RECENTS);
522         if (recentsRootTask != null) {
523             recentsRootTask.moveToFront(reason);
524         }
525     }
526 
setNextTaskIdForUser(int taskId, int userId)527     void setNextTaskIdForUser(int taskId, int userId) {
528         final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
529         if (taskId > currentTaskId) {
530             mCurTaskIdForUser.put(userId, taskId);
531         }
532     }
533 
finishNoHistoryActivitiesIfNeeded(ActivityRecord next)534     void finishNoHistoryActivitiesIfNeeded(ActivityRecord next) {
535         for (int i = mNoHistoryActivities.size() - 1; i >= 0; --i) {
536             final ActivityRecord noHistoryActivity = mNoHistoryActivities.get(i);
537             if (!noHistoryActivity.finishing && noHistoryActivity != next
538                     && next.occludesParent()
539                     && noHistoryActivity.getDisplayId() == next.getDisplayId()) {
540                 ProtoLog.d(WM_DEBUG_STATES, "no-history finish of %s on new resume",
541                         noHistoryActivity);
542                 noHistoryActivity.finishIfPossible("resume-no-history", false /* oomAdj */);
543                 mNoHistoryActivities.remove(noHistoryActivity);
544             }
545         }
546     }
547 
nextTaskIdForUser(int taskId, int userId)548     private static int nextTaskIdForUser(int taskId, int userId) {
549         int nextTaskId = taskId + 1;
550         if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
551             // Wrap around as there will be smaller task ids that are available now.
552             nextTaskId -= MAX_TASK_IDS_PER_USER;
553         }
554         return nextTaskId;
555     }
556 
getNextTaskIdForUser()557     int getNextTaskIdForUser() {
558         return getNextTaskIdForUser(mRootWindowContainer.mCurrentUser);
559     }
560 
getNextTaskIdForUser(int userId)561     int getNextTaskIdForUser(int userId) {
562         final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
563         // for a userId u, a taskId can only be in the range
564         // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
565         // was 10, user 0 could only have taskIds 0 to 9, user 1: 10 to 19, user 2: 20 to 29, so on.
566         int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
567         while (mRecentTasks.containsTaskId(candidateTaskId, userId)
568                 || mRootWindowContainer.anyTaskForId(
569                         candidateTaskId, MATCH_ATTACHED_TASK_OR_RECENT_TASKS) != null) {
570             candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
571             if (candidateTaskId == currentTaskId) {
572                 // Something wrong!
573                 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
574                 throw new IllegalStateException("Cannot get an available task id."
575                         + " Reached limit of " + MAX_TASK_IDS_PER_USER
576                         + " running tasks per user.");
577             }
578         }
579         mCurTaskIdForUser.put(userId, candidateTaskId);
580         return candidateTaskId;
581     }
582 
waitActivityVisibleOrLaunched(WaitResult w, ActivityRecord r, LaunchingState launchingState)583     void waitActivityVisibleOrLaunched(WaitResult w, ActivityRecord r,
584             LaunchingState launchingState) {
585         if (w.result != ActivityManager.START_TASK_TO_FRONT
586                 && w.result != ActivityManager.START_SUCCESS) {
587             // Not a result code that can make activity visible or launched.
588             return;
589         }
590         final WaitInfo waitInfo = new WaitInfo(w, r.mActivityComponent, launchingState);
591         mWaitingActivityLaunched.add(waitInfo);
592         do {
593             try {
594                 mService.mGlobalLock.wait();
595             } catch (InterruptedException ignored) {
596             }
597         } while (mWaitingActivityLaunched.contains(waitInfo));
598     }
599 
cleanupActivity(ActivityRecord r)600     void cleanupActivity(ActivityRecord r) {
601         // Make sure this record is no longer in the pending finishes list.
602         // This could happen, for example, if we are trimming activities
603         // down to the max limit while they are still waiting to finish.
604         mFinishingActivities.remove(r);
605 
606         stopWaitingForActivityVisible(r);
607     }
608 
609     /** There is no valid launch time, just stop waiting. */
stopWaitingForActivityVisible(ActivityRecord r)610     void stopWaitingForActivityVisible(ActivityRecord r) {
611         reportActivityLaunched(false /* timeout */, r, WaitResult.INVALID_DELAY,
612                 WaitResult.LAUNCH_STATE_UNKNOWN);
613     }
614 
reportActivityLaunched(boolean timeout, ActivityRecord r, long totalTime, @WaitResult.LaunchState int launchState)615     void reportActivityLaunched(boolean timeout, ActivityRecord r, long totalTime,
616             @WaitResult.LaunchState int launchState) {
617         boolean changed = false;
618         for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
619             final WaitInfo info = mWaitingActivityLaunched.get(i);
620             if (!info.matches(r)) {
621                 continue;
622             }
623             final WaitResult w = info.mResult;
624             w.timeout = timeout;
625             w.who = r.mActivityComponent;
626             w.totalTime = totalTime;
627             w.launchState = launchState;
628             mWaitingActivityLaunched.remove(i);
629             changed = true;
630         }
631         if (changed) {
632             mService.mGlobalLock.notifyAll();
633         }
634     }
635 
reportWaitingActivityLaunchedIfNeeded(ActivityRecord r, int result)636     void reportWaitingActivityLaunchedIfNeeded(ActivityRecord r, int result) {
637         if (mWaitingActivityLaunched.isEmpty()) {
638             return;
639         }
640 
641         if (result != START_DELIVERED_TO_TOP && result != START_TASK_TO_FRONT) {
642             return;
643         }
644 
645         boolean changed = false;
646 
647         for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
648             final WaitInfo info = mWaitingActivityLaunched.get(i);
649             if (!info.matches(r)) {
650                 continue;
651             }
652             final WaitResult w = info.mResult;
653             w.result = result;
654             if (result == START_DELIVERED_TO_TOP) {
655                 // Unlike START_TASK_TO_FRONT, When an intent is delivered to top, there
656                 // will be no followup launch signals. Assign the result and launched component.
657                 w.who = r.mActivityComponent;
658                 mWaitingActivityLaunched.remove(i);
659                 changed = true;
660             }
661         }
662         if (changed) {
663             mService.mGlobalLock.notifyAll();
664         }
665     }
666 
resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags, ProfilerInfo profilerInfo)667     ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
668             ProfilerInfo profilerInfo) {
669         final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
670         if (aInfo != null) {
671             // Store the found target back into the intent, because now that
672             // we have it we never want to do this again.  For example, if the
673             // user navigates back to this point in the history, we should
674             // always restart the exact same activity.
675             intent.setComponent(new ComponentName(
676                     aInfo.applicationInfo.packageName, aInfo.name));
677 
678             final boolean requestDebug = (startFlags & (START_FLAG_DEBUG
679                     | START_FLAG_NATIVE_DEBUGGING | START_FLAG_TRACK_ALLOCATION)) != 0;
680             final boolean requestProfile = profilerInfo != null;
681             if (requestDebug || requestProfile) {
682                 final boolean debuggable = (Build.IS_DEBUGGABLE
683                         || (aInfo.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0)
684                         && !aInfo.processName.equals("system");
685                 if ((requestDebug && !debuggable) || (requestProfile
686                         && (!debuggable && !aInfo.applicationInfo.isProfileableByShell()))) {
687                     Slog.w(TAG, "Ignore debugging for non-debuggable app: " + aInfo.packageName);
688                 } else {
689                      // Mimic an AMS synchronous call by passing a message to AMS and wait for AMS
690                      // to notify us that the task has completed.
691                      // TODO(b/80414790) look into further untangling for the situation where the
692                      // caller is on the same thread as the handler we are posting to.
693                     synchronized (mService.mGlobalLock) {
694                         // Post message to AMS.
695                         mService.mH.post(() -> {
696                             try {
697                                 mService.mAmInternal.setDebugFlagsForStartingActivity(aInfo,
698                                         startFlags, profilerInfo, mService.mGlobalLock);
699                             } catch (Throwable e) {
700                                 // Simply ignore it because the debugging doesn't take effect.
701                                 Slog.w(TAG, e);
702                                 synchronized (mService.mGlobalLockWithoutBoost) {
703                                     mService.mGlobalLockWithoutBoost.notifyAll();
704                                 }
705                             }
706                         });
707                         try {
708                             mService.mGlobalLock.wait();
709                         } catch (InterruptedException ignore) {
710 
711                         }
712                     }
713                 }
714             }
715             final String intentLaunchToken = intent.getLaunchToken();
716             if (aInfo.launchToken == null && intentLaunchToken != null) {
717                 aInfo.launchToken = intentLaunchToken;
718             }
719         }
720         return aInfo;
721     }
722 
resolveIntent(Intent intent, String resolvedType, int userId, int flags, int filterCallingUid)723     ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags,
724             int filterCallingUid) {
725         try {
726             Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "resolveIntent");
727             int modifiedFlags = flags
728                     | PackageManager.MATCH_DEFAULT_ONLY | ActivityManagerService.STOCK_PM_FLAGS;
729             if (intent.isWebIntent()
730                         || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) {
731                 modifiedFlags |= PackageManager.MATCH_INSTANT;
732             }
733             int privateResolveFlags  = 0;
734             if (intent.isWebIntent()
735                         && (intent.getFlags() & Intent.FLAG_ACTIVITY_REQUIRE_NON_BROWSER) != 0) {
736                 privateResolveFlags |= PackageManagerInternal.RESOLVE_NON_BROWSER_ONLY;
737             }
738             if ((intent.getFlags() & Intent.FLAG_ACTIVITY_REQUIRE_DEFAULT) != 0) {
739                 privateResolveFlags |= PackageManagerInternal.RESOLVE_NON_RESOLVER_ONLY;
740             }
741 
742             // In order to allow cross-profile lookup, we clear the calling identity here.
743             // Note the binder identity won't affect the result, but filterCallingUid will.
744 
745             // Cross-user/profile call check are done at the entry points
746             // (e.g. AMS.startActivityAsUser).
747             final long token = Binder.clearCallingIdentity();
748             try {
749                 return mService.getPackageManagerInternalLocked().resolveIntent(
750                         intent, resolvedType, modifiedFlags, privateResolveFlags, userId, true,
751                         filterCallingUid);
752             } finally {
753                 Binder.restoreCallingIdentity(token);
754             }
755         } finally {
756             Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
757         }
758     }
759 
resolveActivity(Intent intent, String resolvedType, int startFlags, ProfilerInfo profilerInfo, int userId, int filterCallingUid)760     ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
761             ProfilerInfo profilerInfo, int userId, int filterCallingUid) {
762         final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId, 0, filterCallingUid);
763         return resolveActivity(intent, rInfo, startFlags, profilerInfo);
764     }
765 
realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig)766     boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
767             boolean andResume, boolean checkConfig) throws RemoteException {
768 
769         if (!mRootWindowContainer.allPausedActivitiesComplete()) {
770             // While there are activities pausing we skipping starting any new activities until
771             // pauses are complete. NOTE: that we also do this for activities that are starting in
772             // the paused state because they will first be resumed then paused on the client side.
773             ProtoLog.v(WM_DEBUG_STATES,
774                     "realStartActivityLocked: Skipping start of r=%s some activities pausing...",
775                     r);
776             return false;
777         }
778 
779         final Task task = r.getTask();
780         final Task rootTask = task.getRootTask();
781 
782         beginDeferResume();
783         // The LaunchActivityItem also contains process configuration, so the configuration change
784         // from WindowProcessController#setProcess can be deferred. The major reason is that if
785         // the activity has FixedRotationAdjustments, it needs to be applied with configuration.
786         // In general, this reduces a binder transaction if process configuration is changed.
787         proc.pauseConfigurationDispatch();
788 
789         try {
790             r.startFreezingScreenLocked(proc, 0);
791 
792             // schedule launch ticks to collect information about slow apps.
793             r.startLaunchTickingLocked();
794 
795             r.setProcess(proc);
796 
797             // Ensure activity is allowed to be resumed after process has set.
798             if (andResume && !r.canResumeByCompat()) {
799                 andResume = false;
800             }
801 
802             r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
803 
804             // Have the window manager re-evaluate the orientation of the screen based on the new
805             // activity order.  Note that as a result of this, it can call back into the activity
806             // manager with a new orientation.  We don't care about that, because the activity is
807             // not currently running so we are just restarting it anyway.
808             if (checkConfig) {
809                 // Deferring resume here because we're going to launch new activity shortly.
810                 // We don't want to perform a redundant launch of the same record while ensuring
811                 // configurations and trying to resume top activity of focused root task.
812                 mRootWindowContainer.ensureVisibilityAndConfig(r, r.getDisplayId(),
813                         false /* markFrozenIfConfigChanged */, true /* deferResume */);
814             }
815 
816             if (mKeyguardController.checkKeyguardVisibility(r) && r.allowMoveToFront()) {
817                 // We only set the visibility to true if the activity is not being launched in
818                 // background, and is allowed to be visible based on keyguard state. This avoids
819                 // setting this into motion in window manager that is later cancelled due to later
820                 // calls to ensure visible activities that set visibility back to false.
821                 r.setVisibility(true);
822             }
823 
824             final int applicationInfoUid =
825                     (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
826             if ((r.mUserId != proc.mUserId) || (r.info.applicationInfo.uid != applicationInfoUid)) {
827                 Slog.wtf(TAG,
828                         "User ID for activity changing for " + r
829                                 + " appInfo.uid=" + r.info.applicationInfo.uid
830                                 + " info.ai.uid=" + applicationInfoUid
831                                 + " old=" + r.app + " new=" + proc);
832             }
833 
834             // Send the controller to client if the process is the first time to launch activity.
835             // So the client can save binder transactions of getting the controller from activity
836             // task manager service.
837             final IActivityClientController activityClientController =
838                     proc.hasEverLaunchedActivity() ? null : mService.mActivityClientController;
839             r.launchCount++;
840             r.lastLaunchTime = SystemClock.uptimeMillis();
841             proc.setLastActivityLaunchTime(r.lastLaunchTime);
842 
843             if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
844 
845             final LockTaskController lockTaskController = mService.getLockTaskController();
846             if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE
847                     || task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV
848                     || (task.mLockTaskAuth == LOCK_TASK_AUTH_ALLOWLISTED
849                             && lockTaskController.getLockTaskModeState()
850                                     == LOCK_TASK_MODE_LOCKED)) {
851                 lockTaskController.startLockTaskMode(task, false, 0 /* blank UID */);
852             }
853 
854             try {
855                 if (!proc.hasThread()) {
856                     throw new RemoteException();
857                 }
858                 List<ResultInfo> results = null;
859                 List<ReferrerIntent> newIntents = null;
860                 if (andResume) {
861                     // We don't need to deliver new intents and/or set results if activity is going
862                     // to pause immediately after launch.
863                     results = r.results;
864                     newIntents = r.newIntents;
865                 }
866                 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
867                         "Launching: " + r + " savedState=" + r.getSavedState()
868                                 + " with results=" + results + " newIntents=" + newIntents
869                                 + " andResume=" + andResume);
870                 EventLogTags.writeWmRestartActivity(r.mUserId, System.identityHashCode(r),
871                         task.mTaskId, r.shortComponentName);
872                 if (r.isActivityTypeHome()) {
873                     // Home process is the root process of the task.
874                     updateHomeProcess(task.getBottomMostActivity().app);
875                 }
876                 mService.getPackageManagerInternalLocked().notifyPackageUse(
877                         r.intent.getComponent().getPackageName(), NOTIFY_PACKAGE_USE_ACTIVITY);
878                 r.forceNewConfig = false;
879                 mService.getAppWarningsLocked().onStartActivity(r);
880                 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
881 
882                 // Because we could be starting an Activity in the system process this may not go
883                 // across a Binder interface which would create a new Configuration. Consequently
884                 // we have to always create a new Configuration here.
885                 final Configuration procConfig = proc.prepareConfigurationForLaunchingActivity();
886                 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
887                         procConfig, r.getMergedOverrideConfiguration());
888                 r.setLastReportedConfiguration(mergedConfiguration);
889 
890                 logIfTransactionTooLarge(r.intent, r.getSavedState());
891 
892                 final TaskFragment organizedTaskFragment = r.getOrganizedTaskFragment();
893                 if (organizedTaskFragment != null) {
894                     // Sending TaskFragmentInfo to client to ensure the info is updated before
895                     // the activity creation.
896                     mService.mTaskFragmentOrganizerController.dispatchPendingInfoChangedEvent(
897                             organizedTaskFragment);
898                 }
899 
900                 // Create activity launch transaction.
901                 final ClientTransaction clientTransaction = ClientTransaction.obtain(
902                         proc.getThread(), r.token);
903 
904                 final boolean isTransitionForward = r.isTransitionForward();
905                 final IBinder fragmentToken = r.getTaskFragment().getFragmentToken();
906                 clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
907                         System.identityHashCode(r), r.info,
908                         // TODO: Have this take the merged configuration instead of separate global
909                         // and override configs.
910                         mergedConfiguration.getGlobalConfiguration(),
911                         mergedConfiguration.getOverrideConfiguration(), r.compat,
912                         r.getFilteredReferrer(r.launchedFromPackage), task.voiceInteractor,
913                         proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(),
914                         results, newIntents, r.takeOptions(), isTransitionForward,
915                         proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,
916                         r.shareableActivityToken, r.getLaunchedFromBubble(), fragmentToken));
917 
918                 // Set desired final state.
919                 final ActivityLifecycleItem lifecycleItem;
920                 if (andResume) {
921                     lifecycleItem = ResumeActivityItem.obtain(isTransitionForward,
922                             r.shouldSendCompatFakeFocus());
923                 } else {
924                     lifecycleItem = PauseActivityItem.obtain();
925                 }
926                 clientTransaction.setLifecycleStateRequest(lifecycleItem);
927 
928                 // Schedule transaction.
929                 mService.getLifecycleManager().scheduleTransaction(clientTransaction);
930 
931                 if (procConfig.seq > mRootWindowContainer.getConfiguration().seq) {
932                     // If the seq is increased, there should be something changed (e.g. registered
933                     // activity configuration).
934                     proc.setLastReportedConfiguration(procConfig);
935                 }
936                 if ((proc.mInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0
937                         && mService.mHasHeavyWeightFeature) {
938                     // This may be a heavy-weight process! Note that the package manager will ensure
939                     // that only activity can run in the main process of the .apk, which is the only
940                     // thing that will be considered heavy-weight.
941                     if (proc.mName.equals(proc.mInfo.packageName)) {
942                         if (mService.mHeavyWeightProcess != null
943                                 && mService.mHeavyWeightProcess != proc) {
944                             Slog.w(TAG, "Starting new heavy weight process " + proc
945                                     + " when already running "
946                                     + mService.mHeavyWeightProcess);
947                         }
948                         mService.setHeavyWeightProcess(r);
949                     }
950                 }
951 
952             } catch (RemoteException e) {
953                 if (r.launchFailed) {
954                     // This is the second time we failed -- finish activity and give up.
955                     Slog.e(TAG, "Second failure launching "
956                             + r.intent.getComponent().flattenToShortString() + ", giving up", e);
957                     proc.appDied("2nd-crash");
958                     r.finishIfPossible("2nd-crash", false /* oomAdj */);
959                     return false;
960                 }
961 
962                 // This is the first time we failed -- restart process and
963                 // retry.
964                 r.launchFailed = true;
965                 r.detachFromProcess();
966                 throw e;
967             }
968         } finally {
969             endDeferResume();
970             proc.resumeConfigurationDispatch();
971         }
972 
973         r.launchFailed = false;
974 
975         // TODO(lifecycler): Resume or pause requests are done as part of launch transaction,
976         // so updating the state should be done accordingly.
977         if (andResume && readyToResume()) {
978             // As part of the process of launching, ActivityThread also performs
979             // a resume.
980             rootTask.minimalResumeActivityLocked(r);
981         } else {
982             // This activity is not starting in the resumed state... which should look like we asked
983             // it to pause+stop (but remain visible), and it has done so and reported back the
984             // current icicle and other state.
985             ProtoLog.v(WM_DEBUG_STATES, "Moving to PAUSED: %s "
986                     + "(starting in paused state)", r);
987             r.setState(PAUSED, "realStartActivityLocked");
988             mRootWindowContainer.executeAppTransitionForAllDisplay();
989         }
990         // Perform OOM scoring after the activity state is set, so the process can be updated with
991         // the latest state.
992         proc.onStartActivity(mService.mTopProcessState, r.info);
993 
994         // Launch the new version setup screen if needed.  We do this -after-
995         // launching the initial activity (that is, home), so that it can have
996         // a chance to initialize itself while in the background, making the
997         // switch back to it faster and look better.
998         if (mRootWindowContainer.isTopDisplayFocusedRootTask(rootTask)) {
999             mService.getActivityStartController().startSetupActivity();
1000         }
1001 
1002         // Update any services we are bound to that might care about whether
1003         // their client may have activities.
1004         if (r.app != null) {
1005             r.app.updateServiceConnectionActivities();
1006         }
1007 
1008         return true;
1009     }
1010 
updateHomeProcess(WindowProcessController app)1011     void updateHomeProcess(WindowProcessController app) {
1012         if (app != null && mService.mHomeProcess != app) {
1013             scheduleStartHome("homeChanged");
1014             mService.mHomeProcess = app;
1015         }
1016     }
1017 
scheduleStartHome(String reason)1018     private void scheduleStartHome(String reason) {
1019         if (!mHandler.hasMessages(START_HOME_MSG)) {
1020             mHandler.obtainMessage(START_HOME_MSG, reason).sendToTarget();
1021         }
1022     }
1023 
logIfTransactionTooLarge(Intent intent, Bundle icicle)1024     private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
1025         int extrasSize = 0;
1026         if (intent != null) {
1027             final Bundle extras = intent.getExtras();
1028             if (extras != null) {
1029                 extrasSize = extras.getSize();
1030             }
1031         }
1032         int icicleSize = (icicle == null ? 0 : icicle.getSize());
1033         if (extrasSize + icicleSize > 200000) {
1034             Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
1035                     + ", icicle size: " + icicleSize);
1036         }
1037     }
1038 
startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig)1039     void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
1040         // Is this activity's application already running?
1041         final WindowProcessController wpc =
1042                 mService.getProcessController(r.processName, r.info.applicationInfo.uid);
1043 
1044         boolean knownToBeDead = false;
1045         if (wpc != null && wpc.hasThread()) {
1046             try {
1047                 realStartActivityLocked(r, wpc, andResume, checkConfig);
1048                 return;
1049             } catch (RemoteException e) {
1050                 Slog.w(TAG, "Exception when starting activity "
1051                         + r.intent.getComponent().flattenToShortString(), e);
1052             }
1053 
1054             // If a dead object exception was thrown -- fall through to
1055             // restart the application.
1056             knownToBeDead = true;
1057             // Remove the process record so it won't be considered as alive.
1058             mService.mProcessNames.remove(wpc.mName, wpc.mUid);
1059             mService.mProcessMap.remove(wpc.getPid());
1060         }
1061 
1062         r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
1063 
1064         final boolean isTop = andResume && r.isTopRunningActivity();
1065         mService.startProcessAsync(r, knownToBeDead, isTop,
1066                 isTop ? HostingRecord.HOSTING_TYPE_TOP_ACTIVITY
1067                         : HostingRecord.HOSTING_TYPE_ACTIVITY);
1068     }
1069 
checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, @Nullable String callingFeatureId, boolean ignoreTargetSecurity, boolean launchingInTask, WindowProcessController callerApp, ActivityRecord resultRecord, Task resultRootTask)1070     boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo, String resultWho,
1071             int requestCode, int callingPid, int callingUid, String callingPackage,
1072             @Nullable String callingFeatureId, boolean ignoreTargetSecurity,
1073             boolean launchingInTask, WindowProcessController callerApp, ActivityRecord resultRecord,
1074             Task resultRootTask) {
1075         final boolean isCallerRecents = mService.getRecentTasks() != null
1076                 && mService.getRecentTasks().isCallerRecents(callingUid);
1077         final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1078                 callingUid);
1079         if (startAnyPerm == PERMISSION_GRANTED || (isCallerRecents && launchingInTask)) {
1080             // If the caller has START_ANY_ACTIVITY, ignore all checks below. In addition, if the
1081             // caller is the recents component and we are specifically starting an activity in an
1082             // existing task, then also allow the activity to be fully relaunched.
1083             return true;
1084         }
1085         final int componentRestriction = getComponentRestrictionForCallingPackage(aInfo,
1086                 callingPackage, callingFeatureId, callingPid, callingUid, ignoreTargetSecurity);
1087         final int actionRestriction = getActionRestrictionForCallingPackage(
1088                 intent.getAction(), callingPackage, callingFeatureId, callingPid, callingUid);
1089         if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1090                 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1091             if (resultRecord != null) {
1092                 resultRecord.sendResult(INVALID_UID, resultWho, requestCode,
1093                         Activity.RESULT_CANCELED, null /* data */, null /* dataGrants */);
1094             }
1095             final String msg;
1096             if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1097                 msg = "Permission Denial: starting " + intent.toString()
1098                         + " from " + callerApp + " (pid=" + callingPid
1099                         + ", uid=" + callingUid + ")" + " with revoked permission "
1100                         + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1101             } else if (!aInfo.exported) {
1102                 msg = "Permission Denial: starting " + intent.toString()
1103                         + " from " + callerApp + " (pid=" + callingPid
1104                         + ", uid=" + callingUid + ")"
1105                         + " not exported from uid " + aInfo.applicationInfo.uid;
1106             } else {
1107                 msg = "Permission Denial: starting " + intent.toString()
1108                         + " from " + callerApp + " (pid=" + callingPid
1109                         + ", uid=" + callingUid + ")"
1110                         + " requires " + aInfo.permission;
1111             }
1112             Slog.w(TAG, msg);
1113             throw new SecurityException(msg);
1114         }
1115 
1116         if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1117             final String message = "Appop Denial: starting " + intent.toString()
1118                     + " from " + callerApp + " (pid=" + callingPid
1119                     + ", uid=" + callingUid + ")"
1120                     + " requires " + AppOpsManager.permissionToOp(
1121                             ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1122             Slog.w(TAG, message);
1123             return false;
1124         } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1125             final String message = "Appop Denial: starting " + intent.toString()
1126                     + " from " + callerApp + " (pid=" + callingPid
1127                     + ", uid=" + callingUid + ")"
1128                     + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1129             Slog.w(TAG, message);
1130             return false;
1131         }
1132 
1133         return true;
1134     }
1135 
1136     /** Check if caller is allowed to launch activities on specified task display area. */
isCallerAllowedToLaunchOnTaskDisplayArea(int callingPid, int callingUid, TaskDisplayArea taskDisplayArea, ActivityInfo aInfo)1137     boolean isCallerAllowedToLaunchOnTaskDisplayArea(int callingPid, int callingUid,
1138             TaskDisplayArea taskDisplayArea, ActivityInfo aInfo) {
1139         return isCallerAllowedToLaunchOnDisplay(callingPid, callingUid,
1140                 taskDisplayArea != null ? taskDisplayArea.getDisplayId() : DEFAULT_DISPLAY, aInfo);
1141     }
1142 
1143     /** Check if caller is allowed to launch activities on specified display. */
isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId, ActivityInfo aInfo)1144     boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId,
1145             ActivityInfo aInfo) {
1146         ProtoLog.d(WM_DEBUG_TASKS, "Launch on display check: displayId=%d callingPid=%d "
1147                 + "callingUid=%d", launchDisplayId, callingPid, callingUid);
1148 
1149         if (callingPid == -1 && callingUid == -1) {
1150             ProtoLog.d(WM_DEBUG_TASKS, "Launch on display check: no caller info, skip check");
1151             return true;
1152         }
1153 
1154         final DisplayContent displayContent =
1155                 mRootWindowContainer.getDisplayContentOrCreate(launchDisplayId);
1156         if (displayContent == null || displayContent.isRemoved()) {
1157             Slog.w(TAG, "Launch on display check: display not found");
1158             return false;
1159         }
1160 
1161         // Check if the caller has enough privileges to embed activities and launch to private
1162         // displays.
1163         final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
1164                 callingUid);
1165         if (startAnyPerm == PERMISSION_GRANTED) {
1166             ProtoLog.d(WM_DEBUG_TASKS, "Launch on display check: allow launch any on display");
1167             return true;
1168         }
1169 
1170         // Check if caller is already present on display
1171         final boolean uidPresentOnDisplay = displayContent.isUidPresent(callingUid);
1172 
1173         final Display display = displayContent.mDisplay;
1174         if (!display.isTrusted()) {
1175             // Limit launching on untrusted displays because their contents can be read from Surface
1176             // by apps that created them.
1177             if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
1178                 ProtoLog.d(WM_DEBUG_TASKS, "Launch on display check: disallow launch on "
1179                         + "virtual display for not-embedded activity.");
1180                 return false;
1181             }
1182             // Check if the caller is allowed to embed activities from other apps.
1183             if (mService.checkPermission(ACTIVITY_EMBEDDING, callingPid, callingUid)
1184                     == PERMISSION_DENIED && !uidPresentOnDisplay) {
1185                 ProtoLog.d(WM_DEBUG_TASKS, "Launch on display check: disallow activity "
1186                         + "embedding without permission.");
1187                 return false;
1188             }
1189         }
1190 
1191         if (!displayContent.isPrivate()) {
1192             // Anyone can launch on a public display.
1193             ProtoLog.d(WM_DEBUG_TASKS, "Launch on display check: allow launch on public "
1194                     + "display");
1195             return true;
1196         }
1197 
1198         // Check if the caller is the owner of the display.
1199         if (display.getOwnerUid() == callingUid) {
1200             ProtoLog.d(WM_DEBUG_TASKS, "Launch on display check: allow launch for owner of the"
1201                     + " display");
1202             return true;
1203         }
1204 
1205         if (uidPresentOnDisplay) {
1206             ProtoLog.d(WM_DEBUG_TASKS, "Launch on display check: allow launch for caller "
1207                     + "present on the display");
1208             return true;
1209         }
1210 
1211         Slog.w(TAG, "Launch on display check: denied");
1212         return false;
1213     }
1214 
getUserInfo(int userId)1215     UserInfo getUserInfo(int userId) {
1216         final long identity = Binder.clearCallingIdentity();
1217         try {
1218             return UserManager.get(mService.mContext).getUserInfo(userId);
1219         } finally {
1220             Binder.restoreCallingIdentity(identity);
1221         }
1222     }
1223 
getAppOpsManager()1224     private AppOpsManager getAppOpsManager() {
1225         if (mAppOpsManager == null) {
1226             mAppOpsManager = mService.mContext.getSystemService(AppOpsManager.class);
1227         }
1228         return mAppOpsManager;
1229     }
1230 
getComponentRestrictionForCallingPackage(ActivityInfo activityInfo, String callingPackage, @Nullable String callingFeatureId, int callingPid, int callingUid, boolean ignoreTargetSecurity)1231     private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
1232             String callingPackage, @Nullable String callingFeatureId, int callingPid,
1233             int callingUid, boolean ignoreTargetSecurity) {
1234         if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1235                 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
1236                 == PERMISSION_DENIED) {
1237             return ACTIVITY_RESTRICTION_PERMISSION;
1238         }
1239 
1240         if (activityInfo.permission == null) {
1241             return ACTIVITY_RESTRICTION_NONE;
1242         }
1243 
1244         final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1245         if (opCode == AppOpsManager.OP_NONE) {
1246             return ACTIVITY_RESTRICTION_NONE;
1247         }
1248 
1249         if (getAppOpsManager().noteOpNoThrow(opCode, callingUid,
1250                 callingPackage, callingFeatureId, "") != AppOpsManager.MODE_ALLOWED) {
1251             if (!ignoreTargetSecurity) {
1252                 return ACTIVITY_RESTRICTION_APPOP;
1253             }
1254         }
1255 
1256         return ACTIVITY_RESTRICTION_NONE;
1257     }
1258 
getActionRestrictionForCallingPackage(String action, String callingPackage, @Nullable String callingFeatureId, int callingPid, int callingUid)1259     private int getActionRestrictionForCallingPackage(String action, String callingPackage,
1260             @Nullable String callingFeatureId, int callingPid, int callingUid) {
1261         if (action == null) {
1262             return ACTIVITY_RESTRICTION_NONE;
1263         }
1264 
1265         String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1266         if (permission == null) {
1267             return ACTIVITY_RESTRICTION_NONE;
1268         }
1269 
1270         final PackageInfo packageInfo;
1271         try {
1272             packageInfo = mService.mContext.getPackageManager()
1273                     .getPackageInfoAsUser(callingPackage, PackageManager.GET_PERMISSIONS,
1274                             UserHandle.getUserId(callingUid));
1275         } catch (PackageManager.NameNotFoundException e) {
1276             Slog.i(TAG, "Cannot find package info for " + callingPackage);
1277             return ACTIVITY_RESTRICTION_NONE;
1278         }
1279 
1280         if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
1281             return ACTIVITY_RESTRICTION_NONE;
1282         }
1283 
1284         if (mService.checkPermission(permission, callingPid, callingUid) == PERMISSION_DENIED) {
1285             return ACTIVITY_RESTRICTION_PERMISSION;
1286         }
1287 
1288         final int opCode = AppOpsManager.permissionToOpCode(permission);
1289         if (opCode == AppOpsManager.OP_NONE) {
1290             return ACTIVITY_RESTRICTION_NONE;
1291         }
1292 
1293         if (getAppOpsManager().noteOpNoThrow(opCode, callingUid,
1294                 callingPackage, callingFeatureId, "") != AppOpsManager.MODE_ALLOWED) {
1295             if (CAMERA.equals(permission)) {
1296                 SensorPrivacyManagerInternal spmi =
1297                         LocalServices.getService(SensorPrivacyManagerInternal.class);
1298 
1299                 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
1300                 final boolean cameraPrivacyEnabled = spmi.isSensorPrivacyEnabled(
1301                         user.getIdentifier(), SensorPrivacyManager.Sensors.CAMERA);
1302                 if (cameraPrivacyEnabled) {
1303                     AppOpsManagerInternal aomi = LocalServices.getService(
1304                             AppOpsManagerInternal.class);
1305                     int numCameraRestrictions = aomi.getOpRestrictionCount(
1306                             AppOpsManager.OP_CAMERA, user, callingPackage, null);
1307                     if (numCameraRestrictions == 1) {
1308                         // Only restricted by the toggles, do not restrict
1309                         return ACTIVITY_RESTRICTION_NONE;
1310                     }
1311                 }
1312             }
1313             return ACTIVITY_RESTRICTION_APPOP;
1314         }
1315 
1316         return ACTIVITY_RESTRICTION_NONE;
1317     }
1318 
setLaunchSource(int uid)1319     void setLaunchSource(int uid) {
1320         mLaunchingActivityWakeLock.setWorkSource(new WorkSource(uid));
1321     }
1322 
acquireLaunchWakelock()1323     void acquireLaunchWakelock() {
1324         if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != SYSTEM_UID) {
1325             throw new IllegalStateException("Calling must be system uid");
1326         }
1327         mLaunchingActivityWakeLock.acquire();
1328         if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1329             // To be safe, don't allow the wake lock to be held for too long.
1330             mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1331         }
1332     }
1333 
1334     /**
1335      * Called when all resumed tasks/root-tasks are idle.
1336      */
1337     @GuardedBy("mService")
checkFinishBootingLocked()1338     private void checkFinishBootingLocked() {
1339         final boolean booting = mService.isBooting();
1340         boolean enableScreen = false;
1341         mService.setBooting(false);
1342         if (!mService.isBooted()) {
1343             mService.setBooted(true);
1344             enableScreen = true;
1345         }
1346         if (booting || enableScreen) {
1347             mService.postFinishBooting(booting, enableScreen);
1348         }
1349     }
1350 
activityIdleInternal(ActivityRecord r, boolean fromTimeout, boolean processPausingActivities, Configuration config)1351     void activityIdleInternal(ActivityRecord r, boolean fromTimeout,
1352             boolean processPausingActivities, Configuration config) {
1353         if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + r);
1354 
1355         if (r != null) {
1356             if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternal: Callers="
1357                     + Debug.getCallers(4));
1358             mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1359             r.finishLaunchTickingLocked();
1360             if (fromTimeout) {
1361                 reportActivityLaunched(fromTimeout, r, INVALID_DELAY, -1 /* launchState */);
1362             }
1363 
1364             // This is a hack to semi-deal with a race condition
1365             // in the client where it can be constructed with a
1366             // newer configuration from when we asked it to launch.
1367             // We'll update with whatever configuration it now says
1368             // it used to launch.
1369             if (config != null) {
1370                 r.setLastReportedGlobalConfiguration(config);
1371             }
1372 
1373             // We are now idle.  If someone is waiting for a thumbnail from
1374             // us, we can now deliver.
1375             r.idle = true;
1376 
1377             // Check if able to finish booting when device is booting and all resumed activities
1378             // are idle.
1379             if ((mService.isBooting() && mRootWindowContainer.allResumedActivitiesIdle())
1380                     || fromTimeout) {
1381                 checkFinishBootingLocked();
1382             }
1383 
1384             // When activity is idle, we consider the relaunch must be successful, so let's clear
1385             // the flag.
1386             r.mRelaunchReason = RELAUNCH_REASON_NONE;
1387         }
1388 
1389         if (mRootWindowContainer.allResumedActivitiesIdle()) {
1390             if (r != null) {
1391                 mService.scheduleAppGcsLocked();
1392                 mRecentTasks.onActivityIdle(r);
1393             }
1394 
1395             if (mLaunchingActivityWakeLock.isHeld()) {
1396                 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1397                 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != SYSTEM_UID) {
1398                     throw new IllegalStateException("Calling must be system uid");
1399                 }
1400                 mLaunchingActivityWakeLock.release();
1401             }
1402             mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
1403         }
1404 
1405         // Atomically retrieve all of the other things to do.
1406         processStoppingAndFinishingActivities(r, processPausingActivities, "idle");
1407 
1408         if (DEBUG_IDLE) {
1409             Slogf.i(TAG, "activityIdleInternal(): r=%s, mStartingUsers=%s", r, mStartingUsers);
1410         }
1411 
1412         if (!mStartingUsers.isEmpty()) {
1413             final ArrayList<UserState> startingUsers = new ArrayList<>(mStartingUsers);
1414             mStartingUsers.clear();
1415             // Complete user switch.
1416             for (int i = 0; i < startingUsers.size(); i++) {
1417                 UserState userState = startingUsers.get(i);
1418                 Slogf.i(TAG, "finishing switch of user %d", userState.mHandle.getIdentifier());
1419                 mService.mAmInternal.finishUserSwitch(userState);
1420             }
1421         }
1422 
1423         mService.mH.post(() -> mService.mAmInternal.trimApplications());
1424     }
1425 
1426     /** This doesn't just find a task, it also moves the task to front. */
findTaskToMoveToFront(Task task, int flags, ActivityOptions options, String reason, boolean forceNonResizeable)1427     void findTaskToMoveToFront(Task task, int flags, ActivityOptions options, String reason,
1428             boolean forceNonResizeable) {
1429         Task currentRootTask = task.getRootTask();
1430         if (currentRootTask == null) {
1431             Slog.e(TAG, "findTaskToMoveToFront: can't move task="
1432                     + task + " to front. Root task is null");
1433             return;
1434         }
1435 
1436         try {
1437             if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
1438                 mUserLeaving = true;
1439             }
1440 
1441             final Transition newTransition = task.mTransitionController.isShellTransitionsEnabled()
1442                     ? task.mTransitionController.isCollecting() ? null
1443                     : task.mTransitionController.createTransition(TRANSIT_TO_FRONT) : null;
1444             task.mTransitionController.collect(task);
1445             reason = reason + " findTaskToMoveToFront";
1446             boolean reparented = false;
1447             if (task.isResizeable() && canUseActivityOptionsLaunchBounds(options)) {
1448                 final Rect bounds = options.getLaunchBounds();
1449                 task.setBounds(bounds);
1450 
1451                 Task targetRootTask =
1452                         mRootWindowContainer.getOrCreateRootTask(null, options, task, ON_TOP);
1453 
1454                 if (targetRootTask != currentRootTask) {
1455                     moveHomeRootTaskToFrontIfNeeded(flags, targetRootTask.getDisplayArea(), reason);
1456                     task.reparent(targetRootTask, ON_TOP, REPARENT_KEEP_ROOT_TASK_AT_FRONT,
1457                             !ANIMATE, DEFER_RESUME, reason);
1458                     currentRootTask = targetRootTask;
1459                     reparented = true;
1460                     // task.reparent() should already placed the task on top,
1461                     // still need moveTaskToFrontLocked() below for any transition settings.
1462                 }
1463                 if (targetRootTask.shouldResizeRootTaskWithLaunchBounds()) {
1464                     targetRootTask.resize(bounds, !PRESERVE_WINDOWS, !DEFER_RESUME);
1465                 } else {
1466                     // WM resizeTask must be done after the task is moved to the correct stack,
1467                     // because Task's setBounds() also updates dim layer's bounds, but that has
1468                     // dependency on the root task.
1469                     task.resize(false /* relayout */, false /* forced */);
1470                 }
1471             }
1472 
1473             if (!reparented) {
1474                 moveHomeRootTaskToFrontIfNeeded(flags, currentRootTask.getDisplayArea(), reason);
1475             }
1476 
1477             final ActivityRecord r = task.getTopNonFinishingActivity();
1478             currentRootTask.moveTaskToFront(task, false /* noAnimation */, options,
1479                     r == null ? null : r.appTimeTracker, reason);
1480 
1481             if (DEBUG_ROOT_TASK) Slog.d(TAG_ROOT_TASK,
1482                     "findTaskToMoveToFront: moved to front of root task=" + currentRootTask);
1483 
1484             handleNonResizableTaskIfNeeded(task, WINDOWING_MODE_UNDEFINED,
1485                     mRootWindowContainer.getDefaultTaskDisplayArea(), currentRootTask,
1486                     forceNonResizeable);
1487             if (r != null && (options == null || !options.getDisableStartingWindow())) {
1488                 // Use a starting window to reduce the transition latency for reshowing the task.
1489                 // Note that with shell transition, this should be executed before requesting
1490                 // transition to avoid delaying the starting window.
1491                 r.showStartingWindow(true /* taskSwitch */);
1492             }
1493             if (newTransition != null) {
1494                 task.mTransitionController.requestStartTransition(newTransition, task,
1495                         options != null ? options.getRemoteTransition() : null,
1496                         null /* displayChange */);
1497             }
1498         } finally {
1499             mUserLeaving = false;
1500         }
1501     }
1502 
moveHomeRootTaskToFrontIfNeeded(int flags, TaskDisplayArea taskDisplayArea, String reason)1503     private void moveHomeRootTaskToFrontIfNeeded(int flags, TaskDisplayArea taskDisplayArea,
1504             String reason) {
1505         final Task focusedRootTask = taskDisplayArea.getFocusedRootTask();
1506 
1507         if ((taskDisplayArea.getWindowingMode() == WINDOWING_MODE_FULLSCREEN
1508                 && (flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0)
1509                 || (focusedRootTask != null && focusedRootTask.isActivityTypeRecents())) {
1510             // We move root home task to front when we are on a fullscreen display area and
1511             // caller has requested the home activity to move with it. Or the previous root task
1512             // is recents.
1513             taskDisplayArea.moveHomeRootTaskToFront(reason);
1514         }
1515     }
1516 
canUseActivityOptionsLaunchBounds(ActivityOptions options)1517     boolean canUseActivityOptionsLaunchBounds(ActivityOptions options) {
1518         // We use the launch bounds in the activity options is the device supports freeform
1519         // window management or is launching into the root pinned task.
1520         if (options == null || options.getLaunchBounds() == null) {
1521             return false;
1522         }
1523         return (mService.mSupportsPictureInPicture
1524                 && options.getLaunchWindowingMode() == WINDOWING_MODE_PINNED)
1525                 || mService.mSupportsFreeformWindowManagement;
1526     }
1527 
getLaunchParamsController()1528     LaunchParamsController getLaunchParamsController() {
1529         return mLaunchParamsController;
1530     }
1531 
setSplitScreenResizing(boolean resizing)1532     void setSplitScreenResizing(boolean resizing) {
1533         if (resizing == mDockedRootTaskResizing) {
1534             return;
1535         }
1536 
1537         mDockedRootTaskResizing = resizing;
1538         mWindowManager.setDockedRootTaskResizing(resizing);
1539     }
1540 
removePinnedRootTaskInSurfaceTransaction(Task rootTask)1541     private void removePinnedRootTaskInSurfaceTransaction(Task rootTask) {
1542         /**
1543          * Workaround: Force-stop all the activities in the root pinned task before we reparent them
1544          * to the fullscreen root task.  This is to guarantee that when we are removing a root task,
1545          * that the client receives onStop() before new windowing mode is set.
1546          * We do this by detaching the root task from the display so that it will be considered
1547          * invisible when ensureActivitiesVisible() is called, and all of its activities will be
1548          * marked invisible as well and added to the stopping list.  After which we process the
1549          * stopping list by handling the idle.
1550          */
1551         rootTask.cancelAnimation();
1552         rootTask.setForceHidden(FLAG_FORCE_HIDDEN_FOR_PINNED_TASK, true /* set */);
1553         rootTask.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
1554         activityIdleInternal(null /* idleActivity */, false /* fromTimeout */,
1555                 true /* processPausingActivities */, null /* configuration */);
1556 
1557         // Reparent all the tasks to the bottom of the display
1558         final DisplayContent toDisplay =
1559                 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
1560 
1561         mService.deferWindowLayout();
1562         try {
1563             rootTask.setWindowingMode(WINDOWING_MODE_UNDEFINED);
1564             if (rootTask.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
1565                 rootTask.setBounds(null);
1566             }
1567             toDisplay.getDefaultTaskDisplayArea().positionTaskBehindHome(rootTask);
1568 
1569             // Follow on the workaround: activities are kept force hidden till the new windowing
1570             // mode is set.
1571             rootTask.setForceHidden(FLAG_FORCE_HIDDEN_FOR_PINNED_TASK, false /* set */);
1572             mRootWindowContainer.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
1573             mRootWindowContainer.resumeFocusedTasksTopActivities();
1574         } finally {
1575             mService.continueWindowLayout();
1576         }
1577     }
1578 
removeRootTaskInSurfaceTransaction(Task rootTask)1579     private void removeRootTaskInSurfaceTransaction(Task rootTask) {
1580         if (rootTask.getWindowingMode() == WINDOWING_MODE_PINNED) {
1581             removePinnedRootTaskInSurfaceTransaction(rootTask);
1582         } else {
1583             final PooledConsumer c = PooledLambda.obtainConsumer(
1584                     ActivityTaskSupervisor::processRemoveTask, this, PooledLambda.__(Task.class));
1585             rootTask.forAllLeafTasks(c, true /* traverseTopToBottom */);
1586             c.recycle();
1587         }
1588     }
1589 
processRemoveTask(Task task)1590     private void processRemoveTask(Task task) {
1591         removeTask(task, true /* killProcess */, REMOVE_FROM_RECENTS, "remove-root-task");
1592     }
1593 
1594     /**
1595      * Removes the root task associated with the given {@param task}. If the {@param task} is the
1596      * pinned task, then its child tasks are not explicitly removed when the root task is
1597      * destroyed, but instead moved back onto the TaskDisplayArea.
1598      */
removeRootTask(Task task)1599     void removeRootTask(Task task) {
1600         mWindowManager.inSurfaceTransaction(() -> removeRootTaskInSurfaceTransaction(task));
1601     }
1602 
1603     /**
1604      * Removes the task with the specified task id.
1605      *
1606      * @param taskId Identifier of the task to be removed.
1607      * @param killProcess Kill any process associated with the task if possible.
1608      * @param removeFromRecents Whether to also remove the task from recents.
1609      * @return Returns true if the given task was found and removed.
1610      */
removeTaskById(int taskId, boolean killProcess, boolean removeFromRecents, String reason)1611     boolean removeTaskById(int taskId, boolean killProcess, boolean removeFromRecents,
1612             String reason) {
1613         final Task task =
1614                 mRootWindowContainer.anyTaskForId(taskId, MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
1615         if (task != null) {
1616             removeTask(task, killProcess, removeFromRecents, reason);
1617             return true;
1618         }
1619         Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
1620         return false;
1621     }
1622 
removeTask(Task task, boolean killProcess, boolean removeFromRecents, String reason)1623     void removeTask(Task task, boolean killProcess, boolean removeFromRecents, String reason) {
1624         if (task.mInRemoveTask) {
1625             // Prevent recursion.
1626             return;
1627         }
1628         task.mTransitionController.requestCloseTransitionIfNeeded(task);
1629         task.mInRemoveTask = true;
1630         try {
1631             task.removeActivities(reason, false /* excludingTaskOverlay */);
1632             cleanUpRemovedTaskLocked(task, killProcess, removeFromRecents);
1633             mService.getLockTaskController().clearLockedTask(task);
1634             mService.getTaskChangeNotificationController().notifyTaskStackChanged();
1635             if (task.isPersistable) {
1636                 mService.notifyTaskPersisterLocked(null, true);
1637             }
1638         } finally {
1639             task.mInRemoveTask = false;
1640         }
1641     }
1642 
cleanUpRemovedTaskLocked(Task task, boolean killProcess, boolean removeFromRecents)1643     void cleanUpRemovedTaskLocked(Task task, boolean killProcess, boolean removeFromRecents) {
1644         if (removeFromRecents) {
1645             mRecentTasks.remove(task);
1646         }
1647         ComponentName component = task.getBaseIntent().getComponent();
1648         if (component == null) {
1649             Slog.w(TAG, "No component for base intent of task: " + task);
1650             return;
1651         }
1652 
1653         // Find any running services associated with this app and stop if needed.
1654         final Message msg = PooledLambda.obtainMessage(ActivityManagerInternal::cleanUpServices,
1655                 mService.mAmInternal, task.mUserId, component, new Intent(task.getBaseIntent()));
1656         mService.mH.sendMessage(msg);
1657 
1658         if (!killProcess) {
1659             return;
1660         }
1661 
1662         // Determine if the process(es) for this task should be killed.
1663         final String pkg = component.getPackageName();
1664         ArrayList<Object> procsToKill = new ArrayList<>();
1665         ArrayMap<String, SparseArray<WindowProcessController>> pmap =
1666                 mService.mProcessNames.getMap();
1667         for (int i = 0; i < pmap.size(); i++) {
1668 
1669             SparseArray<WindowProcessController> uids = pmap.valueAt(i);
1670             for (int j = 0; j < uids.size(); j++) {
1671                 WindowProcessController proc = uids.valueAt(j);
1672                 if (proc.mUserId != task.mUserId) {
1673                     // Don't kill process for a different user.
1674                     continue;
1675                 }
1676                 if (proc == mService.mHomeProcess) {
1677                     // Don't kill the home process along with tasks from the same package.
1678                     continue;
1679                 }
1680                 if (!proc.mPkgList.contains(pkg)) {
1681                     // Don't kill process that is not associated with this task.
1682                     continue;
1683                 }
1684 
1685                 if (!proc.shouldKillProcessForRemovedTask(task)) {
1686                     // Don't kill process(es) that has an activity in a different task that is also
1687                     // in recents, or has an activity not stopped.
1688                     return;
1689                 }
1690 
1691                 if (proc.hasForegroundServices()) {
1692                     // Don't kill process(es) with foreground service.
1693                     return;
1694                 }
1695 
1696                 // Add process to kill list.
1697                 procsToKill.add(proc);
1698             }
1699         }
1700 
1701         // Kill the running processes. Post on handle since we don't want to hold the service lock
1702         // while calling into AM.
1703         final Message m = PooledLambda.obtainMessage(
1704                 ActivityManagerInternal::killProcessesForRemovedTask, mService.mAmInternal,
1705                 procsToKill);
1706         mService.mH.sendMessage(m);
1707     }
1708 
1709     /**
1710      * Called to restore the state of the task into the root task that it's supposed to go into.
1711      *
1712      * @param task The recent task to be restored.
1713      * @param aOptions The activity options to use for restoration.
1714      * @param onTop If the root task for the task should be the topmost on the display.
1715      * @return true if the task has been restored successfully.
1716      */
restoreRecentTaskLocked(Task task, ActivityOptions aOptions, boolean onTop)1717     boolean restoreRecentTaskLocked(Task task, ActivityOptions aOptions, boolean onTop) {
1718         final Task rootTask =
1719                 mRootWindowContainer.getOrCreateRootTask(null, aOptions, task, onTop);
1720         final WindowContainer parent = task.getParent();
1721 
1722         if (parent == rootTask || task == rootTask) {
1723             // Nothing else to do since it is already restored in the right root task.
1724             return true;
1725         }
1726 
1727         if (parent != null) {
1728             // Task has already been restored once. Just re-parent it to the new root task.
1729             task.reparent(rootTask, POSITION_TOP, true /*moveParents*/, "restoreRecentTaskLocked");
1730             return true;
1731         }
1732 
1733         rootTask.addChild(task, onTop, true /* showForAllUsers */);
1734         if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
1735                 "Added restored task=" + task + " to root task=" + rootTask);
1736         return true;
1737     }
1738 
1739     @Override
onRecentTaskAdded(Task task)1740     public void onRecentTaskAdded(Task task) {
1741         task.touchActiveTime();
1742     }
1743 
1744     @Override
onRecentTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess)1745     public void onRecentTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess) {
1746         if (wasTrimmed) {
1747             // Task was trimmed from the recent tasks list -- remove the active task record as well
1748             // since the user won't really be able to go back to it
1749             removeTaskById(task.mTaskId, killProcess, false /* removeFromRecents */,
1750                     "recent-task-trimmed");
1751         }
1752         task.removedFromRecents();
1753     }
1754 
1755     /**
1756      * Returns the reparent target root task, creating the root task if necessary.  This call
1757      * also enforces the various checks on tasks that are going to be reparented from one root
1758      * task to another.
1759      */
1760     // TODO: Look into changing users to this method to DisplayContent.resolveWindowingMode()
getReparentTargetRootTask(Task task, Task rootTask, boolean toTop)1761     Task getReparentTargetRootTask(Task task, Task rootTask, boolean toTop) {
1762         final Task prevRootTask = task.getRootTask();
1763         final int rootTaskId = rootTask.mTaskId;
1764         final boolean inMultiWindowMode = rootTask.inMultiWindowMode();
1765 
1766         // Check that we aren't reparenting to the same root task that the task is already in
1767         if (prevRootTask != null && prevRootTask.mTaskId == rootTaskId) {
1768             Slog.w(TAG, "Can not reparent to same root task, task=" + task
1769                     + " already in rootTaskId=" + rootTaskId);
1770             return prevRootTask;
1771         }
1772 
1773         // Ensure that we aren't trying to move into a multi-window root task without multi-window
1774         // support
1775         if (inMultiWindowMode && !mService.mSupportsMultiWindow) {
1776             throw new IllegalArgumentException("Device doesn't support multi-window, can not"
1777                     + " reparent task=" + task + " to root-task=" + rootTask);
1778         }
1779 
1780         // Ensure that we're not moving a task to a dynamic root task if device doesn't support
1781         // multi-display.
1782         if (rootTask.getDisplayId() != DEFAULT_DISPLAY && !mService.mSupportsMultiDisplay) {
1783             throw new IllegalArgumentException("Device doesn't support multi-display, can not"
1784                     + " reparent task=" + task + " to rootTaskId=" + rootTaskId);
1785         }
1786 
1787         // Ensure that we aren't trying to move into a freeform root task without freeform support
1788         if (rootTask.getWindowingMode() == WINDOWING_MODE_FREEFORM
1789                 && !mService.mSupportsFreeformWindowManagement) {
1790             throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
1791                     + " task=" + task);
1792         }
1793 
1794         if (rootTask.inPinnedWindowingMode()) {
1795             throw new IllegalArgumentException("No support to reparent to PIP, task=" + task);
1796         }
1797 
1798         // Leave the task in its current root task or a fullscreen root task if it isn't
1799         // resizeable and the preferred root task is in multi-window mode.
1800         if (inMultiWindowMode
1801                 && !task.supportsMultiWindowInDisplayArea(rootTask.getDisplayArea())) {
1802             Slog.w(TAG, "Can not move unresizeable task=" + task + " to multi-window root task="
1803                     + rootTask + " Moving to a fullscreen root task instead.");
1804             if (prevRootTask != null) {
1805                 return prevRootTask;
1806             }
1807             rootTask = rootTask.getDisplayArea().createRootTask(
1808                     WINDOWING_MODE_FULLSCREEN, rootTask.getActivityType(), toTop);
1809         }
1810         return rootTask;
1811     }
1812 
goingToSleepLocked()1813     void goingToSleepLocked() {
1814         scheduleSleepTimeout();
1815         if (!mGoingToSleepWakeLock.isHeld()) {
1816             mGoingToSleepWakeLock.acquire();
1817             if (mLaunchingActivityWakeLock.isHeld()) {
1818                 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != SYSTEM_UID) {
1819                     throw new IllegalStateException("Calling must be system uid");
1820                 }
1821                 mLaunchingActivityWakeLock.release();
1822                 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1823             }
1824         }
1825 
1826         mRootWindowContainer.applySleepTokens(false /* applyToRootTasks */);
1827 
1828         checkReadyForSleepLocked(true /* allowDelay */);
1829     }
1830 
shutdownLocked(int timeout)1831     boolean shutdownLocked(int timeout) {
1832         goingToSleepLocked();
1833 
1834         boolean timedout = false;
1835         final long endTime = System.currentTimeMillis() + timeout;
1836         while (true) {
1837             if (!mRootWindowContainer.putTasksToSleep(
1838                     true /* allowDelay */, true /* shuttingDown */)) {
1839                 long timeRemaining = endTime - System.currentTimeMillis();
1840                 if (timeRemaining > 0) {
1841                     try {
1842                         mService.mGlobalLock.wait(timeRemaining);
1843                     } catch (InterruptedException e) {
1844                     }
1845                 } else {
1846                     Slog.w(TAG, "Activity manager shutdown timed out");
1847                     timedout = true;
1848                     break;
1849                 }
1850             } else {
1851                 break;
1852             }
1853         }
1854 
1855         // Force checkReadyForSleep to complete.
1856         checkReadyForSleepLocked(false /* allowDelay */);
1857 
1858         return timedout;
1859     }
1860 
comeOutOfSleepIfNeededLocked()1861     void comeOutOfSleepIfNeededLocked() {
1862         removeSleepTimeouts();
1863         if (mGoingToSleepWakeLock.isHeld()) {
1864             mGoingToSleepWakeLock.release();
1865         }
1866     }
1867 
checkReadyForSleepLocked(boolean allowDelay)1868     void checkReadyForSleepLocked(boolean allowDelay) {
1869         if (!mService.isSleepingOrShuttingDownLocked()) {
1870             // Do not care.
1871             return;
1872         }
1873 
1874         if (!mRootWindowContainer.putTasksToSleep(
1875                 allowDelay, false /* shuttingDown */)) {
1876             return;
1877         }
1878 
1879         // End power mode launch before going sleep
1880         mService.endLaunchPowerMode(ActivityTaskManagerService.POWER_MODE_REASON_ALL);
1881 
1882         removeSleepTimeouts();
1883 
1884         if (mGoingToSleepWakeLock.isHeld()) {
1885             mGoingToSleepWakeLock.release();
1886         }
1887         if (mService.mShuttingDown) {
1888             mService.mGlobalLock.notifyAll();
1889         }
1890     }
1891 
reportResumedActivityLocked(ActivityRecord r)1892     boolean reportResumedActivityLocked(ActivityRecord r) {
1893         // A resumed activity cannot be stopping. remove from list
1894         mStoppingActivities.remove(r);
1895 
1896         final Task rootTask = r.getRootTask();
1897         if (rootTask.getDisplayArea().allResumedActivitiesComplete()) {
1898             mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
1899             // Make sure activity & window visibility should be identical
1900             // for all displays in this stage.
1901             mRootWindowContainer.executeAppTransitionForAllDisplay();
1902             return true;
1903         }
1904         return false;
1905     }
1906 
1907     // Called when WindowManager has finished animating the launchingBehind activity to the back.
handleLaunchTaskBehindCompleteLocked(ActivityRecord r)1908     private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
1909         final Task task = r.getTask();
1910         final Task rootTask = task.getRootTask();
1911 
1912         mRecentTasks.add(task);
1913         mService.getTaskChangeNotificationController().notifyTaskStackChanged();
1914         rootTask.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
1915 
1916         // When launching tasks behind, update the last active time of the top task after the new
1917         // task has been shown briefly
1918         final ActivityRecord top = rootTask.getTopNonFinishingActivity();
1919         if (top != null) {
1920             top.getTask().touchActiveTime();
1921         }
1922     }
1923 
scheduleLaunchTaskBehindComplete(IBinder token)1924     void scheduleLaunchTaskBehindComplete(IBinder token) {
1925         mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
1926     }
1927 
1928     /**
1929      * Processes the activities to be stopped or destroyed. This should be called when the resumed
1930      * activities are idle or drawn.
1931      */
processStoppingAndFinishingActivities(ActivityRecord launchedActivity, boolean processPausingActivities, String reason)1932     private void processStoppingAndFinishingActivities(ActivityRecord launchedActivity,
1933             boolean processPausingActivities, String reason) {
1934         // Stop any activities that are scheduled to do so but have been waiting for the transition
1935         // animation to finish.
1936         ArrayList<ActivityRecord> readyToStopActivities = null;
1937         for (int i = mStoppingActivities.size() - 1; i >= 0; --i) {
1938             final ActivityRecord s = mStoppingActivities.get(i);
1939             final boolean animating = s.isInTransition();
1940             ProtoLog.v(WM_DEBUG_STATES, "Stopping %s: nowVisible=%b animating=%b "
1941                     + "finishing=%s", s, s.nowVisible, animating, s.finishing);
1942             if (!animating || mService.mShuttingDown) {
1943                 if (!processPausingActivities && s.isState(PAUSING)) {
1944                     // Defer processing pausing activities in this iteration and reschedule
1945                     // a delayed idle to reprocess it again
1946                     removeIdleTimeoutForActivity(launchedActivity);
1947                     scheduleIdleTimeout(launchedActivity);
1948                     continue;
1949                 }
1950 
1951                 ProtoLog.v(WM_DEBUG_STATES, "Ready to stop: %s", s);
1952                 if (readyToStopActivities == null) {
1953                     readyToStopActivities = new ArrayList<>();
1954                 }
1955                 readyToStopActivities.add(s);
1956 
1957                 mStoppingActivities.remove(i);
1958             }
1959         }
1960 
1961         final int numReadyStops = readyToStopActivities == null ? 0 : readyToStopActivities.size();
1962         for (int i = 0; i < numReadyStops; i++) {
1963             final ActivityRecord r = readyToStopActivities.get(i);
1964             if (r.isInHistory()) {
1965                 if (r.finishing) {
1966                     // TODO(b/137329632): Wait for idle of the right activity, not just any.
1967                     r.destroyIfPossible(reason);
1968                 } else {
1969                     r.stopIfPossible();
1970                 }
1971             }
1972         }
1973 
1974         final int numFinishingActivities = mFinishingActivities.size();
1975         if (numFinishingActivities == 0) {
1976             return;
1977         }
1978 
1979         // Finish any activities that are scheduled to do so but have been waiting for the next one
1980         // to start.
1981         final ArrayList<ActivityRecord> finishingActivities = new ArrayList<>(mFinishingActivities);
1982         mFinishingActivities.clear();
1983         for (int i = 0; i < numFinishingActivities; i++) {
1984             final ActivityRecord r = finishingActivities.get(i);
1985             if (r.isInHistory()) {
1986                 r.destroyImmediately("finish-" + reason);
1987             }
1988         }
1989     }
1990 
removeHistoryRecords(WindowProcessController app)1991     void removeHistoryRecords(WindowProcessController app) {
1992         removeHistoryRecords(mStoppingActivities, app, "mStoppingActivities");
1993         removeHistoryRecords(mFinishingActivities, app, "mFinishingActivities");
1994         removeHistoryRecords(mNoHistoryActivities, app, "mNoHistoryActivities");
1995     }
1996 
removeHistoryRecords(ArrayList<ActivityRecord> list, WindowProcessController app, String listName)1997     private void removeHistoryRecords(ArrayList<ActivityRecord> list, WindowProcessController app,
1998             String listName) {
1999         int i = list.size();
2000         if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
2001                 "Removing app " + this + " from list " + listName + " with " + i + " entries");
2002         while (i > 0) {
2003             i--;
2004             ActivityRecord r = list.get(i);
2005             if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "Record #" + i + " " + r);
2006             if (r.app == app) {
2007                 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "---> REMOVING this entry!");
2008                 list.remove(i);
2009                 r.removeTimeouts();
2010             }
2011         }
2012     }
2013 
dump(PrintWriter pw, String prefix)2014     public void dump(PrintWriter pw, String prefix) {
2015         pw.println();
2016         pw.println("ActivityTaskSupervisor state:");
2017         mRootWindowContainer.dump(pw, prefix, true /* dumpAll */);
2018         getKeyguardController().dump(pw, prefix);
2019         mService.getLockTaskController().dump(pw, prefix);
2020         pw.print(prefix);
2021         pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
2022         pw.println(prefix + "mUserRootTaskInFront=" + mRootWindowContainer.mUserRootTaskInFront);
2023         pw.println(prefix + "mVisibilityTransactionDepth=" + mVisibilityTransactionDepth);
2024         pw.print(prefix); pw.print("isHomeRecentsComponent=");
2025         pw.println(mRecentTasks.isRecentsComponentHomeActivity(mRootWindowContainer.mCurrentUser));
2026         if (!mWaitingActivityLaunched.isEmpty()) {
2027             pw.println(prefix + "mWaitingActivityLaunched=");
2028             for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
2029                 mWaitingActivityLaunched.get(i).dump(pw, prefix + "  ");
2030             }
2031         }
2032         pw.println(prefix + "mNoHistoryActivities=" + mNoHistoryActivities);
2033         pw.println();
2034     }
2035 
printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage, boolean needSep, String prefix, Runnable header)2036     static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
2037             boolean needSep, String prefix, Runnable header) {
2038         if (activity != null) {
2039             if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
2040                 if (needSep) {
2041                     pw.println();
2042                 }
2043                 if (header != null) {
2044                     header.run();
2045                 }
2046                 pw.print(prefix);
2047                 pw.println(activity);
2048                 return true;
2049             }
2050         }
2051         return false;
2052     }
2053 
dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list, String prefix, String label, boolean complete, boolean brief, boolean client, String dumpPackage, boolean needNL, Runnable header, Task lastTask)2054     static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
2055             String prefix, String label, boolean complete, boolean brief, boolean client,
2056             String dumpPackage, boolean needNL, Runnable header, Task lastTask) {
2057         boolean printed = false;
2058         for (int i = list.size() - 1; i >= 0; i--) {
2059             final ActivityRecord r = list.get(i);
2060             ActivityRecord.dumpActivity(fd, pw, i, r, prefix, label, complete, brief,
2061                     client, dumpPackage, needNL, header, lastTask);
2062             lastTask = r.getTask();
2063             header = null;
2064             needNL = client && r.attachedToProcess();
2065         }
2066         return printed;
2067     }
2068 
scheduleIdleTimeout(ActivityRecord next)2069     void scheduleIdleTimeout(ActivityRecord next) {
2070         if (DEBUG_IDLE) Slog.d(TAG_IDLE, "scheduleIdleTimeout: Callers=" + Debug.getCallers(4));
2071         Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
2072         mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
2073     }
2074 
scheduleIdle()2075     final void scheduleIdle() {
2076         if (!mHandler.hasMessages(IDLE_NOW_MSG)) {
2077             if (DEBUG_IDLE) Slog.d(TAG_IDLE, "scheduleIdle: Callers=" + Debug.getCallers(4));
2078             mHandler.sendEmptyMessage(IDLE_NOW_MSG);
2079         }
2080     }
2081 
2082     /**
2083      * Updates the record of top resumed activity when it changes and handles reporting of the
2084      * state changes to previous and new top activities. It will immediately dispatch top resumed
2085      * state loss message to previous top activity (if haven't done it already). After the previous
2086      * activity releases the top state and reports back, message about acquiring top state will be
2087      * sent to the new top resumed activity.
2088      */
updateTopResumedActivityIfNeeded(String reason)2089     void updateTopResumedActivityIfNeeded(String reason) {
2090         final ActivityRecord prevTopActivity = mTopResumedActivity;
2091         final Task topRootTask = mRootWindowContainer.getTopDisplayFocusedRootTask();
2092         if (topRootTask == null || topRootTask.getTopResumedActivity() == prevTopActivity) {
2093             if (mService.isSleepingLocked()) {
2094                 // There won't be a next resumed activity. The top process should still be updated
2095                 // according to the current top focused activity.
2096                 mService.updateTopApp(null /* topResumedActivity */);
2097             }
2098             return;
2099         }
2100 
2101         // Ask previous activity to release the top state.
2102         final boolean prevActivityReceivedTopState =
2103                 prevTopActivity != null && !mTopResumedActivityWaitingForPrev;
2104         // mTopResumedActivityWaitingForPrev == true at this point would mean that an activity
2105         // before the prevTopActivity one hasn't reported back yet. So server never sent the top
2106         // resumed state change message to prevTopActivity.
2107         if (prevActivityReceivedTopState
2108                 && prevTopActivity.scheduleTopResumedActivityChanged(false /* onTop */)) {
2109             scheduleTopResumedStateLossTimeout(prevTopActivity);
2110             mTopResumedActivityWaitingForPrev = true;
2111         }
2112 
2113         // Update the current top activity.
2114         mTopResumedActivity = topRootTask.getTopResumedActivity();
2115         // Update process state if there is no activity state change (e.g. focus change between
2116         // multi-window mode activities) to make sure that the current top has top oom-adj.
2117         // If the previous top is null, there should be activity state change from it, Then the
2118         // process state should also have been updated so no need to update again.
2119         if (mTopResumedActivity != null && prevTopActivity != null) {
2120             if (mTopResumedActivity.app != null) {
2121                 mTopResumedActivity.app.addToPendingTop();
2122             }
2123             mService.updateOomAdj();
2124         }
2125         // Update the last resumed activity and focused app when the top resumed activity changed
2126         // because the new top resumed activity might be already resumed and thus won't have
2127         // activity state change to update the records to AMS.
2128         if (mTopResumedActivity != null) {
2129             mService.setLastResumedActivityUncheckLocked(mTopResumedActivity, reason);
2130         }
2131         scheduleTopResumedActivityStateIfNeeded();
2132 
2133         mService.updateTopApp(mTopResumedActivity);
2134     }
2135 
2136     /** Schedule top resumed state change if previous top activity already reported back. */
scheduleTopResumedActivityStateIfNeeded()2137     private void scheduleTopResumedActivityStateIfNeeded() {
2138         if (mTopResumedActivity != null && !mTopResumedActivityWaitingForPrev) {
2139             mTopResumedActivity.scheduleTopResumedActivityChanged(true /* onTop */);
2140         }
2141     }
2142 
2143     /**
2144      * Limit the time given to the app to report handling of the state loss.
2145      */
scheduleTopResumedStateLossTimeout(ActivityRecord r)2146     private void scheduleTopResumedStateLossTimeout(ActivityRecord r) {
2147         final Message msg = mHandler.obtainMessage(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG);
2148         msg.obj = r;
2149         r.topResumedStateLossTime = SystemClock.uptimeMillis();
2150         mHandler.sendMessageDelayed(msg, TOP_RESUMED_STATE_LOSS_TIMEOUT);
2151         ProtoLog.v(WM_DEBUG_STATES, "Waiting for top state to be released by %s", r);
2152     }
2153 
2154     /**
2155      * Handle a loss of top resumed state by an activity - update internal state and inform next top
2156      * activity if needed.
2157      */
handleTopResumedStateReleased(boolean timeout)2158     void handleTopResumedStateReleased(boolean timeout) {
2159         ProtoLog.v(WM_DEBUG_STATES, "Top resumed state released %s",
2160                     (timeout ? "(due to timeout)" : "(transition complete)"));
2161 
2162         mHandler.removeMessages(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG);
2163         if (!mTopResumedActivityWaitingForPrev) {
2164             // Top resumed activity state loss already handled.
2165             return;
2166         }
2167         mTopResumedActivityWaitingForPrev = false;
2168         scheduleTopResumedActivityStateIfNeeded();
2169     }
2170 
removeIdleTimeoutForActivity(ActivityRecord r)2171     void removeIdleTimeoutForActivity(ActivityRecord r) {
2172         if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
2173                 + Debug.getCallers(4));
2174         mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
2175     }
2176 
scheduleResumeTopActivities()2177     final void scheduleResumeTopActivities() {
2178         if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
2179             mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
2180         }
2181     }
2182 
scheduleProcessStoppingAndFinishingActivitiesIfNeeded()2183     void scheduleProcessStoppingAndFinishingActivitiesIfNeeded() {
2184         if (mStoppingActivities.isEmpty() && mFinishingActivities.isEmpty()) {
2185             return;
2186         }
2187         if (mRootWindowContainer.allResumedActivitiesIdle()) {
2188             scheduleIdle();
2189             return;
2190         }
2191         if (!mHandler.hasMessages(PROCESS_STOPPING_AND_FINISHING_MSG)
2192                 && mRootWindowContainer.allResumedActivitiesVisible()) {
2193             mHandler.sendEmptyMessage(PROCESS_STOPPING_AND_FINISHING_MSG);
2194         }
2195     }
2196 
removeSleepTimeouts()2197     void removeSleepTimeouts() {
2198         mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
2199     }
2200 
scheduleSleepTimeout()2201     final void scheduleSleepTimeout() {
2202         removeSleepTimeouts();
2203         mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
2204     }
2205 
removeRestartTimeouts(ActivityRecord r)2206     void removeRestartTimeouts(ActivityRecord r) {
2207         mHandler.removeMessages(RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG, r);
2208     }
2209 
scheduleRestartTimeout(ActivityRecord r)2210     final void scheduleRestartTimeout(ActivityRecord r) {
2211         removeRestartTimeouts(r);
2212         mHandler.sendMessageDelayed(mHandler.obtainMessage(RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG, r),
2213                 WindowManagerService.WINDOW_FREEZE_TIMEOUT_DURATION);
2214     }
2215 
handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode, TaskDisplayArea preferredTaskDisplayArea, Task actualRootTask)2216     void handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode,
2217             TaskDisplayArea preferredTaskDisplayArea, Task actualRootTask) {
2218         handleNonResizableTaskIfNeeded(task, preferredWindowingMode, preferredTaskDisplayArea,
2219                 actualRootTask, false /* forceNonResizable */);
2220     }
2221 
handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode, TaskDisplayArea preferredTaskDisplayArea, Task actualRootTask, boolean forceNonResizable)2222     void handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode,
2223             TaskDisplayArea preferredTaskDisplayArea, Task actualRootTask,
2224             boolean forceNonResizable) {
2225         final boolean isSecondaryDisplayPreferred = preferredTaskDisplayArea != null
2226                 && preferredTaskDisplayArea.getDisplayId() != DEFAULT_DISPLAY;
2227         if (!task.isActivityTypeStandardOrUndefined()) {
2228             return;
2229         }
2230 
2231         // Handle incorrect launch/move to secondary display if needed.
2232         if (isSecondaryDisplayPreferred) {
2233             if (!task.canBeLaunchedOnDisplay(task.getDisplayId())) {
2234                 throw new IllegalStateException("Task resolved to incompatible display");
2235             }
2236 
2237             final DisplayContent preferredDisplay = preferredTaskDisplayArea.mDisplayContent;
2238             if (preferredDisplay != task.getDisplayContent()) {
2239                 Slog.w(TAG, "Failed to put " + task + " on display " + preferredDisplay.mDisplayId);
2240                 // Display a warning toast that we failed to put a task on a secondary display.
2241                 mService.getTaskChangeNotificationController()
2242                         .notifyActivityLaunchOnSecondaryDisplayFailed(task.getTaskInfo(),
2243                                 preferredDisplay.mDisplayId);
2244             } else if (!forceNonResizable) {
2245                 handleForcedResizableTaskIfNeeded(task, FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY);
2246             }
2247             // The information about not support secondary display should already be notified, we
2248             // don't want to show another message on default display about split-screen. And it may
2249             // be the case that a resizable activity is launched on a non-resizable task.
2250             return;
2251         }
2252 
2253         if (!forceNonResizable) {
2254             handleForcedResizableTaskIfNeeded(task, FORCED_RESIZEABLE_REASON_SPLIT_SCREEN);
2255         }
2256     }
2257 
2258     /** Notifies that the top activity of the task is forced to be resizeable. */
handleForcedResizableTaskIfNeeded(Task task, int reason)2259     private void handleForcedResizableTaskIfNeeded(Task task, int reason) {
2260         final ActivityRecord topActivity = task.getTopNonFinishingActivity();
2261         if (topActivity == null || topActivity.noDisplay
2262                 || !topActivity.canForceResizeNonResizable(task.getWindowingMode())) {
2263             return;
2264         }
2265         mService.getTaskChangeNotificationController().notifyActivityForcedResizable(
2266                 task.mTaskId, reason, topActivity.info.applicationInfo.packageName);
2267     }
2268 
scheduleUpdateMultiWindowMode(Task task)2269     void scheduleUpdateMultiWindowMode(Task task) {
2270         final PooledConsumer c = PooledLambda.obtainConsumer(
2271                 ActivityTaskSupervisor::addToMultiWindowModeChangedList, this,
2272                 PooledLambda.__(ActivityRecord.class));
2273         task.forAllActivities(c);
2274         c.recycle();
2275 
2276         if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
2277             mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
2278         }
2279     }
2280 
addToMultiWindowModeChangedList(ActivityRecord r)2281     private void addToMultiWindowModeChangedList(ActivityRecord r) {
2282         if (r.attachedToProcess()) {
2283             mMultiWindowModeChangedActivities.add(r);
2284         }
2285     }
2286 
scheduleUpdatePictureInPictureModeIfNeeded(Task task, Task prevRootTask)2287     void scheduleUpdatePictureInPictureModeIfNeeded(Task task, Task prevRootTask) {
2288         final Task rootTask = task.getRootTask();
2289         if ((prevRootTask == null || (prevRootTask != rootTask
2290                 && !prevRootTask.inPinnedWindowingMode() && !rootTask.inPinnedWindowingMode()))) {
2291             return;
2292         }
2293 
2294         scheduleUpdatePictureInPictureModeIfNeeded(task, rootTask.getRequestedOverrideBounds());
2295     }
2296 
scheduleUpdatePictureInPictureModeIfNeeded(Task task, Rect targetRootTaskBounds)2297     void scheduleUpdatePictureInPictureModeIfNeeded(Task task, Rect targetRootTaskBounds) {
2298         final PooledConsumer c = PooledLambda.obtainConsumer(
2299                 ActivityTaskSupervisor::addToPipModeChangedList, this,
2300                 PooledLambda.__(ActivityRecord.class));
2301         task.forAllActivities(c);
2302         c.recycle();
2303 
2304         mPipModeChangedTargetRootTaskBounds = targetRootTaskBounds;
2305 
2306         if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
2307             mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
2308         }
2309     }
2310 
addToPipModeChangedList(ActivityRecord r)2311     private void addToPipModeChangedList(ActivityRecord r) {
2312         if (!r.attachedToProcess()) return;
2313 
2314         mPipModeChangedActivities.add(r);
2315         // If we are scheduling pip change, then remove this activity from multi-window
2316         // change list as the processing of pip change will make sure multi-window changed
2317         // message is processed in the right order relative to pip changed.
2318         mMultiWindowModeChangedActivities.remove(r);
2319     }
2320 
wakeUp(String reason)2321     void wakeUp(String reason) {
2322         mPowerManager.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_APPLICATION,
2323                 "android.server.am:TURN_ON:" + reason);
2324     }
2325 
2326     /** Starts a batch of visibility updates. */
beginActivityVisibilityUpdate()2327     void beginActivityVisibilityUpdate() {
2328         if (mVisibilityTransactionDepth == 0) {
2329             getKeyguardController().updateVisibility();
2330         }
2331         mVisibilityTransactionDepth++;
2332     }
2333 
2334     /** Ends a batch of visibility updates. */
endActivityVisibilityUpdate()2335     void endActivityVisibilityUpdate() {
2336         mVisibilityTransactionDepth--;
2337         if (mVisibilityTransactionDepth == 0) {
2338             computeProcessActivityStateBatch();
2339         }
2340     }
2341 
2342     /** Returns {@code true} if the caller is on the path to update visibility. */
inActivityVisibilityUpdate()2343     boolean inActivityVisibilityUpdate() {
2344         return mVisibilityTransactionDepth > 0;
2345     }
2346 
setDeferRootVisibilityUpdate(boolean deferUpdate)2347     void setDeferRootVisibilityUpdate(boolean deferUpdate) {
2348         mDeferRootVisibilityUpdate = deferUpdate;
2349     }
2350 
isRootVisibilityUpdateDeferred()2351     boolean isRootVisibilityUpdateDeferred() {
2352         return mDeferRootVisibilityUpdate;
2353     }
2354 
2355     /**
2356      * Called when the state or visibility of an attached activity is changed.
2357      *
2358      * @param wpc The process who owns the activity.
2359      * @param forceBatch Whether to put the changed record to a pending list. If the caller is not
2360      *                   in the path of visibility update ({@link #inActivityVisibilityUpdate}), it
2361      *                   must call {@link #computeProcessActivityStateBatch} manually.
2362      */
onProcessActivityStateChanged(WindowProcessController wpc, boolean forceBatch)2363     void onProcessActivityStateChanged(WindowProcessController wpc, boolean forceBatch) {
2364         if (forceBatch || inActivityVisibilityUpdate()) {
2365             if (!mActivityStateChangedProcs.contains(wpc)) {
2366                 mActivityStateChangedProcs.add(wpc);
2367             }
2368             return;
2369         }
2370         wpc.computeProcessActivityState();
2371     }
2372 
computeProcessActivityStateBatch()2373     void computeProcessActivityStateBatch() {
2374         if (mActivityStateChangedProcs.isEmpty()) {
2375             return;
2376         }
2377         for (int i = mActivityStateChangedProcs.size() - 1; i >= 0; i--) {
2378             mActivityStateChangedProcs.get(i).computeProcessActivityState();
2379         }
2380         mActivityStateChangedProcs.clear();
2381     }
2382 
2383     /**
2384      * Begin deferring resume to avoid duplicate resumes in one pass.
2385      */
beginDeferResume()2386     void beginDeferResume() {
2387         mDeferResumeCount++;
2388     }
2389 
2390     /**
2391      * End deferring resume and determine if resume can be called.
2392      */
endDeferResume()2393     void endDeferResume() {
2394         mDeferResumeCount--;
2395     }
2396 
2397     /** @return True if resume can be called. */
readyToResume()2398     boolean readyToResume() {
2399         return mDeferResumeCount == 0;
2400     }
2401 
2402     private final class ActivityTaskSupervisorHandler extends Handler {
2403 
ActivityTaskSupervisorHandler(Looper looper)2404         ActivityTaskSupervisorHandler(Looper looper) {
2405             super(looper);
2406         }
2407 
2408         @Override
handleMessage(Message msg)2409         public void handleMessage(Message msg) {
2410             synchronized (mService.mGlobalLock) {
2411                 if (handleMessageInner(msg)) {
2412                     return;
2413                 }
2414             }
2415             // The cases that some invocations cannot be locked by WM.
2416             switch (msg.what) {
2417                 case RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG: {
2418                     final ActivityRecord r = (ActivityRecord) msg.obj;
2419                     String processName = null;
2420                     int uid = 0;
2421                     synchronized (mService.mGlobalLock) {
2422                         if (r.attachedToProcess() && r.isState(RESTARTING_PROCESS)) {
2423                             processName = r.app.mName;
2424                             uid = r.app.mUid;
2425                         }
2426                     }
2427                     if (processName != null) {
2428                         mService.mAmInternal.killProcess(processName, uid,
2429                                 "restartActivityProcessTimeout");
2430                     }
2431                 } break;
2432             }
2433         }
2434 
activityIdleFromMessage(ActivityRecord idleActivity, boolean fromTimeout)2435         private void activityIdleFromMessage(ActivityRecord idleActivity, boolean fromTimeout) {
2436             activityIdleInternal(idleActivity, fromTimeout,
2437                     fromTimeout /* processPausingActivities */, null /* config */);
2438         }
2439 
2440         /**
2441          * Handles the message with lock held.
2442          *
2443          * @return {@code true} if the message is handled.
2444          */
handleMessageInner(Message msg)2445         private boolean handleMessageInner(Message msg) {
2446             switch (msg.what) {
2447                 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
2448                     for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
2449                         final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
2450                         r.updateMultiWindowMode();
2451                     }
2452                 } break;
2453                 case REPORT_PIP_MODE_CHANGED_MSG: {
2454                     for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
2455                         final ActivityRecord r = mPipModeChangedActivities.remove(i);
2456                         r.updatePictureInPictureMode(mPipModeChangedTargetRootTaskBounds,
2457                                 false /* forceUpdate */);
2458                     }
2459                 } break;
2460                 case IDLE_TIMEOUT_MSG: {
2461                     if (DEBUG_IDLE) Slog.d(TAG_IDLE,
2462                             "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
2463                     // We don't at this point know if the activity is fullscreen, so we need to be
2464                     // conservative and assume it isn't.
2465                     activityIdleFromMessage((ActivityRecord) msg.obj, true /* fromTimeout */);
2466                 } break;
2467                 case IDLE_NOW_MSG: {
2468                     if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
2469                     activityIdleFromMessage((ActivityRecord) msg.obj, false /* fromTimeout */);
2470                 } break;
2471                 case RESUME_TOP_ACTIVITY_MSG: {
2472                     mRootWindowContainer.resumeFocusedTasksTopActivities();
2473                 } break;
2474                 case SLEEP_TIMEOUT_MSG: {
2475                     if (mService.isSleepingOrShuttingDownLocked()) {
2476                         Slog.w(TAG, "Sleep timeout!  Sleeping now.");
2477                         checkReadyForSleepLocked(false /* allowDelay */);
2478                     }
2479                 } break;
2480                 case LAUNCH_TIMEOUT_MSG: {
2481                     if (mLaunchingActivityWakeLock.isHeld()) {
2482                         Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
2483                         if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != SYSTEM_UID) {
2484                             throw new IllegalStateException("Calling must be system uid");
2485                         }
2486                         mLaunchingActivityWakeLock.release();
2487                     }
2488                 } break;
2489                 case PROCESS_STOPPING_AND_FINISHING_MSG: {
2490                     processStoppingAndFinishingActivities(null /* launchedActivity */,
2491                             false /* processPausingActivities */, "transit");
2492                 } break;
2493                 case LAUNCH_TASK_BEHIND_COMPLETE: {
2494                     final ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
2495                     if (r != null) {
2496                         handleLaunchTaskBehindCompleteLocked(r);
2497                     }
2498                 } break;
2499                 case START_HOME_MSG: {
2500                     mHandler.removeMessages(START_HOME_MSG);
2501 
2502                     // Start home activities on displays with no activities.
2503                     mRootWindowContainer.startHomeOnEmptyDisplays((String) msg.obj);
2504                 } break;
2505                 case TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG: {
2506                     final ActivityRecord r = (ActivityRecord) msg.obj;
2507                     Slog.w(TAG, "Activity top resumed state loss timeout for " + r);
2508                     if (r.hasProcess()) {
2509                         mService.logAppTooSlow(r.app, r.topResumedStateLossTime,
2510                                 "top state loss for " + r);
2511                     }
2512                     handleTopResumedStateReleased(true /* timeout */);
2513                 } break;
2514                 default:
2515                     return false;
2516             }
2517             return true;
2518         }
2519     }
2520 
2521     /**
2522      * Start the given task from the recent tasks. Do not hold WM global lock when calling this
2523      * method to avoid potential deadlock or permission deny by UriGrantsManager when resolving
2524      * activity (see {@link ActivityStarter.Request#resolveActivity} and
2525      * {@link com.android.server.am.ContentProviderHelper#checkContentProviderUriPermission}).
2526      *
2527      * @return The result code of starter.
2528      */
startActivityFromRecents(int callingPid, int callingUid, int taskId, SafeActivityOptions options)2529     int startActivityFromRecents(int callingPid, int callingUid, int taskId,
2530             SafeActivityOptions options) {
2531         final Task task;
2532         final int taskCallingUid;
2533         final String callingPackage;
2534         final String callingFeatureId;
2535         final Intent intent;
2536         final int userId;
2537         final ActivityOptions activityOptions = options != null
2538                 ? options.getOptions(this)
2539                 : null;
2540         boolean moveHomeTaskForward = true;
2541         synchronized (mService.mGlobalLock) {
2542             int activityType = ACTIVITY_TYPE_UNDEFINED;
2543             if (activityOptions != null) {
2544                 activityType = activityOptions.getLaunchActivityType();
2545                 final int windowingMode = activityOptions.getLaunchWindowingMode();
2546                 if (activityOptions.freezeRecentTasksReordering()
2547                         && mService.checkPermission(MANAGE_ACTIVITY_TASKS, callingPid, callingUid)
2548                                 == PERMISSION_GRANTED) {
2549                     mRecentTasks.setFreezeTaskListReordering();
2550                 }
2551                 if (activityOptions.getLaunchRootTask() != null) {
2552                     // Don't move home activity forward if there is a launch root set.
2553                     moveHomeTaskForward = false;
2554                 }
2555             }
2556             if (activityType == ACTIVITY_TYPE_HOME || activityType == ACTIVITY_TYPE_RECENTS) {
2557                 throw new IllegalArgumentException("startActivityFromRecents: Task "
2558                         + taskId + " can't be launch in the home/recents root task.");
2559             }
2560 
2561             boolean shouldStartActivity = false;
2562             mService.deferWindowLayout();
2563             try {
2564                 task = mRootWindowContainer.anyTaskForId(taskId,
2565                         MATCH_ATTACHED_TASK_OR_RECENT_TASKS_AND_RESTORE, activityOptions, ON_TOP);
2566                 if (task == null) {
2567                     mWindowManager.executeAppTransition();
2568                     throw new IllegalArgumentException(
2569                             "startActivityFromRecents: Task " + taskId + " not found.");
2570                 }
2571 
2572                 if (moveHomeTaskForward) {
2573                     // We always want to return to the home activity instead of the recents
2574                     // activity from whatever is started from the recents activity, so move
2575                     // the home root task forward.
2576                     // TODO (b/115289124): Multi-display supports for recents.
2577                     mRootWindowContainer.getDefaultTaskDisplayArea().moveHomeRootTaskToFront(
2578                             "startActivityFromRecents");
2579                 }
2580 
2581                 // If the user must confirm credentials (e.g. when first launching a work
2582                 // app and the Work Challenge is present) let startActivityInPackage handle
2583                 // the intercepting.
2584                 if (!mService.mAmInternal.shouldConfirmCredentials(task.mUserId)
2585                         && task.getRootActivity() != null) {
2586                     final ActivityRecord targetActivity = task.getTopNonFinishingActivity();
2587 
2588                     mRootWindowContainer.startPowerModeLaunchIfNeeded(
2589                             true /* forceSend */, targetActivity);
2590                     final LaunchingState launchingState =
2591                             mActivityMetricsLogger.notifyActivityLaunching(task.intent);
2592                     try {
2593                         mService.moveTaskToFrontLocked(null /* appThread */,
2594                                 null /* callingPackage */, task.mTaskId, 0, options);
2595                         // Apply options to prevent pendingOptions be taken when scheduling
2596                         // activity lifecycle transaction to make sure the override pending app
2597                         // transition will be applied immediately.
2598                         if (activityOptions != null
2599                                 && activityOptions.getAnimationType() == ANIM_REMOTE_ANIMATION) {
2600                             targetActivity.mPendingRemoteAnimation =
2601                                     activityOptions.getRemoteAnimationAdapter();
2602                         }
2603                         targetActivity.applyOptionsAnimation();
2604                         if (activityOptions != null && activityOptions.getLaunchCookie() != null) {
2605                             targetActivity.mLaunchCookie = activityOptions.getLaunchCookie();
2606                         }
2607                     } finally {
2608                         mActivityMetricsLogger.notifyActivityLaunched(launchingState,
2609                                 START_TASK_TO_FRONT, false /* newActivityCreated */,
2610                                 targetActivity, activityOptions);
2611                     }
2612 
2613                     mService.getActivityStartController().postStartActivityProcessingForLastStarter(
2614                             task.getTopNonFinishingActivity(), ActivityManager.START_TASK_TO_FRONT,
2615                             task.getRootTask());
2616 
2617                     // As it doesn't go to ActivityStarter.executeRequest() path, we need to resume
2618                     // app switching here also.
2619                     mService.resumeAppSwitches();
2620                     return ActivityManager.START_TASK_TO_FRONT;
2621                 }
2622                 // The task is empty or needs to show the confirmation for credential.
2623                 shouldStartActivity = true;
2624             } finally {
2625                 if (!shouldStartActivity) {
2626                     mService.continueWindowLayout();
2627                 }
2628             }
2629             taskCallingUid = task.mCallingUid;
2630             callingPackage = task.mCallingPackage;
2631             callingFeatureId = task.mCallingFeatureId;
2632             intent = task.intent;
2633             intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
2634             userId = task.mUserId;
2635         }
2636         // ActivityStarter will acquire the lock where the places need, so execute the request
2637         // outside of the lock.
2638         try {
2639             // We need to temporarily disable the explicit intent filter matching enforcement
2640             // because Task does not store the resolved type of the intent data, causing filter
2641             // mismatch in certain cases. (b/240373119)
2642             PackageManagerServiceUtils.DISABLE_ENFORCE_INTENTS_TO_MATCH_INTENT_FILTERS.set(true);
2643             return mService.getActivityStartController().startActivityInPackage(taskCallingUid,
2644                     callingPid, callingUid, callingPackage, callingFeatureId, intent, null, null,
2645                     null, 0, 0, options, userId, task, "startActivityFromRecents",
2646                     false /* validateIncomingUser */, null /* originatingPendingIntent */,
2647                     false /* allowBackgroundActivityStart */);
2648         } finally {
2649             PackageManagerServiceUtils.DISABLE_ENFORCE_INTENTS_TO_MATCH_INTENT_FILTERS.set(false);
2650             synchronized (mService.mGlobalLock) {
2651                 mService.continueWindowLayout();
2652             }
2653         }
2654     }
2655 
2656     /**
2657      * Fills the info that needs to iterate all activities of task, such as the number of
2658      * non-finishing activities and collecting launch cookies.
2659      */
2660     static class TaskInfoHelper implements Consumer<ActivityRecord> {
2661         private TaskInfo mInfo;
2662         private ActivityRecord mTopRunning;
2663 
fillAndReturnTop(Task task, TaskInfo info)2664         ActivityRecord fillAndReturnTop(Task task, TaskInfo info) {
2665             info.numActivities = 0;
2666             info.baseActivity = null;
2667             mInfo = info;
2668             task.forAllActivities(this);
2669             final ActivityRecord top = mTopRunning;
2670             mTopRunning = null;
2671             mInfo = null;
2672             return top;
2673         }
2674 
2675         @Override
accept(ActivityRecord r)2676         public void accept(ActivityRecord r) {
2677             if (r.mLaunchCookie != null) {
2678                 mInfo.addLaunchCookie(r.mLaunchCookie);
2679             }
2680             if (r.finishing) {
2681                 return;
2682             }
2683             mInfo.numActivities++;
2684             mInfo.baseActivity = r.mActivityComponent;
2685             if (mTopRunning == null) {
2686                 mTopRunning = r;
2687             }
2688         }
2689     }
2690 
2691     /**
2692      * Internal container to store a match qualifier alongside a WaitResult.
2693      */
2694     private static class WaitInfo {
2695         final WaitResult mResult;
2696         final ComponentName mTargetComponent;
2697         /**
2698          * The target component may not be the final drawn activity. The launching state is managed
2699          * by {@link ActivityMetricsLogger} that can track consecutive launching sequence.
2700          */
2701         final LaunchingState mLaunchingState;
2702 
WaitInfo(WaitResult result, ComponentName component, LaunchingState launchingState)2703         WaitInfo(WaitResult result, ComponentName component, LaunchingState launchingState) {
2704             mResult = result;
2705             mTargetComponent = component;
2706             mLaunchingState = launchingState;
2707         }
2708 
matches(ActivityRecord r)2709         boolean matches(ActivityRecord r) {
2710             if (!mLaunchingState.hasActiveTransitionInfo()) {
2711                 return mTargetComponent.equals(r.mActivityComponent);
2712             }
2713             return mLaunchingState.contains(r);
2714         }
2715 
dump(PrintWriter pw, String prefix)2716         void dump(PrintWriter pw, String prefix) {
2717             pw.println(prefix + "WaitInfo:");
2718             pw.println(prefix + "  mTargetComponent=" + mTargetComponent);
2719             pw.println(prefix + "  mResult=");
2720             mResult.dump(pw, prefix + "    ");
2721         }
2722     }
2723 }
2724