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