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