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_LAUNCHABLE;
79 import static com.android.server.wm.Task.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
80 import static com.android.server.wm.Task.LOCK_TASK_AUTH_WHITELISTED;
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 
736         try {
737             r.startFreezingScreenLocked(proc, 0);
738 
739             // schedule launch ticks to collect information about slow apps.
740             r.startLaunchTickingLocked();
741 
742             r.setProcess(proc);
743 
744             // Ensure activity is allowed to be resumed after process has set.
745             if (andResume && !r.canResumeByCompat()) {
746                 andResume = false;
747             }
748 
749             r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
750 
751             // Have the window manager re-evaluate the orientation of the screen based on the new
752             // activity order.  Note that as a result of this, it can call back into the activity
753             // manager with a new orientation.  We don't care about that, because the activity is
754             // not currently running so we are just restarting it anyway.
755             if (checkConfig) {
756                 // Deferring resume here because we're going to launch new activity shortly.
757                 // We don't want to perform a redundant launch of the same record while ensuring
758                 // configurations and trying to resume top activity of focused stack.
759                 mRootWindowContainer.ensureVisibilityAndConfig(r, r.getDisplayId(),
760                         false /* markFrozenIfConfigChanged */, true /* deferResume */);
761             }
762 
763             if (r.getRootTask().checkKeyguardVisibility(r, true /* shouldBeVisible */,
764                     true /* isTop */) && r.allowMoveToFront()) {
765                 // We only set the visibility to true if the activity is not being launched in
766                 // background, and is allowed to be visible based on keyguard state. This avoids
767                 // setting this into motion in window manager that is later cancelled due to later
768                 // calls to ensure visible activities that set visibility back to false.
769                 r.setVisibility(true);
770             }
771 
772             final int applicationInfoUid =
773                     (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
774             if ((r.mUserId != proc.mUserId) || (r.info.applicationInfo.uid != applicationInfoUid)) {
775                 Slog.wtf(TAG,
776                         "User ID for activity changing for " + r
777                                 + " appInfo.uid=" + r.info.applicationInfo.uid
778                                 + " info.ai.uid=" + applicationInfoUid
779                                 + " old=" + r.app + " new=" + proc);
780             }
781 
782             r.launchCount++;
783             r.lastLaunchTime = SystemClock.uptimeMillis();
784             proc.setLastActivityLaunchTime(r.lastLaunchTime);
785 
786             if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
787 
788             final LockTaskController lockTaskController = mService.getLockTaskController();
789             if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE
790                     || task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV
791                     || (task.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED
792                             && lockTaskController.getLockTaskModeState()
793                                     == LOCK_TASK_MODE_LOCKED)) {
794                 lockTaskController.startLockTaskMode(task, false, 0 /* blank UID */);
795             }
796 
797             try {
798                 if (!proc.hasThread()) {
799                     throw new RemoteException();
800                 }
801                 List<ResultInfo> results = null;
802                 List<ReferrerIntent> newIntents = null;
803                 if (andResume) {
804                     // We don't need to deliver new intents and/or set results if activity is going
805                     // to pause immediately after launch.
806                     results = r.results;
807                     newIntents = r.newIntents;
808                 }
809                 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
810                         "Launching: " + r + " savedState=" + r.getSavedState()
811                                 + " with results=" + results + " newIntents=" + newIntents
812                                 + " andResume=" + andResume);
813                 EventLogTags.writeWmRestartActivity(r.mUserId, System.identityHashCode(r),
814                         task.mTaskId, r.shortComponentName);
815                 if (r.isActivityTypeHome()) {
816                     // Home process is the root process of the task.
817                     updateHomeProcess(task.getBottomMostActivity().app);
818                 }
819                 mService.getPackageManagerInternalLocked().notifyPackageUse(
820                         r.intent.getComponent().getPackageName(), NOTIFY_PACKAGE_USE_ACTIVITY);
821                 r.setSleeping(false);
822                 r.forceNewConfig = false;
823                 mService.getAppWarningsLocked().onStartActivity(r);
824                 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
825 
826                 // Because we could be starting an Activity in the system process this may not go
827                 // across a Binder interface which would create a new Configuration. Consequently
828                 // we have to always create a new Configuration here.
829 
830                 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
831                         proc.getConfiguration(), r.getMergedOverrideConfiguration());
832                 r.setLastReportedConfiguration(mergedConfiguration);
833 
834                 logIfTransactionTooLarge(r.intent, r.getSavedState());
835 
836 
837                 // Create activity launch transaction.
838                 final ClientTransaction clientTransaction = ClientTransaction.obtain(
839                         proc.getThread(), r.appToken);
840 
841                 final DisplayContent dc = r.getDisplay().mDisplayContent;
842                 clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
843                         System.identityHashCode(r), r.info,
844                         // TODO: Have this take the merged configuration instead of separate global
845                         // and override configs.
846                         mergedConfiguration.getGlobalConfiguration(),
847                         mergedConfiguration.getOverrideConfiguration(), r.compat,
848                         r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
849                         r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
850                         dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
851                         r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
852 
853                 // Set desired final state.
854                 final ActivityLifecycleItem lifecycleItem;
855                 if (andResume) {
856                     lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
857                 } else {
858                     lifecycleItem = PauseActivityItem.obtain();
859                 }
860                 clientTransaction.setLifecycleStateRequest(lifecycleItem);
861 
862                 // Schedule transaction.
863                 mService.getLifecycleManager().scheduleTransaction(clientTransaction);
864 
865                 if ((proc.mInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0
866                         && mService.mHasHeavyWeightFeature) {
867                     // This may be a heavy-weight process! Note that the package manager will ensure
868                     // that only activity can run in the main process of the .apk, which is the only
869                     // thing that will be considered heavy-weight.
870                     if (proc.mName.equals(proc.mInfo.packageName)) {
871                         if (mService.mHeavyWeightProcess != null
872                                 && mService.mHeavyWeightProcess != proc) {
873                             Slog.w(TAG, "Starting new heavy weight process " + proc
874                                     + " when already running "
875                                     + mService.mHeavyWeightProcess);
876                         }
877                         mService.setHeavyWeightProcess(r);
878                     }
879                 }
880 
881             } catch (RemoteException e) {
882                 if (r.launchFailed) {
883                     // This is the second time we failed -- finish activity and give up.
884                     Slog.e(TAG, "Second failure launching "
885                             + r.intent.getComponent().flattenToShortString() + ", giving up", e);
886                     proc.appDied("2nd-crash");
887                     r.finishIfPossible("2nd-crash", false /* oomAdj */);
888                     return false;
889                 }
890 
891                 // This is the first time we failed -- restart process and
892                 // retry.
893                 r.launchFailed = true;
894                 proc.removeActivity(r);
895                 throw e;
896             }
897         } finally {
898             endDeferResume();
899         }
900 
901         r.launchFailed = false;
902 
903         // TODO(lifecycler): Resume or pause requests are done as part of launch transaction,
904         // so updating the state should be done accordingly.
905         if (andResume && readyToResume()) {
906             // As part of the process of launching, ActivityThread also performs
907             // a resume.
908             stack.minimalResumeActivityLocked(r);
909         } else {
910             // This activity is not starting in the resumed state... which should look like we asked
911             // it to pause+stop (but remain visible), and it has done so and reported back the
912             // current icicle and other state.
913             if (DEBUG_STATES) Slog.v(TAG_STATES,
914                     "Moving to PAUSED: " + r + " (starting in paused state)");
915             r.setState(PAUSED, "realStartActivityLocked");
916             mRootWindowContainer.executeAppTransitionForAllDisplay();
917         }
918         // Perform OOM scoring after the activity state is set, so the process can be updated with
919         // the latest state.
920         proc.onStartActivity(mService.mTopProcessState, r.info);
921 
922         // Launch the new version setup screen if needed.  We do this -after-
923         // launching the initial activity (that is, home), so that it can have
924         // a chance to initialize itself while in the background, making the
925         // switch back to it faster and look better.
926         if (mRootWindowContainer.isTopDisplayFocusedStack(stack)) {
927             mService.getActivityStartController().startSetupActivity();
928         }
929 
930         // Update any services we are bound to that might care about whether
931         // their client may have activities.
932         if (r.app != null) {
933             r.app.updateServiceConnectionActivities();
934         }
935 
936         return true;
937     }
938 
updateHomeProcess(WindowProcessController app)939     void updateHomeProcess(WindowProcessController app) {
940         if (app != null && mService.mHomeProcess != app) {
941             if (!mHandler.hasMessages(REPORT_HOME_CHANGED_MSG)) {
942                 mHandler.sendEmptyMessage(REPORT_HOME_CHANGED_MSG);
943             }
944             mService.mHomeProcess = app;
945         }
946     }
947 
logIfTransactionTooLarge(Intent intent, Bundle icicle)948     private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
949         int extrasSize = 0;
950         if (intent != null) {
951             final Bundle extras = intent.getExtras();
952             if (extras != null) {
953                 extrasSize = extras.getSize();
954             }
955         }
956         int icicleSize = (icicle == null ? 0 : icicle.getSize());
957         if (extrasSize + icicleSize > 200000) {
958             Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
959                     + ", icicle size: " + icicleSize);
960         }
961     }
962 
startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig)963     void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
964         // Is this activity's application already running?
965         final WindowProcessController wpc =
966                 mService.getProcessController(r.processName, r.info.applicationInfo.uid);
967 
968         boolean knownToBeDead = false;
969         if (wpc != null && wpc.hasThread()) {
970             try {
971                 realStartActivityLocked(r, wpc, andResume, checkConfig);
972                 return;
973             } catch (RemoteException e) {
974                 Slog.w(TAG, "Exception when starting activity "
975                         + r.intent.getComponent().flattenToShortString(), e);
976             }
977 
978             // If a dead object exception was thrown -- fall through to
979             // restart the application.
980             knownToBeDead = true;
981         }
982 
983         r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
984 
985         final boolean isTop = andResume && r.isTopRunningActivity();
986         mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
987     }
988 
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)989     boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo, String resultWho,
990             int requestCode, int callingPid, int callingUid, String callingPackage,
991             @Nullable String callingFeatureId, boolean ignoreTargetSecurity,
992             boolean launchingInTask, WindowProcessController callerApp, ActivityRecord resultRecord,
993             ActivityStack resultStack) {
994         final boolean isCallerRecents = mService.getRecentTasks() != null
995                 && mService.getRecentTasks().isCallerRecents(callingUid);
996         final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
997                 callingUid);
998         if (startAnyPerm == PERMISSION_GRANTED || (isCallerRecents && launchingInTask)) {
999             // If the caller has START_ANY_ACTIVITY, ignore all checks below. In addition, if the
1000             // caller is the recents component and we are specifically starting an activity in an
1001             // existing task, then also allow the activity to be fully relaunched.
1002             return true;
1003         }
1004         final int componentRestriction = getComponentRestrictionForCallingPackage(aInfo,
1005                 callingPackage, callingFeatureId, callingPid, callingUid, ignoreTargetSecurity);
1006         final int actionRestriction = getActionRestrictionForCallingPackage(
1007                 intent.getAction(), callingPackage, callingFeatureId, callingPid, callingUid);
1008         if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1009                 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1010             if (resultRecord != null) {
1011                 resultRecord.sendResult(INVALID_UID, resultWho, requestCode,
1012                         Activity.RESULT_CANCELED, null /* data */, null /* dataGrants */);
1013             }
1014             final String msg;
1015             if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1016                 msg = "Permission Denial: starting " + intent.toString()
1017                         + " from " + callerApp + " (pid=" + callingPid
1018                         + ", uid=" + callingUid + ")" + " with revoked permission "
1019                         + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1020             } else if (!aInfo.exported) {
1021                 msg = "Permission Denial: starting " + intent.toString()
1022                         + " from " + callerApp + " (pid=" + callingPid
1023                         + ", uid=" + callingUid + ")"
1024                         + " not exported from uid " + aInfo.applicationInfo.uid;
1025             } else {
1026                 msg = "Permission Denial: starting " + intent.toString()
1027                         + " from " + callerApp + " (pid=" + callingPid
1028                         + ", uid=" + callingUid + ")"
1029                         + " requires " + aInfo.permission;
1030             }
1031             Slog.w(TAG, msg);
1032             throw new SecurityException(msg);
1033         }
1034 
1035         if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1036             final String message = "Appop Denial: starting " + intent.toString()
1037                     + " from " + callerApp + " (pid=" + callingPid
1038                     + ", uid=" + callingUid + ")"
1039                     + " requires " + AppOpsManager.permissionToOp(
1040                             ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1041             Slog.w(TAG, message);
1042             return false;
1043         } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1044             final String message = "Appop Denial: starting " + intent.toString()
1045                     + " from " + callerApp + " (pid=" + callingPid
1046                     + ", uid=" + callingUid + ")"
1047                     + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1048             Slog.w(TAG, message);
1049             return false;
1050         }
1051 
1052         return true;
1053     }
1054 
1055     /** Check if caller is allowed to launch activities on specified task display area. */
isCallerAllowedToLaunchOnTaskDisplayArea(int callingPid, int callingUid, TaskDisplayArea taskDisplayArea, ActivityInfo aInfo)1056     boolean isCallerAllowedToLaunchOnTaskDisplayArea(int callingPid, int callingUid,
1057             TaskDisplayArea taskDisplayArea, ActivityInfo aInfo) {
1058         return isCallerAllowedToLaunchOnDisplay(callingPid, callingUid,
1059                 taskDisplayArea != null ? taskDisplayArea.getDisplayId() : DEFAULT_DISPLAY, aInfo);
1060     }
1061 
1062     /** Check if caller is allowed to launch activities on specified display. */
isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId, ActivityInfo aInfo)1063     boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId,
1064             ActivityInfo aInfo) {
1065         if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId
1066                 + " callingPid=" + callingPid + " callingUid=" + callingUid);
1067 
1068         if (callingPid == -1 && callingUid == -1) {
1069             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: no caller info, skip check");
1070             return true;
1071         }
1072 
1073         final DisplayContent displayContent =
1074                 mRootWindowContainer.getDisplayContentOrCreate(launchDisplayId);
1075         if (displayContent == null || displayContent.isRemoved()) {
1076             Slog.w(TAG, "Launch on display check: display not found");
1077             return false;
1078         }
1079 
1080         // Check if the caller has enough privileges to embed activities and launch to private
1081         // displays.
1082         final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
1083                 callingUid);
1084         if (startAnyPerm == PERMISSION_GRANTED) {
1085             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1086                     + " allow launch any on display");
1087             return true;
1088         }
1089 
1090         // Check if caller is already present on display
1091         final boolean uidPresentOnDisplay = displayContent.isUidPresent(callingUid);
1092 
1093         final int displayOwnerUid = displayContent.mDisplay.getOwnerUid();
1094         if (displayContent.mDisplay.getType() == TYPE_VIRTUAL && displayOwnerUid != SYSTEM_UID) {
1095             // Limit launching on virtual displays, because their contents can be read from Surface
1096             // by apps that created them.
1097             if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
1098                 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1099                         + " disallow launch on virtual display for not-embedded activity.");
1100                 return false;
1101             }
1102             // Check if the caller is allowed to embed activities from other apps.
1103             if (mService.checkPermission(ACTIVITY_EMBEDDING, callingPid, callingUid)
1104                     == PERMISSION_DENIED && !uidPresentOnDisplay) {
1105                 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1106                         + " disallow activity embedding without permission.");
1107                 return false;
1108             }
1109         }
1110 
1111         if (!displayContent.isPrivate()) {
1112             // Anyone can launch on a public display.
1113             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1114                     + " allow launch on public display");
1115             return true;
1116         }
1117 
1118         // Check if the caller is the owner of the display.
1119         if (displayOwnerUid == callingUid) {
1120             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1121                     + " allow launch for owner of the display");
1122             return true;
1123         }
1124 
1125         if (uidPresentOnDisplay) {
1126             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1127                     + " allow launch for caller present on the display");
1128             return true;
1129         }
1130 
1131         Slog.w(TAG, "Launch on display check: denied");
1132         return false;
1133     }
1134 
getUserInfo(int userId)1135     UserInfo getUserInfo(int userId) {
1136         final long identity = Binder.clearCallingIdentity();
1137         try {
1138             return UserManager.get(mService.mContext).getUserInfo(userId);
1139         } finally {
1140             Binder.restoreCallingIdentity(identity);
1141         }
1142     }
1143 
getAppOpsManager()1144     private AppOpsManager getAppOpsManager() {
1145         if (mAppOpsManager == null) {
1146             mAppOpsManager = mService.mContext.getSystemService(AppOpsManager.class);
1147         }
1148         return mAppOpsManager;
1149     }
1150 
getComponentRestrictionForCallingPackage(ActivityInfo activityInfo, String callingPackage, @Nullable String callingFeatureId, int callingPid, int callingUid, boolean ignoreTargetSecurity)1151     private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
1152             String callingPackage, @Nullable String callingFeatureId, int callingPid,
1153             int callingUid, boolean ignoreTargetSecurity) {
1154         if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1155                 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
1156                 == PERMISSION_DENIED) {
1157             return ACTIVITY_RESTRICTION_PERMISSION;
1158         }
1159 
1160         if (activityInfo.permission == null) {
1161             return ACTIVITY_RESTRICTION_NONE;
1162         }
1163 
1164         final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1165         if (opCode == AppOpsManager.OP_NONE) {
1166             return ACTIVITY_RESTRICTION_NONE;
1167         }
1168 
1169         if (getAppOpsManager().noteOpNoThrow(opCode, callingUid,
1170                 callingPackage, callingFeatureId, "") != AppOpsManager.MODE_ALLOWED) {
1171             if (!ignoreTargetSecurity) {
1172                 return ACTIVITY_RESTRICTION_APPOP;
1173             }
1174         }
1175 
1176         return ACTIVITY_RESTRICTION_NONE;
1177     }
1178 
getActionRestrictionForCallingPackage(String action, String callingPackage, @Nullable String callingFeatureId, int callingPid, int callingUid)1179     private int getActionRestrictionForCallingPackage(String action, String callingPackage,
1180             @Nullable String callingFeatureId, int callingPid, int callingUid) {
1181         if (action == null) {
1182             return ACTIVITY_RESTRICTION_NONE;
1183         }
1184 
1185         String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1186         if (permission == null) {
1187             return ACTIVITY_RESTRICTION_NONE;
1188         }
1189 
1190         final PackageInfo packageInfo;
1191         try {
1192             packageInfo = mService.mContext.getPackageManager()
1193                     .getPackageInfoAsUser(callingPackage, PackageManager.GET_PERMISSIONS,
1194                             UserHandle.getUserId(callingUid));
1195         } catch (PackageManager.NameNotFoundException e) {
1196             Slog.i(TAG, "Cannot find package info for " + callingPackage);
1197             return ACTIVITY_RESTRICTION_NONE;
1198         }
1199 
1200         if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
1201             return ACTIVITY_RESTRICTION_NONE;
1202         }
1203 
1204         if (mService.checkPermission(permission, callingPid, callingUid) == PERMISSION_DENIED) {
1205             return ACTIVITY_RESTRICTION_PERMISSION;
1206         }
1207 
1208         final int opCode = AppOpsManager.permissionToOpCode(permission);
1209         if (opCode == AppOpsManager.OP_NONE) {
1210             return ACTIVITY_RESTRICTION_NONE;
1211         }
1212 
1213         if (getAppOpsManager().noteOpNoThrow(opCode, callingUid,
1214                 callingPackage, callingFeatureId, "") != AppOpsManager.MODE_ALLOWED) {
1215             return ACTIVITY_RESTRICTION_APPOP;
1216         }
1217 
1218         return ACTIVITY_RESTRICTION_NONE;
1219     }
1220 
setLaunchSource(int uid)1221     void setLaunchSource(int uid) {
1222         mLaunchingActivityWakeLock.setWorkSource(new WorkSource(uid));
1223     }
1224 
acquireLaunchWakelock()1225     void acquireLaunchWakelock() {
1226         if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1227             throw new IllegalStateException("Calling must be system uid");
1228         }
1229         mLaunchingActivityWakeLock.acquire();
1230         if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1231             // To be safe, don't allow the wake lock to be held for too long.
1232             mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1233         }
1234     }
1235 
1236     /**
1237      * Called when all resumed tasks/stacks are idle.
1238      * @return the state of mService.mAm.mBooting before this was called.
1239      */
1240     @GuardedBy("mService")
checkFinishBootingLocked()1241     private boolean checkFinishBootingLocked() {
1242         final boolean booting = mService.isBooting();
1243         boolean enableScreen = false;
1244         mService.setBooting(false);
1245         if (!mService.isBooted()) {
1246             mService.setBooted(true);
1247             enableScreen = true;
1248         }
1249         if (booting || enableScreen) {
1250             mService.postFinishBooting(booting, enableScreen);
1251         }
1252         return booting;
1253     }
1254 
activityIdleInternal(ActivityRecord r, boolean fromTimeout, boolean processPausingActivities, Configuration config)1255     void activityIdleInternal(ActivityRecord r, boolean fromTimeout,
1256             boolean processPausingActivities, Configuration config) {
1257         if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + r);
1258 
1259         boolean booting = false;
1260 
1261         if (r != null) {
1262             if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternal: Callers="
1263                     + Debug.getCallers(4));
1264             mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1265             r.finishLaunchTickingLocked();
1266             if (fromTimeout) {
1267                 reportActivityLaunchedLocked(fromTimeout, r, INVALID_DELAY,
1268                         -1 /* launchState */);
1269             }
1270 
1271             // This is a hack to semi-deal with a race condition
1272             // in the client where it can be constructed with a
1273             // newer configuration from when we asked it to launch.
1274             // We'll update with whatever configuration it now says
1275             // it used to launch.
1276             if (config != null) {
1277                 r.setLastReportedGlobalConfiguration(config);
1278             }
1279 
1280             // We are now idle.  If someone is waiting for a thumbnail from
1281             // us, we can now deliver.
1282             r.idle = true;
1283 
1284             //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
1285 
1286             // Check if able to finish booting when device is booting and all resumed activities
1287             // are idle.
1288             if ((mService.isBooting() && mRootWindowContainer.allResumedActivitiesIdle())
1289                     || fromTimeout) {
1290                 booting = checkFinishBootingLocked();
1291             }
1292 
1293             // When activity is idle, we consider the relaunch must be successful, so let's clear
1294             // the flag.
1295             r.mRelaunchReason = RELAUNCH_REASON_NONE;
1296         }
1297 
1298         if (mRootWindowContainer.allResumedActivitiesIdle()) {
1299             if (r != null) {
1300                 mService.scheduleAppGcsLocked();
1301             }
1302 
1303             if (mLaunchingActivityWakeLock.isHeld()) {
1304                 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1305                 if (VALIDATE_WAKE_LOCK_CALLER &&
1306                         Binder.getCallingUid() != Process.myUid()) {
1307                     throw new IllegalStateException("Calling must be system uid");
1308                 }
1309                 mLaunchingActivityWakeLock.release();
1310             }
1311             mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
1312         }
1313 
1314         // Atomically retrieve all of the other things to do.
1315         processStoppingAndFinishingActivities(r, processPausingActivities, "idle");
1316 
1317         if (!mStartingUsers.isEmpty()) {
1318             final ArrayList<UserState> startingUsers = new ArrayList<>(mStartingUsers);
1319             mStartingUsers.clear();
1320 
1321             if (!booting) {
1322                 // Complete user switch.
1323                 for (int i = 0; i < startingUsers.size(); i++) {
1324                     mService.mAmInternal.finishUserSwitch(startingUsers.get(i));
1325                 }
1326             }
1327         }
1328 
1329         mService.mH.post(() -> mService.mAmInternal.trimApplications());
1330     }
1331 
1332     /** 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)1333     void findTaskToMoveToFront(Task task, int flags, ActivityOptions options, String reason,
1334             boolean forceNonResizeable) {
1335         ActivityStack currentStack = task.getStack();
1336         if (currentStack == null) {
1337             Slog.e(TAG, "findTaskToMoveToFront: can't move task="
1338                     + task + " to front. Stack is null");
1339             return;
1340         }
1341 
1342         if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
1343             mUserLeaving = true;
1344         }
1345 
1346         reason = reason + " findTaskToMoveToFront";
1347         boolean reparented = false;
1348         if (task.isResizeable() && canUseActivityOptionsLaunchBounds(options)) {
1349             final Rect bounds = options.getLaunchBounds();
1350             task.setBounds(bounds);
1351 
1352             ActivityStack stack =
1353                     mRootWindowContainer.getLaunchStack(null, options, task, ON_TOP);
1354 
1355             if (stack != currentStack) {
1356                 moveHomeStackToFrontIfNeeded(flags, stack.getDisplayArea(), reason);
1357                 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE, DEFER_RESUME,
1358                         reason);
1359                 currentStack = stack;
1360                 reparented = true;
1361                 // task.reparent() should already placed the task on top,
1362                 // still need moveTaskToFrontLocked() below for any transition settings.
1363             }
1364             if (stack.shouldResizeStackWithLaunchBounds()) {
1365                 stack.resize(bounds, !PRESERVE_WINDOWS, !DEFER_RESUME);
1366             } else {
1367                 // WM resizeTask must be done after the task is moved to the correct stack,
1368                 // because Task's setBounds() also updates dim layer's bounds, but that has
1369                 // dependency on the stack.
1370                 task.resize(false /* relayout */, false /* forced */);
1371             }
1372         }
1373 
1374         if (!reparented) {
1375             moveHomeStackToFrontIfNeeded(flags, currentStack.getDisplayArea(), reason);
1376         }
1377 
1378         final ActivityRecord r = task.getTopNonFinishingActivity();
1379         currentStack.moveTaskToFront(task, false /* noAnimation */, options,
1380                 r == null ? null : r.appTimeTracker, reason);
1381 
1382         if (DEBUG_STACK) Slog.d(TAG_STACK,
1383                 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
1384 
1385         handleNonResizableTaskIfNeeded(task, WINDOWING_MODE_UNDEFINED,
1386                 mRootWindowContainer.getDefaultTaskDisplayArea(), currentStack, forceNonResizeable);
1387     }
1388 
moveHomeStackToFrontIfNeeded(int flags, TaskDisplayArea taskDisplayArea, String reason)1389     private void moveHomeStackToFrontIfNeeded(int flags, TaskDisplayArea taskDisplayArea,
1390             String reason) {
1391         final ActivityStack focusedStack = taskDisplayArea.getFocusedStack();
1392 
1393         if ((taskDisplayArea.getWindowingMode() == WINDOWING_MODE_FULLSCREEN
1394                 && (flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0)
1395                 || (focusedStack != null && focusedStack.isActivityTypeRecents())) {
1396             // We move home stack to front when we are on a fullscreen display area and caller has
1397             // requested the home activity to move with it. Or the previous stack is recents.
1398             taskDisplayArea.moveHomeStackToFront(reason);
1399         }
1400     }
1401 
canUseActivityOptionsLaunchBounds(ActivityOptions options)1402     boolean canUseActivityOptionsLaunchBounds(ActivityOptions options) {
1403         // We use the launch bounds in the activity options is the device supports freeform
1404         // window management or is launching into the pinned stack.
1405         if (options == null || options.getLaunchBounds() == null) {
1406             return false;
1407         }
1408         return (mService.mSupportsPictureInPicture
1409                 && options.getLaunchWindowingMode() == WINDOWING_MODE_PINNED)
1410                 || mService.mSupportsFreeformWindowManagement;
1411     }
1412 
getLaunchParamsController()1413     LaunchParamsController getLaunchParamsController() {
1414         return mLaunchParamsController;
1415     }
1416 
setSplitScreenResizing(boolean resizing)1417     void setSplitScreenResizing(boolean resizing) {
1418         if (resizing == mDockedStackResizing) {
1419             return;
1420         }
1421 
1422         mDockedStackResizing = resizing;
1423         mWindowManager.setDockedStackResizing(resizing);
1424     }
1425 
removePinnedStackInSurfaceTransaction(ActivityStack stack)1426     private void removePinnedStackInSurfaceTransaction(ActivityStack stack) {
1427         /**
1428          * Workaround: Force-stop all the activities in the pinned stack before we reparent them
1429          * to the fullscreen stack.  This is to guarantee that when we are removing a stack,
1430          * that the client receives onStop() before new windowing mode is set.
1431          * We do this by detaching the stack from the display so that it will be considered
1432          * invisible when ensureActivitiesVisible() is called, and all of its activities will be
1433          * marked invisible as well and added to the stopping list.  After which we process the
1434          * stopping list by handling the idle.
1435          */
1436         stack.cancelAnimation();
1437         stack.setForceHidden(FLAG_FORCE_HIDDEN_FOR_PINNED_TASK, true /* set */);
1438         stack.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
1439         activityIdleInternal(null /* idleActivity */, false /* fromTimeout */,
1440                 true /* processPausingActivities */, null /* configuration */);
1441 
1442         // Reparent all the tasks to the bottom of the display
1443         final DisplayContent toDisplay =
1444                 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
1445 
1446         mService.deferWindowLayout();
1447         try {
1448             stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
1449             stack.setBounds(null);
1450             toDisplay.getDefaultTaskDisplayArea().positionTaskBehindHome(stack);
1451 
1452             // Follow on the workaround: activities are kept force hidden till the new windowing
1453             // mode is set.
1454             stack.setForceHidden(FLAG_FORCE_HIDDEN_FOR_PINNED_TASK, false /* set */);
1455             mRootWindowContainer.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
1456             mRootWindowContainer.resumeFocusedStacksTopActivities();
1457         } finally {
1458             mService.continueWindowLayout();
1459         }
1460     }
1461 
removeStackInSurfaceTransaction(ActivityStack stack)1462     private void removeStackInSurfaceTransaction(ActivityStack stack) {
1463         if (stack.getWindowingMode() == WINDOWING_MODE_PINNED) {
1464             removePinnedStackInSurfaceTransaction(stack);
1465         } else {
1466             final PooledConsumer c = PooledLambda.obtainConsumer(
1467                     ActivityStackSupervisor::processRemoveTask, this, PooledLambda.__(Task.class));
1468             stack.forAllLeafTasks(c, true /* traverseTopToBottom */);
1469             c.recycle();
1470         }
1471     }
1472 
processRemoveTask(Task task)1473     private void processRemoveTask(Task task) {
1474         removeTask(task, true /* killProcess */, REMOVE_FROM_RECENTS, "remove-stack");
1475     }
1476 
1477     /**
1478      * Removes the stack associated with the given {@param stack}. If the {@param stack} is the
1479      * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
1480      * instead moved back onto the fullscreen stack.
1481      */
removeStack(ActivityStack stack)1482     void removeStack(ActivityStack stack) {
1483         mWindowManager.inSurfaceTransaction(() -> removeStackInSurfaceTransaction(stack));
1484     }
1485 
1486     /**
1487      * Removes the task with the specified task id.
1488      *
1489      * @param taskId Identifier of the task to be removed.
1490      * @param killProcess Kill any process associated with the task if possible.
1491      * @param removeFromRecents Whether to also remove the task from recents.
1492      * @return Returns true if the given task was found and removed.
1493      */
removeTaskById(int taskId, boolean killProcess, boolean removeFromRecents, String reason)1494     boolean removeTaskById(int taskId, boolean killProcess, boolean removeFromRecents,
1495             String reason) {
1496         final Task task =
1497                 mRootWindowContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1498         if (task != null) {
1499             removeTask(task, killProcess, removeFromRecents, reason);
1500             return true;
1501         }
1502         Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
1503         return false;
1504     }
1505 
removeTask(Task task, boolean killProcess, boolean removeFromRecents, String reason)1506     void removeTask(Task task, boolean killProcess, boolean removeFromRecents, String reason) {
1507         if (task.mInRemoveTask) {
1508             // Prevent recursion.
1509             return;
1510         }
1511         task.mInRemoveTask = true;
1512         try {
1513             task.performClearTask(reason);
1514             cleanUpRemovedTaskLocked(task, killProcess, removeFromRecents);
1515             mService.getLockTaskController().clearLockedTask(task);
1516             mService.getTaskChangeNotificationController().notifyTaskStackChanged();
1517             if (task.isPersistable) {
1518                 mService.notifyTaskPersisterLocked(null, true);
1519             }
1520         } finally {
1521             task.mInRemoveTask = false;
1522         }
1523     }
1524 
cleanUpRemovedTaskLocked(Task task, boolean killProcess, boolean removeFromRecents)1525     void cleanUpRemovedTaskLocked(Task task, boolean killProcess, boolean removeFromRecents) {
1526         if (removeFromRecents) {
1527             mRecentTasks.remove(task);
1528         }
1529         ComponentName component = task.getBaseIntent().getComponent();
1530         if (component == null) {
1531             Slog.w(TAG, "No component for base intent of task: " + task);
1532             return;
1533         }
1534 
1535         // Find any running services associated with this app and stop if needed.
1536         final Message msg = PooledLambda.obtainMessage(ActivityManagerInternal::cleanUpServices,
1537                 mService.mAmInternal, task.mUserId, component, new Intent(task.getBaseIntent()));
1538         mService.mH.sendMessage(msg);
1539 
1540         if (!killProcess) {
1541             return;
1542         }
1543 
1544         // Determine if the process(es) for this task should be killed.
1545         final String pkg = component.getPackageName();
1546         ArrayList<Object> procsToKill = new ArrayList<>();
1547         ArrayMap<String, SparseArray<WindowProcessController>> pmap =
1548                 mService.mProcessNames.getMap();
1549         for (int i = 0; i < pmap.size(); i++) {
1550 
1551             SparseArray<WindowProcessController> uids = pmap.valueAt(i);
1552             for (int j = 0; j < uids.size(); j++) {
1553                 WindowProcessController proc = uids.valueAt(j);
1554                 if (proc.mUserId != task.mUserId) {
1555                     // Don't kill process for a different user.
1556                     continue;
1557                 }
1558                 if (proc == mService.mHomeProcess) {
1559                     // Don't kill the home process along with tasks from the same package.
1560                     continue;
1561                 }
1562                 if (!proc.mPkgList.contains(pkg)) {
1563                     // Don't kill process that is not associated with this task.
1564                     continue;
1565                 }
1566 
1567                 if (!proc.shouldKillProcessForRemovedTask(task)) {
1568                     // Don't kill process(es) that has an activity in a different task that is also
1569                     // in recents, or has an activity not stopped.
1570                     return;
1571                 }
1572 
1573                 if (proc.hasForegroundServices()) {
1574                     // Don't kill process(es) with foreground service.
1575                     return;
1576                 }
1577 
1578                 // Add process to kill list.
1579                 procsToKill.add(proc);
1580             }
1581         }
1582 
1583         // Kill the running processes. Post on handle since we don't want to hold the service lock
1584         // while calling into AM.
1585         final Message m = PooledLambda.obtainMessage(
1586                 ActivityManagerInternal::killProcessesForRemovedTask, mService.mAmInternal,
1587                 procsToKill);
1588         mService.mH.sendMessage(m);
1589     }
1590 
1591     /**
1592      * Called to restore the state of the task into the stack that it's supposed to go into.
1593      *
1594      * @param task The recent task to be restored.
1595      * @param aOptions The activity options to use for restoration.
1596      * @param onTop If the stack for the task should be the topmost on the display.
1597      * @return true if the task has been restored successfully.
1598      */
restoreRecentTaskLocked(Task task, ActivityOptions aOptions, boolean onTop)1599     boolean restoreRecentTaskLocked(Task task, ActivityOptions aOptions, boolean onTop) {
1600         final ActivityStack stack =
1601                 mRootWindowContainer.getLaunchStack(null, aOptions, task, onTop);
1602         final WindowContainer parent = task.getParent();
1603 
1604         if (parent == stack || task == stack) {
1605             // Nothing else to do since it is already restored in the right stack.
1606             return true;
1607         }
1608 
1609         if (parent != null) {
1610             // Task has already been restored once. Just re-parent it to the new stack.
1611             task.reparent(stack, POSITION_TOP, true /*moveParents*/, "restoreRecentTaskLocked");
1612             return true;
1613         }
1614 
1615         stack.addChild(task, onTop, true /* showForAllUsers */);
1616         if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
1617                 "Added restored task=" + task + " to stack=" + stack);
1618         return true;
1619     }
1620 
1621     @Override
onRecentTaskAdded(Task task)1622     public void onRecentTaskAdded(Task task) {
1623         task.touchActiveTime();
1624     }
1625 
1626     @Override
onRecentTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess)1627     public void onRecentTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess) {
1628         if (wasTrimmed) {
1629             // Task was trimmed from the recent tasks list -- remove the active task record as well
1630             // since the user won't really be able to go back to it
1631             removeTaskById(task.mTaskId, killProcess, false /* removeFromRecents */,
1632                     "recent-task-trimmed");
1633         }
1634         task.removedFromRecents();
1635     }
1636 
1637     /**
1638      * Returns the reparent target stack, creating the stack if necessary.  This call also enforces
1639      * the various checks on tasks that are going to be reparented from one stack to another.
1640      */
1641     // TODO: Look into changing users to this method to DisplayContent.resolveWindowingMode()
getReparentTargetStack(Task task, ActivityStack stack, boolean toTop)1642     ActivityStack getReparentTargetStack(Task task, ActivityStack stack, boolean toTop) {
1643         final ActivityStack prevStack = task.getStack();
1644         final int rootTaskId = stack.mTaskId;
1645         final boolean inMultiWindowMode = stack.inMultiWindowMode();
1646 
1647         // Check that we aren't reparenting to the same stack that the task is already in
1648         if (prevStack != null && prevStack.mTaskId == rootTaskId) {
1649             Slog.w(TAG, "Can not reparent to same stack, task=" + task
1650                     + " already in stackId=" + rootTaskId);
1651             return prevStack;
1652         }
1653 
1654         // Ensure that we aren't trying to move into a multi-window stack without multi-window
1655         // support
1656         if (inMultiWindowMode && !mService.mSupportsMultiWindow) {
1657             throw new IllegalArgumentException("Device doesn't support multi-window, can not"
1658                     + " reparent task=" + task + " to stack=" + stack);
1659         }
1660 
1661         // Ensure that we're not moving a task to a dynamic stack if device doesn't support
1662         // multi-display.
1663         if (stack.getDisplayId() != DEFAULT_DISPLAY && !mService.mSupportsMultiDisplay) {
1664             throw new IllegalArgumentException("Device doesn't support multi-display, can not"
1665                     + " reparent task=" + task + " to stackId=" + rootTaskId);
1666         }
1667 
1668         // Ensure that we aren't trying to move into a freeform stack without freeform support
1669         if (stack.getWindowingMode() == WINDOWING_MODE_FREEFORM
1670                 && !mService.mSupportsFreeformWindowManagement) {
1671             throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
1672                     + " task=" + task);
1673         }
1674 
1675         // Leave the task in its current stack or a fullscreen stack if it isn't resizeable and the
1676         // preferred stack is in multi-window mode.
1677         if (inMultiWindowMode && !task.isResizeable()) {
1678             Slog.w(TAG, "Can not move unresizeable task=" + task + " to multi-window stack=" + stack
1679                     + " Moving to a fullscreen stack instead.");
1680             if (prevStack != null) {
1681                 return prevStack;
1682             }
1683             stack = stack.getDisplayArea().createStack(
1684                     WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), toTop);
1685         }
1686         return stack;
1687     }
1688 
goingToSleepLocked()1689     void goingToSleepLocked() {
1690         scheduleSleepTimeout();
1691         if (!mGoingToSleepWakeLock.isHeld()) {
1692             mGoingToSleepWakeLock.acquire();
1693             if (mLaunchingActivityWakeLock.isHeld()) {
1694                 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1695                     throw new IllegalStateException("Calling must be system uid");
1696                 }
1697                 mLaunchingActivityWakeLock.release();
1698                 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1699             }
1700         }
1701 
1702         mRootWindowContainer.applySleepTokens(false /* applyToStacks */);
1703 
1704         checkReadyForSleepLocked(true /* allowDelay */);
1705     }
1706 
shutdownLocked(int timeout)1707     boolean shutdownLocked(int timeout) {
1708         goingToSleepLocked();
1709 
1710         boolean timedout = false;
1711         final long endTime = System.currentTimeMillis() + timeout;
1712         while (true) {
1713             if (!mRootWindowContainer.putStacksToSleep(
1714                     true /* allowDelay */, true /* shuttingDown */)) {
1715                 long timeRemaining = endTime - System.currentTimeMillis();
1716                 if (timeRemaining > 0) {
1717                     try {
1718                         mService.mGlobalLock.wait(timeRemaining);
1719                     } catch (InterruptedException e) {
1720                     }
1721                 } else {
1722                     Slog.w(TAG, "Activity manager shutdown timed out");
1723                     timedout = true;
1724                     break;
1725                 }
1726             } else {
1727                 break;
1728             }
1729         }
1730 
1731         // Force checkReadyForSleep to complete.
1732         checkReadyForSleepLocked(false /* allowDelay */);
1733 
1734         return timedout;
1735     }
1736 
comeOutOfSleepIfNeededLocked()1737     void comeOutOfSleepIfNeededLocked() {
1738         removeSleepTimeouts();
1739         if (mGoingToSleepWakeLock.isHeld()) {
1740             mGoingToSleepWakeLock.release();
1741         }
1742     }
1743 
checkReadyForSleepLocked(boolean allowDelay)1744     void checkReadyForSleepLocked(boolean allowDelay) {
1745         if (!mService.isSleepingOrShuttingDownLocked()) {
1746             // Do not care.
1747             return;
1748         }
1749 
1750         if (!mRootWindowContainer.putStacksToSleep(
1751                 allowDelay, false /* shuttingDown */)) {
1752             return;
1753         }
1754 
1755         // Send launch end powerhint before going sleep
1756         mRootWindowContainer.sendPowerHintForLaunchEndIfNeeded();
1757 
1758         removeSleepTimeouts();
1759 
1760         if (mGoingToSleepWakeLock.isHeld()) {
1761             mGoingToSleepWakeLock.release();
1762         }
1763         if (mService.mShuttingDown) {
1764             mService.mGlobalLock.notifyAll();
1765         }
1766     }
1767 
reportResumedActivityLocked(ActivityRecord r)1768     boolean reportResumedActivityLocked(ActivityRecord r) {
1769         // A resumed activity cannot be stopping. remove from list
1770         mStoppingActivities.remove(r);
1771 
1772         final ActivityStack stack = r.getRootTask();
1773         if (stack.getDisplayArea().allResumedActivitiesComplete()) {
1774             mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
1775             // Make sure activity & window visibility should be identical
1776             // for all displays in this stage.
1777             mRootWindowContainer.executeAppTransitionForAllDisplay();
1778             return true;
1779         }
1780         return false;
1781     }
1782 
1783     // Called when WindowManager has finished animating the launchingBehind activity to the back.
handleLaunchTaskBehindCompleteLocked(ActivityRecord r)1784     private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
1785         final Task task = r.getTask();
1786         final ActivityStack stack = task.getStack();
1787 
1788         mRecentTasks.add(task);
1789         mService.getTaskChangeNotificationController().notifyTaskStackChanged();
1790         stack.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
1791 
1792         // When launching tasks behind, update the last active time of the top task after the new
1793         // task has been shown briefly
1794         final ActivityRecord top = stack.getTopNonFinishingActivity();
1795         if (top != null) {
1796             top.getTask().touchActiveTime();
1797         }
1798     }
1799 
scheduleLaunchTaskBehindComplete(IBinder token)1800     void scheduleLaunchTaskBehindComplete(IBinder token) {
1801         mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
1802     }
1803 
1804     /** Checks whether the userid is a profile of the current user. */
isCurrentProfileLocked(int userId)1805     boolean isCurrentProfileLocked(int userId) {
1806         if (userId == mRootWindowContainer.mCurrentUser) return true;
1807         return mService.mAmInternal.isCurrentProfile(userId);
1808     }
1809 
1810     /**
1811      * Processes the activities to be stopped or destroyed. This should be called when the resumed
1812      * activities are idle or drawn.
1813      */
processStoppingAndFinishingActivities(ActivityRecord launchedActivity, boolean processPausingActivities, String reason)1814     private void processStoppingAndFinishingActivities(ActivityRecord launchedActivity,
1815             boolean processPausingActivities, String reason) {
1816         // Stop any activities that are scheduled to do so but have been waiting for the transition
1817         // animation to finish.
1818         ArrayList<ActivityRecord> readyToStopActivities = null;
1819         for (int i = mStoppingActivities.size() - 1; i >= 0; --i) {
1820             final ActivityRecord s = mStoppingActivities.get(i);
1821             final boolean animating = s.isAnimating(TRANSITION | PARENTS,
1822                     ANIMATION_TYPE_APP_TRANSITION | ANIMATION_TYPE_RECENTS);
1823             if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + s.nowVisible
1824                     + " animating=" + animating + " finishing=" + s.finishing);
1825             if (!animating || mService.mShuttingDown) {
1826                 if (!processPausingActivities && s.isState(PAUSING)) {
1827                     // Defer processing pausing activities in this iteration and reschedule
1828                     // a delayed idle to reprocess it again
1829                     removeIdleTimeoutForActivity(launchedActivity);
1830                     scheduleIdleTimeout(launchedActivity);
1831                     continue;
1832                 }
1833 
1834                 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
1835                 if (readyToStopActivities == null) {
1836                     readyToStopActivities = new ArrayList<>();
1837                 }
1838                 readyToStopActivities.add(s);
1839 
1840                 mStoppingActivities.remove(i);
1841             }
1842         }
1843 
1844         final int numReadyStops = readyToStopActivities == null ? 0 : readyToStopActivities.size();
1845         for (int i = 0; i < numReadyStops; i++) {
1846             final ActivityRecord r = readyToStopActivities.get(i);
1847             if (r.isInHistory()) {
1848                 if (r.finishing) {
1849                     // TODO(b/137329632): Wait for idle of the right activity, not just any.
1850                     r.destroyIfPossible(reason);
1851                 } else {
1852                     r.stopIfPossible();
1853                 }
1854             }
1855         }
1856 
1857         final int numFinishingActivities = mFinishingActivities.size();
1858         if (numFinishingActivities == 0) {
1859             return;
1860         }
1861 
1862         // Finish any activities that are scheduled to do so but have been waiting for the next one
1863         // to start.
1864         final ArrayList<ActivityRecord> finishingActivities = new ArrayList<>(mFinishingActivities);
1865         mFinishingActivities.clear();
1866         for (int i = 0; i < numFinishingActivities; i++) {
1867             final ActivityRecord r = finishingActivities.get(i);
1868             if (r.isInHistory()) {
1869                 r.destroyImmediately(true /* removeFromApp */, "finish-" + reason);
1870             }
1871         }
1872     }
1873 
removeHistoryRecords(WindowProcessController app)1874     void removeHistoryRecords(WindowProcessController app) {
1875         removeHistoryRecords(mStoppingActivities, app, "mStoppingActivities");
1876         removeHistoryRecords(mFinishingActivities, app, "mFinishingActivities");
1877     }
1878 
removeHistoryRecords(ArrayList<ActivityRecord> list, WindowProcessController app, String listName)1879     private void removeHistoryRecords(ArrayList<ActivityRecord> list, WindowProcessController app,
1880             String listName) {
1881         int i = list.size();
1882         if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
1883                 "Removing app " + this + " from list " + listName + " with " + i + " entries");
1884         while (i > 0) {
1885             i--;
1886             ActivityRecord r = list.get(i);
1887             if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "Record #" + i + " " + r);
1888             if (r.app == app) {
1889                 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "---> REMOVING this entry!");
1890                 list.remove(i);
1891                 r.removeTimeouts();
1892             }
1893         }
1894     }
1895 
dump(PrintWriter pw, String prefix)1896     public void dump(PrintWriter pw, String prefix) {
1897         pw.println();
1898         pw.println("ActivityStackSupervisor state:");
1899         mRootWindowContainer.dump(pw, prefix, true /* dumpAll */);
1900         getKeyguardController().dump(pw, prefix);
1901         mService.getLockTaskController().dump(pw, prefix);
1902         pw.print(prefix);
1903         pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
1904         pw.println(prefix + "mUserStackInFront=" + mRootWindowContainer.mUserStackInFront);
1905         pw.println(prefix + "mVisibilityTransactionDepth=" + mVisibilityTransactionDepth);
1906         if (!mWaitingForActivityVisible.isEmpty()) {
1907             pw.println(prefix + "mWaitingForActivityVisible=");
1908             for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
1909                 pw.print(prefix + prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
1910             }
1911         }
1912         pw.print(prefix); pw.print("isHomeRecentsComponent=");
1913         pw.println(mRecentTasks.isRecentsComponentHomeActivity(mRootWindowContainer.mCurrentUser));
1914         pw.println();
1915     }
1916 
printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage, boolean needSep, String prefix, Runnable header)1917     static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
1918             boolean needSep, String prefix, Runnable header) {
1919         if (activity != null) {
1920             if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
1921                 if (needSep) {
1922                     pw.println();
1923                 }
1924                 if (header != null) {
1925                     header.run();
1926                 }
1927                 pw.print(prefix);
1928                 pw.println(activity);
1929                 return true;
1930             }
1931         }
1932         return false;
1933     }
1934 
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)1935     static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
1936             String prefix, String label, boolean complete, boolean brief, boolean client,
1937             String dumpPackage, boolean needNL, Runnable header, Task lastTask) {
1938         String innerPrefix = null;
1939         String[] args = null;
1940         boolean printed = false;
1941         for (int i=list.size()-1; i>=0; i--) {
1942             final ActivityRecord r = list.get(i);
1943             if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
1944                 continue;
1945             }
1946             if (innerPrefix == null) {
1947                 innerPrefix = prefix + "      ";
1948                 args = new String[0];
1949             }
1950             printed = true;
1951             final boolean full = !brief && (complete || !r.isInHistory());
1952             if (needNL) {
1953                 pw.println("");
1954                 needNL = false;
1955             }
1956             if (header != null) {
1957                 header.run();
1958                 header = null;
1959             }
1960             if (lastTask != r.getTask()) {
1961                 lastTask = r.getTask();
1962                 pw.print(prefix);
1963                 pw.print(full ? "* " : "  ");
1964                 pw.println(lastTask);
1965                 if (full) {
1966                     lastTask.dump(pw, prefix + "  ");
1967                 } else if (complete) {
1968                     // Complete + brief == give a summary.  Isn't that obvious?!?
1969                     if (lastTask.intent != null) {
1970                         pw.print(prefix); pw.print("  ");
1971                                 pw.println(lastTask.intent.toInsecureString());
1972                     }
1973                 }
1974             }
1975             pw.print(prefix); pw.print(full ? "  * " : "    "); pw.print(label);
1976             pw.print(" #"); pw.print(i); pw.print(": ");
1977             pw.println(r);
1978             if (full) {
1979                 r.dump(pw, innerPrefix, true /* dumpAll */);
1980             } else if (complete) {
1981                 // Complete + brief == give a summary.  Isn't that obvious?!?
1982                 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
1983                 if (r.app != null) {
1984                     pw.print(innerPrefix); pw.println(r.app);
1985                 }
1986             }
1987             if (client && r.attachedToProcess()) {
1988                 // flush anything that is already in the PrintWriter since the thread is going
1989                 // to write to the file descriptor directly
1990                 pw.flush();
1991                 try {
1992                     TransferPipe tp = new TransferPipe();
1993                     try {
1994                         r.app.getThread().dumpActivity(
1995                                 tp.getWriteFd(), r.appToken, innerPrefix, args);
1996                         // Short timeout, since blocking here can deadlock with the application.
1997                         tp.go(fd, 2000);
1998                     } finally {
1999                         tp.kill();
2000                     }
2001                 } catch (IOException e) {
2002                     pw.println(innerPrefix + "Failure while dumping the activity: " + e);
2003                 } catch (RemoteException e) {
2004                     pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
2005                 }
2006                 needNL = true;
2007             }
2008         }
2009         return printed;
2010     }
2011 
scheduleIdleTimeout(ActivityRecord next)2012     void scheduleIdleTimeout(ActivityRecord next) {
2013         if (DEBUG_IDLE) Slog.d(TAG_IDLE, "scheduleIdleTimeout: Callers=" + Debug.getCallers(4));
2014         Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
2015         mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
2016     }
2017 
scheduleIdle()2018     final void scheduleIdle() {
2019         mHandler.sendEmptyMessage(IDLE_NOW_MSG);
2020     }
2021 
2022     /**
2023      * Updates the record of top resumed activity when it changes and handles reporting of the
2024      * state changes to previous and new top activities. It will immediately dispatch top resumed
2025      * state loss message to previous top activity (if haven't done it already). After the previous
2026      * activity releases the top state and reports back, message about acquiring top state will be
2027      * sent to the new top resumed activity.
2028      */
updateTopResumedActivityIfNeeded()2029     void updateTopResumedActivityIfNeeded() {
2030         final ActivityRecord prevTopActivity = mTopResumedActivity;
2031         final ActivityStack topStack = mRootWindowContainer.getTopDisplayFocusedStack();
2032         if (topStack == null || topStack.mResumedActivity == prevTopActivity) {
2033             return;
2034         }
2035 
2036         // Ask previous activity to release the top state.
2037         final boolean prevActivityReceivedTopState =
2038                 prevTopActivity != null && !mTopResumedActivityWaitingForPrev;
2039         // mTopResumedActivityWaitingForPrev == true at this point would mean that an activity
2040         // before the prevTopActivity one hasn't reported back yet. So server never sent the top
2041         // resumed state change message to prevTopActivity.
2042         if (prevActivityReceivedTopState
2043                 && prevTopActivity.scheduleTopResumedActivityChanged(false /* onTop */)) {
2044             scheduleTopResumedStateLossTimeout(prevTopActivity);
2045             mTopResumedActivityWaitingForPrev = true;
2046         }
2047 
2048         // Update the current top activity.
2049         mTopResumedActivity = topStack.mResumedActivity;
2050         scheduleTopResumedActivityStateIfNeeded();
2051     }
2052 
2053     /** Schedule top resumed state change if previous top activity already reported back. */
scheduleTopResumedActivityStateIfNeeded()2054     private void scheduleTopResumedActivityStateIfNeeded() {
2055         if (mTopResumedActivity != null && !mTopResumedActivityWaitingForPrev) {
2056             mTopResumedActivity.scheduleTopResumedActivityChanged(true /* onTop */);
2057         }
2058     }
2059 
2060     /**
2061      * Limit the time given to the app to report handling of the state loss.
2062      */
scheduleTopResumedStateLossTimeout(ActivityRecord r)2063     private void scheduleTopResumedStateLossTimeout(ActivityRecord r) {
2064         final Message msg = mHandler.obtainMessage(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG);
2065         msg.obj = r;
2066         r.topResumedStateLossTime = SystemClock.uptimeMillis();
2067         mHandler.sendMessageDelayed(msg, TOP_RESUMED_STATE_LOSS_TIMEOUT);
2068         if (DEBUG_STATES) Slog.v(TAG_STATES, "Waiting for top state to be released by " + r);
2069     }
2070 
2071     /**
2072      * Handle a loss of top resumed state by an activity - update internal state and inform next top
2073      * activity if needed.
2074      */
handleTopResumedStateReleased(boolean timeout)2075     void handleTopResumedStateReleased(boolean timeout) {
2076         if (DEBUG_STATES) {
2077             Slog.v(TAG_STATES, "Top resumed state released "
2078                     + (timeout ? " (due to timeout)" : " (transition complete)"));
2079         }
2080         mHandler.removeMessages(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG);
2081         if (!mTopResumedActivityWaitingForPrev) {
2082             // Top resumed activity state loss already handled.
2083             return;
2084         }
2085         mTopResumedActivityWaitingForPrev = false;
2086         scheduleTopResumedActivityStateIfNeeded();
2087     }
2088 
removeIdleTimeoutForActivity(ActivityRecord r)2089     void removeIdleTimeoutForActivity(ActivityRecord r) {
2090         if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
2091                 + Debug.getCallers(4));
2092         mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
2093     }
2094 
scheduleResumeTopActivities()2095     final void scheduleResumeTopActivities() {
2096         if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
2097             mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
2098         }
2099     }
2100 
scheduleProcessStoppingAndFinishingActivities()2101     void scheduleProcessStoppingAndFinishingActivities() {
2102         if (!mHandler.hasMessages(PROCESS_STOPPING_AND_FINISHING_MSG)) {
2103             mHandler.sendEmptyMessage(PROCESS_STOPPING_AND_FINISHING_MSG);
2104         }
2105     }
2106 
removeSleepTimeouts()2107     void removeSleepTimeouts() {
2108         mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
2109     }
2110 
scheduleSleepTimeout()2111     final void scheduleSleepTimeout() {
2112         removeSleepTimeouts();
2113         mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
2114     }
2115 
removeRestartTimeouts(ActivityRecord r)2116     void removeRestartTimeouts(ActivityRecord r) {
2117         mHandler.removeMessages(RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG, r);
2118     }
2119 
scheduleRestartTimeout(ActivityRecord r)2120     final void scheduleRestartTimeout(ActivityRecord r) {
2121         removeRestartTimeouts(r);
2122         mHandler.sendMessageDelayed(mHandler.obtainMessage(RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG, r),
2123                 WindowManagerService.WINDOW_FREEZE_TIMEOUT_DURATION);
2124     }
2125 
handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode, TaskDisplayArea preferredTaskDisplayArea, ActivityStack actualStack)2126     void handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode,
2127             TaskDisplayArea preferredTaskDisplayArea, ActivityStack actualStack) {
2128         handleNonResizableTaskIfNeeded(task, preferredWindowingMode, preferredTaskDisplayArea,
2129                 actualStack, false /* forceNonResizable */);
2130     }
2131 
handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode, TaskDisplayArea preferredTaskDisplayArea, ActivityStack actualStack, boolean forceNonResizable)2132     void handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode,
2133             TaskDisplayArea preferredTaskDisplayArea, ActivityStack actualStack,
2134             boolean forceNonResizable) {
2135         final boolean isSecondaryDisplayPreferred = preferredTaskDisplayArea != null
2136                 && preferredTaskDisplayArea.getDisplayId() != DEFAULT_DISPLAY;
2137         final boolean inSplitScreenMode = actualStack != null
2138                 && actualStack.getDisplayArea().isSplitScreenModeActivated();
2139         if (((!inSplitScreenMode && preferredWindowingMode != WINDOWING_MODE_SPLIT_SCREEN_PRIMARY)
2140                 && !isSecondaryDisplayPreferred) || !task.isActivityTypeStandardOrUndefined()) {
2141             return;
2142         }
2143 
2144         // Handle incorrect launch/move to secondary display if needed.
2145         if (isSecondaryDisplayPreferred) {
2146             if (!task.canBeLaunchedOnDisplay(task.getDisplayId())) {
2147                 throw new IllegalStateException("Task resolved to incompatible display");
2148             }
2149 
2150             final DisplayContent preferredDisplay = preferredTaskDisplayArea.mDisplayContent;
2151 
2152             final boolean singleTaskInstance = preferredDisplay != null
2153                     && preferredDisplay.isSingleTaskInstance();
2154 
2155             if (preferredDisplay != task.getDisplayContent()) {
2156                 // Suppress the warning toast if the preferredDisplay was set to singleTask.
2157                 // The singleTaskInstance displays will only contain one task and any attempt to
2158                 // launch new task will re-route to the default display.
2159                 if (singleTaskInstance) {
2160                     mService.getTaskChangeNotificationController()
2161                             .notifyActivityLaunchOnSecondaryDisplayRerouted(task.getTaskInfo(),
2162                                     preferredDisplay.mDisplayId);
2163                     return;
2164                 }
2165 
2166                 Slog.w(TAG, "Failed to put " + task + " on display " + preferredDisplay.mDisplayId);
2167                 // Display a warning toast that we failed to put a task on a secondary display.
2168                 mService.getTaskChangeNotificationController()
2169                         .notifyActivityLaunchOnSecondaryDisplayFailed(task.getTaskInfo(),
2170                                 preferredDisplay.mDisplayId);
2171             } else if (!forceNonResizable) {
2172                 handleForcedResizableTaskIfNeeded(task, FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY);
2173             }
2174             // The information about not support secondary display should already be notified, we
2175             // don't want to show another message on default display about split-screen. And it may
2176             // be the case that a resizable activity is launched on a non-resizable task.
2177             return;
2178         }
2179 
2180         if (!task.supportsSplitScreenWindowingMode() || forceNonResizable) {
2181             // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
2182             // we need to move it to top of fullscreen stack, otherwise it will be covered.
2183             final TaskDisplayArea taskDisplayArea = task.getDisplayArea();
2184             if (taskDisplayArea.isSplitScreenModeActivated()) {
2185                 // Display a warning toast that we tried to put an app that doesn't support
2186                 // split-screen in split-screen.
2187                 mService.getTaskChangeNotificationController()
2188                         .notifyActivityDismissingDockedStack();
2189                 taskDisplayArea.onSplitScreenModeDismissed((ActivityStack) task);
2190                 taskDisplayArea.mDisplayContent.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2191                         true /* notifyClients */);
2192             }
2193             return;
2194         }
2195 
2196         handleForcedResizableTaskIfNeeded(task, FORCED_RESIZEABLE_REASON_SPLIT_SCREEN);
2197     }
2198 
2199     /** Notifies that the top activity of the task is forced to be resizeable. */
handleForcedResizableTaskIfNeeded(Task task, int reason)2200     private void handleForcedResizableTaskIfNeeded(Task task, int reason) {
2201         final ActivityRecord topActivity = task.getTopNonFinishingActivity();
2202         if (topActivity == null || topActivity.noDisplay
2203                 || !topActivity.isNonResizableOrForcedResizable(task.getWindowingMode())) {
2204             return;
2205         }
2206         mService.getTaskChangeNotificationController().notifyActivityForcedResizable(
2207                 task.mTaskId, reason, topActivity.info.applicationInfo.packageName);
2208     }
2209 
activityRelaunchedLocked(IBinder token)2210     void activityRelaunchedLocked(IBinder token) {
2211         final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2212         if (r != null) {
2213             r.finishRelaunching();
2214             if (r.getRootTask().shouldSleepOrShutDownActivities()) {
2215                 // Activity is always relaunched to either resumed or paused state. If it was
2216                 // relaunched while hidden (by keyguard or smth else), it should be stopped.
2217                 r.getStack().ensureActivitiesVisible(null /* starting */, 0 /* configChanges */,
2218                         false /* preserveWindows */);
2219             }
2220         }
2221     }
2222 
logStackState()2223     void logStackState() {
2224         mActivityMetricsLogger.logWindowState();
2225     }
2226 
scheduleUpdateMultiWindowMode(Task task)2227     void scheduleUpdateMultiWindowMode(Task task) {
2228         final PooledConsumer c = PooledLambda.obtainConsumer(
2229                 ActivityStackSupervisor::addToMultiWindowModeChangedList, this,
2230                 PooledLambda.__(ActivityRecord.class));
2231         task.forAllActivities(c);
2232         c.recycle();
2233 
2234         if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
2235             mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
2236         }
2237     }
2238 
addToMultiWindowModeChangedList(ActivityRecord r)2239     private void addToMultiWindowModeChangedList(ActivityRecord r) {
2240         if (r.attachedToProcess()) {
2241             mMultiWindowModeChangedActivities.add(r);
2242         }
2243     }
2244 
scheduleUpdatePictureInPictureModeIfNeeded(Task task, ActivityStack prevStack)2245     void scheduleUpdatePictureInPictureModeIfNeeded(Task task, ActivityStack prevStack) {
2246         final ActivityStack stack = task.getStack();
2247         if ((prevStack == null || (prevStack != stack
2248                 && !prevStack.inPinnedWindowingMode() && !stack.inPinnedWindowingMode()))) {
2249             return;
2250         }
2251 
2252         scheduleUpdatePictureInPictureModeIfNeeded(task, stack.getRequestedOverrideBounds());
2253     }
2254 
scheduleUpdatePictureInPictureModeIfNeeded(Task task, Rect targetStackBounds)2255     private void scheduleUpdatePictureInPictureModeIfNeeded(Task task, Rect targetStackBounds) {
2256         final PooledConsumer c = PooledLambda.obtainConsumer(
2257                 ActivityStackSupervisor::addToPipModeChangedList, this,
2258                 PooledLambda.__(ActivityRecord.class));
2259         task.forAllActivities(c);
2260         c.recycle();
2261 
2262         mPipModeChangedTargetStackBounds = targetStackBounds;
2263 
2264         if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
2265             mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
2266         }
2267     }
2268 
addToPipModeChangedList(ActivityRecord r)2269     private void addToPipModeChangedList(ActivityRecord r) {
2270         if (!r.attachedToProcess()) return;
2271 
2272         mPipModeChangedActivities.add(r);
2273         // If we are scheduling pip change, then remove this activity from multi-window
2274         // change list as the processing of pip change will make sure multi-window changed
2275         // message is processed in the right order relative to pip changed.
2276         mMultiWindowModeChangedActivities.remove(r);
2277     }
2278 
updatePictureInPictureMode(Task task, Rect targetStackBounds, boolean forceUpdate)2279     void updatePictureInPictureMode(Task task, Rect targetStackBounds, boolean forceUpdate) {
2280         mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG);
2281         final PooledConsumer c = PooledLambda.obtainConsumer(
2282                 ActivityRecord::updatePictureInPictureMode,
2283                 PooledLambda.__(ActivityRecord.class), targetStackBounds, forceUpdate);
2284         task.getStack().setBounds(targetStackBounds);
2285         task.forAllActivities(c);
2286         c.recycle();
2287     }
2288 
wakeUp(String reason)2289     void wakeUp(String reason) {
2290         mPowerManager.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_APPLICATION,
2291                 "android.server.am:TURN_ON:" + reason);
2292     }
2293 
2294     /** Starts a batch of visibility updates. */
beginActivityVisibilityUpdate()2295     void beginActivityVisibilityUpdate() {
2296         mVisibilityTransactionDepth++;
2297     }
2298 
2299     /** Ends a batch of visibility updates. */
endActivityVisibilityUpdate()2300     void endActivityVisibilityUpdate() {
2301         mVisibilityTransactionDepth--;
2302         if (mVisibilityTransactionDepth == 0) {
2303             getKeyguardController().visibilitiesUpdated();
2304         }
2305     }
2306 
2307     /** Returns {@code true} if the caller is on the path to update visibility. */
inActivityVisibilityUpdate()2308     boolean inActivityVisibilityUpdate() {
2309         return mVisibilityTransactionDepth > 0;
2310     }
2311 
2312     /**
2313      * Begin deferring resume to avoid duplicate resumes in one pass.
2314      */
beginDeferResume()2315     void beginDeferResume() {
2316         mDeferResumeCount++;
2317     }
2318 
2319     /**
2320      * End deferring resume and determine if resume can be called.
2321      */
endDeferResume()2322     void endDeferResume() {
2323         mDeferResumeCount--;
2324     }
2325 
2326     /** @return True if resume can be called. */
readyToResume()2327     boolean readyToResume() {
2328         return mDeferResumeCount == 0;
2329     }
2330 
2331     private final class ActivityStackSupervisorHandler extends Handler {
2332 
ActivityStackSupervisorHandler(Looper looper)2333         ActivityStackSupervisorHandler(Looper looper) {
2334             super(looper);
2335         }
2336 
2337         @Override
handleMessage(Message msg)2338         public void handleMessage(Message msg) {
2339             synchronized (mService.mGlobalLock) {
2340                 if (handleMessageInner(msg)) {
2341                     return;
2342                 }
2343             }
2344             // The cases that some invocations cannot be locked by WM.
2345             switch (msg.what) {
2346                 case RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG: {
2347                     final ActivityRecord r = (ActivityRecord) msg.obj;
2348                     String processName = null;
2349                     int uid = 0;
2350                     synchronized (mService.mGlobalLock) {
2351                         if (r.attachedToProcess()
2352                                 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
2353                             processName = r.app.mName;
2354                             uid = r.app.mUid;
2355                         }
2356                     }
2357                     if (processName != null) {
2358                         mService.mAmInternal.killProcess(processName, uid,
2359                                 "restartActivityProcessTimeout");
2360                     }
2361                 } break;
2362             }
2363         }
2364 
activityIdleFromMessage(ActivityRecord idleActivity, boolean fromTimeout)2365         private void activityIdleFromMessage(ActivityRecord idleActivity, boolean fromTimeout) {
2366             activityIdleInternal(idleActivity, fromTimeout,
2367                     fromTimeout /* processPausingActivities */, null /* config */);
2368         }
2369 
2370         /**
2371          * Handles the message with lock held.
2372          *
2373          * @return {@code true} if the message is handled.
2374          */
handleMessageInner(Message msg)2375         private boolean handleMessageInner(Message msg) {
2376             switch (msg.what) {
2377                 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
2378                     for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
2379                         final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
2380                         r.updateMultiWindowMode();
2381                     }
2382                 } break;
2383                 case REPORT_PIP_MODE_CHANGED_MSG: {
2384                     for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
2385                         final ActivityRecord r = mPipModeChangedActivities.remove(i);
2386                         r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds,
2387                                 false /* forceUpdate */);
2388                     }
2389                 } break;
2390                 case IDLE_TIMEOUT_MSG: {
2391                     if (DEBUG_IDLE) Slog.d(TAG_IDLE,
2392                             "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
2393                     // We don't at this point know if the activity is fullscreen, so we need to be
2394                     // conservative and assume it isn't.
2395                     activityIdleFromMessage((ActivityRecord) msg.obj, true /* fromTimeout */);
2396                 } break;
2397                 case IDLE_NOW_MSG: {
2398                     if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
2399                     activityIdleFromMessage((ActivityRecord) msg.obj, false /* fromTimeout */);
2400                 } break;
2401                 case RESUME_TOP_ACTIVITY_MSG: {
2402                     mRootWindowContainer.resumeFocusedStacksTopActivities();
2403                 } break;
2404                 case SLEEP_TIMEOUT_MSG: {
2405                     if (mService.isSleepingOrShuttingDownLocked()) {
2406                         Slog.w(TAG, "Sleep timeout!  Sleeping now.");
2407                         checkReadyForSleepLocked(false /* allowDelay */);
2408                     }
2409                 } break;
2410                 case LAUNCH_TIMEOUT_MSG: {
2411                     if (mLaunchingActivityWakeLock.isHeld()) {
2412                         Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
2413                         if (VALIDATE_WAKE_LOCK_CALLER
2414                                 && Binder.getCallingUid() != Process.myUid()) {
2415                             throw new IllegalStateException("Calling must be system uid");
2416                         }
2417                         mLaunchingActivityWakeLock.release();
2418                     }
2419                 } break;
2420                 case PROCESS_STOPPING_AND_FINISHING_MSG: {
2421                     processStoppingAndFinishingActivities(null /* launchedActivity */,
2422                             false /* processPausingActivities */, "transit");
2423                 } break;
2424                 case LAUNCH_TASK_BEHIND_COMPLETE: {
2425                     final ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
2426                     if (r != null) {
2427                         handleLaunchTaskBehindCompleteLocked(r);
2428                     }
2429                 } break;
2430                 case REPORT_HOME_CHANGED_MSG: {
2431                     mHandler.removeMessages(REPORT_HOME_CHANGED_MSG);
2432 
2433                     // Start home activities on displays with no activities.
2434                     mRootWindowContainer.startHomeOnEmptyDisplays("homeChanged");
2435                 } break;
2436                 case TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG: {
2437                     final ActivityRecord r = (ActivityRecord) msg.obj;
2438                     Slog.w(TAG, "Activity top resumed state loss timeout for " + r);
2439                     if (r.hasProcess()) {
2440                         mService.logAppTooSlow(r.app, r.topResumedStateLossTime,
2441                                 "top state loss for " + r);
2442                     }
2443                     handleTopResumedStateReleased(true /* timeout */);
2444                 } break;
2445                 default:
2446                     return false;
2447             }
2448             return true;
2449         }
2450     }
2451 
startActivityFromRecents(int callingPid, int callingUid, int taskId, SafeActivityOptions options)2452     int startActivityFromRecents(int callingPid, int callingUid, int taskId,
2453             SafeActivityOptions options) {
2454         Task task = null;
2455         final String callingPackage;
2456         final String callingFeatureId;
2457         final Intent intent;
2458         final int userId;
2459         int activityType = ACTIVITY_TYPE_UNDEFINED;
2460         int windowingMode = WINDOWING_MODE_UNDEFINED;
2461         final ActivityOptions activityOptions = options != null
2462                 ? options.getOptions(this)
2463                 : null;
2464         if (activityOptions != null) {
2465             activityType = activityOptions.getLaunchActivityType();
2466             windowingMode = activityOptions.getLaunchWindowingMode();
2467             if (activityOptions.freezeRecentTasksReordering()
2468                     && mRecentTasks.isCallerRecents(callingUid)) {
2469                 mRecentTasks.setFreezeTaskListReordering();
2470             }
2471         }
2472         if (activityType == ACTIVITY_TYPE_HOME || activityType == ACTIVITY_TYPE_RECENTS) {
2473             throw new IllegalArgumentException("startActivityFromRecents: Task "
2474                     + taskId + " can't be launch in the home/recents stack.");
2475         }
2476 
2477         mService.deferWindowLayout();
2478         try {
2479             task = mRootWindowContainer.anyTaskForId(taskId,
2480                     MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE, activityOptions, ON_TOP);
2481             if (task == null) {
2482                 mWindowManager.executeAppTransition();
2483                 throw new IllegalArgumentException(
2484                         "startActivityFromRecents: Task " + taskId + " not found.");
2485             }
2486 
2487             if (windowingMode != WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2488                 // We always want to return to the home activity instead of the recents activity
2489                 // from whatever is started from the recents activity, so move the home stack
2490                 // forward.
2491                 // TODO (b/115289124): Multi-display supports for recents.
2492                 mRootWindowContainer.getDefaultTaskDisplayArea().moveHomeStackToFront(
2493                         "startActivityFromRecents");
2494             }
2495 
2496             // If the user must confirm credentials (e.g. when first launching a work app and the
2497             // Work Challenge is present) let startActivityInPackage handle the intercepting.
2498             if (!mService.mAmInternal.shouldConfirmCredentials(task.mUserId)
2499                     && task.getRootActivity() != null) {
2500                 final ActivityRecord targetActivity = task.getTopNonFinishingActivity();
2501 
2502                 mRootWindowContainer.sendPowerHintForLaunchStartIfNeeded(
2503                         true /* forceSend */, targetActivity);
2504                 final LaunchingState launchingState =
2505                         mActivityMetricsLogger.notifyActivityLaunching(task.intent);
2506                 try {
2507                     mService.moveTaskToFrontLocked(null /* appThread */, null /* callingPackage */,
2508                             task.mTaskId, 0, options);
2509                     // Apply options to prevent pendingOptions be taken by client to make sure
2510                     // the override pending app transition will be applied immediately.
2511                     targetActivity.applyOptionsLocked();
2512                 } finally {
2513                     mActivityMetricsLogger.notifyActivityLaunched(launchingState,
2514                             START_TASK_TO_FRONT, targetActivity);
2515                 }
2516 
2517                 mService.getActivityStartController().postStartActivityProcessingForLastStarter(
2518                         task.getTopNonFinishingActivity(), ActivityManager.START_TASK_TO_FRONT,
2519                         task.getStack());
2520                 return ActivityManager.START_TASK_TO_FRONT;
2521             }
2522             callingPackage = task.mCallingPackage;
2523             callingFeatureId = task.mCallingFeatureId;
2524             intent = task.intent;
2525             intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
2526             userId = task.mUserId;
2527             return mService.getActivityStartController().startActivityInPackage(task.mCallingUid,
2528                     callingPid, callingUid, callingPackage, callingFeatureId, intent, null, null,
2529                     null, 0, 0, options, userId, task, "startActivityFromRecents",
2530                     false /* validateIncomingUser */, null /* originatingPendingIntent */,
2531                     false /* allowBackgroundActivityStart */);
2532         } finally {
2533             mService.continueWindowLayout();
2534         }
2535     }
2536 
2537     /**
2538      * Internal container to store a match qualifier alongside a WaitResult.
2539      */
2540     static class WaitInfo {
2541         private final ComponentName mTargetComponent;
2542         private final WaitResult mResult;
2543 
WaitInfo(ComponentName targetComponent, WaitResult result)2544         WaitInfo(ComponentName targetComponent, WaitResult result) {
2545             this.mTargetComponent = targetComponent;
2546             this.mResult = result;
2547         }
2548 
matches(ComponentName targetComponent)2549         public boolean matches(ComponentName targetComponent) {
2550             return mTargetComponent == null || mTargetComponent.equals(targetComponent);
2551         }
2552 
getResult()2553         public WaitResult getResult() {
2554             return mResult;
2555         }
2556 
getComponent()2557         public ComponentName getComponent() {
2558             return mTargetComponent;
2559         }
2560 
dump(PrintWriter pw, String prefix)2561         public void dump(PrintWriter pw, String prefix) {
2562             pw.println(prefix + "WaitInfo:");
2563             pw.println(prefix + "  mTargetComponent=" + mTargetComponent);
2564             pw.println(prefix + "  mResult=");
2565             mResult.dump(pw, prefix);
2566         }
2567     }
2568 }
2569