OSDN Git Service

Merge "DO NOT MERGE Backporting potential usb tapjacking precaution." into lmp-dev...
[android-x86/frameworks-base.git] / services / core / java / com / android / server / am / ActivityStackSupervisor.java
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.am;
18
19 import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
20 import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
21 import static android.Manifest.permission.START_ANY_ACTIVITY;
22 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
23 import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
24 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
25 import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
26 import static android.app.ActivityManager.START_TASK_TO_FRONT;
27 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
28 import static android.app.ActivityManager.StackId.FIRST_DYNAMIC_STACK_ID;
29 import static android.app.ActivityManager.StackId.FIRST_STATIC_STACK_ID;
30 import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
31 import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
32 import static android.app.ActivityManager.StackId.HOME_STACK_ID;
33 import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
34 import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
35 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
36 import static android.app.ActivityManager.StackId.RECENTS_STACK_ID;
37 import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
38 import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
39 import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
40 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
41 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
42 import static android.os.Process.SYSTEM_UID;
43 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
44 import static android.view.Display.DEFAULT_DISPLAY;
45 import static android.view.Display.FLAG_PRIVATE;
46 import static android.view.Display.INVALID_DISPLAY;
47 import static android.view.Display.REMOVE_MODE_DESTROY_CONTENT;
48 import static android.view.Display.TYPE_VIRTUAL;
49
50 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN;
51 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
52 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONTAINERS;
53 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
54 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
55 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
56 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
57 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
58 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
59 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
60 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
61 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
62 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
63 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBLE_BEHIND;
64 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONTAINERS;
65 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
66 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IDLE;
67 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
68 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
69 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
70 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
71 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
72 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
73 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
74 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
75 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBLE_BEHIND;
76 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
77 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
78 import static com.android.server.am.ActivityManagerService.ANIMATE;
79 import static com.android.server.am.ActivityManagerService.FIRST_SUPERVISOR_STACK_MSG;
80 import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
81 import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
82 import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
83 import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
84 import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
85 import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
86 import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
87 import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
88 import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
89 import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
90 import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
91 import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
92 import static com.android.server.am.ActivityStack.STACK_VISIBLE;
93 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
94 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
95 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
96 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
97 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
98 import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
99 import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
100 import static com.android.server.am.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
101 import static com.android.server.wm.AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS;
102 import static java.lang.Integer.MAX_VALUE;
103
104 import android.Manifest;
105 import android.annotation.IntDef;
106 import android.annotation.NonNull;
107 import android.annotation.UserIdInt;
108 import android.app.Activity;
109 import android.app.ActivityManager;
110 import android.app.ActivityManager.RunningTaskInfo;
111 import android.app.ActivityManager.StackId;
112 import android.app.ActivityManager.StackInfo;
113 import android.app.ActivityOptions;
114 import android.app.AppOpsManager;
115 import android.app.IActivityContainerCallback;
116 import android.app.ProfilerInfo;
117 import android.app.ResultInfo;
118 import android.app.StatusBarManager;
119 import android.app.WaitResult;
120 import android.app.admin.IDevicePolicyManager;
121 import android.content.ComponentName;
122 import android.content.Context;
123 import android.content.IIntentSender;
124 import android.content.Intent;
125 import android.content.pm.ActivityInfo;
126 import android.content.pm.ApplicationInfo;
127 import android.content.pm.PackageInfo;
128 import android.content.pm.PackageManager;
129 import android.content.pm.ResolveInfo;
130 import android.content.pm.UserInfo;
131 import android.content.res.Configuration;
132 import android.graphics.Rect;
133 import android.hardware.display.DisplayManager;
134 import android.hardware.display.DisplayManager.DisplayListener;
135 import android.hardware.display.DisplayManagerGlobal;
136 import android.hardware.display.DisplayManagerInternal;
137 import android.hardware.display.VirtualDisplay;
138 import android.hardware.input.InputManager;
139 import android.hardware.input.InputManagerInternal;
140 import android.os.Binder;
141 import android.os.Bundle;
142 import android.os.Debug;
143 import android.os.Handler;
144 import android.os.IBinder;
145 import android.os.Looper;
146 import android.os.Message;
147 import android.os.ParcelFileDescriptor;
148 import android.os.PowerManager;
149 import android.os.Process;
150 import android.os.RemoteException;
151 import android.os.ServiceManager;
152 import android.os.SystemClock;
153 import android.os.Trace;
154 import android.os.TransactionTooLargeException;
155 import android.os.UserHandle;
156 import android.os.UserManager;
157 import android.os.WorkSource;
158 import android.provider.MediaStore;
159 import android.provider.Settings;
160 import android.provider.Settings.SettingNotFoundException;
161 import android.service.voice.IVoiceInteractionSession;
162 import android.util.ArrayMap;
163 import android.util.ArraySet;
164 import android.util.EventLog;
165 import android.util.IntArray;
166 import android.util.MergedConfiguration;
167 import android.util.Slog;
168 import android.util.SparseArray;
169 import android.util.SparseIntArray;
170 import android.view.Display;
171 import android.view.InputEvent;
172 import android.view.Surface;
173
174 import com.android.internal.content.ReferrerIntent;
175 import com.android.internal.logging.MetricsLogger;
176 import com.android.internal.os.TransferPipe;
177 import com.android.internal.statusbar.IStatusBarService;
178 import com.android.internal.util.ArrayUtils;
179 import com.android.internal.widget.LockPatternUtils;
180 import com.android.server.LocalServices;
181 import com.android.server.am.ActivityStack.ActivityState;
182 import com.android.server.wm.PinnedStackWindowController;
183 import com.android.server.wm.WindowManagerService;
184
185 import java.io.FileDescriptor;
186 import java.io.IOException;
187 import java.io.PrintWriter;
188 import java.lang.annotation.Retention;
189 import java.lang.annotation.RetentionPolicy;
190 import java.util.ArrayList;
191 import java.util.Arrays;
192 import java.util.List;
193 import java.util.Set;
194
195 public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener {
196     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_AM;
197     private static final String TAG_CONTAINERS = TAG + POSTFIX_CONTAINERS;
198     private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
199     private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
200     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
201     private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
202     private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
203     private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
204     private static final String TAG_STACK = TAG + POSTFIX_STACK;
205     private static final String TAG_STATES = TAG + POSTFIX_STATES;
206     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
207     static final String TAG_TASKS = TAG + POSTFIX_TASKS;
208     private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND;
209
210     /** How long we wait until giving up on the last activity telling us it is idle. */
211     static final int IDLE_TIMEOUT = 10 * 1000;
212
213     /** How long we can hold the sleep wake lock before giving up. */
214     static final int SLEEP_TIMEOUT = 5 * 1000;
215
216     // How long we can hold the launch wake lock before giving up.
217     static final int LAUNCH_TIMEOUT = 10 * 1000;
218
219     static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
220     static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
221     static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
222     static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
223     static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
224     static final int HANDLE_DISPLAY_ADDED = FIRST_SUPERVISOR_STACK_MSG + 5;
225     static final int HANDLE_DISPLAY_CHANGED = FIRST_SUPERVISOR_STACK_MSG + 6;
226     static final int HANDLE_DISPLAY_REMOVED = FIRST_SUPERVISOR_STACK_MSG + 7;
227     static final int CONTAINER_CALLBACK_VISIBILITY = FIRST_SUPERVISOR_STACK_MSG + 8;
228     static final int LOCK_TASK_START_MSG = FIRST_SUPERVISOR_STACK_MSG + 9;
229     static final int LOCK_TASK_END_MSG = FIRST_SUPERVISOR_STACK_MSG + 10;
230     static final int CONTAINER_CALLBACK_TASK_LIST_EMPTY = FIRST_SUPERVISOR_STACK_MSG + 11;
231     static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
232     static final int SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG = FIRST_SUPERVISOR_STACK_MSG + 13;
233     static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
234     static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
235
236     private static final String VIRTUAL_DISPLAY_BASE_NAME = "ActivityViewVirtualDisplay";
237
238     private static final String LOCK_TASK_TAG = "Lock-to-App";
239
240     // Used to indicate if an object (e.g. stack) that we are trying to get
241     // should be created if it doesn't exist already.
242     static final boolean CREATE_IF_NEEDED = true;
243
244     // Used to indicate that windows of activities should be preserved during the resize.
245     static final boolean PRESERVE_WINDOWS = true;
246
247     // Used to indicate if an object (e.g. task) should be moved/created
248     // at the top of its container (e.g. stack).
249     static final boolean ON_TOP = true;
250
251     // Used to indicate that an objects (e.g. task) removal from its container
252     // (e.g. stack) is due to it moving to another container.
253     static final boolean MOVING = true;
254
255     // Force the focus to change to the stack we are moving a task to..
256     static final boolean FORCE_FOCUS = true;
257
258     // Don't execute any calls to resume.
259     static final boolean DEFER_RESUME = true;
260
261     // Used to indicate that a task is removed it should also be removed from recents.
262     static final boolean REMOVE_FROM_RECENTS = true;
263
264     // Used to indicate that pausing an activity should occur immediately without waiting for
265     // the activity callback indicating that it has completed pausing
266     static final boolean PAUSE_IMMEDIATELY = true;
267
268     /**
269      * The modes which affect which tasks are returned when calling
270      * {@link ActivityStackSupervisor#anyTaskForIdLocked(int)}.
271      */
272     @Retention(RetentionPolicy.SOURCE)
273     @IntDef({
274             MATCH_TASK_IN_STACKS_ONLY,
275             MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
276             MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
277     })
278     public @interface AnyTaskForIdMatchTaskMode {}
279     // Match only tasks in the current stacks
280     static final int MATCH_TASK_IN_STACKS_ONLY = 0;
281     // Match either tasks in the current stacks, or in the recent tasks if not found in the stacks
282     static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS = 1;
283     // Match either tasks in the current stacks, or in the recent tasks, restoring it to the
284     // provided stack id
285     static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE = 2;
286
287     // Activity actions an app cannot start if it uses a permission which is not granted.
288     private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION =
289             new ArrayMap<>();
290
291     static {
292         ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE,
293                 Manifest.permission.CAMERA);
294         ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE,
295                 Manifest.permission.CAMERA);
296         ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL,
297                 Manifest.permission.CALL_PHONE);
298     }
299
300     /** Action restriction: launching the activity is not restricted. */
301     private static final int ACTIVITY_RESTRICTION_NONE = 0;
302     /** Action restriction: launching the activity is restricted by a permission. */
303     private static final int ACTIVITY_RESTRICTION_PERMISSION = 1;
304     /** Action restriction: launching the activity is restricted by an app op. */
305     private static final int ACTIVITY_RESTRICTION_APPOP = 2;
306
307     /** Status Bar Service **/
308     private IBinder mToken = new Binder();
309     private IStatusBarService mStatusBarService;
310     private IDevicePolicyManager mDevicePolicyManager;
311
312     // For debugging to make sure the caller when acquiring/releasing our
313     // wake lock is the system process.
314     static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
315     /** The number of distinct task ids that can be assigned to the tasks of a single user */
316     private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
317
318     final ActivityManagerService mService;
319
320     private RecentTasks mRecentTasks;
321
322     final ActivityStackSupervisorHandler mHandler;
323
324     /** Short cut */
325     WindowManagerService mWindowManager;
326     DisplayManager mDisplayManager;
327
328     /** Counter for next free stack ID to use for dynamic activity stacks. */
329     private int mNextFreeStackId = FIRST_DYNAMIC_STACK_ID;
330
331     /**
332      * Maps the task identifier that activities are currently being started in to the userId of the
333      * task. Each time a new task is created, the entry for the userId of the task is incremented
334      */
335     private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20);
336
337     /** The current user */
338     int mCurrentUser;
339
340     /** The stack containing the launcher app. Assumed to always be attached to
341      * Display.DEFAULT_DISPLAY. */
342     ActivityStack mHomeStack;
343
344     /** The stack currently receiving input or launching the next activity. */
345     ActivityStack mFocusedStack;
346
347     /** If this is the same as mFocusedStack then the activity on the top of the focused stack has
348      * been resumed. If stacks are changing position this will hold the old stack until the new
349      * stack becomes resumed after which it will be set to mFocusedStack. */
350     private ActivityStack mLastFocusedStack;
351
352     /** List of activities that are waiting for a new activity to become visible before completing
353      * whatever operation they are supposed to do. */
354     // TODO: Remove mActivitiesWaitingForVisibleActivity list and just remove activity from
355     // mStoppingActivities when something else comes up.
356     final ArrayList<ActivityRecord> mActivitiesWaitingForVisibleActivity = new ArrayList<>();
357
358     /** List of processes waiting to find out when a specific activity becomes visible. */
359     private final ArrayList<WaitInfo> mWaitingForActivityVisible = new ArrayList<>();
360
361     /** List of processes waiting to find out about the next launched activity. */
362     final ArrayList<WaitResult> mWaitingActivityLaunched = new ArrayList<>();
363
364     /** List of activities that are ready to be stopped, but waiting for the next activity to
365      * settle down before doing so. */
366     final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>();
367
368     /** List of activities that are ready to be finished, but waiting for the previous activity to
369      * settle down before doing so.  It contains ActivityRecord objects. */
370     final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>();
371
372     /** List of activities that are in the process of going to sleep. */
373     final ArrayList<ActivityRecord> mGoingToSleepActivities = new ArrayList<>();
374
375     /** List of activities whose multi-window mode changed that we need to report to the
376      * application */
377     final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
378
379     /** List of activities whose picture-in-picture mode changed that we need to report to the
380      * application */
381     final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
382
383     /** The target stack bounds for the picture-in-picture mode changed that we need to report to
384      * the application */
385     Rect mPipModeChangedTargetStackBounds;
386
387     /** Used on user changes */
388     final ArrayList<UserState> mStartingUsers = new ArrayList<>();
389
390     /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity
391      * is being brought in front of us. */
392     boolean mUserLeaving = false;
393
394     /** Set when we have taken too long waiting to go to sleep. */
395     boolean mSleepTimeout = false;
396
397     /**
398      * We don't want to allow the device to go to sleep while in the process
399      * of launching an activity.  This is primarily to allow alarm intent
400      * receivers to launch an activity and get that to run before the device
401      * goes back to sleep.
402      */
403     PowerManager.WakeLock mLaunchingActivity;
404
405     /**
406      * Set when the system is going to sleep, until we have
407      * successfully paused the current activity and released our wake lock.
408      * At that point the system is allowed to actually sleep.
409      */
410     PowerManager.WakeLock mGoingToSleep;
411
412     /** Stack id of the front stack when user switched, indexed by userId. */
413     SparseIntArray mUserStackInFront = new SparseIntArray(2);
414
415     // TODO: Add listener for removal of references.
416     /** Mapping from (ActivityStack/TaskStack).mStackId to their current state */
417     SparseArray<ActivityContainer> mActivityContainers = new SparseArray<>();
418
419     // TODO: There should be an ActivityDisplayController coordinating am/wm interaction.
420     /** Mapping from displayId to display current state */
421     private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();
422
423     private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>();
424
425     private DisplayManagerInternal mDisplayManagerInternal;
426     private InputManagerInternal mInputManagerInternal;
427
428     /** The chain of tasks in lockTask mode. The current frontmost task is at the top, and tasks
429      * may be finished until there is only one entry left. If this is empty the system is not
430      * in lockTask mode. */
431     ArrayList<TaskRecord> mLockTaskModeTasks = new ArrayList<>();
432     /** Store the current lock task mode. Possible values:
433      * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
434      * {@link ActivityManager#LOCK_TASK_MODE_PINNED}
435      */
436     private int mLockTaskModeState;
437     /**
438      * Notifies the user when entering/exiting lock-task.
439      */
440     private LockTaskNotify mLockTaskNotify;
441
442     /** Used to keep resumeTopActivityUncheckedLocked() from being entered recursively */
443     boolean inResumeTopActivity;
444
445     /**
446      * Temporary rect used during docked stack resize calculation so we don't need to create a new
447      * object each time.
448      */
449     private final Rect tempRect = new Rect();
450
451     // The default minimal size that will be used if the activity doesn't specify its minimal size.
452     // It will be calculated when the default display gets added.
453     int mDefaultMinSizeOfResizeableTask = -1;
454
455     // Whether tasks have moved and we need to rank the tasks before next OOM scoring
456     private boolean mTaskLayersChanged = true;
457
458     final ActivityMetricsLogger mActivityMetricsLogger;
459
460     private final ArrayList<ActivityRecord> mTmpActivityList = new ArrayList<>();
461
462     @Override
463     protected int getChildCount() {
464         return mActivityDisplays.size();
465     }
466
467     @Override
468     protected ActivityDisplay getChildAt(int index) {
469         return mActivityDisplays.valueAt(index);
470     }
471
472     @Override
473     protected ConfigurationContainer getParent() {
474         return null;
475     }
476
477     Configuration getDisplayOverrideConfiguration(int displayId) {
478         final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
479         if (activityDisplay == null) {
480             throw new IllegalArgumentException("No display found with id: " + displayId);
481         }
482
483         return activityDisplay.getOverrideConfiguration();
484     }
485
486     void setDisplayOverrideConfiguration(Configuration overrideConfiguration, int displayId) {
487         final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
488         if (activityDisplay == null) {
489             throw new IllegalArgumentException("No display found with id: " + displayId);
490         }
491
492         activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
493     }
494
495     /** Check if placing task or activity on specified display is allowed. */
496     boolean canPlaceEntityOnDisplay(int displayId, boolean resizeable) {
497         return displayId == DEFAULT_DISPLAY || (mService.mSupportsMultiDisplay
498                 && (resizeable || displayConfigMatchesGlobal(displayId)));
499     }
500
501     /**
502      * Check if configuration of specified display matches current global config.
503      * Used to check if we can put a non-resizeable activity on a secondary display and it will get
504      * the same config as on the default display.
505      * @param displayId Id of the display to check.
506      * @return {@code true} if configuration matches.
507      */
508     private boolean displayConfigMatchesGlobal(int displayId) {
509         if (displayId == DEFAULT_DISPLAY) {
510             return true;
511         }
512         if (displayId == INVALID_DISPLAY) {
513             return false;
514         }
515         final ActivityDisplay targetDisplay = getActivityDisplayOrCreateLocked(displayId);
516         if (targetDisplay == null) {
517             throw new IllegalArgumentException("No display found with id: " + displayId);
518         }
519         return getConfiguration().equals(targetDisplay.getConfiguration());
520     }
521
522     static class FindTaskResult {
523         ActivityRecord r;
524         boolean matchedByRootAffinity;
525     }
526     private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
527
528     /**
529      * Temp storage for display ids sorted in focus order.
530      * Maps position to id. Using {@link SparseIntArray} instead of {@link ArrayList} because
531      * it's more efficient, as the number of displays is usually small.
532      */
533     private SparseIntArray mTmpOrderedDisplayIds = new SparseIntArray();
534
535     /**
536      * Used to keep track whether app visibilities got changed since the last pause. Useful to
537      * determine whether to invoke the task stack change listener after pausing.
538      */
539     boolean mAppVisibilitiesChangedSinceLastPause;
540
541     /**
542      * Set of tasks that are in resizing mode during an app transition to fill the "void".
543      */
544     private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
545
546
547     /**
548      * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked}
549      * will be ignored. Useful for the case where the caller is handling resizing of other stack and
550      * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger
551      * like the docked stack going empty.
552      */
553     private boolean mAllowDockedStackResize = true;
554
555     /**
556      * Is dock currently minimized.
557      */
558     boolean mIsDockMinimized;
559
560     final KeyguardController mKeyguardController;
561
562     /**
563      * Description of a request to start a new activity, which has been held
564      * due to app switches being disabled.
565      */
566     static class PendingActivityLaunch {
567         final ActivityRecord r;
568         final ActivityRecord sourceRecord;
569         final int startFlags;
570         final ActivityStack stack;
571         final ProcessRecord callerApp;
572
573         PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
574                 int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
575             r = _r;
576             sourceRecord = _sourceRecord;
577             startFlags = _startFlags;
578             stack = _stack;
579             callerApp = _callerApp;
580         }
581
582         void sendErrorResult(String message) {
583             try {
584                 if (callerApp.thread != null) {
585                     callerApp.thread.scheduleCrash(message);
586                 }
587             } catch (RemoteException e) {
588                 Slog.e(TAG, "Exception scheduling crash of failed "
589                         + "activity launcher sourceRecord=" + sourceRecord, e);
590             }
591         }
592     }
593
594     public ActivityStackSupervisor(ActivityManagerService service, Looper looper) {
595         mService = service;
596         mHandler = new ActivityStackSupervisorHandler(looper);
597         mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
598         mKeyguardController = new KeyguardController(service, this);
599     }
600
601     void setRecentTasks(RecentTasks recentTasks) {
602         mRecentTasks = recentTasks;
603     }
604
605     /**
606      * At the time when the constructor runs, the power manager has not yet been
607      * initialized.  So we initialize our wakelocks afterwards.
608      */
609     void initPowerManagement() {
610         PowerManager pm = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
611         mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
612         mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*launch*");
613         mLaunchingActivity.setReferenceCounted(false);
614     }
615
616     // This function returns a IStatusBarService. The value is from ServiceManager.
617     // getService and is cached.
618     private IStatusBarService getStatusBarService() {
619         synchronized (mService) {
620             if (mStatusBarService == null) {
621                 mStatusBarService = IStatusBarService.Stub.asInterface(
622                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
623                 if (mStatusBarService == null) {
624                     Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
625                 }
626             }
627             return mStatusBarService;
628         }
629     }
630
631     private IDevicePolicyManager getDevicePolicyManager() {
632         synchronized (mService) {
633             if (mDevicePolicyManager == null) {
634                 mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
635                     ServiceManager.checkService(Context.DEVICE_POLICY_SERVICE));
636                 if (mDevicePolicyManager == null) {
637                     Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
638                 }
639             }
640             return mDevicePolicyManager;
641         }
642     }
643
644     void setWindowManager(WindowManagerService wm) {
645         synchronized (mService) {
646             mWindowManager = wm;
647             mKeyguardController.setWindowManager(wm);
648
649             mDisplayManager =
650                     (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
651             mDisplayManager.registerDisplayListener(this, null);
652             mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
653
654             Display[] displays = mDisplayManager.getDisplays();
655             for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
656                 final int displayId = displays[displayNdx].getDisplayId();
657                 ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
658                 if (activityDisplay.mDisplay == null) {
659                     throw new IllegalStateException("Default Display does not exist");
660                 }
661                 mActivityDisplays.put(displayId, activityDisplay);
662                 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
663             }
664
665             mHomeStack = mFocusedStack = mLastFocusedStack =
666                     getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
667
668             mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
669         }
670     }
671
672     ActivityStack getFocusedStack() {
673         return mFocusedStack;
674     }
675
676     ActivityStack getLastStack() {
677         return mLastFocusedStack;
678     }
679
680     boolean isFocusedStack(ActivityStack stack) {
681         if (stack == null) {
682             return false;
683         }
684
685         final ActivityRecord parent = stack.mActivityContainer.mParentActivity;
686         if (parent != null) {
687             stack = parent.getStack();
688         }
689         return stack == mFocusedStack;
690     }
691
692     /** The top most stack on its display. */
693     boolean isFrontStackOnDisplay(ActivityStack stack) {
694         return isFrontOfStackList(stack, stack.mActivityContainer.mActivityDisplay.mStacks);
695     }
696
697     private boolean isFrontOfStackList(ActivityStack stack, List<ActivityStack> stackList) {
698         if (stack == null) {
699             return false;
700         }
701
702         final ActivityRecord parent = stack.mActivityContainer.mParentActivity;
703         if (parent != null) {
704             stack = parent.getStack();
705         }
706         return stack == stackList.get((stackList.size() - 1));
707     }
708
709     /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
710     void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
711         if (!focusCandidate.isFocusable()) {
712             // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
713             focusCandidate = getNextFocusableStackLocked(focusCandidate);
714         }
715
716         if (focusCandidate != mFocusedStack) {
717             mLastFocusedStack = mFocusedStack;
718             mFocusedStack = focusCandidate;
719
720             EventLogTags.writeAmFocusedStack(
721                     mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
722                     mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
723         }
724
725         final ActivityRecord r = topRunningActivityLocked();
726         if (mService.mBooting || !mService.mBooted) {
727             if (r != null && r.idle) {
728                 checkFinishBootingLocked();
729             }
730         }
731     }
732
733     void moveHomeStackToFront(String reason) {
734         mHomeStack.moveToFront(reason);
735     }
736
737     void moveRecentsStackToFront(String reason) {
738         final ActivityStack recentsStack = getStack(RECENTS_STACK_ID);
739         if (recentsStack != null) {
740             recentsStack.moveToFront(reason);
741         }
742     }
743
744     /** Returns true if the focus activity was adjusted to the home stack top activity. */
745     boolean moveHomeStackTaskToTop(String reason) {
746         mHomeStack.moveHomeStackTaskToTop();
747
748         final ActivityRecord top = getHomeActivity();
749         if (top == null) {
750             return false;
751         }
752         moveFocusableActivityStackToFrontLocked(top, reason);
753         return true;
754     }
755
756     boolean resumeHomeStackTask(ActivityRecord prev, String reason) {
757         if (!mService.mBooting && !mService.mBooted) {
758             // Not ready yet!
759             return false;
760         }
761
762         if (prev != null) {
763             prev.getTask().setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
764         }
765
766         mHomeStack.moveHomeStackTaskToTop();
767         ActivityRecord r = getHomeActivity();
768         final String myReason = reason + " resumeHomeStackTask";
769
770         // Only resume home activity if isn't finishing.
771         if (r != null && !r.finishing) {
772             moveFocusableActivityStackToFrontLocked(r, myReason);
773             return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
774         }
775         return mService.startHomeActivityLocked(mCurrentUser, myReason);
776     }
777
778     TaskRecord anyTaskForIdLocked(int id) {
779         return anyTaskForIdLocked(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
780                 INVALID_STACK_ID);
781     }
782
783     /**
784      * Returns a {@link TaskRecord} for the input id if available. {@code null} otherwise.
785      * @param id Id of the task we would like returned.
786      * @param matchMode The mode to match the given task id in.
787      * @param stackId The stack to restore the task to (default launch stack will be used if
788      *                stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}). Only
789      *                valid if the matchMode is
790      *                {@link #MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE}.
791      */
792     TaskRecord anyTaskForIdLocked(int id, @AnyTaskForIdMatchTaskMode int matchMode, int stackId) {
793         // If there is a stack id set, ensure that we are attempting to actually restore a task
794         if (matchMode != MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE &&
795                 stackId != INVALID_STACK_ID) {
796             throw new IllegalArgumentException("Should not specify stackId for non-restore lookup");
797         }
798
799         int numDisplays = mActivityDisplays.size();
800         for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
801             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
802             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
803                 ActivityStack stack = stacks.get(stackNdx);
804                 final TaskRecord task = stack.taskForIdLocked(id);
805                 if (task != null) {
806                     return task;
807                 }
808             }
809         }
810
811         // If we are matching stack tasks only, return now
812         if (matchMode == MATCH_TASK_IN_STACKS_ONLY) {
813             return null;
814         }
815
816         // Otherwise, check the recent tasks and return if we find it there and we are not restoring
817         // the task from recents
818         if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
819         final TaskRecord task = mRecentTasks.taskForIdLocked(id);
820
821         if (task == null) {
822             if (DEBUG_RECENTS) {
823                 Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
824             }
825
826             return null;
827         }
828
829         if (matchMode == MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) {
830             return task;
831         }
832
833         // Implicitly, this case is MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
834         if (!restoreRecentTaskLocked(task, stackId)) {
835             if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
836                     "Couldn't restore task id=" + id + " found in recents");
837             return null;
838         }
839         if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
840         return task;
841     }
842
843     ActivityRecord isInAnyStackLocked(IBinder token) {
844         int numDisplays = mActivityDisplays.size();
845         for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
846             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
847             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
848                 final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
849                 if (r != null) {
850                     return r;
851                 }
852             }
853         }
854         return null;
855     }
856
857     /**
858      * Detects whether we should show a lock screen in front of this task for a locked user.
859      * <p>
860      * We'll do this if either of the following holds:
861      * <ul>
862      *   <li>The top activity explicitly belongs to {@param userId}.</li>
863      *   <li>The top activity returns a result to an activity belonging to {@param userId}.</li>
864      * </ul>
865      *
866      * @return {@code true} if the top activity looks like it belongs to {@param userId}.
867      */
868     private boolean taskTopActivityIsUser(TaskRecord task, @UserIdInt int userId) {
869         // To handle the case that work app is in the task but just is not the top one.
870         final ActivityRecord activityRecord = task.getTopActivity();
871         final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null);
872
873         return (activityRecord != null && activityRecord.userId == userId)
874                 || (resultTo != null && resultTo.userId == userId);
875     }
876
877     /**
878      * Find all visible task stacks containing {@param userId} and intercept them with an activity
879      * to block out the contents and possibly start a credential-confirming intent.
880      *
881      * @param userId user handle for the locked managed profile.
882      */
883     void lockAllProfileTasks(@UserIdInt int userId) {
884         mWindowManager.deferSurfaceLayout();
885         try {
886             final List<ActivityStack> stacks = getStacks();
887             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; stackNdx--) {
888                 final List<TaskRecord> tasks = stacks.get(stackNdx).getAllTasks();
889                 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) {
890                     final TaskRecord task = tasks.get(taskNdx);
891
892                     // Check the task for a top activity belonging to userId, or returning a result
893                     // to an activity belonging to userId. Example case: a document picker for
894                     // personal files, opened by a work app, should still get locked.
895                     if (taskTopActivityIsUser(task, userId)) {
896                         mService.mTaskChangeNotificationController.notifyTaskProfileLocked(
897                                 task.taskId, userId);
898                     }
899                 }
900             }
901         } finally {
902             mWindowManager.continueSurfaceLayout();
903         }
904     }
905
906     void setNextTaskIdForUserLocked(int taskId, int userId) {
907         final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
908         if (taskId > currentTaskId) {
909             mCurTaskIdForUser.put(userId, taskId);
910         }
911     }
912
913     static int nextTaskIdForUser(int taskId, int userId) {
914         int nextTaskId = taskId + 1;
915         if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
916             // Wrap around as there will be smaller task ids that are available now.
917             nextTaskId -= MAX_TASK_IDS_PER_USER;
918         }
919         return nextTaskId;
920     }
921
922     int getNextTaskIdForUserLocked(int userId) {
923         final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
924         // for a userId u, a taskId can only be in the range
925         // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
926         // was 10, user 0 could only have taskIds 0 to 9, user 1: 10 to 19, user 2: 20 to 29, so on.
927         int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
928         while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
929                 || anyTaskForIdLocked(candidateTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
930                         INVALID_STACK_ID) != null) {
931             candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
932             if (candidateTaskId == currentTaskId) {
933                 // Something wrong!
934                 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
935                 throw new IllegalStateException("Cannot get an available task id."
936                         + " Reached limit of " + MAX_TASK_IDS_PER_USER
937                         + " running tasks per user.");
938             }
939         }
940         mCurTaskIdForUser.put(userId, candidateTaskId);
941         return candidateTaskId;
942     }
943
944     ActivityRecord getResumedActivityLocked() {
945         ActivityStack stack = mFocusedStack;
946         if (stack == null) {
947             return null;
948         }
949         ActivityRecord resumedActivity = stack.mResumedActivity;
950         if (resumedActivity == null || resumedActivity.app == null) {
951             resumedActivity = stack.mPausingActivity;
952             if (resumedActivity == null || resumedActivity.app == null) {
953                 resumedActivity = stack.topRunningActivityLocked();
954             }
955         }
956         return resumedActivity;
957     }
958
959     boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
960         final String processName = app.processName;
961         boolean didSomething = false;
962         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
963             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
964             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
965                 final ActivityStack stack = stacks.get(stackNdx);
966                 if (!isFocusedStack(stack)) {
967                     continue;
968                 }
969                 stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
970                 final ActivityRecord top = stack.topRunningActivityLocked();
971                 final int size = mTmpActivityList.size();
972                 for (int i = 0; i < size; i++) {
973                     final ActivityRecord activity = mTmpActivityList.get(i);
974                     if (activity.app == null && app.uid == activity.info.applicationInfo.uid
975                             && processName.equals(activity.processName)) {
976                         try {
977                             if (realStartActivityLocked(activity, app,
978                                     top == activity /* andResume */, true /* checkConfig */)) {
979                                 didSomething = true;
980                             }
981                         } catch (RemoteException e) {
982                             Slog.w(TAG, "Exception in new application when starting activity "
983                                     + top.intent.getComponent().flattenToShortString(), e);
984                             throw e;
985                         }
986                     }
987                 }
988             }
989         }
990         if (!didSomething) {
991             ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
992         }
993         return didSomething;
994     }
995
996     boolean allResumedActivitiesIdle() {
997         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
998             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
999             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1000                 final ActivityStack stack = stacks.get(stackNdx);
1001                 if (!isFocusedStack(stack) || stack.numActivities() == 0) {
1002                     continue;
1003                 }
1004                 final ActivityRecord resumedActivity = stack.mResumedActivity;
1005                 if (resumedActivity == null || !resumedActivity.idle) {
1006                     if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
1007                              + stack.mStackId + " " + resumedActivity + " not idle");
1008                     return false;
1009                 }
1010             }
1011         }
1012         // Send launch end powerhint when idle
1013         mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
1014         return true;
1015     }
1016
1017     boolean allResumedActivitiesComplete() {
1018         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1019             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1020             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1021                 final ActivityStack stack = stacks.get(stackNdx);
1022                 if (isFocusedStack(stack)) {
1023                     final ActivityRecord r = stack.mResumedActivity;
1024                     if (r != null && r.state != RESUMED) {
1025                         return false;
1026                     }
1027                 }
1028             }
1029         }
1030         // TODO: Not sure if this should check if all Paused are complete too.
1031         if (DEBUG_STACK) Slog.d(TAG_STACK,
1032                 "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
1033                 mLastFocusedStack + " to=" + mFocusedStack);
1034         mLastFocusedStack = mFocusedStack;
1035         return true;
1036     }
1037
1038     boolean allResumedActivitiesVisible() {
1039         boolean foundResumed = false;
1040         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1041             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1042             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1043                 final ActivityStack stack = stacks.get(stackNdx);
1044                 final ActivityRecord r = stack.mResumedActivity;
1045                 if (r != null) {
1046                     if (!r.nowVisible || mActivitiesWaitingForVisibleActivity.contains(r)) {
1047                         return false;
1048                     }
1049                     foundResumed = true;
1050                 }
1051             }
1052         }
1053         return foundResumed;
1054     }
1055
1056     /**
1057      * Pause all activities in either all of the stacks or just the back stacks.
1058      * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
1059      * @param resuming The resuming activity.
1060      * @param dontWait The resuming activity isn't going to wait for all activities to be paused
1061      *                 before resuming.
1062      * @return true if any activity was paused as a result of this call.
1063      */
1064     boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
1065         boolean someActivityPaused = false;
1066         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1067             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1068             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1069                 final ActivityStack stack = stacks.get(stackNdx);
1070                 if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
1071                     if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
1072                             " mResumedActivity=" + stack.mResumedActivity);
1073                     someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
1074                             dontWait);
1075                 }
1076             }
1077         }
1078         return someActivityPaused;
1079     }
1080
1081     boolean allPausedActivitiesComplete() {
1082         boolean pausing = true;
1083         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1084             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1085             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1086                 final ActivityStack stack = stacks.get(stackNdx);
1087                 final ActivityRecord r = stack.mPausingActivity;
1088                 if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
1089                     if (DEBUG_STATES) {
1090                         Slog.d(TAG_STATES,
1091                                 "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
1092                         pausing = false;
1093                     } else {
1094                         return false;
1095                     }
1096                 }
1097             }
1098         }
1099         return pausing;
1100     }
1101
1102     void pauseChildStacks(ActivityRecord parent, boolean userLeaving, boolean uiSleeping,
1103             ActivityRecord resuming, boolean dontWait) {
1104         // TODO: Put all stacks in supervisor and iterate through them instead.
1105         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1106             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1107             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1108                 final ActivityStack stack = stacks.get(stackNdx);
1109                 if (stack.mResumedActivity != null &&
1110                         stack.mActivityContainer.mParentActivity == parent) {
1111                     stack.startPausingLocked(userLeaving, uiSleeping, resuming, dontWait);
1112                 }
1113             }
1114         }
1115     }
1116
1117     void cancelInitializingActivities() {
1118         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1119             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1120             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1121                 stacks.get(stackNdx).cancelInitializingActivities();
1122             }
1123         }
1124     }
1125
1126     void waitActivityVisible(ComponentName name, WaitResult result) {
1127         final WaitInfo waitInfo = new WaitInfo(name, result);
1128         mWaitingForActivityVisible.add(waitInfo);
1129     }
1130
1131     void cleanupActivity(ActivityRecord r) {
1132         // Make sure this record is no longer in the pending finishes list.
1133         // This could happen, for example, if we are trimming activities
1134         // down to the max limit while they are still waiting to finish.
1135         mFinishingActivities.remove(r);
1136         mActivitiesWaitingForVisibleActivity.remove(r);
1137
1138         for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
1139             if (mWaitingForActivityVisible.get(i).matches(r.realActivity)) {
1140                 mWaitingForActivityVisible.remove(i);
1141             }
1142         }
1143     }
1144
1145     void reportActivityVisibleLocked(ActivityRecord r) {
1146         sendWaitingVisibleReportLocked(r);
1147     }
1148
1149     void sendWaitingVisibleReportLocked(ActivityRecord r) {
1150         boolean changed = false;
1151         for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
1152             final WaitInfo w = mWaitingForActivityVisible.get(i);
1153             if (w.matches(r.realActivity)) {
1154                 final WaitResult result = w.getResult();
1155                 changed = true;
1156                 result.timeout = false;
1157                 result.who = w.getComponent();
1158                 result.totalTime = SystemClock.uptimeMillis() - result.thisTime;
1159                 result.thisTime = result.totalTime;
1160                 mWaitingForActivityVisible.remove(w);
1161             }
1162         }
1163         if (changed) {
1164             mService.notifyAll();
1165         }
1166     }
1167
1168     void reportTaskToFrontNoLaunch(ActivityRecord r) {
1169         boolean changed = false;
1170         for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1171             WaitResult w = mWaitingActivityLaunched.remove(i);
1172             if (w.who == null) {
1173                 changed = true;
1174                 // Set result to START_TASK_TO_FRONT so that startActivityMayWait() knows that
1175                 // the starting activity ends up moving another activity to front, and it should
1176                 // wait for this new activity to become visible instead.
1177                 // Do not modify other fields.
1178                 w.result = START_TASK_TO_FRONT;
1179             }
1180         }
1181         if (changed) {
1182             mService.notifyAll();
1183         }
1184     }
1185
1186     void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
1187             long thisTime, long totalTime) {
1188         boolean changed = false;
1189         for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1190             WaitResult w = mWaitingActivityLaunched.remove(i);
1191             if (w.who == null) {
1192                 changed = true;
1193                 w.timeout = timeout;
1194                 if (r != null) {
1195                     w.who = new ComponentName(r.info.packageName, r.info.name);
1196                 }
1197                 w.thisTime = thisTime;
1198                 w.totalTime = totalTime;
1199                 // Do not modify w.result.
1200             }
1201         }
1202         if (changed) {
1203             mService.notifyAll();
1204         }
1205     }
1206
1207     ActivityRecord topRunningActivityLocked() {
1208         final ActivityStack focusedStack = mFocusedStack;
1209         ActivityRecord r = focusedStack.topRunningActivityLocked();
1210         if (r != null) {
1211             return r;
1212         }
1213
1214         // Look in other non-focused and non-home stacks.
1215         mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
1216
1217         for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
1218             final int displayId = mTmpOrderedDisplayIds.get(i);
1219             final List<ActivityStack> stacks = mActivityDisplays.get(displayId).mStacks;
1220             if (stacks == null) {
1221                 continue;
1222             }
1223             for (int j = stacks.size() - 1; j >= 0; --j) {
1224                 final ActivityStack stack = stacks.get(j);
1225                 if (stack != focusedStack && isFrontStackOnDisplay(stack) && stack.isFocusable()) {
1226                     r = stack.topRunningActivityLocked();
1227                     if (r != null) {
1228                         return r;
1229                     }
1230                 }
1231             }
1232         }
1233         return null;
1234     }
1235
1236     void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
1237         // Gather all of the running tasks for each stack into runningTaskLists.
1238         ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1239                 new ArrayList<ArrayList<RunningTaskInfo>>();
1240         final int numDisplays = mActivityDisplays.size();
1241         for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
1242             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1243             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1244                 final ActivityStack stack = stacks.get(stackNdx);
1245                 ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
1246                 runningTaskLists.add(stackTaskList);
1247                 stack.getTasksLocked(stackTaskList, callingUid, allowed);
1248             }
1249         }
1250
1251         // The lists are already sorted from most recent to oldest. Just pull the most recent off
1252         // each list and add it to list. Stop when all lists are empty or maxNum reached.
1253         while (maxNum > 0) {
1254             long mostRecentActiveTime = Long.MIN_VALUE;
1255             ArrayList<RunningTaskInfo> selectedStackList = null;
1256             final int numTaskLists = runningTaskLists.size();
1257             for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1258                 ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
1259                 if (!stackTaskList.isEmpty()) {
1260                     final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1261                     if (lastActiveTime > mostRecentActiveTime) {
1262                         mostRecentActiveTime = lastActiveTime;
1263                         selectedStackList = stackTaskList;
1264                     }
1265                 }
1266             }
1267             if (selectedStackList != null) {
1268                 list.add(selectedStackList.remove(0));
1269                 --maxNum;
1270             } else {
1271                 break;
1272             }
1273         }
1274     }
1275
1276     ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1277             ProfilerInfo profilerInfo) {
1278         final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
1279         if (aInfo != null) {
1280             // Store the found target back into the intent, because now that
1281             // we have it we never want to do this again.  For example, if the
1282             // user navigates back to this point in the history, we should
1283             // always restart the exact same activity.
1284             intent.setComponent(new ComponentName(
1285                     aInfo.applicationInfo.packageName, aInfo.name));
1286
1287             // Don't debug things in the system process
1288             if (!aInfo.processName.equals("system")) {
1289                 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
1290                     mService.setDebugApp(aInfo.processName, true, false);
1291                 }
1292
1293                 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1294                     mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1295                 }
1296
1297                 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1298                     mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1299                 }
1300
1301                 if (profilerInfo != null) {
1302                     mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
1303                 }
1304             }
1305             final String intentLaunchToken = intent.getLaunchToken();
1306             if (aInfo.launchToken == null && intentLaunchToken != null) {
1307                 aInfo.launchToken = intentLaunchToken;
1308             }
1309         }
1310         return aInfo;
1311     }
1312
1313     ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
1314         return resolveIntent(intent, resolvedType, userId, 0);
1315     }
1316
1317     ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
1318         synchronized (mService) {
1319             return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType,
1320                     PackageManager.MATCH_INSTANT | PackageManager.MATCH_DEFAULT_ONLY | flags
1321                     | ActivityManagerService.STOCK_PM_FLAGS, userId);
1322         }
1323     }
1324
1325     ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1326             ProfilerInfo profilerInfo, int userId) {
1327         final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1328         return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1329     }
1330
1331     final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1332             boolean andResume, boolean checkConfig) throws RemoteException {
1333
1334         if (!allPausedActivitiesComplete()) {
1335             // While there are activities pausing we skipping starting any new activities until
1336             // pauses are complete. NOTE: that we also do this for activities that are starting in
1337             // the paused state because they will first be resumed then paused on the client side.
1338             if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1339                     "realStartActivityLocked: Skipping start of r=" + r
1340                     + " some activities pausing...");
1341             return false;
1342         }
1343
1344         r.startFreezingScreenLocked(app, 0);
1345         if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */, true /* isTop */)) {
1346             // We only set the visibility to true if the activity is allowed to be visible based on
1347             // keyguard state. This avoids setting this into motion in window manager that is later
1348             // cancelled due to later calls to ensure visible activities that set visibility back to
1349             // false.
1350             r.setVisibility(true);
1351         }
1352
1353         // schedule launch ticks to collect information about slow apps.
1354         r.startLaunchTickingLocked();
1355
1356         // Have the window manager re-evaluate the orientation of the screen based on the new
1357         // activity order.  Note that as a result of this, it can call back into the activity
1358         // manager with a new orientation.  We don't care about that, because the activity is not
1359         // currently running so we are just restarting it anyway.
1360         if (checkConfig) {
1361             final int displayId = r.getDisplayId();
1362             final Configuration config = mWindowManager.updateOrientationFromAppTokens(
1363                     getDisplayOverrideConfiguration(displayId),
1364                     r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
1365             // Deferring resume here because we're going to launch new activity shortly.
1366             // We don't want to perform a redundant launch of the same record while ensuring
1367             // configurations and trying to resume top activity of focused stack.
1368             mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
1369                     displayId);
1370         }
1371
1372         if (mKeyguardController.isKeyguardLocked()) {
1373             r.notifyUnknownVisibilityLaunched();
1374         }
1375         final int applicationInfoUid =
1376                 (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
1377         if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
1378             Slog.wtf(TAG,
1379                     "User ID for activity changing for " + r
1380                             + " appInfo.uid=" + r.appInfo.uid
1381                             + " info.ai.uid=" + applicationInfoUid
1382                             + " old=" + r.app + " new=" + app);
1383         }
1384
1385         r.app = app;
1386         app.waitingToKill = null;
1387         r.launchCount++;
1388         r.lastLaunchTime = SystemClock.uptimeMillis();
1389
1390         if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1391
1392         int idx = app.activities.indexOf(r);
1393         if (idx < 0) {
1394             app.activities.add(r);
1395         }
1396         mService.updateLruProcessLocked(app, true, null);
1397         mService.updateOomAdjLocked();
1398
1399         final TaskRecord task = r.getTask();
1400         if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1401                 task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
1402             setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE", false);
1403         }
1404
1405         final ActivityStack stack = task.getStack();
1406         try {
1407             if (app.thread == null) {
1408                 throw new RemoteException();
1409             }
1410             List<ResultInfo> results = null;
1411             List<ReferrerIntent> newIntents = null;
1412             if (andResume) {
1413                 // We don't need to deliver new intents and/or set results if activity is going
1414                 // to pause immediately after launch.
1415                 results = r.results;
1416                 newIntents = r.newIntents;
1417             }
1418             if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1419                     "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1420                     + " newIntents=" + newIntents + " andResume=" + andResume);
1421             EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
1422                     System.identityHashCode(r), task.taskId, r.shortComponentName);
1423             if (r.isHomeActivity()) {
1424                 // Home process is the root process of the task.
1425                 mService.mHomeProcess = task.mActivities.get(0).app;
1426             }
1427             mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
1428                                       PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
1429             r.sleeping = false;
1430             r.forceNewConfig = false;
1431             mService.showUnsupportedZoomDialogIfNeededLocked(r);
1432             mService.showAskCompatModeDialogLocked(r);
1433             r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1434             ProfilerInfo profilerInfo = null;
1435             if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1436                 if (mService.mProfileProc == null || mService.mProfileProc == app) {
1437                     mService.mProfileProc = app;
1438                     final String profileFile = mService.mProfileFile;
1439                     if (profileFile != null) {
1440                         ParcelFileDescriptor profileFd = mService.mProfileFd;
1441                         if (profileFd != null) {
1442                             try {
1443                                 profileFd = profileFd.dup();
1444                             } catch (IOException e) {
1445                                 if (profileFd != null) {
1446                                     try {
1447                                         profileFd.close();
1448                                     } catch (IOException o) {
1449                                     }
1450                                     profileFd = null;
1451                                 }
1452                             }
1453                         }
1454
1455                         profilerInfo = new ProfilerInfo(profileFile, profileFd,
1456                                 mService.mSamplingInterval, mService.mAutoStopProfiler,
1457                                 mService.mStreamingOutput);
1458                     }
1459                 }
1460             }
1461
1462             app.hasShownUi = true;
1463             app.pendingUiClean = true;
1464             app.forceProcessStateUpTo(mService.mTopProcessState);
1465             // Because we could be starting an Activity in the system process this may not go across
1466             // a Binder interface which would create a new Configuration. Consequently we have to
1467             // always create a new Configuration here.
1468
1469             final MergedConfiguration mergedConfiguration = new MergedConfiguration(
1470                     mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
1471             r.setLastReportedConfiguration(mergedConfiguration);
1472
1473             logIfTransactionTooLarge(r.intent, r.icicle);
1474             app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1475                     System.identityHashCode(r), r.info,
1476                     // TODO: Have this take the merged configuration instead of separate global and
1477                     // override configs.
1478                     mergedConfiguration.getGlobalConfiguration(),
1479                     mergedConfiguration.getOverrideConfiguration(), r.compat,
1480                     r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1481                     r.persistentState, results, newIntents, !andResume,
1482                     mService.isNextTransitionForward(), profilerInfo);
1483
1484             if ((app.info.privateFlags&ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1485                 // This may be a heavy-weight process!  Note that the package
1486                 // manager will ensure that only activity can run in the main
1487                 // process of the .apk, which is the only thing that will be
1488                 // considered heavy-weight.
1489                 if (app.processName.equals(app.info.packageName)) {
1490                     if (mService.mHeavyWeightProcess != null
1491                             && mService.mHeavyWeightProcess != app) {
1492                         Slog.w(TAG, "Starting new heavy weight process " + app
1493                                 + " when already running "
1494                                 + mService.mHeavyWeightProcess);
1495                     }
1496                     mService.mHeavyWeightProcess = app;
1497                     Message msg = mService.mHandler.obtainMessage(
1498                             ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1499                     msg.obj = r;
1500                     mService.mHandler.sendMessage(msg);
1501                 }
1502             }
1503
1504         } catch (RemoteException e) {
1505             if (r.launchFailed) {
1506                 // This is the second time we failed -- finish activity
1507                 // and give up.
1508                 Slog.e(TAG, "Second failure launching "
1509                       + r.intent.getComponent().flattenToShortString()
1510                       + ", giving up", e);
1511                 mService.appDiedLocked(app);
1512                 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1513                         "2nd-crash", false);
1514                 return false;
1515             }
1516
1517             // This is the first time we failed -- restart process and
1518             // retry.
1519             r.launchFailed = true;
1520             app.activities.remove(r);
1521             throw e;
1522         }
1523
1524         r.launchFailed = false;
1525         if (stack.updateLRUListLocked(r)) {
1526             Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
1527         }
1528
1529         if (andResume) {
1530             // As part of the process of launching, ActivityThread also performs
1531             // a resume.
1532             stack.minimalResumeActivityLocked(r);
1533         } else {
1534             // This activity is not starting in the resumed state... which should look like we asked
1535             // it to pause+stop (but remain visible), and it has done so and reported back the
1536             // current icicle and other state.
1537             if (DEBUG_STATES) Slog.v(TAG_STATES,
1538                     "Moving to PAUSED: " + r + " (starting in paused state)");
1539             r.state = PAUSED;
1540         }
1541
1542         // Launch the new version setup screen if needed.  We do this -after-
1543         // launching the initial activity (that is, home), so that it can have
1544         // a chance to initialize itself while in the background, making the
1545         // switch back to it faster and look better.
1546         if (isFocusedStack(stack)) {
1547             mService.startSetupActivityLocked();
1548         }
1549
1550         // Update any services we are bound to that might care about whether
1551         // their client may have activities.
1552         if (r.app != null) {
1553             mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1554         }
1555
1556         return true;
1557     }
1558
1559     private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
1560         int extrasSize = 0;
1561         if (intent != null) {
1562             final Bundle extras = intent.getExtras();
1563             if (extras != null) {
1564                 extrasSize = extras.getSize();
1565             }
1566         }
1567         int icicleSize = (icicle == null ? 0 : icicle.getSize());
1568         if (extrasSize + icicleSize > 200000) {
1569             Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
1570                     + ", icicle size: " + icicleSize);
1571         }
1572     }
1573
1574     void startSpecificActivityLocked(ActivityRecord r,
1575             boolean andResume, boolean checkConfig) {
1576         // Is this activity's application already running?
1577         ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1578                 r.info.applicationInfo.uid, true);
1579
1580         r.getStack().setLaunchTime(r);
1581
1582         if (app != null && app.thread != null) {
1583             try {
1584                 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1585                         || !"android".equals(r.info.packageName)) {
1586                     // Don't add this if it is a platform component that is marked
1587                     // to run in multiple processes, because this is actually
1588                     // part of the framework so doesn't make sense to track as a
1589                     // separate apk in the process.
1590                     app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1591                             mService.mProcessStats);
1592                 }
1593                 realStartActivityLocked(r, app, andResume, checkConfig);
1594                 return;
1595             } catch (RemoteException e) {
1596                 Slog.w(TAG, "Exception when starting activity "
1597                         + r.intent.getComponent().flattenToShortString(), e);
1598             }
1599
1600             // If a dead object exception was thrown -- fall through to
1601             // restart the application.
1602         }
1603
1604         mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
1605                 "activity", r.intent.getComponent(), false, false, true);
1606     }
1607
1608     boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
1609             String resultWho, int requestCode, int callingPid, int callingUid,
1610             String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
1611             ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
1612         final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1613                 callingUid);
1614         if (startAnyPerm == PERMISSION_GRANTED) {
1615             return true;
1616         }
1617         final int componentRestriction = getComponentRestrictionForCallingPackage(
1618                 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1619         final int actionRestriction = getActionRestrictionForCallingPackage(
1620                 intent.getAction(), callingPackage, callingPid, callingUid);
1621         if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1622                 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1623             if (resultRecord != null) {
1624                 resultStack.sendActivityResultLocked(-1,
1625                         resultRecord, resultWho, requestCode,
1626                         Activity.RESULT_CANCELED, null);
1627             }
1628             final String msg;
1629             if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1630                 msg = "Permission Denial: starting " + intent.toString()
1631                         + " from " + callerApp + " (pid=" + callingPid
1632                         + ", uid=" + callingUid + ")" + " with revoked permission "
1633                         + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1634             } else if (!aInfo.exported) {
1635                 msg = "Permission Denial: starting " + intent.toString()
1636                         + " from " + callerApp + " (pid=" + callingPid
1637                         + ", uid=" + callingUid + ")"
1638                         + " not exported from uid " + aInfo.applicationInfo.uid;
1639             } else {
1640                 msg = "Permission Denial: starting " + intent.toString()
1641                         + " from " + callerApp + " (pid=" + callingPid
1642                         + ", uid=" + callingUid + ")"
1643                         + " requires " + aInfo.permission;
1644             }
1645             Slog.w(TAG, msg);
1646             throw new SecurityException(msg);
1647         }
1648
1649         if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1650             final String message = "Appop Denial: starting " + intent.toString()
1651                     + " from " + callerApp + " (pid=" + callingPid
1652                     + ", uid=" + callingUid + ")"
1653                     + " requires " + AppOpsManager.permissionToOp(
1654                             ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1655             Slog.w(TAG, message);
1656             return false;
1657         } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1658             final String message = "Appop Denial: starting " + intent.toString()
1659                     + " from " + callerApp + " (pid=" + callingPid
1660                     + ", uid=" + callingUid + ")"
1661                     + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1662             Slog.w(TAG, message);
1663             return false;
1664         }
1665         if (options != null) {
1666             if (options.getLaunchTaskId() != INVALID_STACK_ID) {
1667                 final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1668                         callingPid, callingUid);
1669                 if (startInTaskPerm != PERMISSION_GRANTED) {
1670                     final String msg = "Permission Denial: starting " + intent.toString()
1671                             + " from " + callerApp + " (pid=" + callingPid
1672                             + ", uid=" + callingUid + ") with launchTaskId="
1673                             + options.getLaunchTaskId();
1674                     Slog.w(TAG, msg);
1675                     throw new SecurityException(msg);
1676                 }
1677             }
1678             // Check if someone tries to launch an activity on a private display with a different
1679             // owner.
1680             final int launchDisplayId = options.getLaunchDisplayId();
1681             if (launchDisplayId != INVALID_DISPLAY
1682                     && !isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, launchDisplayId)) {
1683                 final String msg = "Permission Denial: starting " + intent.toString()
1684                         + " from " + callerApp + " (pid=" + callingPid
1685                         + ", uid=" + callingUid + ") with launchDisplayId="
1686                         + launchDisplayId;
1687                 Slog.w(TAG, msg);
1688                 throw new SecurityException(msg);
1689             }
1690         }
1691
1692         return true;
1693     }
1694
1695     /** Check if caller is allowed to launch activities on specified display. */
1696     boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId) {
1697         if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId
1698                 + " callingPid=" + callingPid + " callingUid=" + callingUid);
1699
1700         final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(launchDisplayId);
1701         if (activityDisplay == null) {
1702             Slog.w(TAG, "Launch on display check: display not found");
1703             return false;
1704         }
1705
1706         // Check if the caller can manage activity stacks.
1707         final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
1708                 callingUid);
1709         if (startAnyPerm == PERMISSION_GRANTED) {
1710             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1711                     + " allow launch any on display");
1712             return true;
1713         }
1714
1715         if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL
1716                 && activityDisplay.mDisplay.getOwnerUid() != SYSTEM_UID) {
1717             // Limit launching on virtual displays, because their contents can be read from Surface
1718             // by apps that created them.
1719             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1720                     + " disallow launch on virtual display for not-embedded activity");
1721             return false;
1722         }
1723
1724         if (!activityDisplay.isPrivate()) {
1725             // Anyone can launch on a public display.
1726             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1727                     + " allow launch on public display");
1728             return true;
1729         }
1730
1731         // Check if the caller is the owner of the display.
1732         if (activityDisplay.mDisplay.getOwnerUid() == callingUid) {
1733             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1734                     + " allow launch for owner of the display");
1735             return true;
1736         }
1737
1738         // Check if caller is present on display
1739         if (activityDisplay.isUidPresent(callingUid)) {
1740             if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1741                     + " allow launch for caller present on the display");
1742             return true;
1743         }
1744
1745         Slog.w(TAG, "Launch on display check: denied");
1746         return false;
1747     }
1748
1749     /** Update lists of UIDs that are present on displays and have access to them. */
1750     void updateUIDsPresentOnDisplay() {
1751         mDisplayAccessUIDs.clear();
1752         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1753             final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
1754             // Only bother calculating the whitelist for private displays
1755             if (activityDisplay.isPrivate()) {
1756                 mDisplayAccessUIDs.append(
1757                         activityDisplay.mDisplayId, activityDisplay.getPresentUIDs());
1758             }
1759         }
1760         // Store updated lists in DisplayManager. Callers from outside of AM should get them there.
1761         mDisplayManagerInternal.setDisplayAccessUIDs(mDisplayAccessUIDs);
1762     }
1763
1764     UserInfo getUserInfo(int userId) {
1765         final long identity = Binder.clearCallingIdentity();
1766         try {
1767             return UserManager.get(mService.mContext).getUserInfo(userId);
1768         } finally {
1769             Binder.restoreCallingIdentity(identity);
1770         }
1771     }
1772
1773     private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
1774             String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
1775         if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1776                 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
1777                 == PackageManager.PERMISSION_DENIED) {
1778             return ACTIVITY_RESTRICTION_PERMISSION;
1779         }
1780
1781         if (activityInfo.permission == null) {
1782             return ACTIVITY_RESTRICTION_NONE;
1783         }
1784
1785         final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1786         if (opCode == AppOpsManager.OP_NONE) {
1787             return ACTIVITY_RESTRICTION_NONE;
1788         }
1789
1790         if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1791                 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1792             if (!ignoreTargetSecurity) {
1793                 return ACTIVITY_RESTRICTION_APPOP;
1794             }
1795         }
1796
1797         return ACTIVITY_RESTRICTION_NONE;
1798     }
1799
1800     private int getActionRestrictionForCallingPackage(String action,
1801             String callingPackage, int callingPid, int callingUid) {
1802         if (action == null) {
1803             return ACTIVITY_RESTRICTION_NONE;
1804         }
1805
1806         String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1807         if (permission == null) {
1808             return ACTIVITY_RESTRICTION_NONE;
1809         }
1810
1811         final PackageInfo packageInfo;
1812         try {
1813             packageInfo = mService.mContext.getPackageManager()
1814                     .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1815         } catch (PackageManager.NameNotFoundException e) {
1816             Slog.i(TAG, "Cannot find package info for " + callingPackage);
1817             return ACTIVITY_RESTRICTION_NONE;
1818         }
1819
1820         if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
1821             return ACTIVITY_RESTRICTION_NONE;
1822         }
1823
1824         if (mService.checkPermission(permission, callingPid, callingUid) ==
1825                 PackageManager.PERMISSION_DENIED) {
1826             return ACTIVITY_RESTRICTION_PERMISSION;
1827         }
1828
1829         final int opCode = AppOpsManager.permissionToOpCode(permission);
1830         if (opCode == AppOpsManager.OP_NONE) {
1831             return ACTIVITY_RESTRICTION_NONE;
1832         }
1833
1834         if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1835                 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1836             return ACTIVITY_RESTRICTION_APPOP;
1837         }
1838
1839         return ACTIVITY_RESTRICTION_NONE;
1840     }
1841
1842     void setLaunchSource(int uid) {
1843         mLaunchingActivity.setWorkSource(new WorkSource(uid));
1844     }
1845
1846     void acquireLaunchWakelock() {
1847         if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1848             throw new IllegalStateException("Calling must be system uid");
1849         }
1850         mLaunchingActivity.acquire();
1851         if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1852             // To be safe, don't allow the wake lock to be held for too long.
1853             mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1854         }
1855     }
1856
1857     /**
1858      * Called when the frontmost task is idle.
1859      * @return the state of mService.mBooting before this was called.
1860      */
1861     private boolean checkFinishBootingLocked() {
1862         final boolean booting = mService.mBooting;
1863         boolean enableScreen = false;
1864         mService.mBooting = false;
1865         if (!mService.mBooted) {
1866             mService.mBooted = true;
1867             enableScreen = true;
1868         }
1869         if (booting || enableScreen) {
1870             mService.postFinishBooting(booting, enableScreen);
1871         }
1872         return booting;
1873     }
1874
1875     // Checked.
1876     final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
1877             boolean processPausingActivities, Configuration config) {
1878         if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
1879
1880         ArrayList<ActivityRecord> finishes = null;
1881         ArrayList<UserState> startingUsers = null;
1882         int NS = 0;
1883         int NF = 0;
1884         boolean booting = false;
1885         boolean activityRemoved = false;
1886
1887         ActivityRecord r = ActivityRecord.forTokenLocked(token);
1888         if (r != null) {
1889             if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1890                     + Debug.getCallers(4));
1891             mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1892             r.finishLaunchTickingLocked();
1893             if (fromTimeout) {
1894                 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
1895             }
1896
1897             // This is a hack to semi-deal with a race condition
1898             // in the client where it can be constructed with a
1899             // newer configuration from when we asked it to launch.
1900             // We'll update with whatever configuration it now says
1901             // it used to launch.
1902             if (config != null) {
1903                 r.setLastReportedGlobalConfiguration(config);
1904             }
1905
1906             // We are now idle.  If someone is waiting for a thumbnail from
1907             // us, we can now deliver.
1908             r.idle = true;
1909
1910             //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
1911             if (isFocusedStack(r.getStack()) || fromTimeout) {
1912                 booting = checkFinishBootingLocked();
1913             }
1914         }
1915
1916         if (allResumedActivitiesIdle()) {
1917             if (r != null) {
1918                 mService.scheduleAppGcsLocked();
1919             }
1920
1921             if (mLaunchingActivity.isHeld()) {
1922                 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1923                 if (VALIDATE_WAKE_LOCK_CALLER &&
1924                         Binder.getCallingUid() != Process.myUid()) {
1925                     throw new IllegalStateException("Calling must be system uid");
1926                 }
1927                 mLaunchingActivity.release();
1928             }
1929             ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1930         }
1931
1932         // Atomically retrieve all of the other things to do.
1933         final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
1934                 true /* remove */, processPausingActivities);
1935         NS = stops != null ? stops.size() : 0;
1936         if ((NF = mFinishingActivities.size()) > 0) {
1937             finishes = new ArrayList<>(mFinishingActivities);
1938             mFinishingActivities.clear();
1939         }
1940
1941         if (mStartingUsers.size() > 0) {
1942             startingUsers = new ArrayList<>(mStartingUsers);
1943             mStartingUsers.clear();
1944         }
1945
1946         // Stop any activities that are scheduled to do so but have been
1947         // waiting for the next one to start.
1948         for (int i = 0; i < NS; i++) {
1949             r = stops.get(i);
1950             final ActivityStack stack = r.getStack();
1951             if (stack != null) {
1952                 if (r.finishing) {
1953                     stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1954                 } else {
1955                     stack.stopActivityLocked(r);
1956                 }
1957             }
1958         }
1959
1960         // Finish any activities that are scheduled to do so but have been
1961         // waiting for the next one to start.
1962         for (int i = 0; i < NF; i++) {
1963             r = finishes.get(i);
1964             final ActivityStack stack = r.getStack();
1965             if (stack != null) {
1966                 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1967             }
1968         }
1969
1970         if (!booting) {
1971             // Complete user switch
1972             if (startingUsers != null) {
1973                 for (int i = 0; i < startingUsers.size(); i++) {
1974                     mService.mUserController.finishUserSwitch(startingUsers.get(i));
1975                 }
1976             }
1977         }
1978
1979         mService.trimApplications();
1980         //dump();
1981         //mWindowManager.dump();
1982
1983         if (activityRemoved) {
1984             resumeFocusedStackTopActivityLocked();
1985         }
1986
1987         return r;
1988     }
1989
1990     boolean handleAppDiedLocked(ProcessRecord app) {
1991         boolean hasVisibleActivities = false;
1992         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1993             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1994             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1995                 hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
1996             }
1997         }
1998         return hasVisibleActivities;
1999     }
2000
2001     void closeSystemDialogsLocked() {
2002         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2003             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2004             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2005                 stacks.get(stackNdx).closeSystemDialogsLocked();
2006             }
2007         }
2008     }
2009
2010     void removeUserLocked(int userId) {
2011         mUserStackInFront.delete(userId);
2012     }
2013
2014     /**
2015      * Update the last used stack id for non-current user (current user's last
2016      * used stack is the focused stack)
2017      */
2018     void updateUserStackLocked(int userId, ActivityStack stack) {
2019         if (userId != mCurrentUser) {
2020             mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
2021         }
2022     }
2023
2024     /**
2025      * @return true if some activity was finished (or would have finished if doit were true).
2026      */
2027     boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
2028             boolean doit, boolean evenPersistent, int userId) {
2029         boolean didSomething = false;
2030         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2031             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2032             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2033                 final ActivityStack stack = stacks.get(stackNdx);
2034                 if (stack.finishDisabledPackageActivitiesLocked(
2035                         packageName, filterByClasses, doit, evenPersistent, userId)) {
2036                     didSomething = true;
2037                 }
2038             }
2039         }
2040         return didSomething;
2041     }
2042
2043     void updatePreviousProcessLocked(ActivityRecord r) {
2044         // Now that this process has stopped, we may want to consider
2045         // it to be the previous app to try to keep around in case
2046         // the user wants to return to it.
2047
2048         // First, found out what is currently the foreground app, so that
2049         // we don't blow away the previous app if this activity is being
2050         // hosted by the process that is actually still the foreground.
2051         ProcessRecord fgApp = null;
2052         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2053             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2054             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2055                 final ActivityStack stack = stacks.get(stackNdx);
2056                 if (isFocusedStack(stack)) {
2057                     if (stack.mResumedActivity != null) {
2058                         fgApp = stack.mResumedActivity.app;
2059                     } else if (stack.mPausingActivity != null) {
2060                         fgApp = stack.mPausingActivity.app;
2061                     }
2062                     break;
2063                 }
2064             }
2065         }
2066
2067         // Now set this one as the previous process, only if that really
2068         // makes sense to.
2069         if (r.app != null && fgApp != null && r.app != fgApp
2070                 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
2071                 && r.app != mService.mHomeProcess) {
2072             mService.mPreviousProcess = r.app;
2073             mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
2074         }
2075     }
2076
2077     boolean resumeFocusedStackTopActivityLocked() {
2078         return resumeFocusedStackTopActivityLocked(null, null, null);
2079     }
2080
2081     boolean resumeFocusedStackTopActivityLocked(
2082             ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
2083         if (targetStack != null && isFocusedStack(targetStack)) {
2084             return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
2085         }
2086         final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2087         if (r == null || r.state != RESUMED) {
2088             mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
2089         } else if (r.state == RESUMED) {
2090             // Kick off any lingering app transitions form the MoveTaskToFront operation.
2091             mFocusedStack.executeAppTransition(targetOptions);
2092         }
2093         return false;
2094     }
2095
2096     void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
2097         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2098             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2099             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2100                 stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
2101             }
2102         }
2103     }
2104
2105     TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
2106         TaskRecord finishedTask = null;
2107         ActivityStack focusedStack = getFocusedStack();
2108         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2109             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2110             final int numStacks = stacks.size();
2111             for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2112                 final ActivityStack stack = stacks.get(stackNdx);
2113                 TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
2114                 if (stack == focusedStack || finishedTask == null) {
2115                     finishedTask = t;
2116                 }
2117             }
2118         }
2119         return finishedTask;
2120     }
2121
2122     void finishVoiceTask(IVoiceInteractionSession session) {
2123         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2124             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2125             final int numStacks = stacks.size();
2126             for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2127                 final ActivityStack stack = stacks.get(stackNdx);
2128                 stack.finishVoiceTask(session);
2129             }
2130         }
2131     }
2132
2133     void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
2134             String reason, boolean forceNonResizeable) {
2135         if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
2136             mUserLeaving = true;
2137         }
2138         if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
2139             // Caller wants the home activity moved with it.  To accomplish this,
2140             // we'll just indicate that this task returns to the home task.
2141             task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
2142         }
2143         ActivityStack currentStack = task.getStack();
2144         if (currentStack == null) {
2145             Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
2146                     + task + " to front. Stack is null");
2147             return;
2148         }
2149
2150         if (task.isResizeable() && options != null) {
2151             int stackId = options.getLaunchStackId();
2152             if (canUseActivityOptionsLaunchBounds(options, stackId)) {
2153                 final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
2154                 task.updateOverrideConfiguration(bounds);
2155                 if (stackId == INVALID_STACK_ID) {
2156                     stackId = task.getLaunchStackId();
2157                 }
2158                 if (stackId != currentStack.mStackId) {
2159                     task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE,
2160                             DEFER_RESUME, "findTaskToMoveToFrontLocked");
2161                     stackId = currentStack.mStackId;
2162                     // moveTaskToStackUncheckedLocked() should already placed the task on top,
2163                     // still need moveTaskToFrontLocked() below for any transition settings.
2164                 }
2165                 if (StackId.resizeStackWithLaunchBounds(stackId)) {
2166                     resizeStackLocked(stackId, bounds,
2167                             null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2168                             !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */, !DEFER_RESUME);
2169                 } else {
2170                     // WM resizeTask must be done after the task is moved to the correct stack,
2171                     // because Task's setBounds() also updates dim layer's bounds, but that has
2172                     // dependency on the stack.
2173                     task.resizeWindowContainer();
2174                 }
2175             }
2176         }
2177
2178         final ActivityRecord r = task.getTopActivity();
2179         currentStack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
2180                 r == null ? null : r.appTimeTracker, reason);
2181
2182         if (DEBUG_STACK) Slog.d(TAG_STACK,
2183                 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
2184
2185         handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
2186                 currentStack.mStackId, forceNonResizeable);
2187     }
2188
2189     boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
2190         // We use the launch bounds in the activity options is the device supports freeform
2191         // window management or is launching into the pinned stack.
2192         if (options.getLaunchBounds() == null) {
2193             return false;
2194         }
2195         return (mService.mSupportsPictureInPicture && launchStackId == PINNED_STACK_ID)
2196                 || mService.mSupportsFreeformWindowManagement;
2197     }
2198
2199     protected <T extends ActivityStack> T getStack(int stackId) {
2200         return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2201     }
2202
2203     protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
2204             boolean createOnTop) {
2205         final ActivityContainer activityContainer = mActivityContainers.get(stackId);
2206         if (activityContainer != null) {
2207             return (T) activityContainer.mStack;
2208         }
2209         if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
2210             return null;
2211         }
2212         if (stackId == DOCKED_STACK_ID) {
2213             // Make sure recents stack exist when creating a dock stack as it normally need to be on
2214             // the other side of the docked stack and we make visibility decisions based on that.
2215             getStack(RECENTS_STACK_ID, CREATE_IF_NEEDED, createOnTop);
2216         }
2217         return (T) createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
2218     }
2219
2220     /**
2221      * Get a topmost stack on the display, that is a valid launch stack for specified activity.
2222      * If there is no such stack, new dynamic stack can be created.
2223      * @param displayId Target display.
2224      * @param r Activity that should be launched there.
2225      * @return Existing stack if there is a valid one, new dynamic stack if it is valid or null.
2226      */
2227     ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r) {
2228         final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
2229         if (activityDisplay == null) {
2230             throw new IllegalArgumentException(
2231                     "Display with displayId=" + displayId + " not found.");
2232         }
2233
2234         // Return the topmost valid stack on the display.
2235         for (int i = activityDisplay.mStacks.size() - 1; i >= 0; --i) {
2236             final ActivityStack stack = activityDisplay.mStacks.get(i);
2237             if (mService.mActivityStarter.isValidLaunchStackId(stack.mStackId, displayId, r)) {
2238                 return stack;
2239             }
2240         }
2241
2242         // If there is no valid stack on the external display - check if new dynamic stack will do.
2243         if (displayId != Display.DEFAULT_DISPLAY) {
2244             final int newDynamicStackId = getNextStackId();
2245             if (mService.mActivityStarter.isValidLaunchStackId(newDynamicStackId, displayId, r)) {
2246                 return createStackOnDisplay(newDynamicStackId, displayId, true /*onTop*/);
2247             }
2248         }
2249
2250         Slog.w(TAG, "getValidLaunchStackOnDisplay: can't launch on displayId " + displayId);
2251         return null;
2252     }
2253
2254     ArrayList<ActivityStack> getStacks() {
2255         ArrayList<ActivityStack> allStacks = new ArrayList<>();
2256         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2257             allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
2258         }
2259         return allStacks;
2260     }
2261
2262     ArrayList<ActivityStack> getStacksOnDefaultDisplay() {
2263         return mActivityDisplays.valueAt(DEFAULT_DISPLAY).mStacks;
2264     }
2265
2266     /**
2267      * Get next focusable stack in the system. This will search across displays and stacks
2268      * in last-focused order for a focusable and visible stack, different from the target stack.
2269      *
2270      * @param currentFocus The stack that previously had focus and thus needs to be ignored when
2271      *                     searching for next candidate.
2272      * @return Next focusable {@link ActivityStack}, null if not found.
2273      */
2274     ActivityStack getNextFocusableStackLocked(ActivityStack currentFocus) {
2275         mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2276
2277         for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2278             final int displayId = mTmpOrderedDisplayIds.get(i);
2279             // If a display is registered in WM, it must also be available in AM.
2280             @SuppressWarnings("ConstantConditions")
2281             final List<ActivityStack> stacks = getActivityDisplayOrCreateLocked(displayId).mStacks;
2282             for (int j = stacks.size() - 1; j >= 0; --j) {
2283                 final ActivityStack stack = stacks.get(j);
2284                 if (stack != currentFocus && stack.isFocusable()
2285                         && stack.shouldBeVisible(null) != STACK_INVISIBLE) {
2286                     return stack;
2287                 }
2288             }
2289         }
2290
2291         return null;
2292     }
2293
2294     /**
2295      * Get next valid stack for launching provided activity in the system. This will search across
2296      * displays and stacks in last-focused order for a focusable and visible stack, except those
2297      * that are on a currently focused display.
2298      *
2299      * @param r The activity that is being launched.
2300      * @param currentFocus The display that previously had focus and thus needs to be ignored when
2301      *                     searching for the next candidate.
2302      * @return Next valid {@link ActivityStack}, null if not found.
2303      */
2304     ActivityStack getNextValidLaunchStackLocked(@NonNull ActivityRecord r, int currentFocus) {
2305         mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2306         for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2307             final int displayId = mTmpOrderedDisplayIds.get(i);
2308             if (displayId == currentFocus) {
2309                 continue;
2310             }
2311             final ActivityStack stack = getValidLaunchStackOnDisplay(displayId, r);
2312             if (stack != null) {
2313                 return stack;
2314             }
2315         }
2316         return null;
2317     }
2318
2319     ActivityRecord getHomeActivity() {
2320         return getHomeActivityForUser(mCurrentUser);
2321     }
2322
2323     ActivityRecord getHomeActivityForUser(int userId) {
2324         final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
2325         for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
2326             final TaskRecord task = tasks.get(taskNdx);
2327             if (task.isHomeTask()) {
2328                 final ArrayList<ActivityRecord> activities = task.mActivities;
2329                 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2330                     final ActivityRecord r = activities.get(activityNdx);
2331                     if (r.isHomeActivity()
2332                             && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
2333                         return r;
2334                     }
2335                 }
2336             }
2337         }
2338         return null;
2339     }
2340
2341     /**
2342      * Returns if a stack should be treated as if it's docked. Returns true if the stack is
2343      * the docked stack itself, or if it's side-by-side to the docked stack.
2344      */
2345     boolean isStackDockedInEffect(int stackId) {
2346         return stackId == DOCKED_STACK_ID ||
2347                 (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
2348     }
2349
2350     ActivityContainer createVirtualActivityContainer(ActivityRecord parentActivity,
2351             IActivityContainerCallback callback) {
2352         ActivityContainer activityContainer =
2353                 new VirtualActivityContainer(parentActivity, callback);
2354         mActivityContainers.put(activityContainer.mStackId, activityContainer);
2355         if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS,
2356                 "createActivityContainer: " + activityContainer);
2357         parentActivity.mChildContainers.add(activityContainer);
2358         return activityContainer;
2359     }
2360
2361     void removeChildActivityContainers(ActivityRecord parentActivity) {
2362         final ArrayList<ActivityContainer> childStacks = parentActivity.mChildContainers;
2363         for (int containerNdx = childStacks.size() - 1; containerNdx >= 0; --containerNdx) {
2364             ActivityContainer container = childStacks.remove(containerNdx);
2365             if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS, "removeChildActivityContainers: removing "
2366                     + container);
2367             container.release();
2368         }
2369     }
2370
2371     void deleteActivityContainerRecord(int stackId) {
2372         if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS,
2373                 "deleteActivityContainerRecord: callers=" + Debug.getCallers(4));
2374         mActivityContainers.remove(stackId);
2375     }
2376
2377     void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
2378             boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
2379         if (stackId == DOCKED_STACK_ID) {
2380             resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
2381                     preserveWindows, deferResume);
2382             return;
2383         }
2384         final ActivityStack stack = getStack(stackId);
2385         if (stack == null) {
2386             Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2387             return;
2388         }
2389
2390         if (!allowResizeInDockedMode && !StackId.tasksAreFloating(stackId) &&
2391                 getStack(DOCKED_STACK_ID) != null) {
2392             // If the docked stack exists, don't resize non-floating stacks independently of the
2393             // size computed from the docked stack size (otherwise they will be out of sync)
2394             return;
2395         }
2396
2397         Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
2398         mWindowManager.deferSurfaceLayout();
2399         try {
2400             stack.resize(bounds, tempTaskBounds, tempTaskInsetBounds);
2401             if (!deferResume) {
2402                 stack.ensureVisibleActivitiesConfigurationLocked(
2403                         stack.topRunningActivityLocked(), preserveWindows);
2404             }
2405         } finally {
2406             mWindowManager.continueSurfaceLayout();
2407             Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2408         }
2409     }
2410
2411     void deferUpdateBounds(int stackId) {
2412         final ActivityStack stack = getStack(stackId);
2413         if (stack != null) {
2414             stack.deferUpdateBounds();
2415         }
2416     }
2417
2418     void continueUpdateBounds(int stackId) {
2419         final ActivityStack stack = getStack(stackId);
2420         if (stack != null) {
2421             stack.continueUpdateBounds();
2422         }
2423     }
2424
2425     void notifyAppTransitionDone() {
2426         continueUpdateBounds(RECENTS_STACK_ID);
2427         for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2428             final int taskId = mResizingTasksDuringAnimation.valueAt(i);
2429             final TaskRecord task =
2430                     anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID);
2431             if (task != null) {
2432                 task.setTaskDockedResizing(false);
2433             }
2434         }
2435         mResizingTasksDuringAnimation.clear();
2436     }
2437
2438     private void moveTasksToFullscreenStackInSurfaceTransaction(int fromStackId,
2439             boolean onTop) {
2440
2441         final ActivityStack stack = getStack(fromStackId);
2442         if (stack == null) {
2443             return;
2444         }
2445
2446         mWindowManager.deferSurfaceLayout();
2447         try {
2448             if (fromStackId == DOCKED_STACK_ID) {
2449                 // We are moving all tasks from the docked stack to the fullscreen stack,
2450                 // which is dismissing the docked stack, so resize all other stacks to
2451                 // fullscreen here already so we don't end up with resize trashing.
2452                 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2453                     if (StackId.isResizeableByDockedStack(i)) {
2454                         ActivityStack otherStack = getStack(i);
2455                         if (otherStack != null) {
2456                             resizeStackLocked(i, null, null, null, PRESERVE_WINDOWS,
2457                                     true /* allowResizeInDockedMode */, DEFER_RESUME);
2458                         }
2459                     }
2460                 }
2461
2462                 // Also disable docked stack resizing since we have manually adjusted the
2463                 // size of other stacks above and we don't want to trigger a docked stack
2464                 // resize when we remove task from it below and it is detached from the
2465                 // display because it no longer contains any tasks.
2466                 mAllowDockedStackResize = false;
2467             } else if (fromStackId == PINNED_STACK_ID) {
2468                 if (onTop) {
2469                     // Log if we are expanding the PiP to fullscreen
2470                     MetricsLogger.action(mService.mContext,
2471                             ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN);
2472                 }
2473             }
2474             ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
2475             final boolean isFullscreenStackVisible = fullscreenStack != null &&
2476                     fullscreenStack.shouldBeVisible(null) == STACK_VISIBLE;
2477             // If we are moving from the pinned stack, then the animation takes care of updating
2478             // the picture-in-picture mode.
2479             final boolean schedulePictureInPictureModeChange = (fromStackId == PINNED_STACK_ID);
2480             final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2481             final int size = tasks.size();
2482             if (onTop) {
2483                 for (int i = 0; i < size; i++) {
2484                     final TaskRecord task = tasks.get(i);
2485                     final boolean isTopTask = i == (size - 1);
2486                     if (fromStackId == PINNED_STACK_ID) {
2487                         // Update the return-to to reflect where the pinned stack task was moved
2488                         // from so that we retain the stack that was previously visible if the
2489                         // pinned stack is recreated. See moveActivityToPinnedStackLocked().
2490                         task.setTaskToReturnTo(isFullscreenStackVisible && onTop ?
2491                                 APPLICATION_ACTIVITY_TYPE : HOME_ACTIVITY_TYPE);
2492                     }
2493                     // Defer resume until all the tasks have been moved to the fullscreen stack
2494                     task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
2495                             REPARENT_MOVE_STACK_TO_FRONT, isTopTask /* animate */, DEFER_RESUME,
2496                             schedulePictureInPictureModeChange,
2497                             "moveTasksToFullscreenStack - onTop");
2498                 }
2499             } else {
2500                 for (int i = 0; i < size; i++) {
2501                     final TaskRecord task = tasks.get(i);
2502                     // Position the tasks in the fullscreen stack in order at the bottom of the
2503                     // stack. Also defer resume until all the tasks have been moved to the
2504                     // fullscreen stack.
2505                     task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, i /* position */,
2506                             REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME,
2507                             schedulePictureInPictureModeChange,
2508                             "moveTasksToFullscreenStack - NOT_onTop");
2509                 }
2510             }
2511
2512             ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2513             resumeFocusedStackTopActivityLocked();
2514         } finally {
2515             mAllowDockedStackResize = true;
2516             mWindowManager.continueSurfaceLayout();
2517         }
2518     }
2519
2520     void moveTasksToFullscreenStackLocked(int fromStackId, boolean onTop) {
2521         mWindowManager.inSurfaceTransaction(
2522                 () -> moveTasksToFullscreenStackInSurfaceTransaction(fromStackId, onTop));
2523     }
2524
2525     void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2526             Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2527             boolean preserveWindows) {
2528         resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
2529                 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows,
2530                 false /* deferResume */);
2531     }
2532
2533     void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2534             Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2535             boolean preserveWindows, boolean deferResume) {
2536
2537         if (!mAllowDockedStackResize) {
2538             // Docked stack resize currently disabled.
2539             return;
2540         }
2541
2542         final ActivityStack stack = getStack(DOCKED_STACK_ID);
2543         if (stack == null) {
2544             Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2545             return;
2546         }
2547
2548         Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2549         mWindowManager.deferSurfaceLayout();
2550         try {
2551             // Don't allow re-entry while resizing. E.g. due to docked stack detaching.
2552             mAllowDockedStackResize = false;
2553             ActivityRecord r = stack.topRunningActivityLocked();
2554             stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds);
2555
2556             // TODO: Checking for isAttached might not be needed as if the user passes in null
2557             // dockedBounds then they want the docked stack to be dismissed.
2558             if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2559                 // The dock stack either was dismissed or went fullscreen, which is kinda the same.
2560                 // In this case we make all other static stacks fullscreen and move all
2561                 // docked stack tasks to the fullscreen stack.
2562                 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, ON_TOP);
2563
2564                 // stack shouldn't contain anymore activities, so nothing to resume.
2565                 r = null;
2566             } else {
2567                 // Docked stacks occupy a dedicated region on screen so the size of all other
2568                 // static stacks need to be adjusted so they don't overlap with the docked stack.
2569                 // We get the bounds to use from window manager which has been adjusted for any
2570                 // screen controls and is also the same for all stacks.
2571                 final Rect otherTaskRect = new Rect();
2572                 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2573                     final ActivityStack current = getStack(i);
2574                     if (current != null && StackId.isResizeableByDockedStack(i)) {
2575                         current.getStackDockedModeBounds(
2576                                 tempOtherTaskBounds /* currentTempTaskBounds */,
2577                                 tempRect /* outStackBounds */,
2578                                 otherTaskRect /* outTempTaskBounds */, true /* ignoreVisibility */);
2579
2580                         resizeStackLocked(i, !tempRect.isEmpty() ? tempRect : null,
2581                                 !otherTaskRect.isEmpty() ? otherTaskRect : tempOtherTaskBounds,
2582                                 tempOtherTaskInsetBounds, preserveWindows,
2583                                 true /* allowResizeInDockedMode */, deferResume);
2584                     }
2585                 }
2586             }
2587             if (!deferResume) {
2588                 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows);
2589             }
2590         } finally {
2591             mAllowDockedStackResize = true;
2592             mWindowManager.continueSurfaceLayout();
2593             Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2594         }
2595     }
2596
2597     void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
2598         final PinnedActivityStack stack = getStack(PINNED_STACK_ID);
2599         if (stack == null) {
2600             Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2601             return;
2602         }
2603
2604         // It is possible for the bounds animation from the WM to call this but be delayed by
2605         // another AM call that is holding the AMS lock. In such a case, the pinnedBounds may be
2606         // incorrect if AMS.resizeStackWithBoundsFromWindowManager() is already called while waiting
2607         // for the AMS lock to be freed. So check and make sure these bounds are still good.
2608         final PinnedStackWindowController stackController = stack.getWindowContainerController();
2609         if (stackController.pinnedStackResizeDisallowed()) {
2610             return;
2611         }
2612
2613         Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2614         mWindowManager.deferSurfaceLayout();
2615         try {
2616             ActivityRecord r = stack.topRunningActivityLocked();
2617             Rect insetBounds = null;
2618             if (tempPinnedTaskBounds != null) {
2619                 // We always use 0,0 as the position for the inset rect because
2620                 // if we are getting insets at all in the pinned stack it must mean
2621                 // we are headed for fullscreen.
2622                 insetBounds = tempRect;
2623                 insetBounds.top = 0;
2624                 insetBounds.left = 0;
2625                 insetBounds.right = tempPinnedTaskBounds.width();
2626                 insetBounds.bottom = tempPinnedTaskBounds.height();
2627             }
2628             stack.resize(pinnedBounds, tempPinnedTaskBounds, insetBounds);
2629             stack.ensureVisibleActivitiesConfigurationLocked(r, false);
2630         } finally {
2631             mWindowManager.continueSurfaceLayout();
2632             Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2633         }
2634     }
2635
2636     ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
2637         final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
2638         if (activityDisplay == null) {
2639             return null;
2640         }
2641
2642         final ActivityContainer activityContainer =
2643                 new ActivityContainer(stackId, activityDisplay, onTop);
2644         return activityContainer.mStack;
2645     }
2646
2647
2648     void removeStackInSurfaceTransaction(int stackId) {
2649         final ActivityStack stack = getStack(stackId);
2650         if (stack == null) {
2651             return;
2652         }
2653
2654         final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2655         if (stack.getStackId() == PINNED_STACK_ID) {
2656             /**
2657              * Workaround: Force-stop all the activities in the pinned stack before we reparent them
2658              * to the fullscreen stack.  This is to guarantee that when we are removing a stack,
2659              * that the client receives onStop() before it is reparented.  We do this by detaching
2660              * the stack from the display so that it will be considered invisible when
2661              * ensureActivitiesVisibleLocked() is called, and all of its activitys will be marked
2662              * invisible as well and added to the stopping list.  After which we process the
2663              * stopping list by handling the idle.
2664              */
2665             final PinnedActivityStack pinnedStack = (PinnedActivityStack) stack;
2666             pinnedStack.mForceHidden = true;
2667             pinnedStack.ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2668             pinnedStack.mForceHidden = false;
2669             activityIdleInternalLocked(null, false /* fromTimeout */,
2670                     true /* processPausingActivites */, null /* configuration */);
2671
2672             // Move all the tasks to the bottom of the fullscreen stack
2673             moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
2674         } else {
2675             for (int i = tasks.size() - 1; i >= 0; i--) {
2676                 removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */,
2677                         REMOVE_FROM_RECENTS);
2678             }
2679         }
2680     }
2681
2682     /**
2683      * Removes the stack associated with the given {@param stackId}.  If the {@param stackId} is the
2684      * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
2685      * instead moved back onto the fullscreen stack.
2686      */
2687     void removeStackLocked(int stackId) {
2688         mWindowManager.inSurfaceTransaction(
2689                 () -> removeStackInSurfaceTransaction(stackId));
2690     }
2691
2692     /**
2693      * See {@link #removeTaskByIdLocked(int, boolean, boolean, boolean)}
2694      */
2695     boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents) {
2696         return removeTaskByIdLocked(taskId, killProcess, removeFromRecents, !PAUSE_IMMEDIATELY);
2697     }
2698
2699     /**
2700      * Removes the task with the specified task id.
2701      *
2702      * @param taskId Identifier of the task to be removed.
2703      * @param killProcess Kill any process associated with the task if possible.
2704      * @param removeFromRecents Whether to also remove the task from recents.
2705      * @param pauseImmediately Pauses all task activities immediately without waiting for the
2706      *                         pause-complete callback from the activity.
2707      * @return Returns true if the given task was found and removed.
2708      */
2709     boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents,
2710             boolean pauseImmediately) {
2711         final TaskRecord tr = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
2712                 INVALID_STACK_ID);
2713         if (tr != null) {
2714             tr.removeTaskActivitiesLocked(pauseImmediately);
2715             cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents);
2716             if (tr.isPersistable) {
2717                 mService.notifyTaskPersisterLocked(null, true);
2718             }
2719             return true;
2720         }
2721         Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
2722         return false;
2723     }
2724
2725     void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) {
2726         if (removeFromRecents) {
2727             mRecentTasks.remove(tr);
2728             tr.removedFromRecents();
2729         }
2730         ComponentName component = tr.getBaseIntent().getComponent();
2731         if (component == null) {
2732             Slog.w(TAG, "No component for base intent of task: " + tr);
2733             return;
2734         }
2735
2736         // Find any running services associated with this app and stop if needed.
2737         mService.mServices.cleanUpRemovedTaskLocked(tr, component, new Intent(tr.getBaseIntent()));
2738
2739         if (!killProcess) {
2740             return;
2741         }
2742
2743         // Determine if the process(es) for this task should be killed.
2744         final String pkg = component.getPackageName();
2745         ArrayList<ProcessRecord> procsToKill = new ArrayList<>();
2746         ArrayMap<String, SparseArray<ProcessRecord>> pmap = mService.mProcessNames.getMap();
2747         for (int i = 0; i < pmap.size(); i++) {
2748
2749             SparseArray<ProcessRecord> uids = pmap.valueAt(i);
2750             for (int j = 0; j < uids.size(); j++) {
2751                 ProcessRecord proc = uids.valueAt(j);
2752                 if (proc.userId != tr.userId) {
2753                     // Don't kill process for a different user.
2754                     continue;
2755                 }
2756                 if (proc == mService.mHomeProcess) {
2757                     // Don't kill the home process along with tasks from the same package.
2758                     continue;
2759                 }
2760                 if (!proc.pkgList.containsKey(pkg)) {
2761                     // Don't kill process that is not associated with this task.
2762                     continue;
2763                 }
2764
2765                 for (int k = 0; k < proc.activities.size(); k++) {
2766                     TaskRecord otherTask = proc.activities.get(k).getTask();
2767                     if (tr.taskId != otherTask.taskId && otherTask.inRecents) {
2768                         // Don't kill process(es) that has an activity in a different task that is
2769                         // also in recents.
2770                         return;
2771                     }
2772                 }
2773
2774                 if (proc.foregroundServices) {
2775                     // Don't kill process(es) with foreground service.
2776                     return;
2777                 }
2778
2779                 // Add process to kill list.
2780                 procsToKill.add(proc);
2781             }
2782         }
2783
2784         // Kill the running processes.
2785         for (int i = 0; i < procsToKill.size(); i++) {
2786             ProcessRecord pr = procsToKill.get(i);
2787             if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
2788                     && pr.curReceivers.isEmpty()) {
2789                 pr.kill("remove task", true);
2790             } else {
2791                 // We delay killing processes that are not in the background or running a receiver.
2792                 pr.waitingToKill = "remove task";
2793             }
2794         }
2795     }
2796
2797     int getNextStackId() {
2798         while (true) {
2799             if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2800                     && getStack(mNextFreeStackId) == null) {
2801                 break;
2802             }
2803             mNextFreeStackId++;
2804         }
2805         return mNextFreeStackId;
2806     }
2807
2808     /**
2809      * Restores a recent task to a stack
2810      * @param task The recent task to be restored.
2811      * @param stackId The stack to restore the task to (default launch stack will be used
2812      *                if stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}
2813      *                or is not a static stack).
2814      * @return true if the task has been restored successfully.
2815      */
2816     boolean restoreRecentTaskLocked(TaskRecord task, int stackId) {
2817         if (!StackId.isStaticStack(stackId)) {
2818             // If stack is not static (or stack id is invalid) - use the default one.
2819             // This means that tasks that were on external displays will be restored on the
2820             // primary display.
2821             stackId = task.getLaunchStackId();
2822         } else if (stackId == DOCKED_STACK_ID && !task.supportsSplitScreen()) {
2823             // Preferred stack is the docked stack, but the task can't go in the docked stack.
2824             // Put it in the fullscreen stack.
2825             stackId = FULLSCREEN_WORKSPACE_STACK_ID;
2826         }
2827
2828         final ActivityStack currentStack = task.getStack();
2829         if (currentStack != null) {
2830             // Task has already been restored once. See if we need to do anything more
2831             if (currentStack.mStackId == stackId) {
2832                 // Nothing else to do since it is already restored in the right stack.
2833                 return true;
2834             }
2835             // Remove current stack association, so we can re-associate the task with the
2836             // right stack below.
2837             currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING);
2838         }
2839
2840         final ActivityStack stack =
2841                 getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
2842
2843         if (stack == null) {
2844             // What does this mean??? Not sure how we would get here...
2845             if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2846                     "Unable to find/create stack to restore recent task=" + task);
2847             return false;
2848         }
2849
2850         stack.addTask(task, false /* toTop */, "restoreRecentTask");
2851         // TODO: move call for creation here and other place into Stack.addTask()
2852         task.createWindowContainer(false /* toTop */, true /* showForAllUsers */);
2853         if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2854                 "Added restored task=" + task + " to stack=" + stack);
2855         final ArrayList<ActivityRecord> activities = task.mActivities;
2856         for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2857             activities.get(activityNdx).createWindowContainer();
2858         }
2859         return true;
2860     }
2861
2862     /**
2863      * Move stack with all its existing content to specified display.
2864      * @param stackId Id of stack to move.
2865      * @param displayId Id of display to move stack to.
2866      * @param onTop Indicates whether container should be place on top or on bottom.
2867      */
2868     void moveStackToDisplayLocked(int stackId, int displayId, boolean onTop) {
2869         final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
2870         if (activityDisplay == null) {
2871             throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown displayId="
2872                     + displayId);
2873         }
2874         final ActivityContainer activityContainer = mActivityContainers.get(stackId);
2875         if (activityContainer != null) {
2876             if (activityContainer.isAttachedLocked()) {
2877                 if (activityContainer.getDisplayId() == displayId) {
2878                     throw new IllegalArgumentException("Trying to move stackId=" + stackId
2879                             + " to its current displayId=" + displayId);
2880                 }
2881
2882                 activityContainer.moveToDisplayLocked(activityDisplay, onTop);
2883             } else {
2884                 throw new IllegalStateException("moveStackToDisplayLocked: Stack with stackId="
2885                         + stackId + " is not attached to any display.");
2886             }
2887         } else {
2888             throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
2889                     + stackId);
2890         }
2891         // TODO(multi-display): resize stacks properly if moved from split-screen.
2892     }
2893
2894     /**
2895      * Returns the reparent target stack, creating the stack if necessary.  This call also enforces
2896      * the various checks on tasks that are going to be reparented from one stack to another.
2897      */
2898     ActivityStack getReparentTargetStack(TaskRecord task, int stackId, boolean toTop) {
2899         final ActivityStack prevStack = task.getStack();
2900
2901         // Check that we aren't reparenting to the same stack that the task is already in
2902         if (prevStack != null && prevStack.mStackId == stackId) {
2903             Slog.w(TAG, "Can not reparent to same stack, task=" + task
2904                     + " already in stackId=" + stackId);
2905             return prevStack;
2906         }
2907
2908         // Ensure that we aren't trying to move into a multi-window stack without multi-window
2909         // support
2910         if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
2911             throw new IllegalArgumentException("Device doesn't support multi-window, can not"
2912                     + " reparent task=" + task + " to stackId=" + stackId);
2913         }
2914
2915         // Ensure that we're not moving a task to a dynamic stack if device doesn't support
2916         // multi-display.
2917         // TODO(multi-display): Support non-dynamic stacks on secondary displays.
2918         // TODO: Check ActivityView after fixing b/35349678.
2919         if (StackId.isDynamicStack(stackId) && !mService.mSupportsMultiDisplay) {
2920             throw new IllegalArgumentException("Device doesn't support multi-display, can not"
2921                     + " reparent task=" + task + " to stackId=" + stackId);
2922         }
2923
2924         // Ensure that we aren't trying to move into a freeform stack without freeform
2925         // support
2926         if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
2927             throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
2928                     + " task=" + task);
2929         }
2930
2931         // We don't allow moving a unresizeable task to the docked stack since the docked stack is
2932         // used for split-screen mode and will cause things like the docked divider to show up. We
2933         // instead leave the task in its current stack or move it to the fullscreen stack if it
2934         // isn't currently in a stack.
2935         if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
2936             stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
2937             Slog.w(TAG, "Can not move unresizeable task=" + task + " to docked stack."
2938                     + " Moving to stackId=" + stackId + " instead.");
2939         }
2940
2941         // Temporarily disable resizeablility of the task as we don't want it to be resized if, for
2942         // example, a docked stack is created which will lead to the stack we are moving from being
2943         // resized and and its resizeable tasks being resized.
2944         try {
2945             task.mTemporarilyUnresizable = true;
2946             return getStack(stackId, CREATE_IF_NEEDED, toTop);
2947         } finally {
2948             task.mTemporarilyUnresizable = false;
2949         }
2950     }
2951
2952     boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect destBounds) {
2953         final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2954         if (stack == null) {
2955             throw new IllegalArgumentException(
2956                     "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
2957         }
2958
2959         final ActivityRecord r = stack.topRunningActivityLocked();
2960         if (r == null) {
2961             Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
2962                     + " in stack=" + stack);
2963             return false;
2964         }
2965
2966         if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
2967             Slog.w(TAG,
2968                     "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
2969                             + " r=" + r);
2970             return false;
2971         }
2972
2973         moveActivityToPinnedStackLocked(r, null /* sourceBounds */, 0f /* aspectRatio */,
2974                 true /* moveHomeStackToFront */, "moveTopActivityToPinnedStack");
2975         return true;
2976     }
2977
2978     void moveActivityToPinnedStackLocked(ActivityRecord r, Rect sourceHintBounds, float aspectRatio,
2979             boolean moveHomeStackToFront, String reason) {
2980
2981         mWindowManager.deferSurfaceLayout();
2982
2983         // This will clear the pinned stack by moving an existing task to the full screen stack,
2984         // ensuring only one task is present.
2985         moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
2986
2987         // Need to make sure the pinned stack exist so we can resize it below...
2988         final PinnedActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
2989
2990         try {
2991             final TaskRecord task = r.getTask();
2992
2993             if (r == task.getStack().getVisibleBehindActivity()) {
2994                 // An activity can't be pinned and visible behind at the same time. Go ahead and
2995                 // release it from been visible behind before pinning.
2996                 requestVisibleBehindLocked(r, false);
2997             }
2998
2999             // Resize the pinned stack to match the current size of the task the activity we are
3000             // going to be moving is currently contained in. We do this to have the right starting
3001             // animation bounds for the pinned stack to the desired bounds the caller wants.
3002             resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
3003                     null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
3004                     true /* allowResizeInDockedMode */, !DEFER_RESUME);
3005
3006             if (task.mActivities.size() == 1) {
3007                 // There is only one activity in the task. So, we can just move the task over to
3008                 // the stack without re-parenting the activity in a different task.  We don't
3009                 // move the home stack forward if we are currently entering picture-in-picture
3010                 // while pausing because that changes the focused stack and may prevent the new
3011                 // starting activity from resuming.
3012                 if (moveHomeStackToFront && task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE
3013                         && (r.state == RESUMED || !r.supportsPictureInPictureWhilePausing)) {
3014                     // Move the home stack forward if the task we just moved to the pinned stack
3015                     // was launched from home so home should be visible behind it.
3016                     moveHomeStackToFront(reason);
3017                 }
3018                 // Defer resume until below, and do not schedule PiP changes until we animate below
3019                 task.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
3020                         DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
3021             } else {
3022                 // There are multiple activities in the task and moving the top activity should
3023                 // reveal/leave the other activities in their original task.
3024
3025                 // Currently, we don't support reparenting activities across tasks in two different
3026                 // stacks, so instead, just create a new task in the same stack, reparent the
3027                 // activity into that task, and then reparent the whole task to the new stack. This
3028                 // ensures that all the necessary work to migrate states in the old and new stacks
3029                 // is also done.
3030                 final TaskRecord newTask = task.getStack().createTaskRecord(
3031                         getNextTaskIdForUserLocked(r.userId), r.info, r.intent, null, null, true,
3032                         r.mActivityType);
3033                 r.reparent(newTask, MAX_VALUE, "moveActivityToStack");
3034
3035                 // Defer resume until below, and do not schedule PiP changes until we animate below
3036                 newTask.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
3037                         DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
3038             }
3039
3040             // Reset the state that indicates it can enter PiP while pausing after we've moved it
3041             // to the pinned stack
3042             r.supportsPictureInPictureWhilePausing = false;
3043         } finally {
3044             mWindowManager.continueSurfaceLayout();
3045         }
3046
3047         // Calculate the default bounds (don't use existing stack bounds as we may have just created
3048         // the stack, and schedule the start of the animation into PiP (the bounds animator that
3049         // is triggered by this is posted on another thread)
3050         final Rect destBounds = stack.getDefaultPictureInPictureBounds(aspectRatio);
3051
3052         stack.animateResizePinnedStack(sourceHintBounds, destBounds, -1 /* animationDuration */,
3053                 true /* fromFullscreen */);
3054
3055         // Update the visibility of all activities after the they have been reparented to the new
3056         // stack.  This MUST run after the animation above is scheduled to ensure that the windows
3057         // drawn signal is scheduled after the bounds animation start call on the bounds animator
3058         // thread.
3059         ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
3060         resumeFocusedStackTopActivityLocked();
3061
3062         mService.mTaskChangeNotificationController.notifyActivityPinned(r.packageName,
3063                 r.getTask().taskId);
3064     }
3065
3066     /** Move activity with its stack to front and make the stack focused. */
3067     boolean moveFocusableActivityStackToFrontLocked(ActivityRecord r, String reason) {
3068         if (r == null || !r.isFocusable()) {
3069             if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3070                     "moveActivityStackToFront: unfocusable r=" + r);
3071             return false;
3072         }
3073
3074         final TaskRecord task = r.getTask();
3075         final ActivityStack stack = r.getStack();
3076         if (stack == null) {
3077             Slog.w(TAG, "moveActivityStackToFront: invalid task or stack: r="
3078                     + r + " task=" + task);
3079             return false;
3080         }
3081
3082         if (stack == mFocusedStack && stack.topRunningActivityLocked() == r) {
3083             if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3084                     "moveActivityStackToFront: already on top, r=" + r);
3085             return false;
3086         }
3087
3088         if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3089                 "moveActivityStackToFront: r=" + r);
3090
3091         stack.moveToFront(reason, task);
3092         return true;
3093     }
3094
3095     ActivityRecord findTaskLocked(ActivityRecord r, int displayId) {
3096         mTmpFindTaskResult.r = null;
3097         mTmpFindTaskResult.matchedByRootAffinity = false;
3098         ActivityRecord affinityMatch = null;
3099         if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
3100         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3101             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3102             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3103                 final ActivityStack stack = stacks.get(stackNdx);
3104                 if (!checkActivityBelongsInStack(r, stack)) {
3105                     if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) "
3106                             + stack);
3107                     continue;
3108                 }
3109                 if (!stack.mActivityContainer.isEligibleForNewTasks()) {
3110                     if (DEBUG_TASKS) Slog.d(TAG_TASKS,
3111                             "Skipping stack: (new task not allowed) " + stack);
3112                     continue;
3113                 }
3114                 stack.findTaskLocked(r, mTmpFindTaskResult);
3115                 // It is possible to have tasks in multiple stacks with the same root affinity, so
3116                 // we should keep looking after finding an affinity match to see if there is a
3117                 // better match in another stack. Also, task affinity isn't a good enough reason
3118                 // to target a display which isn't the source of the intent, so skip any affinity
3119                 // matches not on the specified display.
3120                 if (mTmpFindTaskResult.r != null) {
3121                     if (!mTmpFindTaskResult.matchedByRootAffinity) {
3122                         return mTmpFindTaskResult.r;
3123                     } else if (mTmpFindTaskResult.r.getDisplayId() == displayId) {
3124                         // Note: since the traversing through the stacks is top down, the floating
3125                         // tasks should always have lower priority than any affinity-matching tasks
3126                         // in the fullscreen stacks
3127                         affinityMatch = mTmpFindTaskResult.r;
3128                     }
3129                 }
3130             }
3131         }
3132
3133         if (DEBUG_TASKS && affinityMatch == null) Slog.d(TAG_TASKS, "No task found");
3134         return affinityMatch;
3135     }
3136
3137     /**
3138      * Checks that for the given activity {@param r}, its activity type matches the {@param stack}
3139      * type.
3140      */
3141     private boolean checkActivityBelongsInStack(ActivityRecord r, ActivityStack stack) {
3142         if (r.isHomeActivity()) {
3143             return stack.isHomeStack();
3144         } else if (r.isRecentsActivity()) {
3145             return stack.isRecentsStack();
3146         } else if (r.isAssistantActivity()) {
3147             return stack.isAssistantStack();
3148         }
3149         return true;
3150     }
3151
3152     ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
3153                                       boolean compareIntentFilters) {
3154         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3155             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3156             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3157                 final ActivityRecord ar = stacks.get(stackNdx)
3158                         .findActivityLocked(intent, info, compareIntentFilters);
3159                 if (ar != null) {
3160                     return ar;
3161                 }
3162             }
3163         }
3164         return null;
3165     }
3166
3167     void goingToSleepLocked() {
3168         scheduleSleepTimeout();
3169         if (!mGoingToSleep.isHeld()) {
3170             mGoingToSleep.acquire();
3171             if (mLaunchingActivity.isHeld()) {
3172                 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
3173                     throw new IllegalStateException("Calling must be system uid");
3174                 }
3175                 mLaunchingActivity.release();
3176                 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3177             }
3178         }
3179         checkReadyForSleepLocked();
3180     }
3181
3182     boolean shutdownLocked(int timeout) {
3183         goingToSleepLocked();
3184
3185         boolean timedout = false;
3186         final long endTime = System.currentTimeMillis() + timeout;
3187         while (true) {
3188             boolean cantShutdown = false;
3189             for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3190                 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3191                 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3192                     cantShutdown |= stacks.get(stackNdx).checkReadyForSleepLocked();
3193                 }
3194             }
3195             if (cantShutdown) {
3196                 long timeRemaining = endTime - System.currentTimeMillis();
3197                 if (timeRemaining > 0) {
3198                     try {
3199                         mService.wait(timeRemaining);
3200                     } catch (InterruptedException e) {
3201                     }
3202                 } else {
3203                     Slog.w(TAG, "Activity manager shutdown timed out");
3204                     timedout = true;
3205                     break;
3206                 }
3207             } else {
3208                 break;
3209             }
3210         }
3211
3212         // Force checkReadyForSleep to complete.
3213         mSleepTimeout = true;
3214         checkReadyForSleepLocked();
3215
3216         return timedout;
3217     }
3218
3219     void comeOutOfSleepIfNeededLocked() {
3220         removeSleepTimeouts();
3221         if (mGoingToSleep.isHeld()) {
3222             mGoingToSleep.release();
3223         }
3224         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3225             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3226             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3227                 final ActivityStack stack = stacks.get(stackNdx);
3228                 stack.awakeFromSleepingLocked();
3229                 if (isFocusedStack(stack)) {
3230                     resumeFocusedStackTopActivityLocked();
3231                 }
3232             }
3233         }
3234         mGoingToSleepActivities.clear();
3235     }
3236
3237     void activitySleptLocked(ActivityRecord r) {
3238         mGoingToSleepActivities.remove(r);
3239         checkReadyForSleepLocked();
3240     }
3241
3242     void checkReadyForSleepLocked() {
3243         if (!mService.isSleepingOrShuttingDownLocked()) {
3244             // Do not care.
3245             return;
3246         }
3247
3248         if (!mSleepTimeout) {
3249             boolean dontSleep = false;
3250             for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3251                 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3252                 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3253                     dontSleep |= stacks.get(stackNdx).checkReadyForSleepLocked();
3254                 }
3255             }
3256
3257             if (mStoppingActivities.size() > 0) {
3258                 // Still need to tell some activities to stop; can't sleep yet.
3259                 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to stop "
3260                         + mStoppingActivities.size() + " activities");
3261                 scheduleIdleLocked();
3262                 dontSleep = true;
3263             }
3264
3265             if (mGoingToSleepActivities.size() > 0) {
3266                 // Still need to tell some activities to sleep; can't sleep yet.
3267                 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to sleep "
3268                         + mGoingToSleepActivities.size() + " activities");
3269                 dontSleep = true;
3270             }
3271
3272             if (dontSleep) {
3273                 return;
3274             }
3275         }
3276
3277         // Send launch end powerhint before going sleep
3278         mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
3279
3280         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3281             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3282             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3283                 stacks.get(stackNdx).goToSleep();
3284             }
3285         }
3286
3287         removeSleepTimeouts();
3288
3289         if (mGoingToSleep.isHeld()) {
3290             mGoingToSleep.release();
3291         }
3292         if (mService.mShuttingDown) {
3293             mService.notifyAll();
3294         }
3295     }
3296
3297     boolean reportResumedActivityLocked(ActivityRecord r) {
3298         final ActivityStack stack = r.getStack();
3299         if (isFocusedStack(stack)) {
3300             mService.updateUsageStats(r, true);
3301         }
3302         if (allResumedActivitiesComplete()) {
3303             ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
3304             mWindowManager.executeAppTransition();
3305             return true;
3306         }
3307         return false;
3308     }
3309
3310     void handleAppCrashLocked(ProcessRecord app) {
3311         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3312             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3313             int stackNdx = stacks.size() - 1;
3314             while (stackNdx >= 0) {
3315                 stacks.get(stackNdx).handleAppCrashLocked(app);
3316                 stackNdx--;
3317             }
3318         }
3319     }
3320
3321     boolean requestVisibleBehindLocked(ActivityRecord r, boolean visible) {
3322         final ActivityStack stack = r.getStack();
3323         if (stack == null) {
3324             if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
3325                     "requestVisibleBehind: r=" + r + " visible=" + visible + " stack is null");
3326             return false;
3327         }
3328
3329         if (visible && !StackId.activitiesCanRequestVisibleBehind(stack.mStackId)) {
3330             if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND, "requestVisibleBehind: r=" + r
3331                     + " visible=" + visible + " stackId=" + stack.mStackId
3332                     + " can't contain visible behind activities");
3333             return false;
3334         }
3335
3336         final boolean isVisible = stack.hasVisibleBehindActivity();
3337         if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
3338                 "requestVisibleBehind r=" + r + " visible=" + visible + " isVisible=" + isVisible);
3339
3340         final ActivityRecord top = topRunningActivityLocked();
3341         if (top == null || top == r || (visible == isVisible)) {
3342             if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND, "requestVisibleBehind: quick return");
3343             stack.setVisibleBehindActivity(visible ? r : null);
3344             return true;
3345         }
3346
3347         // A non-top activity is reporting a visibility change.
3348         if (visible && top.fullscreen) {
3349             // Let the caller know that it can't be seen.
3350             if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
3351                     "requestVisibleBehind: returning top.fullscreen=" + top.fullscreen
3352                     + " top.state=" + top.state + " top.app=" + top.app + " top.app.thread="
3353                     + top.app.thread);
3354             return false;
3355         } else if (!visible && stack.getVisibleBehindActivity() != r) {
3356             // Only the activity set as currently visible behind should actively reset its
3357             // visible behind state.
3358             if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
3359                     "requestVisibleBehind: returning visible=" + visible
3360                     + " stack.getVisibleBehindActivity()=" + stack.getVisibleBehindActivity()
3361                     + " r=" + r);
3362             return false;
3363         }
3364
3365         stack.setVisibleBehindActivity(visible ? r : null);
3366         if (!visible) {
3367             // If there is a translucent home activity, we need to force it stop being translucent,
3368             // because we can't depend on the application to necessarily perform that operation.
3369             // Check out b/14469711 for details.
3370             final ActivityRecord next = stack.findNextTranslucentActivity(r);
3371             if (next != null && next.isHomeActivity()) {
3372                 mService.convertFromTranslucent(next.appToken);
3373             }
3374         }
3375         if (top.app != null && top.app.thread != null) {
3376             // Notify the top app of the change.
3377             try {
3378                 top.app.thread.scheduleBackgroundVisibleBehindChanged(top.appToken, visible);
3379             } catch (RemoteException e) {
3380             }
3381         }
3382         return true;
3383     }
3384
3385     // Called when WindowManager has finished animating the launchingBehind activity to the back.
3386     private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
3387         final TaskRecord task = r.getTask();
3388         final ActivityStack stack = task.getStack();
3389
3390         r.mLaunchTaskBehind = false;
3391         task.setLastThumbnailLocked(r.screenshotActivityLocked());
3392         mRecentTasks.addLocked(task);
3393         mService.mTaskChangeNotificationController.notifyTaskStackChanged();
3394         r.setVisibility(false);
3395
3396         // When launching tasks behind, update the last active time of the top task after the new
3397         // task has been shown briefly
3398         final ActivityRecord top = stack.topActivity();
3399         if (top != null) {
3400             top.getTask().touchActiveTime();
3401         }
3402     }
3403
3404     void scheduleLaunchTaskBehindComplete(IBinder token) {
3405         mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
3406     }
3407
3408     void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
3409             boolean preserveWindows) {
3410         mKeyguardController.beginActivityVisibilityUpdate();
3411         try {
3412             // First the front stacks. In case any are not fullscreen and are in front of home.
3413             for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3414                 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3415                 final int topStackNdx = stacks.size() - 1;
3416                 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3417                     final ActivityStack stack = stacks.get(stackNdx);
3418                     stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
3419                 }
3420             }
3421         } finally {
3422             mKeyguardController.endActivityVisibilityUpdate();
3423         }
3424     }
3425
3426     void addStartingWindowsForVisibleActivities(boolean taskSwitch) {
3427         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3428             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3429             final int topStackNdx = stacks.size() - 1;
3430             for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3431                 final ActivityStack stack = stacks.get(stackNdx);
3432                 stack.addStartingWindowsForVisibleActivities(taskSwitch);
3433             }
3434         }
3435     }
3436
3437     void invalidateTaskLayers() {
3438         mTaskLayersChanged = true;
3439     }
3440
3441     void rankTaskLayersIfNeeded() {
3442         if (!mTaskLayersChanged) {
3443             return;
3444         }
3445         mTaskLayersChanged = false;
3446         for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
3447             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3448             int baseLayer = 0;
3449             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3450                 baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
3451             }
3452         }
3453     }
3454
3455     void clearOtherAppTimeTrackers(AppTimeTracker except) {
3456         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3457             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3458             final int topStackNdx = stacks.size() - 1;
3459             for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3460                 final ActivityStack stack = stacks.get(stackNdx);
3461                 stack.clearOtherAppTimeTrackers(except);
3462             }
3463         }
3464     }
3465
3466     void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
3467         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3468             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3469             final int numStacks = stacks.size();
3470             for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
3471                 final ActivityStack stack = stacks.get(stackNdx);
3472                 stack.scheduleDestroyActivities(app, reason);
3473             }
3474         }
3475     }
3476
3477     void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
3478         // Examine all activities currently running in the process.
3479         TaskRecord firstTask = null;
3480         // Tasks is non-null only if two or more tasks are found.
3481         ArraySet<TaskRecord> tasks = null;
3482         if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
3483         for (int i = 0; i < app.activities.size(); i++) {
3484             ActivityRecord r = app.activities.get(i);
3485             // First, if we find an activity that is in the process of being destroyed,
3486             // then we just aren't going to do anything for now; we want things to settle
3487             // down before we try to prune more activities.
3488             if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
3489                 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
3490                 return;
3491             }
3492             // Don't consider any activies that are currently not in a state where they
3493             // can be destroyed.
3494             if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
3495                     || r.state == PAUSED || r.state == STOPPING) {
3496                 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
3497                 continue;
3498             }
3499
3500             final TaskRecord task = r.getTask();
3501             if (task != null) {
3502                 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + task
3503                         + " from " + r);
3504                 if (firstTask == null) {
3505                     firstTask = task;
3506                 } else if (firstTask != task) {
3507                     if (tasks == null) {
3508                         tasks = new ArraySet<>();
3509                         tasks.add(firstTask);
3510                     }
3511                     tasks.add(task);
3512                 }
3513             }
3514         }
3515         if (tasks == null) {
3516             if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
3517             return;
3518         }
3519         // If we have activities in multiple tasks that are in a position to be destroyed,
3520         // let's iterate through the tasks and release the oldest one.
3521         final int numDisplays = mActivityDisplays.size();
3522         for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3523             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3524             // Step through all stacks starting from behind, to hit the oldest things first.
3525             for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
3526                 final ActivityStack stack = stacks.get(stackNdx);
3527                 // Try to release activities in this stack; if we manage to, we are done.
3528                 if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
3529                     return;
3530                 }
3531             }
3532         }
3533     }
3534
3535     boolean switchUserLocked(int userId, UserState uss) {
3536         final int focusStackId = mFocusedStack.getStackId();
3537         // We dismiss the docked stack whenever we switch users.
3538         moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, focusStackId == DOCKED_STACK_ID);
3539         // Also dismiss the pinned stack whenever we switch users. Removing the pinned stack will
3540         // also cause all tasks to be moved to the fullscreen stack at a position that is
3541         // appropriate.
3542         removeStackLocked(PINNED_STACK_ID);
3543
3544         mUserStackInFront.put(mCurrentUser, focusStackId);
3545         final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
3546         mCurrentUser = userId;
3547
3548         mStartingUsers.add(uss);
3549         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3550             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3551             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3552                 final ActivityStack stack = stacks.get(stackNdx);
3553                 stack.switchUserLocked(userId);
3554                 TaskRecord task = stack.topTask();
3555                 if (task != null) {
3556                     stack.positionChildWindowContainerAtTop(task);
3557                 }
3558             }
3559         }
3560
3561         ActivityStack stack = getStack(restoreStackId);
3562         if (stack == null) {
3563             stack = mHomeStack;
3564         }
3565         final boolean homeInFront = stack.isHomeStack();
3566         if (stack.isOnHomeDisplay()) {
3567             stack.moveToFront("switchUserOnHomeDisplay");
3568         } else {
3569             // Stack was moved to another display while user was swapped out.
3570             resumeHomeStackTask(null, "switchUserOnOtherDisplay");
3571         }
3572         return homeInFront;
3573     }
3574
3575     /** Checks whether the userid is a profile of the current user. */
3576     boolean isCurrentProfileLocked(int userId) {
3577         if (userId == mCurrentUser) return true;
3578         return mService.mUserController.isCurrentProfileLocked(userId);
3579     }
3580
3581     /**
3582      * Returns whether a stopping activity is present that should be stopped after visible, rather
3583      * than idle.
3584      * @return {@code true} if such activity is present. {@code false} otherwise.
3585      */
3586     boolean isStoppingNoHistoryActivity() {
3587         // Activities that are marked as nohistory should be stopped immediately after the resumed
3588         // activity has become visible.
3589         for (ActivityRecord record : mStoppingActivities) {
3590             if (record.isNoHistory()) {
3591                 return true;
3592             }
3593         }
3594
3595         return false;
3596     }
3597
3598     final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
3599             boolean remove, boolean processPausingActivities) {
3600         ArrayList<ActivityRecord> stops = null;
3601
3602         final boolean nowVisible = allResumedActivitiesVisible();
3603         for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3604             ActivityRecord s = mStoppingActivities.get(activityNdx);
3605             boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
3606             if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
3607                     + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
3608             if (waitingVisible && nowVisible) {
3609                 mActivitiesWaitingForVisibleActivity.remove(s);
3610                 waitingVisible = false;
3611                 if (s.finishing) {
3612                     // If this activity is finishing, it is sitting on top of
3613                     // everyone else but we now know it is no longer needed...
3614                     // so get rid of it.  Otherwise, we need to go through the
3615                     // normal flow and hide it once we determine that it is
3616                     // hidden by the activities in front of it.
3617                     if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
3618                     s.setVisibility(false);
3619                 }
3620             }
3621             if ((!waitingVisible || mService.isSleepingOrShuttingDownLocked()) && remove) {
3622                 if (!processPausingActivities && s.state == PAUSING) {
3623                     // Defer processing pausing activities in this iteration and reschedule
3624                     // a delayed idle to reprocess it again
3625                     removeTimeoutsForActivityLocked(idleActivity);
3626                     scheduleIdleTimeoutLocked(idleActivity);
3627                     continue;
3628                 }
3629
3630                 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
3631                 if (stops == null) {
3632                     stops = new ArrayList<>();
3633                 }
3634                 stops.add(s);
3635                 mStoppingActivities.remove(activityNdx);
3636             }
3637         }
3638
3639         return stops;
3640     }
3641
3642     void validateTopActivitiesLocked() {
3643         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3644             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3645             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3646                 final ActivityStack stack = stacks.get(stackNdx);
3647                 final ActivityRecord r = stack.topRunningActivityLocked();
3648                 final ActivityState state = r == null ? DESTROYED : r.state;
3649                 if (isFocusedStack(stack)) {
3650                     if (r == null) Slog.e(TAG,
3651                             "validateTop...: null top activity, stack=" + stack);
3652                     else {
3653                         final ActivityRecord pausing = stack.mPausingActivity;
3654                         if (pausing != null && pausing == r) Slog.e(TAG,
3655                                 "validateTop...: top stack has pausing activity r=" + r
3656                                 + " state=" + state);
3657                         if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3658                                 "validateTop...: activity in front not resumed r=" + r
3659                                 + " state=" + state);
3660                     }
3661                 } else {
3662                     final ActivityRecord resumed = stack.mResumedActivity;
3663                     if (resumed != null && resumed == r) Slog.e(TAG,
3664                             "validateTop...: back stack has resumed activity r=" + r
3665                             + " state=" + state);
3666                     if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3667                             "validateTop...: activity in back resumed r=" + r + " state=" + state);
3668                 }
3669             }
3670         }
3671     }
3672
3673     private String lockTaskModeToString() {
3674         switch (mLockTaskModeState) {
3675             case LOCK_TASK_MODE_LOCKED:
3676                 return "LOCKED";
3677             case LOCK_TASK_MODE_PINNED:
3678                 return "PINNED";
3679             case LOCK_TASK_MODE_NONE:
3680                 return "NONE";
3681             default: return "unknown=" + mLockTaskModeState;
3682         }
3683     }
3684
3685     public void dump(PrintWriter pw, String prefix) {
3686         pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
3687                 pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
3688         pw.print(prefix); pw.println("mSleepTimeout=" + mSleepTimeout);
3689         pw.print(prefix);
3690         pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
3691         pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
3692         pw.print(prefix); pw.println("mActivityContainers=" + mActivityContainers);
3693         pw.print(prefix); pw.print("mLockTaskModeState=" + lockTaskModeToString());
3694         final SparseArray<String[]> packages = mService.mLockTaskPackages;
3695         if (packages.size() > 0) {
3696             pw.print(prefix); pw.println("mLockTaskPackages (userId:packages)=");
3697             for (int i = 0; i < packages.size(); ++i) {
3698                 pw.print(prefix); pw.print(prefix); pw.print(packages.keyAt(i));
3699                 pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
3700             }
3701         }
3702         if (!mWaitingForActivityVisible.isEmpty()) {
3703             pw.print(prefix); pw.println("mWaitingForActivityVisible=");
3704             for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
3705                 pw.print(prefix); pw.print(prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
3706             }
3707         }
3708
3709         pw.println(" mLockTaskModeTasks" + mLockTaskModeTasks);
3710         mKeyguardController.dump(pw, prefix);
3711     }
3712
3713     /**
3714      * Dump all connected displays' configurations.
3715      * @param prefix Prefix to apply to each line of the dump.
3716      */
3717     void dumpDisplayConfigs(PrintWriter pw, String prefix) {
3718         pw.print(prefix); pw.println("Display override configurations:");
3719         final int displayCount = mActivityDisplays.size();
3720         for (int i = 0; i < displayCount; i++) {
3721             final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(i);
3722             pw.print(prefix); pw.print("  "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
3723                     pw.println(activityDisplay.getOverrideConfiguration());
3724         }
3725     }
3726
3727     /**
3728      * Dumps the activities matching the given {@param name} in the either the focused stack
3729      * or all visible stacks if {@param dumpVisibleStacks} is true.
3730      */
3731     ArrayList<ActivityRecord> getDumpActivitiesLocked(String name, boolean dumpVisibleStacksOnly,
3732             boolean dumpFocusedStackOnly) {
3733         if (dumpFocusedStackOnly) {
3734             return mFocusedStack.getDumpActivitiesLocked(name);
3735         } else {
3736             ArrayList<ActivityRecord> activities = new ArrayList<>();
3737             int numDisplays = mActivityDisplays.size();
3738             for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3739                 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3740                 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3741                     ActivityStack stack = stacks.get(stackNdx);
3742                     if (!dumpVisibleStacksOnly ||
3743                             stack.shouldBeVisible(null) == STACK_VISIBLE) {
3744                         activities.addAll(stack.getDumpActivitiesLocked(name));
3745                     }
3746                 }
3747             }
3748             return activities;
3749         }
3750     }
3751
3752     static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3753             boolean needSep, String prefix) {
3754         if (activity != null) {
3755             if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3756                 if (needSep) {
3757                     pw.println();
3758                 }
3759                 pw.print(prefix);
3760                 pw.println(activity);
3761                 return true;
3762             }
3763         }
3764         return false;
3765     }
3766
3767     boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3768             boolean dumpClient, String dumpPackage) {
3769         boolean printed = false;
3770         boolean needSep = false;
3771         for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3772             ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
3773             pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
3774                     pw.println(" (activities from top to bottom):");
3775             ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3776             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3777                 final ActivityStack stack = stacks.get(stackNdx);
3778                 StringBuilder stackHeader = new StringBuilder(128);
3779                 stackHeader.append("  Stack #");
3780                 stackHeader.append(stack.mStackId);
3781                 stackHeader.append(":");
3782                 stackHeader.append("\n");
3783                 stackHeader.append("  mFullscreen=" + stack.mFullscreen);
3784                 stackHeader.append("\n");
3785                 stackHeader.append("  mBounds=" + stack.mBounds);
3786
3787                 final boolean printedStackHeader = stack.dumpActivitiesLocked(fd, pw, dumpAll,
3788                         dumpClient, dumpPackage, needSep, stackHeader.toString());
3789                 printed |= printedStackHeader;
3790                 if (!printedStackHeader) {
3791                     // Ensure we always dump the stack header even if there are no activities
3792                     pw.println();
3793                     pw.println(stackHeader);
3794                 }
3795
3796                 printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, "    ", "Run", false,
3797                         !dumpAll, false, dumpPackage, true,
3798                         "    Running activities (most recent first):", null);
3799
3800                 needSep = printed;
3801                 boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3802                         "    mPausingActivity: ");
3803                 if (pr) {
3804                     printed = true;
3805                     needSep = false;
3806                 }
3807                 pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3808                         "    mResumedActivity: ");
3809                 if (pr) {
3810                     printed = true;
3811                     needSep = false;
3812                 }
3813                 if (dumpAll) {
3814                     pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3815                             "    mLastPausedActivity: ");
3816                     if (pr) {
3817                         printed = true;
3818                         needSep = true;
3819                     }
3820                     printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3821                             needSep, "    mLastNoHistoryActivity: ");
3822                 }
3823                 needSep = printed;
3824             }
3825         }
3826
3827         printed |= dumpHistoryList(fd, pw, mFinishingActivities, "  ", "Fin", false, !dumpAll,
3828                 false, dumpPackage, true, "  Activities waiting to finish:", null);
3829         printed |= dumpHistoryList(fd, pw, mStoppingActivities, "  ", "Stop", false, !dumpAll,
3830                 false, dumpPackage, true, "  Activities waiting to stop:", null);
3831         printed |= dumpHistoryList(fd, pw, mActivitiesWaitingForVisibleActivity, "  ", "Wait",
3832                 false, !dumpAll, false, dumpPackage, true,
3833                 "  Activities waiting for another to become visible:", null);
3834         printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, "  ", "Sleep", false, !dumpAll,
3835                 false, dumpPackage, true, "  Activities waiting to sleep:", null);
3836         printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, "  ", "Sleep", false, !dumpAll,
3837                 false, dumpPackage, true, "  Activities waiting to sleep:", null);
3838
3839         return printed;
3840     }
3841
3842     static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
3843             String prefix, String label, boolean complete, boolean brief, boolean client,
3844             String dumpPackage, boolean needNL, String header1, String header2) {
3845         TaskRecord lastTask = null;
3846         String innerPrefix = null;
3847         String[] args = null;
3848         boolean printed = false;
3849         for (int i=list.size()-1; i>=0; i--) {
3850             final ActivityRecord r = list.get(i);
3851             if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3852                 continue;
3853             }
3854             if (innerPrefix == null) {
3855                 innerPrefix = prefix + "      ";
3856                 args = new String[0];
3857             }
3858             printed = true;
3859             final boolean full = !brief && (complete || !r.isInHistory());
3860             if (needNL) {
3861                 pw.println("");
3862                 needNL = false;
3863             }
3864             if (header1 != null) {
3865                 pw.println(header1);
3866                 header1 = null;
3867             }
3868             if (header2 != null) {
3869                 pw.println(header2);
3870                 header2 = null;
3871             }
3872             if (lastTask != r.getTask()) {
3873                 lastTask = r.getTask();
3874                 pw.print(prefix);
3875                 pw.print(full ? "* " : "  ");
3876                 pw.println(lastTask);
3877                 if (full) {
3878                     lastTask.dump(pw, prefix + "  ");
3879                 } else if (complete) {
3880                     // Complete + brief == give a summary.  Isn't that obvious?!?
3881                     if (lastTask.intent != null) {
3882                         pw.print(prefix); pw.print("  ");
3883                                 pw.println(lastTask.intent.toInsecureStringWithClip());
3884                     }
3885                 }
3886             }
3887             pw.print(prefix); pw.print(full ? "  * " : "    "); pw.print(label);
3888             pw.print(" #"); pw.print(i); pw.print(": ");
3889             pw.println(r);
3890             if (full) {
3891                 r.dump(pw, innerPrefix);
3892             } else if (complete) {
3893                 // Complete + brief == give a summary.  Isn't that obvious?!?
3894                 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3895                 if (r.app != null) {
3896                     pw.print(innerPrefix); pw.println(r.app);
3897                 }
3898             }
3899             if (client && r.app != null && r.app.thread != null) {
3900                 // flush anything that is already in the PrintWriter since the thread is going
3901                 // to write to the file descriptor directly
3902                 pw.flush();
3903                 try {
3904                     TransferPipe tp = new TransferPipe();
3905                     try {
3906                         r.app.thread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
3907                         // Short timeout, since blocking here can
3908                         // deadlock with the application.
3909                         tp.go(fd, 2000);
3910                     } finally {
3911                         tp.kill();
3912                     }
3913                 } catch (IOException e) {
3914                     pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3915                 } catch (RemoteException e) {
3916                     pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3917                 }
3918                 needNL = true;
3919             }
3920         }
3921         return printed;
3922     }
3923
3924     void scheduleIdleTimeoutLocked(ActivityRecord next) {
3925         if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3926                 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
3927         Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
3928         mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
3929     }
3930
3931     final void scheduleIdleLocked() {
3932         mHandler.sendEmptyMessage(IDLE_NOW_MSG);
3933     }
3934
3935     void removeTimeoutsForActivityLocked(ActivityRecord r) {
3936         if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
3937                 + Debug.getCallers(4));
3938         mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3939     }
3940
3941     final void scheduleResumeTopActivities() {
3942         if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
3943             mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
3944         }
3945     }
3946
3947     void removeSleepTimeouts() {
3948         mSleepTimeout = false;
3949         mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
3950     }
3951
3952     final void scheduleSleepTimeout() {
3953         removeSleepTimeouts();
3954         mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
3955     }
3956
3957     @Override
3958     public void onDisplayAdded(int displayId) {
3959         if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
3960         mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
3961     }
3962
3963     @Override
3964     public void onDisplayRemoved(int displayId) {
3965         if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
3966         mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
3967     }
3968
3969     @Override
3970     public void onDisplayChanged(int displayId) {
3971         if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
3972         mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
3973     }
3974
3975     private void handleDisplayAdded(int displayId) {
3976         synchronized (mService) {
3977             getActivityDisplayOrCreateLocked(displayId);
3978         }
3979     }
3980
3981     /** Check if display with specified id is added to the list. */
3982     boolean isDisplayAdded(int displayId) {
3983         return getActivityDisplayOrCreateLocked(displayId) != null;
3984     }
3985
3986     /**
3987      * Get an existing instance of {@link ActivityDisplay} or create new if there is a
3988      * corresponding record in display manager.
3989      */
3990     private ActivityDisplay getActivityDisplayOrCreateLocked(int displayId) {
3991         ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3992         if (activityDisplay != null) {
3993             return activityDisplay;
3994         }
3995         if (mDisplayManager == null) {
3996             // The system isn't fully initialized yet.
3997             return null;
3998         }
3999         final Display display = mDisplayManager.getDisplay(displayId);
4000         if (display == null) {
4001             // The display is not registered in DisplayManager.
4002             return null;
4003         }
4004         // The display hasn't been added to ActivityManager yet, create a new record now.
4005         activityDisplay = new ActivityDisplay(displayId);
4006         if (activityDisplay.mDisplay == null) {
4007             Slog.w(TAG, "Display " + displayId + " gone before initialization complete");
4008             return null;
4009         }
4010         mActivityDisplays.put(displayId, activityDisplay);
4011         calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
4012         mWindowManager.onDisplayAdded(displayId);
4013         return activityDisplay;
4014     }
4015
4016     private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
4017         mDefaultMinSizeOfResizeableTask =
4018                 mService.mContext.getResources().getDimensionPixelSize(
4019                         com.android.internal.R.dimen.default_minimal_size_resizable_task);
4020     }
4021
4022     private void handleDisplayRemoved(int displayId) {
4023         if (displayId == DEFAULT_DISPLAY) {
4024             throw new IllegalArgumentException("Can't remove the primary display.");
4025         }
4026
4027         synchronized (mService) {
4028             ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
4029             if (activityDisplay != null) {
4030                 final boolean destroyContentOnRemoval
4031                         = activityDisplay.shouldDestroyContentOnRemove();
4032                 final ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
4033                 while (!stacks.isEmpty()) {
4034                     final ActivityStack stack = stacks.get(0);
4035                     if (destroyContentOnRemoval) {
4036                         moveStackToDisplayLocked(stack.mStackId, DEFAULT_DISPLAY,
4037                                 false /* onTop */);
4038                         stack.finishAllActivitiesLocked(true /* immediately */);
4039                     } else {
4040                         // Moving all tasks to fullscreen stack, because it's guaranteed to be
4041                         // a valid launch stack for all activities. This way the task history from
4042                         // external display will be preserved on primary after move.
4043                         moveTasksToFullscreenStackLocked(stack.getStackId(), true /* onTop */);
4044                     }
4045                 }
4046                 mActivityDisplays.remove(displayId);
4047                 mWindowManager.onDisplayRemoved(displayId);
4048             }
4049         }
4050     }
4051
4052     private void handleDisplayChanged(int displayId) {
4053         synchronized (mService) {
4054             ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
4055             if (activityDisplay != null) {
4056                 // TODO: Update the bounds.
4057             }
4058             mWindowManager.onDisplayChanged(displayId);
4059         }
4060     }
4061
4062     private StackInfo getStackInfoLocked(ActivityStack stack) {
4063         final int displayId = stack.mDisplayId;
4064         final ActivityDisplay display = mActivityDisplays.get(displayId);
4065         StackInfo info = new StackInfo();
4066         stack.getWindowContainerBounds(info.bounds);
4067         info.displayId = displayId;
4068         info.stackId = stack.mStackId;
4069         info.userId = stack.mCurrentUser;
4070         info.visible = stack.shouldBeVisible(null) == STACK_VISIBLE;
4071         // A stack might be not attached to a display.
4072         info.position = display != null
4073                 ? display.mStacks.indexOf(stack)
4074                 : 0;
4075
4076         ArrayList<TaskRecord> tasks = stack.getAllTasks();
4077         final int numTasks = tasks.size();
4078         int[] taskIds = new int[numTasks];
4079         String[] taskNames = new String[numTasks];
4080         Rect[] taskBounds = new Rect[numTasks];
4081         int[] taskUserIds = new int[numTasks];
4082         for (int i = 0; i < numTasks; ++i) {
4083             final TaskRecord task = tasks.get(i);
4084             taskIds[i] = task.taskId;
4085             taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
4086                     : task.realActivity != null ? task.realActivity.flattenToString()
4087                     : task.getTopActivity() != null ? task.getTopActivity().packageName
4088                     : "unknown";
4089             taskBounds[i] = new Rect();
4090             task.getWindowContainerBounds(taskBounds[i]);
4091             taskUserIds[i] = task.userId;
4092         }
4093         info.taskIds = taskIds;
4094         info.taskNames = taskNames;
4095         info.taskBounds = taskBounds;
4096         info.taskUserIds = taskUserIds;
4097
4098         final ActivityRecord top = stack.topRunningActivityLocked();
4099         info.topActivity = top != null ? top.intent.getComponent() : null;
4100         return info;
4101     }
4102
4103     StackInfo getStackInfoLocked(int stackId) {
4104         ActivityStack stack = getStack(stackId);
4105         if (stack != null) {
4106             return getStackInfoLocked(stack);
4107         }
4108         return null;
4109     }
4110
4111     ArrayList<StackInfo> getAllStackInfosLocked() {
4112         ArrayList<StackInfo> list = new ArrayList<>();
4113         for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
4114             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
4115             for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
4116                 list.add(getStackInfoLocked(stacks.get(ndx)));
4117             }
4118         }
4119         return list;
4120     }
4121
4122     TaskRecord getLockedTaskLocked() {
4123         final int top = mLockTaskModeTasks.size() - 1;
4124         if (top >= 0) {
4125             return mLockTaskModeTasks.get(top);
4126         }
4127         return null;
4128     }
4129
4130     boolean isLockedTask(TaskRecord task) {
4131         return mLockTaskModeTasks.contains(task);
4132     }
4133
4134     boolean isLastLockedTask(TaskRecord task) {
4135         return mLockTaskModeTasks.size() == 1 && mLockTaskModeTasks.contains(task);
4136     }
4137
4138     void removeLockedTaskLocked(final TaskRecord task) {
4139         if (!mLockTaskModeTasks.remove(task)) {
4140             return;
4141         }
4142         if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "removeLockedTaskLocked: removed " + task);
4143         if (mLockTaskModeTasks.isEmpty()) {
4144             // Last one.
4145             if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
4146                     " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
4147             final Message lockTaskMsg = Message.obtain();
4148             lockTaskMsg.arg1 = task.userId;
4149             lockTaskMsg.what = LOCK_TASK_END_MSG;
4150             mHandler.sendMessage(lockTaskMsg);
4151         }
4152     }
4153
4154     void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4155             int preferredDisplayId, int actualStackId) {
4156         handleNonResizableTaskIfNeeded(task, preferredStackId, preferredDisplayId, actualStackId,
4157                 false /* forceNonResizable */);
4158     }
4159
4160     private void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4161             int preferredDisplayId, int actualStackId, boolean forceNonResizable) {
4162         final boolean isSecondaryDisplayPreferred =
4163                 (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY)
4164                 || StackId.isDynamicStack(preferredStackId);
4165         if (((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
4166                 && !isSecondaryDisplayPreferred) || task.isHomeTask()) {
4167             return;
4168         }
4169
4170         // Handle incorrect launch/move to secondary display if needed.
4171         final boolean launchOnSecondaryDisplayFailed;
4172         if (isSecondaryDisplayPreferred) {
4173             final int actualDisplayId = task.getStack().mDisplayId;
4174             if (!task.canBeLaunchedOnDisplay(actualDisplayId)) {
4175                 // The task landed on an inappropriate display somehow, move it to the default
4176                 // display.
4177                 // TODO(multi-display): Find proper stack for the task on the default display.
4178                 mService.moveTaskToStack(task.taskId, FULLSCREEN_WORKSPACE_STACK_ID,
4179                         true /* toTop */);
4180                 launchOnSecondaryDisplayFailed = true;
4181             } else {
4182                 // The task might have landed on a display different from requested.
4183                 launchOnSecondaryDisplayFailed = actualDisplayId == DEFAULT_DISPLAY
4184                         || (preferredDisplayId != INVALID_DISPLAY
4185                             && preferredDisplayId != actualDisplayId);
4186             }
4187         } else {
4188             // The task wasn't requested to be on a secondary display.
4189             launchOnSecondaryDisplayFailed = false;
4190         }
4191
4192         final ActivityRecord topActivity = task.getTopActivity();
4193         if (launchOnSecondaryDisplayFailed || !task.supportsSplitScreen() || forceNonResizable) {
4194             if (launchOnSecondaryDisplayFailed) {
4195                 // Display a warning toast that we tried to put a non-resizeable task on a secondary
4196                 // display with config different from global config.
4197                 mService.mTaskChangeNotificationController
4198                         .notifyActivityLaunchOnSecondaryDisplayFailed();
4199             } else {
4200                 // Display a warning toast that we tried to put a non-dockable task in the docked
4201                 // stack.
4202                 mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
4203             }
4204
4205             // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
4206             // we need to move it to top of fullscreen stack, otherwise it will be covered.
4207             moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
4208         } else if (topActivity != null && topActivity.isNonResizableOrForcedResizable()
4209                 && !topActivity.noDisplay) {
4210             final String packageName = topActivity.appInfo.packageName;
4211             final int reason = isSecondaryDisplayPreferred
4212                     ? FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY
4213                     : FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
4214             mService.mTaskChangeNotificationController.notifyActivityForcedResizable(
4215                     task.taskId, reason, packageName);
4216         }
4217     }
4218
4219     void showLockTaskToast() {
4220         if (mLockTaskNotify != null) {
4221             mLockTaskNotify.showToast(mLockTaskModeState);
4222         }
4223     }
4224
4225     void showLockTaskEscapeMessageLocked(TaskRecord task) {
4226         if (mLockTaskModeTasks.contains(task)) {
4227             mHandler.sendEmptyMessage(SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG);
4228         }
4229     }
4230
4231     void setLockTaskModeLocked(TaskRecord task, int lockTaskModeState, String reason,
4232             boolean andResume) {
4233         if (task == null) {
4234             // Take out of lock task mode if necessary
4235             final TaskRecord lockedTask = getLockedTaskLocked();
4236             if (lockedTask != null) {
4237                 removeLockedTaskLocked(lockedTask);
4238                 if (!mLockTaskModeTasks.isEmpty()) {
4239                     // There are locked tasks remaining, can only finish this task, not unlock it.
4240                     if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4241                             "setLockTaskModeLocked: Tasks remaining, can't unlock");
4242                     lockedTask.performClearTaskLocked();
4243                     resumeFocusedStackTopActivityLocked();
4244                     return;
4245                 }
4246             }
4247             if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4248                     "setLockTaskModeLocked: No tasks to unlock. Callers=" + Debug.getCallers(4));
4249             return;
4250         }
4251
4252         // Should have already been checked, but do it again.
4253         if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
4254             if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4255                     "setLockTaskModeLocked: Can't lock due to auth");
4256             return;
4257         }
4258         if (isLockTaskModeViolation(task)) {
4259             Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
4260             return;
4261         }
4262
4263         if (mLockTaskModeTasks.isEmpty()) {
4264             // First locktask.
4265             final Message lockTaskMsg = Message.obtain();
4266             lockTaskMsg.obj = task.intent.getComponent().getPackageName();
4267             lockTaskMsg.arg1 = task.userId;
4268             lockTaskMsg.what = LOCK_TASK_START_MSG;
4269             lockTaskMsg.arg2 = lockTaskModeState;
4270             mHandler.sendMessage(lockTaskMsg);
4271         }
4272         // Add it or move it to the top.
4273         if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskModeLocked: Locking to " + task +
4274                 " Callers=" + Debug.getCallers(4));
4275         mLockTaskModeTasks.remove(task);
4276         mLockTaskModeTasks.add(task);
4277
4278         if (task.mLockTaskUid == -1) {
4279             task.mLockTaskUid = task.effectiveUid;
4280         }
4281
4282         if (andResume) {
4283             findTaskToMoveToFrontLocked(task, 0, null, reason,
4284                     lockTaskModeState != LOCK_TASK_MODE_NONE);
4285             resumeFocusedStackTopActivityLocked();
4286             mWindowManager.executeAppTransition();
4287         } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
4288             handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
4289                     task.getStackId(), true /* forceNonResizable */);
4290         }
4291     }
4292
4293     boolean isLockTaskModeViolation(TaskRecord task) {
4294         return isLockTaskModeViolation(task, false);
4295     }
4296
4297     boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) {
4298         if (getLockedTaskLocked() == task && !isNewClearTask) {
4299             return false;
4300         }
4301         final int lockTaskAuth = task.mLockTaskAuth;
4302         switch (lockTaskAuth) {
4303             case LOCK_TASK_AUTH_DONT_LOCK:
4304                 return !mLockTaskModeTasks.isEmpty();
4305             case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
4306             case LOCK_TASK_AUTH_LAUNCHABLE:
4307             case LOCK_TASK_AUTH_WHITELISTED:
4308                 return false;
4309             case LOCK_TASK_AUTH_PINNABLE:
4310                 // Pinnable tasks can't be launched on top of locktask tasks.
4311                 return !mLockTaskModeTasks.isEmpty();
4312             default:
4313                 Slog.w(TAG, "isLockTaskModeViolation: invalid lockTaskAuth value=" + lockTaskAuth);
4314                 return true;
4315         }
4316     }
4317
4318     void onLockTaskPackagesUpdatedLocked() {
4319         boolean didSomething = false;
4320         for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
4321             final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx);
4322             final boolean wasWhitelisted =
4323                     (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4324                     (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
4325             lockedTask.setLockTaskAuth();
4326             final boolean isWhitelisted =
4327                     (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4328                     (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
4329             if (wasWhitelisted && !isWhitelisted) {
4330                 // Lost whitelisting authorization. End it now.
4331                 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "onLockTaskPackagesUpdated: removing " +
4332                         lockedTask + " mLockTaskAuth=" + lockedTask.lockTaskAuthToString());
4333                 removeLockedTaskLocked(lockedTask);
4334                 lockedTask.performClearTaskLocked();
4335                 didSomething = true;
4336             }
4337         }
4338         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
4339             ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
4340             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
4341                 final ActivityStack stack = stacks.get(stackNdx);
4342                 stack.onLockTaskPackagesUpdatedLocked();
4343             }
4344         }
4345         final ActivityRecord r = topRunningActivityLocked();
4346         final TaskRecord task = r != null ? r.getTask() : null;
4347         if (mLockTaskModeTasks.isEmpty() && task != null
4348                 && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
4349             // This task must have just been authorized.
4350             if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK,
4351                     "onLockTaskPackagesUpdated: starting new locktask task=" + task);
4352             setLockTaskModeLocked(task, ActivityManager.LOCK_TASK_MODE_LOCKED, "package updated",
4353                     false);
4354             didSomething = true;
4355         }
4356         if (didSomething) {
4357             resumeFocusedStackTopActivityLocked();
4358         }
4359     }
4360
4361     int getLockTaskModeState() {
4362         return mLockTaskModeState;
4363     }
4364
4365     void activityRelaunchedLocked(IBinder token) {
4366         mWindowManager.notifyAppRelaunchingFinished(token);
4367         if (mService.isSleepingOrShuttingDownLocked()) {
4368             final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4369             if (r != null) {
4370                 r.setSleeping(true, true);
4371             }
4372         }
4373     }
4374
4375     void activityRelaunchingLocked(ActivityRecord r) {
4376         mWindowManager.notifyAppRelaunching(r.appToken);
4377     }
4378
4379     void logStackState() {
4380         mActivityMetricsLogger.logWindowState();
4381     }
4382
4383     void scheduleUpdateMultiWindowMode(TaskRecord task) {
4384         // If the stack is animating in a way where we will be forcing a multi-mode change at the
4385         // end, then ensure that we defer all in between multi-window mode changes
4386         if (task.getStack().deferScheduleMultiWindowModeChanged()) {
4387             return;
4388         }
4389
4390         for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4391             final ActivityRecord r = task.mActivities.get(i);
4392             if (r.app != null && r.app.thread != null) {
4393                 mMultiWindowModeChangedActivities.add(r);
4394             }
4395         }
4396
4397         if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
4398             mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
4399         }
4400     }
4401
4402     void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) {
4403         final ActivityStack stack = task.getStack();
4404         if (prevStack == null || prevStack == stack
4405                 || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
4406             return;
4407         }
4408
4409         scheduleUpdatePictureInPictureModeIfNeeded(task, stack.mBounds, false /* immediate */);
4410     }
4411
4412     void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds,
4413             boolean immediate) {
4414
4415         if (immediate) {
4416             mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG);
4417             for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4418                 final ActivityRecord r = task.mActivities.get(i);
4419                 if (r.app != null && r.app.thread != null) {
4420                     r.updatePictureInPictureMode(targetStackBounds);
4421                 }
4422             }
4423         } else {
4424             for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4425                 final ActivityRecord r = task.mActivities.get(i);
4426                 if (r.app != null && r.app.thread != null) {
4427                     mPipModeChangedActivities.add(r);
4428                 }
4429             }
4430             mPipModeChangedTargetStackBounds = targetStackBounds;
4431
4432             if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
4433                 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
4434             }
4435         }
4436     }
4437
4438     void setDockedStackMinimized(boolean minimized) {
4439         mIsDockMinimized = minimized;
4440     }
4441
4442     private final class ActivityStackSupervisorHandler extends Handler {
4443
4444         public ActivityStackSupervisorHandler(Looper looper) {
4445             super(looper);
4446         }
4447
4448         void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) {
4449             synchronized (mService) {
4450                 activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */,
4451                         processPausingActivities, null);
4452             }
4453         }
4454
4455         @Override
4456         public void handleMessage(Message msg) {
4457             switch (msg.what) {
4458                 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
4459                     synchronized (mService) {
4460                         for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
4461                             final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
4462                             r.updateMultiWindowMode();
4463                         }
4464                     }
4465                 } break;
4466                 case REPORT_PIP_MODE_CHANGED_MSG: {
4467                     synchronized (mService) {
4468                         for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
4469                             final ActivityRecord r = mPipModeChangedActivities.remove(i);
4470                             r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds);
4471                         }
4472                     }
4473                 } break;
4474                 case IDLE_TIMEOUT_MSG: {
4475                     if (DEBUG_IDLE) Slog.d(TAG_IDLE,
4476                             "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
4477                     // We don't at this point know if the activity is fullscreen,
4478                     // so we need to be conservative and assume it isn't.
4479                     activityIdleInternal((ActivityRecord) msg.obj,
4480                             true /* processPausingActivities */);
4481                 } break;
4482                 case IDLE_NOW_MSG: {
4483                     if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
4484                     activityIdleInternal((ActivityRecord) msg.obj,
4485                             false /* processPausingActivities */);
4486                 } break;
4487                 case RESUME_TOP_ACTIVITY_MSG: {
4488                     synchronized (mService) {
4489                         resumeFocusedStackTopActivityLocked();
4490                     }
4491                 } break;
4492                 case SLEEP_TIMEOUT_MSG: {
4493                     synchronized (mService) {
4494                         if (mService.isSleepingOrShuttingDownLocked()) {
4495                             Slog.w(TAG, "Sleep timeout!  Sleeping now.");
4496                             mSleepTimeout = true;
4497                             checkReadyForSleepLocked();
4498                         }
4499                     }
4500                 } break;
4501                 case LAUNCH_TIMEOUT_MSG: {
4502                     synchronized (mService) {
4503                         if (mLaunchingActivity.isHeld()) {
4504                             Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
4505                             if (VALIDATE_WAKE_LOCK_CALLER
4506                                     && Binder.getCallingUid() != Process.myUid()) {
4507                                 throw new IllegalStateException("Calling must be system uid");
4508                             }
4509                             mLaunchingActivity.release();
4510                         }
4511                     }
4512                 } break;
4513                 case HANDLE_DISPLAY_ADDED: {
4514                     handleDisplayAdded(msg.arg1);
4515                 } break;
4516                 case HANDLE_DISPLAY_CHANGED: {
4517                     handleDisplayChanged(msg.arg1);
4518                 } break;
4519                 case HANDLE_DISPLAY_REMOVED: {
4520                     handleDisplayRemoved(msg.arg1);
4521                 } break;
4522                 case CONTAINER_CALLBACK_VISIBILITY: {
4523                     final ActivityContainer container = (ActivityContainer) msg.obj;
4524                     final IActivityContainerCallback callback = container.mCallback;
4525                     if (callback != null) {
4526                         try {
4527                             callback.setVisible(container.asBinder(), msg.arg1 == 1);
4528                         } catch (RemoteException e) {
4529                         }
4530                     }
4531                 } break;
4532                 case LOCK_TASK_START_MSG: {
4533                     // When lock task starts, we disable the status bars.
4534                     try {
4535                         if (mLockTaskNotify == null) {
4536                             mLockTaskNotify = new LockTaskNotify(mService.mContext);
4537                         }
4538                         mLockTaskNotify.show(true);
4539                         mLockTaskModeState = msg.arg2;
4540                         if (getStatusBarService() != null) {
4541                             int flags = 0;
4542                             if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
4543                                 flags = StatusBarManager.DISABLE_MASK
4544                                         & (~StatusBarManager.DISABLE_BACK);
4545                             } else if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
4546                                 flags = StatusBarManager.DISABLE_MASK
4547                                         & (~StatusBarManager.DISABLE_BACK)
4548                                         & (~StatusBarManager.DISABLE_HOME)
4549                                         & (~StatusBarManager.DISABLE_RECENT);
4550                             }
4551                             getStatusBarService().disable(flags, mToken,
4552                                     mService.mContext.getPackageName());
4553                         }
4554                         mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
4555                         if (getDevicePolicyManager() != null) {
4556                             getDevicePolicyManager().notifyLockTaskModeChanged(true,
4557                                     (String)msg.obj, msg.arg1);
4558                         }
4559                     } catch (RemoteException ex) {
4560                         throw new RuntimeException(ex);
4561                     }
4562                 } break;
4563                 case LOCK_TASK_END_MSG: {
4564                     // When lock task ends, we enable the status bars.
4565                     try {
4566                         if (getStatusBarService() != null) {
4567                             getStatusBarService().disable(StatusBarManager.DISABLE_NONE, mToken,
4568                                     mService.mContext.getPackageName());
4569                         }
4570                         mWindowManager.reenableKeyguard(mToken);
4571                         if (getDevicePolicyManager() != null) {
4572                             getDevicePolicyManager().notifyLockTaskModeChanged(false, null,
4573                                     msg.arg1);
4574                         }
4575                         if (mLockTaskNotify == null) {
4576                             mLockTaskNotify = new LockTaskNotify(mService.mContext);
4577                         }
4578                         mLockTaskNotify.show(false);
4579                         try {
4580                             boolean shouldLockKeyguard = Settings.Secure.getInt(
4581                                     mService.mContext.getContentResolver(),
4582                                     Settings.Secure.LOCK_TO_APP_EXIT_LOCKED) != 0;
4583                             if (mLockTaskModeState == LOCK_TASK_MODE_PINNED && shouldLockKeyguard) {
4584                                 mWindowManager.lockNow(null);
4585                                 mWindowManager.dismissKeyguard(null /* callback */);
4586                                 new LockPatternUtils(mService.mContext)
4587                                         .requireCredentialEntry(UserHandle.USER_ALL);
4588                             }
4589                         } catch (SettingNotFoundException e) {
4590                             // No setting, don't lock.
4591                         }
4592                     } catch (RemoteException ex) {
4593                         throw new RuntimeException(ex);
4594                     } finally {
4595                         mLockTaskModeState = LOCK_TASK_MODE_NONE;
4596                     }
4597                 } break;
4598                 case SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG: {
4599                     if (mLockTaskNotify == null) {
4600                         mLockTaskNotify = new LockTaskNotify(mService.mContext);
4601                     }
4602                     mLockTaskNotify.showToast(LOCK_TASK_MODE_PINNED);
4603                 } break;
4604                 case CONTAINER_CALLBACK_TASK_LIST_EMPTY: {
4605                     final ActivityContainer container = (ActivityContainer) msg.obj;
4606                     final IActivityContainerCallback callback = container.mCallback;
4607                     if (callback != null) {
4608                         try {
4609                             callback.onAllActivitiesComplete(container.asBinder());
4610                         } catch (RemoteException e) {
4611                         }
4612                     }
4613                 } break;
4614                 case LAUNCH_TASK_BEHIND_COMPLETE: {
4615                     synchronized (mService) {
4616                         ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
4617                         if (r != null) {
4618                             handleLaunchTaskBehindCompleteLocked(r);
4619                         }
4620                     }
4621                 } break;
4622
4623             }
4624         }
4625     }
4626
4627     class ActivityContainer extends android.app.IActivityContainer.Stub {
4628         final static int FORCE_NEW_TASK_FLAGS = FLAG_ACTIVITY_NEW_TASK |
4629                 FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION;
4630         final int mStackId;
4631         IActivityContainerCallback mCallback = null;
4632         ActivityStack mStack;
4633         ActivityRecord mParentActivity = null;
4634         String mIdString;
4635
4636         boolean mVisible = true;
4637
4638         /** Display this ActivityStack is currently on. Null if not attached to a Display. */
4639         ActivityDisplay mActivityDisplay;
4640
4641         final static int CONTAINER_STATE_HAS_SURFACE = 0;
4642         final static int CONTAINER_STATE_NO_SURFACE = 1;
4643         final static int CONTAINER_STATE_FINISHING = 2;
4644         int mContainerState = CONTAINER_STATE_HAS_SURFACE;
4645
4646         ActivityContainer(int stackId, ActivityDisplay activityDisplay, boolean onTop) {
4647             synchronized (mService) {
4648                 mStackId = stackId;
4649                 mActivityDisplay = activityDisplay;
4650                 mIdString = "ActivtyContainer{" + mStackId + "}";
4651
4652                 createStack(stackId, onTop);
4653                 if (DEBUG_STACK) Slog.d(TAG_STACK, "Creating " + this);
4654             }
4655         }
4656
4657         protected void createStack(int stackId, boolean onTop) {
4658             switch (stackId) {
4659                 case PINNED_STACK_ID:
4660                     new PinnedActivityStack(this, mRecentTasks, onTop);
4661                     break;
4662                 default:
4663                     new ActivityStack(this, mRecentTasks, onTop);
4664                     break;
4665             }
4666         }
4667
4668         /**
4669          * Adds the stack to specified display. Also calls WindowManager to do the same from
4670          * {@link ActivityStack#reparent(ActivityDisplay, boolean)}.
4671          * @param activityDisplay The display to add the stack to.
4672          */
4673         void addToDisplayLocked(ActivityDisplay activityDisplay) {
4674             if (DEBUG_STACK) Slog.d(TAG_STACK, "addToDisplayLocked: " + this
4675                     + " to display=" + activityDisplay);
4676             if (mActivityDisplay != null) {
4677                 throw new IllegalStateException("ActivityContainer is already attached, " +
4678                         "displayId=" + mActivityDisplay.mDisplayId);
4679             }
4680             mActivityDisplay = activityDisplay;
4681             mStack.reparent(activityDisplay, true /* onTop */);
4682         }
4683
4684         @Override
4685         public void addToDisplay(int displayId) {
4686             synchronized (mService) {
4687                 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
4688                 if (activityDisplay == null) {
4689                     return;
4690                 }
4691                 addToDisplayLocked(activityDisplay);
4692             }
4693         }
4694
4695         @Override
4696         public int getDisplayId() {
4697             synchronized (mService) {
4698                 if (mActivityDisplay != null) {
4699                     return mActivityDisplay.mDisplayId;
4700                 }
4701             }
4702             return -1;
4703         }
4704
4705         @Override
4706         public int getStackId() {
4707             synchronized (mService) {
4708                 return mStackId;
4709             }
4710         }
4711
4712         @Override
4713         public boolean injectEvent(InputEvent event) {
4714             final long origId = Binder.clearCallingIdentity();
4715             try {
4716                 synchronized (mService) {
4717                     if (mActivityDisplay != null) {
4718                         return mInputManagerInternal.injectInputEvent(event,
4719                                 mActivityDisplay.mDisplayId,
4720                                 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
4721                     }
4722                 }
4723                 return false;
4724             } finally {
4725                 Binder.restoreCallingIdentity(origId);
4726             }
4727         }
4728
4729         @Override
4730         public void release() {
4731             synchronized (mService) {
4732                 if (mContainerState == CONTAINER_STATE_FINISHING) {
4733                     return;
4734                 }
4735                 mContainerState = CONTAINER_STATE_FINISHING;
4736
4737                 long origId = Binder.clearCallingIdentity();
4738                 try {
4739                     mStack.finishAllActivitiesLocked(false);
4740                     mService.mActivityStarter.removePendingActivityLaunchesLocked(mStack);
4741                 } finally {
4742                     Binder.restoreCallingIdentity(origId);
4743                 }
4744             }
4745         }
4746
4747         /**
4748          * Remove the stack completely. Must be called only when there are no tasks left in it,
4749          * as this method does not finish running activities.
4750          */
4751         void removeLocked() {
4752             if (DEBUG_STACK) Slog.d(TAG_STACK, "removeLocked: " + this + " from display="
4753                     + mActivityDisplay + " Callers=" + Debug.getCallers(2));
4754             if (mActivityDisplay != null) {
4755                 removeFromDisplayLocked();
4756             }
4757             mStack.remove();
4758         }
4759
4760         /**
4761          * Remove the stack from its current {@link ActivityDisplay}, so it can be either destroyed
4762          * completely or re-parented.
4763          */
4764         private void removeFromDisplayLocked() {
4765             if (DEBUG_STACK) Slog.d(TAG_STACK, "removeFromDisplayLocked: " + this
4766                     + " current displayId=" + mActivityDisplay.mDisplayId);
4767
4768             mActivityDisplay.detachStack(mStack);
4769             mActivityDisplay = null;
4770         }
4771
4772         /**
4773          * Move the stack to specified display.
4774          * @param activityDisplay Target display to move the stack to.
4775          * @param onTop Indicates whether container should be place on top or on bottom.
4776          */
4777         void moveToDisplayLocked(ActivityDisplay activityDisplay, boolean onTop) {
4778             if (DEBUG_STACK) Slog.d(TAG_STACK, "moveToDisplayLocked: " + this + " from display="
4779                     + mActivityDisplay + " to display=" + activityDisplay
4780                     + " Callers=" + Debug.getCallers(2));
4781
4782             removeFromDisplayLocked();
4783
4784             mActivityDisplay = activityDisplay;
4785             mStack.reparent(activityDisplay, onTop);
4786         }
4787
4788         @Override
4789         public final int startActivity(Intent intent) {
4790             return mService.startActivity(intent, this);
4791         }
4792
4793         @Override
4794         public final int startActivityIntentSender(IIntentSender intentSender)
4795                 throws TransactionTooLargeException {
4796             mService.enforceNotIsolatedCaller("ActivityContainer.startActivityIntentSender");
4797
4798             if (!(intentSender instanceof PendingIntentRecord)) {
4799                 throw new IllegalArgumentException("Bad PendingIntent object");
4800             }
4801
4802             final int userId = mService.mUserController.handleIncomingUser(Binder.getCallingPid(),
4803                     Binder.getCallingUid(), mCurrentUser, false,
4804                     ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null);
4805
4806             final PendingIntentRecord pendingIntent = (PendingIntentRecord) intentSender;
4807             checkEmbeddedAllowedInner(userId, pendingIntent.key.requestIntent,
4808                     pendingIntent.key.requestResolvedType);
4809
4810             return pendingIntent.sendInner(0, null, null, null, null, null, null, null, 0,
4811                     FORCE_NEW_TASK_FLAGS, FORCE_NEW_TASK_FLAGS, null, this);
4812         }
4813
4814         void checkEmbeddedAllowedInner(int userId, Intent intent, String resolvedType) {
4815             ActivityInfo aInfo = resolveActivity(intent, resolvedType, 0, null, userId);
4816             if (aInfo != null && (aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
4817                 throw new SecurityException(
4818                         "Attempt to embed activity that has not set allowEmbedded=\"true\"");
4819             }
4820         }
4821
4822         @Override
4823         public IBinder asBinder() {
4824             return this;
4825         }
4826
4827         @Override
4828         public void setSurface(Surface surface, int width, int height, int density) {
4829             mService.enforceNotIsolatedCaller("ActivityContainer.attachToSurface");
4830         }
4831
4832         ActivityStackSupervisor getOuter() {
4833             return ActivityStackSupervisor.this;
4834         }
4835
4836         boolean isAttachedLocked() {
4837             return mActivityDisplay != null;
4838         }
4839
4840         // TODO: Make sure every change to ActivityRecord.visible results in a call to this.
4841         void setVisible(boolean visible) {
4842             if (mVisible != visible) {
4843                 mVisible = visible;
4844                 if (mCallback != null) {
4845                     mHandler.obtainMessage(CONTAINER_CALLBACK_VISIBILITY, visible ? 1 : 0,
4846                             0 /* unused */, this).sendToTarget();
4847                 }
4848             }
4849         }
4850
4851         void setDrawn() {
4852         }
4853
4854         // You can always start a new task on a regular ActivityStack.
4855         boolean isEligibleForNewTasks() {
4856             return true;
4857         }
4858
4859         void onTaskListEmptyLocked() {
4860             removeLocked();
4861             mHandler.obtainMessage(CONTAINER_CALLBACK_TASK_LIST_EMPTY, this).sendToTarget();
4862         }
4863
4864         @Override
4865         public String toString() {
4866             return mIdString + (mActivityDisplay == null ? "N" : "A");
4867         }
4868     }
4869
4870     private class VirtualActivityContainer extends ActivityContainer {
4871         Surface mSurface;
4872         boolean mDrawn = false;
4873
4874         VirtualActivityContainer(ActivityRecord parent, IActivityContainerCallback callback) {
4875             super(getNextStackId(), parent.getStack().mActivityContainer.mActivityDisplay,
4876                     true /* onTop */);
4877             mParentActivity = parent;
4878             mCallback = callback;
4879             mContainerState = CONTAINER_STATE_NO_SURFACE;
4880             mIdString = "VirtualActivityContainer{" + mStackId + ", parent=" + mParentActivity + "}";
4881         }
4882
4883         @Override
4884         public void setSurface(Surface surface, int width, int height, int density) {
4885             super.setSurface(surface, width, height, density);
4886
4887             synchronized (mService) {
4888                 final long origId = Binder.clearCallingIdentity();
4889                 try {
4890                     setSurfaceLocked(surface, width, height, density);
4891                 } finally {
4892                     Binder.restoreCallingIdentity(origId);
4893                 }
4894             }
4895         }
4896
4897         private void setSurfaceLocked(Surface surface, int width, int height, int density) {
4898             if (mContainerState == CONTAINER_STATE_FINISHING) {
4899                 return;
4900             }
4901             VirtualActivityDisplay virtualActivityDisplay =
4902                     (VirtualActivityDisplay) mActivityDisplay;
4903             if (virtualActivityDisplay == null) {
4904                 virtualActivityDisplay =
4905                         new VirtualActivityDisplay(width, height, density);
4906                 mActivityDisplay = virtualActivityDisplay;
4907                 mActivityDisplays.put(virtualActivityDisplay.mDisplayId, virtualActivityDisplay);
4908                 addToDisplayLocked(virtualActivityDisplay);
4909             }
4910
4911             if (mSurface != null) {
4912                 mSurface.release();
4913             }
4914
4915             mSurface = surface;
4916             if (surface != null) {
4917                 resumeFocusedStackTopActivityLocked();
4918             } else {
4919                 mContainerState = CONTAINER_STATE_NO_SURFACE;
4920                 ((VirtualActivityDisplay) mActivityDisplay).setSurface(null);
4921                 if (mStack.mPausingActivity == null && mStack.mResumedActivity != null) {
4922                     mStack.startPausingLocked(false, true, null, false);
4923                 }
4924             }
4925
4926             setSurfaceIfReadyLocked();
4927
4928             if (DEBUG_STACK) Slog.d(TAG_STACK,
4929                     "setSurface: " + this + " to display=" + virtualActivityDisplay);
4930         }
4931
4932         @Override
4933         boolean isAttachedLocked() {
4934             return mSurface != null && super.isAttachedLocked();
4935         }
4936
4937         @Override
4938         void setDrawn() {
4939             synchronized (mService) {
4940                 mDrawn = true;
4941                 setSurfaceIfReadyLocked();
4942             }
4943         }
4944
4945         // Never start a new task on an ActivityView if it isn't explicitly specified.
4946         @Override
4947         boolean isEligibleForNewTasks() {
4948             return false;
4949         }
4950
4951         private void setSurfaceIfReadyLocked() {
4952             if (DEBUG_STACK) Slog.v(TAG_STACK, "setSurfaceIfReadyLocked: mDrawn=" + mDrawn +
4953                     " mContainerState=" + mContainerState + " mSurface=" + mSurface);
4954             if (mDrawn && mSurface != null && mContainerState == CONTAINER_STATE_NO_SURFACE) {
4955                 ((VirtualActivityDisplay) mActivityDisplay).setSurface(mSurface);
4956                 mContainerState = CONTAINER_STATE_HAS_SURFACE;
4957             }
4958         }
4959     }
4960
4961     /** Exactly one of these classes per Display in the system. Capable of holding zero or more
4962      * attached {@link ActivityStack}s */
4963     class ActivityDisplay extends ConfigurationContainer {
4964         /** Actual Display this object tracks. */
4965         int mDisplayId;
4966         Display mDisplay;
4967
4968         /** All of the stacks on this display. Order matters, topmost stack is in front of all other
4969          * stacks, bottommost behind. Accessed directly by ActivityManager package classes */
4970         final ArrayList<ActivityStack> mStacks = new ArrayList<>();
4971
4972         ActivityRecord mVisibleBehindActivity;
4973
4974         /** Array of all UIDs that are present on the display. */
4975         private IntArray mDisplayAccessUIDs = new IntArray();
4976
4977         ActivityDisplay() {
4978         }
4979
4980         // After instantiation, check that mDisplay is not null before using this. The alternative
4981         // is for this to throw an exception if mDisplayManager.getDisplay() returns null.
4982         ActivityDisplay(int displayId) {
4983             final Display display = mDisplayManager.getDisplay(displayId);
4984             if (display == null) {
4985                 return;
4986             }
4987             init(display);
4988         }
4989
4990         void init(Display display) {
4991             mDisplay = display;
4992             mDisplayId = display.getDisplayId();
4993         }
4994
4995         void attachStack(ActivityStack stack, int position) {
4996             if (DEBUG_STACK) Slog.v(TAG_STACK, "attachStack: attaching " + stack
4997                     + " to displayId=" + mDisplayId + " position=" + position);
4998             mStacks.add(position, stack);
4999         }
5000
5001         void detachStack(ActivityStack stack) {
5002             if (DEBUG_STACK) Slog.v(TAG_STACK, "detachStack: detaching " + stack
5003                     + " from displayId=" + mDisplayId);
5004             mStacks.remove(stack);
5005         }
5006
5007         void setVisibleBehindActivity(ActivityRecord r) {
5008             mVisibleBehindActivity = r;
5009         }
5010
5011         boolean hasVisibleBehindActivity() {
5012             return mVisibleBehindActivity != null;
5013         }
5014
5015         @Override
5016         public String toString() {
5017             return "ActivityDisplay={" + mDisplayId + " numStacks=" + mStacks.size() + "}";
5018         }
5019
5020         @Override
5021         protected int getChildCount() {
5022             return mStacks.size();
5023         }
5024
5025         @Override
5026         protected ConfigurationContainer getChildAt(int index) {
5027             return mStacks.get(index);
5028         }
5029
5030         @Override
5031         protected ConfigurationContainer getParent() {
5032             return ActivityStackSupervisor.this;
5033         }
5034
5035         boolean isPrivate() {
5036             return (mDisplay.getFlags() & FLAG_PRIVATE) != 0;
5037         }
5038
5039         boolean isUidPresent(int uid) {
5040             for (ActivityStack stack : mStacks) {
5041                 if (stack.isUidPresent(uid)) {
5042                     return true;
5043                 }
5044             }
5045             return false;
5046         }
5047
5048         /** Update and get all UIDs that are present on the display and have access to it. */
5049         private IntArray getPresentUIDs() {
5050             mDisplayAccessUIDs.clear();
5051             for (ActivityStack stack : mStacks) {
5052                 stack.getPresentUIDs(mDisplayAccessUIDs);
5053             }
5054             return mDisplayAccessUIDs;
5055         }
5056
5057         boolean shouldDestroyContentOnRemove() {
5058             return mDisplay.getRemoveMode() == REMOVE_MODE_DESTROY_CONTENT;
5059         }
5060     }
5061
5062     class VirtualActivityDisplay extends ActivityDisplay {
5063         VirtualDisplay mVirtualDisplay;
5064
5065         VirtualActivityDisplay(int width, int height, int density) {
5066             DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
5067             mVirtualDisplay = dm.createVirtualDisplay(mService.mContext, null /* projection */,
5068                     VIRTUAL_DISPLAY_BASE_NAME, width, height, density, null /* surface */,
5069                     DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC |
5070                     DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY, null /* callback */,
5071                     null /* handler */, null /* uniqueId */);
5072
5073             init(mVirtualDisplay.getDisplay());
5074
5075             mWindowManager.onDisplayAdded(mDisplayId);
5076         }
5077
5078         void setSurface(Surface surface) {
5079             if (mVirtualDisplay != null) {
5080                 mVirtualDisplay.setSurface(surface);
5081             }
5082         }
5083
5084         @Override
5085         void detachStack(ActivityStack stack) {
5086             super.detachStack(stack);
5087             if (mVirtualDisplay != null) {
5088                 mVirtualDisplay.release();
5089                 mVirtualDisplay = null;
5090             }
5091         }
5092
5093         @Override
5094         public String toString() {
5095             return "VirtualActivityDisplay={" + mDisplayId + "}";
5096         }
5097     }
5098
5099     ActivityStack findStackBehind(ActivityStack stack) {
5100         // TODO(multi-display): We are only looking for stacks on the default display.
5101         final ActivityDisplay display = mActivityDisplays.get(DEFAULT_DISPLAY);
5102         if (display == null) {
5103             return null;
5104         }
5105         final ArrayList<ActivityStack> stacks = display.mStacks;
5106         for (int i = stacks.size() - 1; i >= 0; i--) {
5107             if (stacks.get(i) == stack && i > 0) {
5108                 return stacks.get(i - 1);
5109             }
5110         }
5111         throw new IllegalStateException("Failed to find a stack behind stack=" + stack
5112                 + " in=" + stacks);
5113     }
5114
5115     /**
5116      * Puts a task into resizing mode during the next app transition.
5117      *
5118      * @param task The task to put into resizing mode
5119      */
5120     private void setResizingDuringAnimation(TaskRecord task) {
5121         mResizingTasksDuringAnimation.add(task.taskId);
5122         task.setTaskDockedResizing(true);
5123     }
5124
5125     final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
5126         final TaskRecord task;
5127         final int callingUid;
5128         final String callingPackage;
5129         final Intent intent;
5130         final int userId;
5131         final ActivityOptions activityOptions = (bOptions != null)
5132                 ? new ActivityOptions(bOptions) : null;
5133         final int launchStackId = (activityOptions != null)
5134                 ? activityOptions.getLaunchStackId() : INVALID_STACK_ID;
5135         if (StackId.isHomeOrRecentsStack(launchStackId)) {
5136             throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
5137                     + taskId + " can't be launch in the home/recents stack.");
5138         }
5139
5140         mWindowManager.deferSurfaceLayout();
5141         try {
5142             if (launchStackId == DOCKED_STACK_ID) {
5143                 mWindowManager.setDockedStackCreateState(
5144                         activityOptions.getDockCreateMode(), null /* initialBounds */);
5145
5146                 // Defer updating the stack in which recents is until the app transition is done, to
5147                 // not run into issues where we still need to draw the task in recents but the
5148                 // docked stack is already created.
5149                 deferUpdateBounds(RECENTS_STACK_ID);
5150                 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
5151             }
5152
5153             task = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
5154                     launchStackId);
5155             if (task == null) {
5156                 continueUpdateBounds(RECENTS_STACK_ID);
5157                 mWindowManager.executeAppTransition();
5158                 throw new IllegalArgumentException(
5159                         "startActivityFromRecentsInner: Task " + taskId + " not found.");
5160             }
5161
5162             // Since we don't have an actual source record here, we assume that the currently
5163             // focused activity was the source.
5164             final ActivityStack focusedStack = getFocusedStack();
5165             final ActivityRecord sourceRecord =
5166                     focusedStack != null ? focusedStack.topActivity() : null;
5167
5168             if (launchStackId != INVALID_STACK_ID) {
5169                 if (task.getStackId() != launchStackId) {
5170                     task.reparent(launchStackId, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE,
5171                             DEFER_RESUME, "startActivityFromRecents");
5172                 }
5173             }
5174
5175             // If the user must confirm credentials (e.g. when first launching a work app and the
5176             // Work Challenge is present) let startActivityInPackage handle the intercepting.
5177             if (!mService.mUserController.shouldConfirmCredentials(task.userId)
5178                     && task.getRootActivity() != null) {
5179                 final ActivityRecord targetActivity = task.getTopActivity();
5180
5181                 mService.mActivityStarter.sendPowerHintForLaunchStartIfNeeded(true /* forceSend */,
5182                         targetActivity);
5183                 mActivityMetricsLogger.notifyActivityLaunching();
5184                 mService.moveTaskToFrontLocked(task.taskId, 0, bOptions, true /* fromRecents */);
5185                 mActivityMetricsLogger.notifyActivityLaunched(ActivityManager.START_TASK_TO_FRONT,
5186                         targetActivity);
5187
5188                 // If we are launching the task in the docked stack, put it into resizing mode so
5189                 // the window renders full-screen with the background filling the void. Also only
5190                 // call this at the end to make sure that tasks exists on the window manager side.
5191                 if (launchStackId == DOCKED_STACK_ID) {
5192                     setResizingDuringAnimation(task);
5193                 }
5194
5195                 mService.mActivityStarter.postStartActivityProcessing(task.getTopActivity(),
5196                         ActivityManager.START_TASK_TO_FRONT,
5197                         sourceRecord != null
5198                                 ? sourceRecord.getTask().getStackId() : INVALID_STACK_ID,
5199                         sourceRecord, task.getStack());
5200                 return ActivityManager.START_TASK_TO_FRONT;
5201             }
5202             callingUid = task.mCallingUid;
5203             callingPackage = task.mCallingPackage;
5204             intent = task.intent;
5205             intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
5206             userId = task.userId;
5207             int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
5208                     null, null, 0, 0, bOptions, userId, null, task, "startActivityFromRecents");
5209             if (launchStackId == DOCKED_STACK_ID) {
5210                 setResizingDuringAnimation(task);
5211             }
5212             return result;
5213         } finally {
5214             mWindowManager.continueSurfaceLayout();
5215         }
5216     }
5217
5218     /**
5219      * @return a list of activities which are the top ones in each visible stack. The first
5220      * entry will be the focused activity.
5221      */
5222     List<IBinder> getTopVisibleActivities() {
5223         final ArrayList<IBinder> topActivityTokens = new ArrayList<>();
5224         // Traverse all displays.
5225         for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
5226             final ActivityDisplay display = mActivityDisplays.valueAt(i);
5227             // Traverse all stacks on a display.
5228             for (int j = display.mStacks.size() - 1; j >= 0; j--) {
5229                 final ActivityStack stack = display.mStacks.get(j);
5230                 // Get top activity from a visible stack and add it to the list.
5231                 if (stack.shouldBeVisible(null /* starting */)
5232                         == ActivityStack.STACK_VISIBLE) {
5233                     final ActivityRecord top = stack.topActivity();
5234                     if (top != null) {
5235                         if (stack == mFocusedStack) {
5236                             topActivityTokens.add(0, top.appToken);
5237                         } else {
5238                             topActivityTokens.add(top.appToken);
5239                         }
5240                     }
5241                 }
5242             }
5243         }
5244         return topActivityTokens;
5245     }
5246
5247     /**
5248      * Internal container to store a match qualifier alongside a WaitResult.
5249      */
5250     static class WaitInfo {
5251         private final ComponentName mTargetComponent;
5252         private final WaitResult mResult;
5253
5254         public WaitInfo(ComponentName targetComponent, WaitResult result) {
5255             this.mTargetComponent = targetComponent;
5256             this.mResult = result;
5257         }
5258
5259         public boolean matches(ComponentName targetComponent) {
5260             return mTargetComponent == null || mTargetComponent.equals(targetComponent);
5261         }
5262
5263         public WaitResult getResult() {
5264             return mResult;
5265         }
5266
5267         public ComponentName getComponent() {
5268             return mTargetComponent;
5269         }
5270
5271         public void dump(PrintWriter pw, String prefix) {
5272             pw.println(prefix + "WaitInfo:");
5273             pw.println(prefix + "  mTargetComponent=" + mTargetComponent);
5274             pw.println(prefix + "  mResult=");
5275             mResult.dump(pw, prefix);
5276         }
5277     }
5278 }