ActivityStackSupervisor.java revision 853304c0b11921db142a3945ab66fae5f0cc7d8a
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
17package com.android.server.am;
18
19import android.Manifest;
20import android.annotation.UserIdInt;
21import android.app.Activity;
22import android.app.ActivityManager;
23import android.app.ActivityManager.RunningTaskInfo;
24import android.app.ActivityManager.StackId;
25import android.app.ActivityManager.StackInfo;
26import android.app.ActivityOptions;
27import android.app.AppGlobals;
28import android.app.AppOpsManager;
29import android.app.IActivityContainer;
30import android.app.IActivityContainerCallback;
31import android.app.IActivityManager;
32import android.app.IActivityManager.WaitResult;
33import android.app.KeyguardManager;
34import android.app.PendingIntent;
35import android.app.ProfilerInfo;
36import android.app.ResultInfo;
37import android.app.StatusBarManager;
38import android.app.admin.IDevicePolicyManager;
39import android.content.ComponentName;
40import android.content.Context;
41import android.content.IIntentSender;
42import android.content.Intent;
43import android.content.IntentSender;
44import android.content.pm.ActivityInfo;
45import android.content.pm.ApplicationInfo;
46import android.content.pm.PackageInfo;
47import android.content.pm.PackageManager;
48import android.content.pm.ResolveInfo;
49import android.content.pm.UserInfo;
50import android.content.res.Configuration;
51import android.graphics.Rect;
52import android.hardware.display.DisplayManager;
53import android.hardware.display.DisplayManager.DisplayListener;
54import android.hardware.display.DisplayManagerGlobal;
55import android.hardware.display.VirtualDisplay;
56import android.hardware.input.InputManager;
57import android.hardware.input.InputManagerInternal;
58import android.os.Binder;
59import android.os.Bundle;
60import android.os.Debug;
61import android.os.Handler;
62import android.os.IBinder;
63import android.os.Looper;
64import android.os.Message;
65import android.os.ParcelFileDescriptor;
66import android.os.PowerManager;
67import android.os.Process;
68import android.os.RemoteException;
69import android.os.ServiceManager;
70import android.os.SystemClock;
71import android.os.Trace;
72import android.os.TransactionTooLargeException;
73import android.os.UserHandle;
74import android.os.UserManager;
75import android.os.WorkSource;
76import android.provider.MediaStore;
77import android.provider.Settings;
78import android.provider.Settings.SettingNotFoundException;
79import android.service.voice.IVoiceInteractionSession;
80import android.util.ArrayMap;
81import android.util.ArraySet;
82import android.util.EventLog;
83import android.util.Slog;
84import android.util.SparseArray;
85import android.util.SparseIntArray;
86import android.view.Display;
87import android.view.DisplayInfo;
88import android.view.InputEvent;
89import android.view.Surface;
90
91import com.android.internal.content.ReferrerIntent;
92import com.android.internal.os.TransferPipe;
93import com.android.internal.statusbar.IStatusBarService;
94import com.android.internal.util.ArrayUtils;
95import com.android.internal.widget.LockPatternUtils;
96import com.android.server.LocalServices;
97import com.android.server.am.ActivityStack.ActivityState;
98import com.android.server.wm.WindowManagerService;
99
100import java.io.FileDescriptor;
101import java.io.IOException;
102import java.io.PrintWriter;
103import java.util.ArrayList;
104import java.util.Arrays;
105import java.util.Collections;
106import java.util.List;
107import java.util.Objects;
108import java.util.Set;
109
110import static android.Manifest.permission.START_ANY_ACTIVITY;
111import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
112import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
113import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
114import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
115import static android.app.ActivityManager.RESIZE_MODE_FORCED;
116import static android.app.ActivityManager.RESIZE_MODE_SYSTEM;
117import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
118import static android.app.ActivityManager.StackId.FIRST_DYNAMIC_STACK_ID;
119import static android.app.ActivityManager.StackId.FIRST_STATIC_STACK_ID;
120import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
121import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
122import static android.app.ActivityManager.StackId.HOME_STACK_ID;
123import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
124import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
125import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
126import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
127import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
128import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS;
129import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZEABLE;
130import static android.content.pm.PackageManager.PERMISSION_GRANTED;
131import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
132import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
133import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONTAINERS;
134import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
135import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKSCREEN;
136import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
137import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
138import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
139import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
140import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
141import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
142import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
143import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
144import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBLE_BEHIND;
145import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONTAINERS;
146import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IDLE;
147import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
148import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
149import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
150import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
151import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
152import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
153import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
154import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
155import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBLE_BEHIND;
156import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
157import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
158import static com.android.server.am.ActivityManagerService.ANIMATE;
159import static com.android.server.am.ActivityManagerService.FIRST_SUPERVISOR_STACK_MSG;
160import static com.android.server.am.ActivityManagerService.NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG;
161import static com.android.server.am.ActivityManagerService.NOTIFY_FORCED_RESIZABLE_MSG;
162import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
163import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
164import static com.android.server.am.ActivityRecord.RECENTS_ACTIVITY_TYPE;
165import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
166import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
167import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
168import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
169import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
170import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
171import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
172import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
173import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
174import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
175import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
176import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
177import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
178import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
179import static com.android.server.wm.AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS;
180
181public final class ActivityStackSupervisor implements DisplayListener {
182    private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_AM;
183    private static final String TAG_CONTAINERS = TAG + POSTFIX_CONTAINERS;
184    private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
185    private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
186    private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
187    private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
188    private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
189    private static final String TAG_STACK = TAG + POSTFIX_STACK;
190    private static final String TAG_STATES = TAG + POSTFIX_STATES;
191    private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
192    static final String TAG_TASKS = TAG + POSTFIX_TASKS;
193    private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND;
194
195    /** How long we wait until giving up on the last activity telling us it is idle. */
196    static final int IDLE_TIMEOUT = 10 * 1000;
197
198    /** How long we can hold the sleep wake lock before giving up. */
199    static final int SLEEP_TIMEOUT = 5 * 1000;
200
201    // How long we can hold the launch wake lock before giving up.
202    static final int LAUNCH_TIMEOUT = 10 * 1000;
203
204    static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
205    static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
206    static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
207    static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
208    static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
209    static final int HANDLE_DISPLAY_ADDED = FIRST_SUPERVISOR_STACK_MSG + 5;
210    static final int HANDLE_DISPLAY_CHANGED = FIRST_SUPERVISOR_STACK_MSG + 6;
211    static final int HANDLE_DISPLAY_REMOVED = FIRST_SUPERVISOR_STACK_MSG + 7;
212    static final int CONTAINER_CALLBACK_VISIBILITY = FIRST_SUPERVISOR_STACK_MSG + 8;
213    static final int LOCK_TASK_START_MSG = FIRST_SUPERVISOR_STACK_MSG + 9;
214    static final int LOCK_TASK_END_MSG = FIRST_SUPERVISOR_STACK_MSG + 10;
215    static final int CONTAINER_CALLBACK_TASK_LIST_EMPTY = FIRST_SUPERVISOR_STACK_MSG + 11;
216    static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
217    static final int SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG = FIRST_SUPERVISOR_STACK_MSG + 13;
218    static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
219    static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
220
221    private static final String VIRTUAL_DISPLAY_BASE_NAME = "ActivityViewVirtualDisplay";
222
223    private static final String LOCK_TASK_TAG = "Lock-to-App";
224
225    // Used to indicate if an object (e.g. stack) that we are trying to get
226    // should be created if it doesn't exist already.
227    static final boolean CREATE_IF_NEEDED = true;
228
229    // Used to indicate that windows of activities should be preserved during the resize.
230    static final boolean PRESERVE_WINDOWS = true;
231
232    // Used to indicate if an object (e.g. task) should be moved/created
233    // at the top of its container (e.g. stack).
234    static final boolean ON_TOP = true;
235
236    // Used to indicate that an objects (e.g. task) removal from its container
237    // (e.g. stack) is due to it moving to another container.
238    static final boolean MOVING = true;
239
240    // Force the focus to change to the stack we are moving a task to..
241    static final boolean FORCE_FOCUS = true;
242
243    // Restore task from the saved recents if it can't be found in any live stack.
244    static final boolean RESTORE_FROM_RECENTS = true;
245
246    // Activity actions an app cannot start if it uses a permission which is not granted.
247    private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION =
248            new ArrayMap<>();
249
250    static {
251        ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE,
252                Manifest.permission.CAMERA);
253        ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE,
254                Manifest.permission.CAMERA);
255        ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL,
256                Manifest.permission.CALL_PHONE);
257    }
258
259    /** Action restriction: launching the activity is not restricted. */
260    private static final int ACTIVITY_RESTRICTION_NONE = 0;
261    /** Action restriction: launching the activity is restricted by a permission. */
262    private static final int ACTIVITY_RESTRICTION_PERMISSION = 1;
263    /** Action restriction: launching the activity is restricted by an app op. */
264    private static final int ACTIVITY_RESTRICTION_APPOP = 2;
265
266    // The height/width divide used when fitting a task within a bounds with method
267    // {@link #fitWithinBounds}.
268    // We always want the task to to be visible in the bounds without affecting its size when
269    // fitting. To make sure this is the case, we don't adjust the task left or top side pass
270    // the input bounds right or bottom side minus the width or height divided by this value.
271    private static final int FIT_WITHIN_BOUNDS_DIVIDER = 3;
272
273    /** Status Bar Service **/
274    private IBinder mToken = new Binder();
275    private IStatusBarService mStatusBarService;
276    private IDevicePolicyManager mDevicePolicyManager;
277
278    // For debugging to make sure the caller when acquiring/releasing our
279    // wake lock is the system process.
280    static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
281    /** The number of distinct task ids that can be assigned to the tasks of a single user */
282    private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
283
284    final ActivityManagerService mService;
285
286    private RecentTasks mRecentTasks;
287
288    final ActivityStackSupervisorHandler mHandler;
289
290    /** Short cut */
291    WindowManagerService mWindowManager;
292    DisplayManager mDisplayManager;
293
294    /** Counter for next free stack ID to use for dynamic activity stacks. */
295    private int mNextFreeStackId = FIRST_DYNAMIC_STACK_ID;
296
297    /**
298     * Maps the task identifier that activities are currently being started in to the userId of the
299     * task. Each time a new task is created, the entry for the userId of the task is incremented
300     */
301    private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20);
302
303    /** The current user */
304    int mCurrentUser;
305
306    /** The stack containing the launcher app. Assumed to always be attached to
307     * Display.DEFAULT_DISPLAY. */
308    ActivityStack mHomeStack;
309
310    /** The stack currently receiving input or launching the next activity. */
311    ActivityStack mFocusedStack;
312
313    /** If this is the same as mFocusedStack then the activity on the top of the focused stack has
314     * been resumed. If stacks are changing position this will hold the old stack until the new
315     * stack becomes resumed after which it will be set to mFocusedStack. */
316    private ActivityStack mLastFocusedStack;
317
318    /** List of activities that are waiting for a new activity to become visible before completing
319     * whatever operation they are supposed to do. */
320    final ArrayList<ActivityRecord> mWaitingVisibleActivities = new ArrayList<>();
321
322    /** List of processes waiting to find out about the next visible activity. */
323    final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible = new ArrayList<>();
324
325    /** List of processes waiting to find out about the next launched activity. */
326    final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched = new ArrayList<>();
327
328    /** List of activities that are ready to be stopped, but waiting for the next activity to
329     * settle down before doing so. */
330    final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>();
331
332    /** List of activities that are ready to be finished, but waiting for the previous activity to
333     * settle down before doing so.  It contains ActivityRecord objects. */
334    final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>();
335
336    /** List of activities that are in the process of going to sleep. */
337    final ArrayList<ActivityRecord> mGoingToSleepActivities = new ArrayList<>();
338
339    /** List of activities whose multi-window mode changed that we need to report to the
340     * application */
341    final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
342
343    /** List of activities whose picture-in-picture mode changed that we need to report to the
344     * application */
345    final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
346
347    /** Used on user changes */
348    final ArrayList<UserState> mStartingUsers = new ArrayList<>();
349
350    /** Used to queue up any background users being started */
351    final ArrayList<UserState> mStartingBackgroundUsers = new ArrayList<>();
352
353    /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity
354     * is being brought in front of us. */
355    boolean mUserLeaving = false;
356
357    /** Set when we have taken too long waiting to go to sleep. */
358    boolean mSleepTimeout = false;
359
360    /**
361     * We don't want to allow the device to go to sleep while in the process
362     * of launching an activity.  This is primarily to allow alarm intent
363     * receivers to launch an activity and get that to run before the device
364     * goes back to sleep.
365     */
366    PowerManager.WakeLock mLaunchingActivity;
367
368    /**
369     * Set when the system is going to sleep, until we have
370     * successfully paused the current activity and released our wake lock.
371     * At that point the system is allowed to actually sleep.
372     */
373    PowerManager.WakeLock mGoingToSleep;
374
375    /** Stack id of the front stack when user switched, indexed by userId. */
376    SparseIntArray mUserStackInFront = new SparseIntArray(2);
377
378    // TODO: Add listener for removal of references.
379    /** Mapping from (ActivityStack/TaskStack).mStackId to their current state */
380    private SparseArray<ActivityContainer> mActivityContainers = new SparseArray<>();
381
382    /** Mapping from displayId to display current state */
383    private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();
384
385    InputManagerInternal mInputManagerInternal;
386
387    /** The chain of tasks in lockTask mode. The current frontmost task is at the top, and tasks
388     * may be finished until there is only one entry left. If this is empty the system is not
389     * in lockTask mode. */
390    ArrayList<TaskRecord> mLockTaskModeTasks = new ArrayList<>();
391    /** Store the current lock task mode. Possible values:
392     * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
393     * {@link ActivityManager#LOCK_TASK_MODE_PINNED}
394     */
395    private int mLockTaskModeState;
396    /**
397     * Notifies the user when entering/exiting lock-task.
398     */
399    private LockTaskNotify mLockTaskNotify;
400
401    /** Used to keep resumeTopActivityUncheckedLocked() from being entered recursively */
402    boolean inResumeTopActivity;
403
404    // temp. rects used during resize calculation so we don't need to create a new object each time.
405    private final Rect tempRect = new Rect();
406    private final Rect tempRect2 = new Rect();
407
408    private final SparseArray<Configuration> mTmpConfigs = new SparseArray<>();
409    private final SparseArray<Rect> mTmpBounds = new SparseArray<>();
410    private final SparseArray<Rect> mTmpInsetBounds = new SparseArray<>();
411
412    // The default minimal size that will be used if the activity doesn't specify its minimal size.
413    // It will be calculated when the default display gets added.
414    int mDefaultMinimalSizeOfResizeableTask = -1;
415
416    // Whether tasks have moved and we need to rank the tasks before next OOM scoring
417    private boolean mTaskLayersChanged = true;
418
419    final ActivityMetricsLogger mActivityMetricsLogger;
420
421    private final ResizeDockedStackTimeout mResizeDockedStackTimeout;
422
423    static class FindTaskResult {
424        ActivityRecord r;
425        boolean matchedByRootAffinity;
426    }
427    private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
428
429    /**
430     * Used to keep track whether app visibilities got changed since the last pause. Useful to
431     * determine whether to invoke the task stack change listener after pausing.
432     */
433    boolean mAppVisibilitiesChangedSinceLastPause;
434
435    /**
436     * Set of tasks that are in resizing mode during an app transition to fill the "void".
437     */
438    private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
439
440    /**
441     * Is dock currently minimized.
442     */
443    boolean mIsDockMinimized;
444
445    /**
446     * Description of a request to start a new activity, which has been held
447     * due to app switches being disabled.
448     */
449    static class PendingActivityLaunch {
450        final ActivityRecord r;
451        final ActivityRecord sourceRecord;
452        final int startFlags;
453        final ActivityStack stack;
454        final ProcessRecord callerApp;
455
456        PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
457                int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
458            r = _r;
459            sourceRecord = _sourceRecord;
460            startFlags = _startFlags;
461            stack = _stack;
462            callerApp = _callerApp;
463        }
464
465        void sendErrorResult(String message) {
466            try {
467                if (callerApp.thread != null) {
468                    callerApp.thread.scheduleCrash(message);
469                }
470            } catch (RemoteException e) {
471                Slog.e(TAG, "Exception scheduling crash of failed "
472                        + "activity launcher sourceRecord=" + sourceRecord, e);
473            }
474        }
475    }
476
477    public ActivityStackSupervisor(ActivityManagerService service) {
478        mService = service;
479        mHandler = new ActivityStackSupervisorHandler(mService.mHandler.getLooper());
480        mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
481        mResizeDockedStackTimeout = new ResizeDockedStackTimeout(service, this, mHandler);
482    }
483
484    void setRecentTasks(RecentTasks recentTasks) {
485        mRecentTasks = recentTasks;
486    }
487
488    /**
489     * At the time when the constructor runs, the power manager has not yet been
490     * initialized.  So we initialize our wakelocks afterwards.
491     */
492    void initPowerManagement() {
493        PowerManager pm = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
494        mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
495        mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*launch*");
496        mLaunchingActivity.setReferenceCounted(false);
497    }
498
499    // This function returns a IStatusBarService. The value is from ServiceManager.
500    // getService and is cached.
501    private IStatusBarService getStatusBarService() {
502        synchronized (mService) {
503            if (mStatusBarService == null) {
504                mStatusBarService = IStatusBarService.Stub.asInterface(
505                    ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
506                if (mStatusBarService == null) {
507                    Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
508                }
509            }
510            return mStatusBarService;
511        }
512    }
513
514    private IDevicePolicyManager getDevicePolicyManager() {
515        synchronized (mService) {
516            if (mDevicePolicyManager == null) {
517                mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
518                    ServiceManager.checkService(Context.DEVICE_POLICY_SERVICE));
519                if (mDevicePolicyManager == null) {
520                    Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
521                }
522            }
523            return mDevicePolicyManager;
524        }
525    }
526
527    void setWindowManager(WindowManagerService wm) {
528        synchronized (mService) {
529            mWindowManager = wm;
530
531            mDisplayManager =
532                    (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
533            mDisplayManager.registerDisplayListener(this, null);
534
535            Display[] displays = mDisplayManager.getDisplays();
536            for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
537                final int displayId = displays[displayNdx].getDisplayId();
538                ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
539                if (activityDisplay.mDisplay == null) {
540                    throw new IllegalStateException("Default Display does not exist");
541                }
542                mActivityDisplays.put(displayId, activityDisplay);
543                calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
544            }
545
546            mHomeStack = mFocusedStack = mLastFocusedStack =
547                    getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
548
549            mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
550        }
551    }
552
553    void notifyActivityDrawnForKeyguard() {
554        if (DEBUG_LOCKSCREEN) mService.logLockScreen("");
555        mWindowManager.notifyActivityDrawnForKeyguard();
556    }
557
558    ActivityStack getFocusedStack() {
559        return mFocusedStack;
560    }
561
562    ActivityStack getLastStack() {
563        return mLastFocusedStack;
564    }
565
566    boolean isFocusedStack(ActivityStack stack) {
567        if (stack == null) {
568            return false;
569        }
570
571        final ActivityRecord parent = stack.mActivityContainer.mParentActivity;
572        if (parent != null) {
573            stack = parent.task.stack;
574        }
575        return stack == mFocusedStack;
576    }
577
578    /** The top most stack. */
579    boolean isFrontStack(ActivityStack stack) {
580        if (stack == null) {
581            return false;
582        }
583
584        final ActivityRecord parent = stack.mActivityContainer.mParentActivity;
585        if (parent != null) {
586            stack = parent.task.stack;
587        }
588        return stack == mHomeStack.mStacks.get((mHomeStack.mStacks.size() - 1));
589    }
590
591    /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
592    void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
593        if (!focusCandidate.isFocusable()) {
594            // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
595            focusCandidate = focusCandidate.getNextFocusableStackLocked();
596        }
597
598        if (focusCandidate != mFocusedStack) {
599            mLastFocusedStack = mFocusedStack;
600            mFocusedStack = focusCandidate;
601
602            EventLogTags.writeAmFocusedStack(
603                    mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
604                    mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
605        }
606
607        final ActivityRecord r = topRunningActivityLocked();
608        if (!mService.mDoingSetFocusedActivity && mService.mFocusedActivity != r) {
609            // The focus activity should always be the top activity in the focused stack.
610            // There will be chaos and anarchy if it isn't...
611            mService.setFocusedActivityLocked(r, reason + " setFocusStack");
612        }
613
614        if (mService.mBooting || !mService.mBooted) {
615            if (r != null && r.idle) {
616                checkFinishBootingLocked();
617            }
618        }
619    }
620
621    void moveHomeStackToFront(String reason) {
622        mHomeStack.moveToFront(reason);
623    }
624
625    /** Returns true if the focus activity was adjusted to the home stack top activity. */
626    boolean moveHomeStackTaskToTop(int homeStackTaskType, String reason) {
627        if (homeStackTaskType == RECENTS_ACTIVITY_TYPE) {
628            mWindowManager.showRecentApps(false /* fromHome */);
629            return false;
630        }
631
632        mHomeStack.moveHomeStackTaskToTop(homeStackTaskType);
633
634        final ActivityRecord top = getHomeActivity();
635        if (top == null) {
636            return false;
637        }
638        mService.setFocusedActivityLocked(top, reason);
639        return true;
640    }
641
642    boolean resumeHomeStackTask(int homeStackTaskType, ActivityRecord prev, String reason) {
643        if (!mService.mBooting && !mService.mBooted) {
644            // Not ready yet!
645            return false;
646        }
647
648        if (homeStackTaskType == RECENTS_ACTIVITY_TYPE) {
649            mWindowManager.showRecentApps(false /* fromHome */);
650            return false;
651        }
652
653        if (prev != null) {
654            prev.task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
655        }
656
657        mHomeStack.moveHomeStackTaskToTop(homeStackTaskType);
658        ActivityRecord r = getHomeActivity();
659        final String myReason = reason + " resumeHomeStackTask";
660
661        // Only resume home activity if isn't finishing.
662        if (r != null && !r.finishing) {
663            mService.setFocusedActivityLocked(r, myReason);
664            return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
665        }
666        return mService.startHomeActivityLocked(mCurrentUser, myReason);
667    }
668
669    TaskRecord anyTaskForIdLocked(int id) {
670        return anyTaskForIdLocked(id, RESTORE_FROM_RECENTS, INVALID_STACK_ID);
671    }
672
673    /**
674     * Returns a {@link TaskRecord} for the input id if available. Null otherwise.
675     * @param id Id of the task we would like returned.
676     * @param restoreFromRecents If the id was not in the active list, but was found in recents,
677     *                           restore the task from recents to the active list.
678     * @param stackId The stack to restore the task to (default launch stack will be used if
679     *                stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}).
680     */
681    TaskRecord anyTaskForIdLocked(int id, boolean restoreFromRecents, int stackId) {
682        int numDisplays = mActivityDisplays.size();
683        for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
684            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
685            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
686                ActivityStack stack = stacks.get(stackNdx);
687                TaskRecord task = stack.taskForIdLocked(id);
688                if (task != null) {
689                    return task;
690                }
691            }
692        }
693
694        // Don't give up! Look in recents.
695        if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
696        TaskRecord task = mRecentTasks.taskForIdLocked(id);
697        if (task == null) {
698            if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
699            return null;
700        }
701
702        if (!restoreFromRecents) {
703            return task;
704        }
705
706        if (!restoreRecentTaskLocked(task, stackId)) {
707            if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
708                    "Couldn't restore task id=" + id + " found in recents");
709            return null;
710        }
711        if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
712        return task;
713    }
714
715    ActivityRecord isInAnyStackLocked(IBinder token) {
716        int numDisplays = mActivityDisplays.size();
717        for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
718            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
719            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
720                final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
721                if (r != null) {
722                    return r;
723                }
724            }
725        }
726        return null;
727    }
728
729    /**
730     * TODO: Handle freefom mode.
731     * @return true when credential confirmation is needed for the user and there is any
732     *         activity started by the user in any visible stack.
733     */
734    boolean isUserLockedProfile(@UserIdInt int userId) {
735        if (!mService.mUserController.shouldConfirmCredentials(userId)) {
736            return false;
737        }
738        final ActivityStack fullScreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
739        final ActivityStack dockedStack = getStack(DOCKED_STACK_ID);
740        final ActivityStack[] activityStacks = new ActivityStack[] {fullScreenStack, dockedStack};
741        for (final ActivityStack activityStack : activityStacks) {
742            if (activityStack == null) {
743                continue;
744            }
745            if (activityStack.topRunningActivityLocked() == null) {
746                continue;
747            }
748            if (activityStack.getStackVisibilityLocked(null) == STACK_INVISIBLE) {
749                continue;
750            }
751            if (activityStack.isDockedStack() && mIsDockMinimized) {
752                continue;
753            }
754            final TaskRecord topTask = activityStack.topTask();
755            if (topTask == null) {
756                continue;
757            }
758            // To handle the case that work app is in the task but just is not the top one.
759            for (int i = topTask.mActivities.size() - 1; i >= 0; i--) {
760                final ActivityRecord activityRecord = topTask.mActivities.get(i);
761                if (activityRecord.userId == userId) {
762                    return true;
763                }
764            }
765        }
766        return false;
767    }
768
769    void setNextTaskIdForUserLocked(int taskId, int userId) {
770        final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
771        if (taskId > currentTaskId) {
772            mCurTaskIdForUser.put(userId, taskId);
773        }
774    }
775
776    int getNextTaskIdForUserLocked(int userId) {
777        final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
778        // for a userId u, a taskId can only be in the range
779        // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
780        // was 10, user 0 could only have taskIds 0 to 9, user 1: 10 to 19, user 2: 20 to 29, so on.
781        int candidateTaskId = currentTaskId;
782        while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
783                || anyTaskForIdLocked(candidateTaskId, !RESTORE_FROM_RECENTS,
784                        INVALID_STACK_ID) != null) {
785            candidateTaskId++;
786            if (candidateTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
787                // Wrap around as there will be smaller task ids that are available now.
788                candidateTaskId -= MAX_TASK_IDS_PER_USER;
789            }
790            if (candidateTaskId == currentTaskId) {
791                // Something wrong!
792                // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
793                throw new IllegalStateException("Cannot get an available task id."
794                        + " Reached limit of " + MAX_TASK_IDS_PER_USER
795                        + " running tasks per user.");
796            }
797        }
798        mCurTaskIdForUser.put(userId, candidateTaskId);
799        return candidateTaskId;
800    }
801
802    ActivityRecord resumedAppLocked() {
803        ActivityStack stack = mFocusedStack;
804        if (stack == null) {
805            return null;
806        }
807        ActivityRecord resumedActivity = stack.mResumedActivity;
808        if (resumedActivity == null || resumedActivity.app == null) {
809            resumedActivity = stack.mPausingActivity;
810            if (resumedActivity == null || resumedActivity.app == null) {
811                resumedActivity = stack.topRunningActivityLocked();
812            }
813        }
814        return resumedActivity;
815    }
816
817    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
818        final String processName = app.processName;
819        boolean didSomething = false;
820        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
821            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
822            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
823                final ActivityStack stack = stacks.get(stackNdx);
824                if (!isFocusedStack(stack)) {
825                    continue;
826                }
827                ActivityRecord hr = stack.topRunningActivityLocked();
828                if (hr != null) {
829                    if (hr.app == null && app.uid == hr.info.applicationInfo.uid
830                            && processName.equals(hr.processName)) {
831                        try {
832                            if (realStartActivityLocked(hr, app, true, true)) {
833                                didSomething = true;
834                            }
835                        } catch (RemoteException e) {
836                            Slog.w(TAG, "Exception in new application when starting activity "
837                                  + hr.intent.getComponent().flattenToShortString(), e);
838                            throw e;
839                        }
840                    }
841                }
842            }
843        }
844        if (!didSomething) {
845            ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
846        }
847        return didSomething;
848    }
849
850    boolean allResumedActivitiesIdle() {
851        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
852            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
853            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
854                final ActivityStack stack = stacks.get(stackNdx);
855                if (!isFocusedStack(stack) || stack.numActivities() == 0) {
856                    continue;
857                }
858                final ActivityRecord resumedActivity = stack.mResumedActivity;
859                if (resumedActivity == null || !resumedActivity.idle) {
860                    if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
861                             + stack.mStackId + " " + resumedActivity + " not idle");
862                    return false;
863                }
864            }
865        }
866        return true;
867    }
868
869    boolean allResumedActivitiesComplete() {
870        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
871            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
872            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
873                final ActivityStack stack = stacks.get(stackNdx);
874                if (isFocusedStack(stack)) {
875                    final ActivityRecord r = stack.mResumedActivity;
876                    if (r != null && r.state != RESUMED) {
877                        return false;
878                    }
879                }
880            }
881        }
882        // TODO: Not sure if this should check if all Paused are complete too.
883        if (DEBUG_STACK) Slog.d(TAG_STACK,
884                "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
885                mLastFocusedStack + " to=" + mFocusedStack);
886        mLastFocusedStack = mFocusedStack;
887        return true;
888    }
889
890    boolean allResumedActivitiesVisible() {
891        boolean foundResumed = false;
892        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
893            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
894            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
895                final ActivityStack stack = stacks.get(stackNdx);
896                final ActivityRecord r = stack.mResumedActivity;
897                if (r != null) {
898                    if (!r.nowVisible || mWaitingVisibleActivities.contains(r)) {
899                        return false;
900                    }
901                    foundResumed = true;
902                }
903            }
904        }
905        return foundResumed;
906    }
907
908    /**
909     * Pause all activities in either all of the stacks or just the back stacks.
910     * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
911     * @return true if any activity was paused as a result of this call.
912     */
913    boolean pauseBackStacks(boolean userLeaving, boolean resuming, boolean dontWait) {
914        boolean someActivityPaused = false;
915        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
916            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
917            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
918                final ActivityStack stack = stacks.get(stackNdx);
919                if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
920                    if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
921                            " mResumedActivity=" + stack.mResumedActivity);
922                    someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
923                            dontWait);
924                }
925            }
926        }
927        return someActivityPaused;
928    }
929
930    boolean allPausedActivitiesComplete() {
931        boolean pausing = true;
932        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
933            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
934            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
935                final ActivityStack stack = stacks.get(stackNdx);
936                final ActivityRecord r = stack.mPausingActivity;
937                if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
938                    if (DEBUG_STATES) {
939                        Slog.d(TAG_STATES,
940                                "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
941                        pausing = false;
942                    } else {
943                        return false;
944                    }
945                }
946            }
947        }
948        return pausing;
949    }
950
951    void pauseChildStacks(ActivityRecord parent, boolean userLeaving, boolean uiSleeping,
952            boolean resuming, boolean dontWait) {
953        // TODO: Put all stacks in supervisor and iterate through them instead.
954        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
955            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
956            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
957                final ActivityStack stack = stacks.get(stackNdx);
958                if (stack.mResumedActivity != null &&
959                        stack.mActivityContainer.mParentActivity == parent) {
960                    stack.startPausingLocked(userLeaving, uiSleeping, resuming, dontWait);
961                }
962            }
963        }
964    }
965
966    void cancelInitializingActivities() {
967        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
968            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
969            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
970                stacks.get(stackNdx).cancelInitializingActivities();
971            }
972        }
973    }
974
975    void reportActivityVisibleLocked(ActivityRecord r) {
976        sendWaitingVisibleReportLocked(r);
977    }
978
979    void sendWaitingVisibleReportLocked(ActivityRecord r) {
980        boolean changed = false;
981        for (int i = mWaitingActivityVisible.size()-1; i >= 0; i--) {
982            WaitResult w = mWaitingActivityVisible.get(i);
983            if (w.who == null) {
984                changed = true;
985                w.timeout = false;
986                if (r != null) {
987                    w.who = new ComponentName(r.info.packageName, r.info.name);
988                }
989                w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
990                w.thisTime = w.totalTime;
991            }
992        }
993        if (changed) {
994            mService.notifyAll();
995        }
996    }
997
998    void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
999            long thisTime, long totalTime) {
1000        boolean changed = false;
1001        for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1002            WaitResult w = mWaitingActivityLaunched.remove(i);
1003            if (w.who == null) {
1004                changed = true;
1005                w.timeout = timeout;
1006                if (r != null) {
1007                    w.who = new ComponentName(r.info.packageName, r.info.name);
1008                }
1009                w.thisTime = thisTime;
1010                w.totalTime = totalTime;
1011            }
1012        }
1013        if (changed) {
1014            mService.notifyAll();
1015        }
1016    }
1017
1018    ActivityRecord topRunningActivityLocked() {
1019        final ActivityStack focusedStack = mFocusedStack;
1020        ActivityRecord r = focusedStack.topRunningActivityLocked();
1021        if (r != null) {
1022            return r;
1023        }
1024
1025        // Return to the home stack.
1026        final ArrayList<ActivityStack> stacks = mHomeStack.mStacks;
1027        for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1028            final ActivityStack stack = stacks.get(stackNdx);
1029            if (stack != focusedStack && isFrontStack(stack) && stack.isFocusable()) {
1030                r = stack.topRunningActivityLocked();
1031                if (r != null) {
1032                    return r;
1033                }
1034            }
1035        }
1036        return null;
1037    }
1038
1039    void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
1040        // Gather all of the running tasks for each stack into runningTaskLists.
1041        ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1042                new ArrayList<ArrayList<RunningTaskInfo>>();
1043        final int numDisplays = mActivityDisplays.size();
1044        for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
1045            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1046            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1047                final ActivityStack stack = stacks.get(stackNdx);
1048                ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
1049                runningTaskLists.add(stackTaskList);
1050                stack.getTasksLocked(stackTaskList, callingUid, allowed);
1051            }
1052        }
1053
1054        // The lists are already sorted from most recent to oldest. Just pull the most recent off
1055        // each list and add it to list. Stop when all lists are empty or maxNum reached.
1056        while (maxNum > 0) {
1057            long mostRecentActiveTime = Long.MIN_VALUE;
1058            ArrayList<RunningTaskInfo> selectedStackList = null;
1059            final int numTaskLists = runningTaskLists.size();
1060            for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1061                ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
1062                if (!stackTaskList.isEmpty()) {
1063                    final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1064                    if (lastActiveTime > mostRecentActiveTime) {
1065                        mostRecentActiveTime = lastActiveTime;
1066                        selectedStackList = stackTaskList;
1067                    }
1068                }
1069            }
1070            if (selectedStackList != null) {
1071                list.add(selectedStackList.remove(0));
1072                --maxNum;
1073            } else {
1074                break;
1075            }
1076        }
1077    }
1078
1079    ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1080            ProfilerInfo profilerInfo) {
1081        final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
1082        if (aInfo != null) {
1083            // Store the found target back into the intent, because now that
1084            // we have it we never want to do this again.  For example, if the
1085            // user navigates back to this point in the history, we should
1086            // always restart the exact same activity.
1087            intent.setComponent(new ComponentName(
1088                    aInfo.applicationInfo.packageName, aInfo.name));
1089
1090            // Don't debug things in the system process
1091            if (!aInfo.processName.equals("system")) {
1092                if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
1093                    mService.setDebugApp(aInfo.processName, true, false);
1094                }
1095
1096                if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1097                    mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1098                }
1099
1100                if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1101                    mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1102                }
1103
1104                if (profilerInfo != null) {
1105                    mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
1106                }
1107            }
1108        }
1109        return aInfo;
1110    }
1111
1112    ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
1113        return resolveIntent(intent, resolvedType, userId, 0);
1114    }
1115
1116    ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
1117        try {
1118            return AppGlobals.getPackageManager().resolveIntent(intent, resolvedType,
1119                    PackageManager.MATCH_DEFAULT_ONLY | flags
1120                    | ActivityManagerService.STOCK_PM_FLAGS, userId);
1121        } catch (RemoteException e) {
1122        }
1123        return null;
1124    }
1125
1126    ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1127            ProfilerInfo profilerInfo, int userId) {
1128        final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1129        return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1130    }
1131
1132    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1133            boolean andResume, boolean checkConfig) throws RemoteException {
1134
1135        if (!allPausedActivitiesComplete()) {
1136            // While there are activities pausing we skipping starting any new activities until
1137            // pauses are complete. NOTE: that we also do this for activities that are starting in
1138            // the paused state because they will first be resumed then paused on the client side.
1139            if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1140                    "realStartActivityLocked: Skipping start of r=" + r
1141                    + " some activities pausing...");
1142            return false;
1143        }
1144
1145        if (andResume) {
1146            r.startFreezingScreenLocked(app, 0);
1147            mWindowManager.setAppVisibility(r.appToken, true);
1148
1149            // schedule launch ticks to collect information about slow apps.
1150            r.startLaunchTickingLocked();
1151        }
1152
1153        // Have the window manager re-evaluate the orientation of
1154        // the screen based on the new activity order.  Note that
1155        // as a result of this, it can call back into the activity
1156        // manager with a new orientation.  We don't care about that,
1157        // because the activity is not currently running so we are
1158        // just restarting it anyway.
1159        if (checkConfig) {
1160            Configuration config = mWindowManager.updateOrientationFromAppTokens(
1161                    mService.mConfiguration,
1162                    r.mayFreezeScreenLocked(app) ? r.appToken : null);
1163            mService.updateConfigurationLocked(config, r, false);
1164        }
1165
1166        r.app = app;
1167        app.waitingToKill = null;
1168        r.launchCount++;
1169        r.lastLaunchTime = SystemClock.uptimeMillis();
1170
1171        if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1172
1173        int idx = app.activities.indexOf(r);
1174        if (idx < 0) {
1175            app.activities.add(r);
1176        }
1177        mService.updateLruProcessLocked(app, true, null);
1178        mService.updateOomAdjLocked();
1179
1180        final TaskRecord task = r.task;
1181        if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1182                task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
1183            setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE", false);
1184        }
1185
1186        final ActivityStack stack = task.stack;
1187        try {
1188            if (app.thread == null) {
1189                throw new RemoteException();
1190            }
1191            List<ResultInfo> results = null;
1192            List<ReferrerIntent> newIntents = null;
1193            if (andResume) {
1194                results = r.results;
1195                newIntents = r.newIntents;
1196            }
1197            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1198                    "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1199                    + " newIntents=" + newIntents + " andResume=" + andResume);
1200            if (andResume) {
1201                EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
1202                        r.userId, System.identityHashCode(r),
1203                        task.taskId, r.shortComponentName);
1204            }
1205            if (r.isHomeActivity()) {
1206                // Home process is the root process of the task.
1207                mService.mHomeProcess = task.mActivities.get(0).app;
1208            }
1209            mService.notifyPackageUse(r.intent.getComponent().getPackageName());
1210            r.sleeping = false;
1211            r.forceNewConfig = false;
1212            mService.showAskCompatModeDialogLocked(r);
1213            r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1214            ProfilerInfo profilerInfo = null;
1215            if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1216                if (mService.mProfileProc == null || mService.mProfileProc == app) {
1217                    mService.mProfileProc = app;
1218                    final String profileFile = mService.mProfileFile;
1219                    if (profileFile != null) {
1220                        ParcelFileDescriptor profileFd = mService.mProfileFd;
1221                        if (profileFd != null) {
1222                            try {
1223                                profileFd = profileFd.dup();
1224                            } catch (IOException e) {
1225                                if (profileFd != null) {
1226                                    try {
1227                                        profileFd.close();
1228                                    } catch (IOException o) {
1229                                    }
1230                                    profileFd = null;
1231                                }
1232                            }
1233                        }
1234
1235                        profilerInfo = new ProfilerInfo(profileFile, profileFd,
1236                                mService.mSamplingInterval, mService.mAutoStopProfiler);
1237                    }
1238                }
1239            }
1240
1241            if (andResume) {
1242                app.hasShownUi = true;
1243                app.pendingUiClean = true;
1244            }
1245            app.forceProcessStateUpTo(mService.mTopProcessState);
1246            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1247                    System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
1248                    new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
1249                    task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
1250                    newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
1251
1252            if ((app.info.privateFlags&ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1253                // This may be a heavy-weight process!  Note that the package
1254                // manager will ensure that only activity can run in the main
1255                // process of the .apk, which is the only thing that will be
1256                // considered heavy-weight.
1257                if (app.processName.equals(app.info.packageName)) {
1258                    if (mService.mHeavyWeightProcess != null
1259                            && mService.mHeavyWeightProcess != app) {
1260                        Slog.w(TAG, "Starting new heavy weight process " + app
1261                                + " when already running "
1262                                + mService.mHeavyWeightProcess);
1263                    }
1264                    mService.mHeavyWeightProcess = app;
1265                    Message msg = mService.mHandler.obtainMessage(
1266                            ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1267                    msg.obj = r;
1268                    mService.mHandler.sendMessage(msg);
1269                }
1270            }
1271
1272        } catch (RemoteException e) {
1273            if (r.launchFailed) {
1274                // This is the second time we failed -- finish activity
1275                // and give up.
1276                Slog.e(TAG, "Second failure launching "
1277                      + r.intent.getComponent().flattenToShortString()
1278                      + ", giving up", e);
1279                mService.appDiedLocked(app);
1280                stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1281                        "2nd-crash", false);
1282                return false;
1283            }
1284
1285            // This is the first time we failed -- restart process and
1286            // retry.
1287            app.activities.remove(r);
1288            throw e;
1289        }
1290
1291        r.launchFailed = false;
1292        if (stack.updateLRUListLocked(r)) {
1293            Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
1294        }
1295
1296        if (andResume) {
1297            // As part of the process of launching, ActivityThread also performs
1298            // a resume.
1299            stack.minimalResumeActivityLocked(r);
1300        } else {
1301            // This activity is not starting in the resumed state... which should look like we asked
1302            // it to pause+stop (but remain visible), and it has done so and reported back the
1303            // current icicle and other state.
1304            if (DEBUG_STATES) Slog.v(TAG_STATES,
1305                    "Moving to PAUSED: " + r + " (starting in paused state)");
1306            r.state = PAUSED;
1307        }
1308
1309        // Launch the new version setup screen if needed.  We do this -after-
1310        // launching the initial activity (that is, home), so that it can have
1311        // a chance to initialize itself while in the background, making the
1312        // switch back to it faster and look better.
1313        if (isFocusedStack(stack)) {
1314            mService.startSetupActivityLocked();
1315        }
1316
1317        // Update any services we are bound to that might care about whether
1318        // their client may have activities.
1319        mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1320
1321        return true;
1322    }
1323
1324    void startSpecificActivityLocked(ActivityRecord r,
1325            boolean andResume, boolean checkConfig) {
1326        // Is this activity's application already running?
1327        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1328                r.info.applicationInfo.uid, true);
1329
1330        r.task.stack.setLaunchTime(r);
1331
1332        if (app != null && app.thread != null) {
1333            try {
1334                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1335                        || !"android".equals(r.info.packageName)) {
1336                    // Don't add this if it is a platform component that is marked
1337                    // to run in multiple processes, because this is actually
1338                    // part of the framework so doesn't make sense to track as a
1339                    // separate apk in the process.
1340                    app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1341                            mService.mProcessStats);
1342                }
1343                realStartActivityLocked(r, app, andResume, checkConfig);
1344                return;
1345            } catch (RemoteException e) {
1346                Slog.w(TAG, "Exception when starting activity "
1347                        + r.intent.getComponent().flattenToShortString(), e);
1348            }
1349
1350            // If a dead object exception was thrown -- fall through to
1351            // restart the application.
1352        }
1353
1354        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
1355                "activity", r.intent.getComponent(), false, false, true);
1356    }
1357
1358    boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
1359            String resultWho, int requestCode, int callingPid, int callingUid,
1360            String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
1361            ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
1362        final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1363                callingUid);
1364        if (startAnyPerm ==  PERMISSION_GRANTED) {
1365            return true;
1366        }
1367        final int componentRestriction = getComponentRestrictionForCallingPackage(
1368                aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1369        final int actionRestriction = getActionRestrictionForCallingPackage(
1370                intent.getAction(), callingPackage, callingPid, callingUid);
1371        if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1372                || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1373            if (resultRecord != null) {
1374                resultStack.sendActivityResultLocked(-1,
1375                        resultRecord, resultWho, requestCode,
1376                        Activity.RESULT_CANCELED, null);
1377            }
1378            final String msg;
1379            if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1380                msg = "Permission Denial: starting " + intent.toString()
1381                        + " from " + callerApp + " (pid=" + callingPid
1382                        + ", uid=" + callingUid + ")" + " with revoked permission "
1383                        + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1384            } else if (!aInfo.exported) {
1385                msg = "Permission Denial: starting " + intent.toString()
1386                        + " from " + callerApp + " (pid=" + callingPid
1387                        + ", uid=" + callingUid + ")"
1388                        + " not exported from uid " + aInfo.applicationInfo.uid;
1389            } else {
1390                msg = "Permission Denial: starting " + intent.toString()
1391                        + " from " + callerApp + " (pid=" + callingPid
1392                        + ", uid=" + callingUid + ")"
1393                        + " requires " + aInfo.permission;
1394            }
1395            Slog.w(TAG, msg);
1396            throw new SecurityException(msg);
1397        }
1398
1399        if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1400            final String message = "Appop Denial: starting " + intent.toString()
1401                    + " from " + callerApp + " (pid=" + callingPid
1402                    + ", uid=" + callingUid + ")"
1403                    + " requires " + AppOpsManager.permissionToOp(
1404                            ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1405            Slog.w(TAG, message);
1406            return false;
1407        } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1408            final String message = "Appop Denial: starting " + intent.toString()
1409                    + " from " + callerApp + " (pid=" + callingPid
1410                    + ", uid=" + callingUid + ")"
1411                    + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1412            Slog.w(TAG, message);
1413            return false;
1414        }
1415        if (options != null && options.getLaunchTaskId() != -1) {
1416            final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1417                    callingPid, callingUid);
1418            if (startInTaskPerm != PERMISSION_GRANTED) {
1419                final String msg = "Permission Denial: starting " + intent.toString()
1420                        + " from " + callerApp + " (pid=" + callingPid
1421                        + ", uid=" + callingUid + ") with launchTaskId="
1422                        + options.getLaunchTaskId();
1423                Slog.w(TAG, msg);
1424                throw new SecurityException(msg);
1425            }
1426        }
1427
1428        return true;
1429    }
1430
1431    UserInfo getUserInfo(int userId) {
1432        final long identity = Binder.clearCallingIdentity();
1433        try {
1434            return UserManager.get(mService.mContext).getUserInfo(userId);
1435        } finally {
1436            Binder.restoreCallingIdentity(identity);
1437        }
1438    }
1439
1440    private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
1441            String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
1442        if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1443                callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
1444                == PackageManager.PERMISSION_DENIED) {
1445            return ACTIVITY_RESTRICTION_PERMISSION;
1446        }
1447
1448        if (activityInfo.permission == null) {
1449            return ACTIVITY_RESTRICTION_NONE;
1450        }
1451
1452        final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1453        if (opCode == AppOpsManager.OP_NONE) {
1454            return ACTIVITY_RESTRICTION_NONE;
1455        }
1456
1457        if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1458                callingPackage) != AppOpsManager.MODE_ALLOWED) {
1459            if (!ignoreTargetSecurity) {
1460                return ACTIVITY_RESTRICTION_APPOP;
1461            }
1462        }
1463
1464        return ACTIVITY_RESTRICTION_NONE;
1465    }
1466
1467    private int getActionRestrictionForCallingPackage(String action,
1468            String callingPackage, int callingPid, int callingUid) {
1469        if (action == null) {
1470            return ACTIVITY_RESTRICTION_NONE;
1471        }
1472
1473        String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1474        if (permission == null) {
1475            return ACTIVITY_RESTRICTION_NONE;
1476        }
1477
1478        final PackageInfo packageInfo;
1479        try {
1480            packageInfo = mService.mContext.getPackageManager()
1481                    .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1482        } catch (PackageManager.NameNotFoundException e) {
1483            Slog.i(TAG, "Cannot find package info for " + callingPackage);
1484            return ACTIVITY_RESTRICTION_NONE;
1485        }
1486
1487        if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
1488            return ACTIVITY_RESTRICTION_NONE;
1489        }
1490
1491        if (mService.checkPermission(permission, callingPid, callingUid) ==
1492                PackageManager.PERMISSION_DENIED) {
1493            return ACTIVITY_RESTRICTION_PERMISSION;
1494        }
1495
1496        final int opCode = AppOpsManager.permissionToOpCode(permission);
1497        if (opCode == AppOpsManager.OP_NONE) {
1498            return ACTIVITY_RESTRICTION_NONE;
1499        }
1500
1501        if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1502                callingPackage) != AppOpsManager.MODE_ALLOWED) {
1503            return ACTIVITY_RESTRICTION_APPOP;
1504        }
1505
1506        return ACTIVITY_RESTRICTION_NONE;
1507    }
1508
1509    boolean moveActivityStackToFront(ActivityRecord r, String reason) {
1510        if (r == null) {
1511            // Not sure what you are trying to do, but it is not going to work...
1512            return false;
1513        }
1514        final TaskRecord task = r.task;
1515        if (task == null || task.stack == null) {
1516            Slog.w(TAG, "Can't move stack to front for r=" + r + " task=" + task);
1517            return false;
1518        }
1519        task.stack.moveToFront(reason, task);
1520        return true;
1521    }
1522
1523    void setLaunchSource(int uid) {
1524        mLaunchingActivity.setWorkSource(new WorkSource(uid));
1525    }
1526
1527    void acquireLaunchWakelock() {
1528        if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1529            throw new IllegalStateException("Calling must be system uid");
1530        }
1531        mLaunchingActivity.acquire();
1532        if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1533            // To be safe, don't allow the wake lock to be held for too long.
1534            mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1535        }
1536    }
1537
1538    /**
1539     * Called when the frontmost task is idle.
1540     * @return the state of mService.mBooting before this was called.
1541     */
1542    private boolean checkFinishBootingLocked() {
1543        final boolean booting = mService.mBooting;
1544        boolean enableScreen = false;
1545        mService.mBooting = false;
1546        if (!mService.mBooted) {
1547            mService.mBooted = true;
1548            enableScreen = true;
1549        }
1550        if (booting || enableScreen) {
1551            mService.postFinishBooting(booting, enableScreen);
1552        }
1553        return booting;
1554    }
1555
1556    // Checked.
1557    final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
1558            Configuration config) {
1559        if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
1560
1561        ArrayList<ActivityRecord> finishes = null;
1562        ArrayList<UserState> startingUsers = null;
1563        int NS = 0;
1564        int NF = 0;
1565        boolean booting = false;
1566        boolean activityRemoved = false;
1567
1568        ActivityRecord r = ActivityRecord.forTokenLocked(token);
1569        if (r != null) {
1570            if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1571                    + Debug.getCallers(4));
1572            mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1573            r.finishLaunchTickingLocked();
1574            if (fromTimeout) {
1575                reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
1576            }
1577
1578            // This is a hack to semi-deal with a race condition
1579            // in the client where it can be constructed with a
1580            // newer configuration from when we asked it to launch.
1581            // We'll update with whatever configuration it now says
1582            // it used to launch.
1583            if (config != null) {
1584                r.configuration = config;
1585            }
1586
1587            // We are now idle.  If someone is waiting for a thumbnail from
1588            // us, we can now deliver.
1589            r.idle = true;
1590
1591            //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
1592            if (isFocusedStack(r.task.stack) || fromTimeout) {
1593                booting = checkFinishBootingLocked();
1594            }
1595        }
1596
1597        if (allResumedActivitiesIdle()) {
1598            if (r != null) {
1599                mService.scheduleAppGcsLocked();
1600            }
1601
1602            if (mLaunchingActivity.isHeld()) {
1603                mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1604                if (VALIDATE_WAKE_LOCK_CALLER &&
1605                        Binder.getCallingUid() != Process.myUid()) {
1606                    throw new IllegalStateException("Calling must be system uid");
1607                }
1608                mLaunchingActivity.release();
1609            }
1610            ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1611        }
1612
1613        // Atomically retrieve all of the other things to do.
1614        final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(true);
1615        NS = stops != null ? stops.size() : 0;
1616        if ((NF = mFinishingActivities.size()) > 0) {
1617            finishes = new ArrayList<>(mFinishingActivities);
1618            mFinishingActivities.clear();
1619        }
1620
1621        if (mStartingUsers.size() > 0) {
1622            startingUsers = new ArrayList<>(mStartingUsers);
1623            mStartingUsers.clear();
1624        }
1625
1626        // Stop any activities that are scheduled to do so but have been
1627        // waiting for the next one to start.
1628        for (int i = 0; i < NS; i++) {
1629            r = stops.get(i);
1630            final ActivityStack stack = r.task.stack;
1631            if (stack != null) {
1632                if (r.finishing) {
1633                    stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1634                } else {
1635                    stack.stopActivityLocked(r);
1636                }
1637            }
1638        }
1639
1640        // Finish any activities that are scheduled to do so but have been
1641        // waiting for the next one to start.
1642        for (int i = 0; i < NF; i++) {
1643            r = finishes.get(i);
1644            final ActivityStack stack = r.task.stack;
1645            if (stack != null) {
1646                activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1647            }
1648        }
1649
1650        if (!booting) {
1651            // Complete user switch
1652            if (startingUsers != null) {
1653                for (int i = 0; i < startingUsers.size(); i++) {
1654                    mService.mUserController.finishUserSwitch(startingUsers.get(i));
1655                }
1656            }
1657        }
1658
1659        mService.trimApplications();
1660        //dump();
1661        //mWindowManager.dump();
1662
1663        if (activityRemoved) {
1664            resumeFocusedStackTopActivityLocked();
1665        }
1666
1667        return r;
1668    }
1669
1670    boolean handleAppDiedLocked(ProcessRecord app) {
1671        boolean hasVisibleActivities = false;
1672        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1673            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1674            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1675                hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
1676            }
1677        }
1678        return hasVisibleActivities;
1679    }
1680
1681    void closeSystemDialogsLocked() {
1682        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1683            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1684            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1685                stacks.get(stackNdx).closeSystemDialogsLocked();
1686            }
1687        }
1688    }
1689
1690    void removeUserLocked(int userId) {
1691        mUserStackInFront.delete(userId);
1692    }
1693
1694    /**
1695     * Update the last used stack id for non-current user (current user's last
1696     * used stack is the focused stack)
1697     */
1698    void updateUserStackLocked(int userId, ActivityStack stack) {
1699        if (userId != mCurrentUser) {
1700            mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
1701        }
1702    }
1703
1704    /**
1705     * @return true if some activity was finished (or would have finished if doit were true).
1706     */
1707    boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
1708            boolean doit, boolean evenPersistent, int userId) {
1709        boolean didSomething = false;
1710        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1711            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1712            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1713                final ActivityStack stack = stacks.get(stackNdx);
1714                if (stack.finishDisabledPackageActivitiesLocked(
1715                        packageName, filterByClasses, doit, evenPersistent, userId)) {
1716                    didSomething = true;
1717                }
1718            }
1719        }
1720        return didSomething;
1721    }
1722
1723    void updatePreviousProcessLocked(ActivityRecord r) {
1724        // Now that this process has stopped, we may want to consider
1725        // it to be the previous app to try to keep around in case
1726        // the user wants to return to it.
1727
1728        // First, found out what is currently the foreground app, so that
1729        // we don't blow away the previous app if this activity is being
1730        // hosted by the process that is actually still the foreground.
1731        ProcessRecord fgApp = null;
1732        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1733            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1734            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1735                final ActivityStack stack = stacks.get(stackNdx);
1736                if (isFocusedStack(stack)) {
1737                    if (stack.mResumedActivity != null) {
1738                        fgApp = stack.mResumedActivity.app;
1739                    } else if (stack.mPausingActivity != null) {
1740                        fgApp = stack.mPausingActivity.app;
1741                    }
1742                    break;
1743                }
1744            }
1745        }
1746
1747        // Now set this one as the previous process, only if that really
1748        // makes sense to.
1749        if (r.app != null && fgApp != null && r.app != fgApp
1750                && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1751                && r.app != mService.mHomeProcess) {
1752            mService.mPreviousProcess = r.app;
1753            mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1754        }
1755    }
1756
1757    boolean resumeFocusedStackTopActivityLocked() {
1758        return resumeFocusedStackTopActivityLocked(null, null, null);
1759    }
1760
1761    boolean resumeFocusedStackTopActivityLocked(
1762            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
1763        if (targetStack != null && isFocusedStack(targetStack)) {
1764            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
1765        }
1766        mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
1767        return false;
1768    }
1769
1770    void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
1771        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1772            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1773            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1774                stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
1775            }
1776        }
1777    }
1778
1779    TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
1780        TaskRecord finishedTask = null;
1781        ActivityStack focusedStack = getFocusedStack();
1782        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1783            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1784            final int numStacks = stacks.size();
1785            for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
1786                final ActivityStack stack = stacks.get(stackNdx);
1787                TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
1788                if (stack == focusedStack || finishedTask == null) {
1789                    finishedTask = t;
1790                }
1791            }
1792        }
1793        return finishedTask;
1794    }
1795
1796    void finishVoiceTask(IVoiceInteractionSession session) {
1797        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1798            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1799            final int numStacks = stacks.size();
1800            for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
1801                final ActivityStack stack = stacks.get(stackNdx);
1802                stack.finishVoiceTask(session);
1803            }
1804        }
1805    }
1806
1807    void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
1808            String reason, boolean forceNonResizeable) {
1809        if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
1810            mUserLeaving = true;
1811        }
1812        if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
1813            // Caller wants the home activity moved with it.  To accomplish this,
1814            // we'll just indicate that this task returns to the home task.
1815            task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
1816        }
1817        if (task.stack == null) {
1818            Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
1819                    + task + " to front. Stack is null");
1820            return;
1821        }
1822
1823        if (task.isResizeable() && options != null) {
1824            int stackId = options.getLaunchStackId();
1825            if (canUseActivityOptionsLaunchBounds(options, stackId)) {
1826                final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
1827                task.updateOverrideConfiguration(bounds);
1828                if (stackId == INVALID_STACK_ID) {
1829                    stackId = task.getLaunchStackId();
1830                }
1831                if (stackId != task.stack.mStackId) {
1832                    final ActivityStack stack = moveTaskToStackUncheckedLocked(
1833                            task, stackId, ON_TOP, !FORCE_FOCUS, reason);
1834                    stackId = stack.mStackId;
1835                    // moveTaskToStackUncheckedLocked() should already placed the task on top,
1836                    // still need moveTaskToFrontLocked() below for any transition settings.
1837                }
1838                if (StackId.resizeStackWithLaunchBounds(stackId)) {
1839                    resizeStackLocked(stackId, bounds,
1840                            null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
1841                            !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */);
1842                } else {
1843                    // WM resizeTask must be done after the task is moved to the correct stack,
1844                    // because Task's setBounds() also updates dim layer's bounds, but that has
1845                    // dependency on the stack.
1846                    mWindowManager.resizeTask(task.taskId, task.mBounds, task.mOverrideConfig,
1847                            false /* relayout */, false /* forced */);
1848                }
1849            }
1850        }
1851
1852        final ActivityRecord r = task.getTopActivity();
1853        task.stack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
1854                r == null ? null : r.appTimeTracker, reason);
1855
1856        if (DEBUG_STACK) Slog.d(TAG_STACK,
1857                "findTaskToMoveToFront: moved to front of stack=" + task.stack);
1858
1859        handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, task.stack.mStackId,
1860                forceNonResizeable);
1861    }
1862
1863    boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
1864        // We use the launch bounds in the activity options is the device supports freeform
1865        // window management or is launching into the pinned stack.
1866        if (options.getLaunchBounds() == null) {
1867            return false;
1868        }
1869        return (mService.mSupportsPictureInPicture && launchStackId == PINNED_STACK_ID)
1870                || mService.mSupportsFreeformWindowManagement;
1871    }
1872
1873    ActivityStack getStack(int stackId) {
1874        return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
1875    }
1876
1877    ActivityStack getStack(int stackId, boolean createStaticStackIfNeeded, boolean createOnTop) {
1878        ActivityContainer activityContainer = mActivityContainers.get(stackId);
1879        if (activityContainer != null) {
1880            return activityContainer.mStack;
1881        }
1882        if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
1883            return null;
1884        }
1885        return createStackOnDisplay(stackId, Display.DEFAULT_DISPLAY, createOnTop);
1886    }
1887
1888    ArrayList<ActivityStack> getStacks() {
1889        ArrayList<ActivityStack> allStacks = new ArrayList<>();
1890        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1891            allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
1892        }
1893        return allStacks;
1894    }
1895
1896    IBinder getHomeActivityToken() {
1897        ActivityRecord homeActivity = getHomeActivity();
1898        if (homeActivity != null) {
1899            return homeActivity.appToken;
1900        }
1901        return null;
1902    }
1903
1904    ActivityRecord getHomeActivity() {
1905        return getHomeActivityForUser(mCurrentUser);
1906    }
1907
1908    ActivityRecord getHomeActivityForUser(int userId) {
1909        final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
1910        for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
1911            final TaskRecord task = tasks.get(taskNdx);
1912            if (task.isHomeTask()) {
1913                final ArrayList<ActivityRecord> activities = task.mActivities;
1914                for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1915                    final ActivityRecord r = activities.get(activityNdx);
1916                    if (r.isHomeActivity()
1917                            && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
1918                        return r;
1919                    }
1920                }
1921            }
1922        }
1923        return null;
1924    }
1925
1926    /**
1927     * Returns if a stack should be treated as if it's docked. Returns true if the stack is
1928     * the docked stack itself, or if it's side-by-side to the docked stack.
1929     */
1930    boolean isStackDockedInEffect(int stackId) {
1931        return stackId == DOCKED_STACK_ID ||
1932                (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
1933    }
1934
1935    ActivityContainer createVirtualActivityContainer(ActivityRecord parentActivity,
1936            IActivityContainerCallback callback) {
1937        ActivityContainer activityContainer =
1938                new VirtualActivityContainer(parentActivity, callback);
1939        mActivityContainers.put(activityContainer.mStackId, activityContainer);
1940        if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS,
1941                "createActivityContainer: " + activityContainer);
1942        parentActivity.mChildContainers.add(activityContainer);
1943        return activityContainer;
1944    }
1945
1946    void removeChildActivityContainers(ActivityRecord parentActivity) {
1947        final ArrayList<ActivityContainer> childStacks = parentActivity.mChildContainers;
1948        for (int containerNdx = childStacks.size() - 1; containerNdx >= 0; --containerNdx) {
1949            ActivityContainer container = childStacks.remove(containerNdx);
1950            if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS, "removeChildActivityContainers: removing "
1951                    + container);
1952            container.release();
1953        }
1954    }
1955
1956    void deleteActivityContainer(IActivityContainer container) {
1957        ActivityContainer activityContainer = (ActivityContainer)container;
1958        if (activityContainer != null) {
1959            if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS,
1960                    "deleteActivityContainer: callers=" + Debug.getCallers(4));
1961            final int stackId = activityContainer.mStackId;
1962            mActivityContainers.remove(stackId);
1963            mWindowManager.removeStack(stackId);
1964        }
1965    }
1966
1967    void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
1968            boolean preserveWindows, boolean allowResizeInDockedMode) {
1969        if (stackId == DOCKED_STACK_ID) {
1970            resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
1971                    preserveWindows);
1972            return;
1973        }
1974        final ActivityStack stack = getStack(stackId);
1975        if (stack == null) {
1976            Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
1977            return;
1978        }
1979
1980        if (!allowResizeInDockedMode && getStack(DOCKED_STACK_ID) != null) {
1981            // If the docked stack exist we don't allow resizes of stacks not caused by the docked
1982            // stack size changing so things don't get out of sync.
1983            return;
1984        }
1985
1986        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
1987        mWindowManager.deferSurfaceLayout();
1988        try {
1989            resizeStackUncheckedLocked(stack, bounds, tempTaskBounds, tempTaskInsetBounds);
1990            ensureConfigurationAndResume(stack, stack.topRunningActivityLocked(), preserveWindows);
1991        } finally {
1992            mWindowManager.continueSurfaceLayout();
1993            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
1994        }
1995    }
1996
1997    void deferUpdateBounds(int stackId) {
1998        final ActivityStack stack = getStack(stackId);
1999        if (stack != null) {
2000            stack.deferUpdateBounds();
2001        }
2002    }
2003
2004    void continueUpdateBounds(int stackId) {
2005        final ActivityStack stack = getStack(stackId);
2006        if (stack != null) {
2007            stack.continueUpdateBounds();
2008        }
2009    }
2010
2011    void notifyAppTransitionDone() {
2012        continueUpdateBounds(HOME_STACK_ID);
2013        for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2014            final int taskId = mResizingTasksDuringAnimation.valueAt(i);
2015            if (anyTaskForIdLocked(taskId) != null) {
2016                mWindowManager.setTaskDockedResizing(taskId, false);
2017            }
2018        }
2019        mResizingTasksDuringAnimation.clear();
2020    }
2021
2022    void resizeStackUncheckedLocked(ActivityStack stack, Rect bounds, Rect tempTaskBounds,
2023            Rect tempTaskInsetBounds) {
2024        bounds = TaskRecord.validateBounds(bounds);
2025
2026        if (!stack.updateBoundsAllowed(bounds, tempTaskBounds, tempTaskInsetBounds)) {
2027            return;
2028        }
2029
2030        mTmpBounds.clear();
2031        mTmpConfigs.clear();
2032        mTmpInsetBounds.clear();
2033        final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2034        final Rect taskBounds = tempTaskBounds != null ? tempTaskBounds : bounds;
2035        final Rect insetBounds = tempTaskInsetBounds != null ? tempTaskInsetBounds : taskBounds;
2036        for (int i = tasks.size() - 1; i >= 0; i--) {
2037            final TaskRecord task = tasks.get(i);
2038            if (task.isResizeable()) {
2039                if (stack.mStackId == FREEFORM_WORKSPACE_STACK_ID) {
2040                    // For freeform stack we don't adjust the size of the tasks to match that
2041                    // of the stack, but we do try to make sure the tasks are still contained
2042                    // with the bounds of the stack.
2043                    tempRect2.set(task.mBounds);
2044                    fitWithinBounds(tempRect2, bounds);
2045                    task.updateOverrideConfiguration(tempRect2);
2046                } else {
2047                    task.updateOverrideConfiguration(taskBounds, insetBounds);
2048                }
2049            }
2050
2051            mTmpConfigs.put(task.taskId, task.mOverrideConfig);
2052            mTmpBounds.put(task.taskId, task.mBounds);
2053            if (tempTaskInsetBounds != null) {
2054                mTmpInsetBounds.put(task.taskId, tempTaskInsetBounds);
2055            }
2056        }
2057
2058        // We might trigger a configuration change. Save the current task bounds for freezing.
2059        mWindowManager.prepareFreezingTaskBounds(stack.mStackId);
2060        stack.mFullscreen = mWindowManager.resizeStack(stack.mStackId, bounds, mTmpConfigs,
2061                mTmpBounds, mTmpInsetBounds);
2062        stack.setBounds(bounds);
2063    }
2064
2065    private void ensureConfigurationAndResume(ActivityStack stack, ActivityRecord r,
2066            boolean preserveWindows) {
2067        if (r == null || !r.visible) {
2068            return;
2069        }
2070        final boolean updated = stack.ensureActivityConfigurationLocked(r, 0,
2071                preserveWindows);
2072        if (!updated) {
2073            resumeFocusedStackTopActivityLocked();
2074        }
2075    }
2076
2077    void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2078            Rect tempDockedTaskInsetBounds,
2079            Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds, boolean preserveWindows) {
2080        final ActivityStack stack = getStack(DOCKED_STACK_ID);
2081        if (stack == null) {
2082            Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2083            return;
2084        }
2085
2086        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2087        mWindowManager.deferSurfaceLayout();
2088        try {
2089            ActivityRecord r = stack.topRunningActivityLocked();
2090            resizeStackUncheckedLocked(stack, dockedBounds, tempDockedTaskBounds,
2091                    tempDockedTaskInsetBounds);
2092
2093            // TODO: Checking for isAttached might not be needed as if the user passes in null
2094            // dockedBounds then they want the docked stack to be dismissed.
2095            if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2096                // The dock stack either was dismissed or went fullscreen, which is kinda the same.
2097                // In this case we make all other static stacks fullscreen and move all
2098                // docked stack tasks to the fullscreen stack.
2099                for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2100                    if (StackId.isResizeableByDockedStack(i) && getStack(i) != null) {
2101                        resizeStackLocked(i, null, null, null, preserveWindows,
2102                                true /* allowResizeInDockedMode */);
2103                    }
2104                }
2105
2106                ArrayList<TaskRecord> tasks = stack.getAllTasks();
2107                final int count = tasks.size();
2108                for (int i = 0; i < count; i++) {
2109                    moveTaskToStackLocked(tasks.get(i).taskId,
2110                            FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP, FORCE_FOCUS, "resizeStack",
2111                            false /* animate */);
2112                }
2113
2114                // stack shouldn't contain anymore activities, so nothing to resume.
2115                r = null;
2116            } else {
2117                // Docked stacks occupy a dedicated region on screen so the size of all other
2118                // static stacks need to be adjusted so they don't overlap with the docked stack.
2119                // We get the bounds to use from window manager which has been adjusted for any
2120                // screen controls and is also the same for all stacks.
2121                mWindowManager.getStackDockedModeBounds(
2122                        HOME_STACK_ID, tempRect, true /* ignoreVisibility */);
2123                for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2124                    if (StackId.isResizeableByDockedStack(i) && getStack(i) != null) {
2125                        resizeStackLocked(i, tempRect, tempOtherTaskBounds,
2126                                tempOtherTaskInsetBounds, preserveWindows,
2127                                true /* allowResizeInDockedMode */);
2128                    }
2129                }
2130            }
2131            ensureConfigurationAndResume(stack, r, preserveWindows);
2132        } finally {
2133            mWindowManager.continueSurfaceLayout();
2134            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2135        }
2136
2137        mResizeDockedStackTimeout.notifyResizing(dockedBounds,
2138                tempDockedTaskBounds != null
2139                || tempDockedTaskInsetBounds != null
2140                || tempOtherTaskBounds != null
2141                || tempOtherTaskInsetBounds != null);
2142    }
2143
2144    void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
2145        final ActivityStack stack = getStack(PINNED_STACK_ID);
2146        if (stack == null) {
2147            Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2148            return;
2149        }
2150        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2151        mWindowManager.deferSurfaceLayout();
2152        try {
2153            ActivityRecord r = stack.topRunningActivityLocked();
2154            resizeStackUncheckedLocked(stack, pinnedBounds, tempPinnedTaskBounds,
2155                    null);
2156            ensureConfigurationAndResume(stack, r, false);
2157        } finally {
2158            mWindowManager.continueSurfaceLayout();
2159            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2160        }
2161    }
2162
2163    boolean resizeTaskLocked(TaskRecord task, Rect bounds, int resizeMode, boolean preserveWindow,
2164            boolean deferResume) {
2165        if (!task.isResizeable()) {
2166            Slog.w(TAG, "resizeTask: task " + task + " not resizeable.");
2167            return true;
2168        }
2169
2170        // If this is a forced resize, let it go through even if the bounds is not changing,
2171        // as we might need a relayout due to surface size change (to/from fullscreen).
2172        final boolean forced = (resizeMode & RESIZE_MODE_FORCED) != 0;
2173        if (Objects.equals(task.mBounds, bounds) && !forced) {
2174            // Nothing to do here...
2175            return true;
2176        }
2177        bounds = TaskRecord.validateBounds(bounds);
2178
2179        if (!mWindowManager.isValidTaskId(task.taskId)) {
2180            // Task doesn't exist in window manager yet (e.g. was restored from recents).
2181            // All we can do for now is update the bounds so it can be used when the task is
2182            // added to window manager.
2183            task.updateOverrideConfiguration(bounds);
2184            if (task.stack != null && task.stack.mStackId != FREEFORM_WORKSPACE_STACK_ID) {
2185                // re-restore the task so it can have the proper stack association.
2186                restoreRecentTaskLocked(task, FREEFORM_WORKSPACE_STACK_ID);
2187            }
2188            return true;
2189        }
2190
2191        // Do not move the task to another stack here.
2192        // This method assumes that the task is already placed in the right stack.
2193        // we do not mess with that decision and we only do the resize!
2194
2195        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeTask_" + task.taskId);
2196
2197        final Configuration overrideConfig =  task.updateOverrideConfiguration(bounds);
2198        // This variable holds information whether the configuration didn't change in a significant
2199        // way and the activity was kept the way it was. If it's false, it means the activity had
2200        // to be relaunched due to configuration change.
2201        boolean kept = true;
2202        if (overrideConfig != null) {
2203            final ActivityRecord r = task.topRunningActivityLocked();
2204            if (r != null) {
2205                final ActivityStack stack = task.stack;
2206                kept = stack.ensureActivityConfigurationLocked(r, 0, preserveWindow);
2207
2208                if (!deferResume) {
2209
2210                    // All other activities must be made visible with their correct configuration.
2211                    ensureActivitiesVisibleLocked(r, 0, !PRESERVE_WINDOWS);
2212                    if (!kept) {
2213                        resumeFocusedStackTopActivityLocked();
2214                    }
2215                }
2216            }
2217        }
2218        mWindowManager.resizeTask(task.taskId, task.mBounds, task.mOverrideConfig, kept, forced);
2219
2220        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2221        return kept;
2222    }
2223
2224    ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
2225        ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
2226        if (activityDisplay == null) {
2227            return null;
2228        }
2229
2230        ActivityContainer activityContainer = new ActivityContainer(stackId);
2231        mActivityContainers.put(stackId, activityContainer);
2232        activityContainer.attachToDisplayLocked(activityDisplay, onTop);
2233        return activityContainer.mStack;
2234    }
2235
2236    int getNextStackId() {
2237        while (true) {
2238            if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2239                    && getStack(mNextFreeStackId) == null) {
2240                break;
2241            }
2242            mNextFreeStackId++;
2243        }
2244        return mNextFreeStackId;
2245    }
2246
2247    /**
2248     * Restores a recent task to a stack
2249     * @param task The recent task to be restored.
2250     * @param stackId The stack to restore the task to (default launch stack will be used
2251     *                if stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}).
2252     * @return true if the task has been restored successfully.
2253     */
2254    private boolean restoreRecentTaskLocked(TaskRecord task, int stackId) {
2255        if (stackId == INVALID_STACK_ID) {
2256            stackId = task.getLaunchStackId();
2257        } else if (stackId == DOCKED_STACK_ID && !task.canGoInDockedStack()) {
2258            // Preferred stack is the docked stack, but the task can't go in the docked stack.
2259            // Put it in the fullscreen stack.
2260            stackId = FULLSCREEN_WORKSPACE_STACK_ID;
2261        }
2262
2263        if (task.stack != null) {
2264            // Task has already been restored once. See if we need to do anything more
2265            if (task.stack.mStackId == stackId) {
2266                // Nothing else to do since it is already restored in the right stack.
2267                return true;
2268            }
2269            // Remove current stack association, so we can re-associate the task with the
2270            // right stack below.
2271            task.stack.removeTask(task, "restoreRecentTaskLocked", MOVING);
2272        }
2273
2274        final ActivityStack stack =
2275                getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
2276
2277        if (stack == null) {
2278            // What does this mean??? Not sure how we would get here...
2279            if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2280                    "Unable to find/create stack to restore recent task=" + task);
2281            return false;
2282        }
2283
2284        stack.addTask(task, false, "restoreRecentTask");
2285        if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2286                "Added restored task=" + task + " to stack=" + stack);
2287        final ArrayList<ActivityRecord> activities = task.mActivities;
2288        for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2289            stack.addConfigOverride(activities.get(activityNdx), task);
2290        }
2291        return true;
2292    }
2293
2294    /**
2295     * Moves the specified task record to the input stack id.
2296     * WARNING: This method performs an unchecked/raw move of the task and
2297     * can leave the system in an unstable state if used incorrectly.
2298     * Use {@link #moveTaskToStackLocked} to perform safe task movement to a stack.
2299     * @param task Task to move.
2300     * @param stackId Id of stack to move task to.
2301     * @param toTop True if the task should be placed at the top of the stack.
2302     * @param forceFocus if focus should be moved to the new stack
2303     * @param reason Reason the task is been moved.
2304     * @return The stack the task was moved to.
2305     */
2306    ActivityStack moveTaskToStackUncheckedLocked(
2307            TaskRecord task, int stackId, boolean toTop, boolean forceFocus, String reason) {
2308
2309        if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
2310            throw new IllegalStateException("moveTaskToStackUncheckedLocked: Device doesn't "
2311                    + "support multi-window task=" + task + " to stackId=" + stackId);
2312        }
2313
2314        final ActivityRecord r = task.getTopActivity();
2315        final ActivityStack prevStack = task.stack;
2316        final boolean wasFocused = isFocusedStack(prevStack) && (topRunningActivityLocked() == r);
2317        final boolean wasResumed = prevStack.mResumedActivity == r;
2318        // In some cases the focused stack isn't the front stack. E.g. pinned stack.
2319        // Whenever we are moving the top activity from the front stack we want to make sure to move
2320        // the stack to the front.
2321        final boolean wasFront = isFrontStack(prevStack)
2322                && (prevStack.topRunningActivityLocked() == r);
2323
2324        if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
2325            // We don't allow moving a unresizeable task to the docked stack since the docked
2326            // stack is used for split-screen mode and will cause things like the docked divider to
2327            // show up. We instead leave the task in its current stack or move it to the fullscreen
2328            // stack if it isn't currently in a stack.
2329            stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
2330            Slog.w(TAG, "Can not move unresizeable task=" + task
2331                    + " to docked stack. Moving to stackId=" + stackId + " instead.");
2332        }
2333
2334        // Temporarily disable resizeablility of task we are moving. We don't want it to be resized
2335        // if a docked stack is created below which will lead to the stack we are moving from and
2336        // its resizeable tasks being resized.
2337        task.mTemporarilyUnresizable = true;
2338        final ActivityStack stack = getStack(stackId, CREATE_IF_NEEDED, toTop);
2339        task.mTemporarilyUnresizable = false;
2340        mWindowManager.moveTaskToStack(task.taskId, stack.mStackId, toTop);
2341        stack.addTask(task, toTop, reason);
2342
2343        // If the task had focus before (or we're requested to move focus),
2344        // move focus to the new stack by moving the stack to the front.
2345        stack.moveToFrontAndResumeStateIfNeeded(
2346                r, forceFocus || wasFocused || wasFront, wasResumed, reason);
2347
2348        return stack;
2349    }
2350
2351    boolean moveTaskToStackLocked(int taskId, int stackId, boolean toTop, boolean forceFocus,
2352            String reason, boolean animate) {
2353        return moveTaskToStackLocked(taskId, stackId, toTop, forceFocus, reason, animate,
2354                false /* deferResume */);
2355    }
2356
2357    boolean moveTaskToStackLocked(int taskId, int stackId, boolean toTop, boolean forceFocus,
2358            String reason, boolean animate, boolean deferResume) {
2359        final TaskRecord task = anyTaskForIdLocked(taskId);
2360        if (task == null) {
2361            Slog.w(TAG, "moveTaskToStack: no task for id=" + taskId);
2362            return false;
2363        }
2364
2365        if (task.stack != null && task.stack.mStackId == stackId) {
2366            // You are already in the right stack silly...
2367            Slog.i(TAG, "moveTaskToStack: taskId=" + taskId + " already in stackId=" + stackId);
2368            return true;
2369        }
2370
2371        if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
2372            throw new IllegalArgumentException("moveTaskToStack:"
2373                    + "Attempt to move task " + taskId + " to unsupported freeform stack");
2374        }
2375
2376        final ActivityRecord topActivity = task.getTopActivity();
2377        final int sourceStackId = task.stack != null ? task.stack.mStackId : INVALID_STACK_ID;
2378        final boolean mightReplaceWindow =
2379                StackId.replaceWindowsOnTaskMove(sourceStackId, stackId) && topActivity != null;
2380        if (mightReplaceWindow) {
2381            // We are about to relaunch the activity because its configuration changed due to
2382            // being maximized, i.e. size change. The activity will first remove the old window
2383            // and then add a new one. This call will tell window manager about this, so it can
2384            // preserve the old window until the new one is drawn. This prevents having a gap
2385            // between the removal and addition, in which no window is visible. We also want the
2386            // entrance of the new window to be properly animated.
2387            // Note here we always set the replacing window first, as the flags might be needed
2388            // during the relaunch. If we end up not doing any relaunch, we clear the flags later.
2389            mWindowManager.setReplacingWindow(topActivity.appToken, animate);
2390        }
2391
2392        mWindowManager.deferSurfaceLayout();
2393        final int preferredLaunchStackId = stackId;
2394        boolean kept = true;
2395        try {
2396            final ActivityStack stack = moveTaskToStackUncheckedLocked(
2397                    task, stackId, toTop, forceFocus, reason + " moveTaskToStack");
2398            stackId = stack.mStackId;
2399
2400            if (!animate) {
2401                stack.mNoAnimActivities.add(topActivity);
2402            }
2403
2404            // We might trigger a configuration change. Save the current task bounds for freezing.
2405            mWindowManager.prepareFreezingTaskBounds(stack.mStackId);
2406
2407            // Make sure the task has the appropriate bounds/size for the stack it is in.
2408            if (stackId == FULLSCREEN_WORKSPACE_STACK_ID && task.mBounds != null) {
2409                kept = resizeTaskLocked(task, stack.mBounds, RESIZE_MODE_SYSTEM,
2410                        !mightReplaceWindow, deferResume);
2411            } else if (stackId == FREEFORM_WORKSPACE_STACK_ID) {
2412                Rect bounds = task.getLaunchBounds();
2413                if (bounds == null) {
2414                    stack.layoutTaskInStack(task, null);
2415                    bounds = task.mBounds;
2416                }
2417                kept = resizeTaskLocked(task, bounds, RESIZE_MODE_FORCED, !mightReplaceWindow,
2418                        deferResume);
2419            } else if (stackId == DOCKED_STACK_ID || stackId == PINNED_STACK_ID) {
2420                kept = resizeTaskLocked(task, stack.mBounds, RESIZE_MODE_SYSTEM,
2421                        !mightReplaceWindow, deferResume);
2422            }
2423        } finally {
2424            mWindowManager.continueSurfaceLayout();
2425        }
2426
2427        if (mightReplaceWindow) {
2428            // If we didn't actual do a relaunch (indicated by kept==true meaning we kept the old
2429            // window), we need to clear the replace window settings. Otherwise, we schedule a
2430            // timeout to remove the old window if the replacing window is not coming in time.
2431            mWindowManager.scheduleClearReplacingWindowIfNeeded(topActivity.appToken, !kept);
2432        }
2433
2434        if (!deferResume) {
2435
2436            // The task might have already been running and its visibility needs to be synchronized with
2437            // the visibility of the stack / windows.
2438            ensureActivitiesVisibleLocked(null, 0, !mightReplaceWindow);
2439            resumeFocusedStackTopActivityLocked();
2440        }
2441
2442        handleNonResizableTaskIfNeeded(task, preferredLaunchStackId, stackId);
2443
2444        return (preferredLaunchStackId == stackId);
2445    }
2446
2447    boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect bounds) {
2448        final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2449        if (stack == null) {
2450            throw new IllegalArgumentException(
2451                    "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
2452        }
2453
2454        final ActivityRecord r = stack.topRunningActivityLocked();
2455        if (r == null) {
2456            Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
2457                    + " in stack=" + stack);
2458            return false;
2459        }
2460
2461        if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
2462            Slog.w(TAG,
2463                    "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
2464                            + " r=" + r);
2465            return false;
2466        }
2467
2468        moveActivityToPinnedStackLocked(r, "moveTopActivityToPinnedStack", bounds);
2469        return true;
2470    }
2471
2472    void moveActivityToPinnedStackLocked(ActivityRecord r, String reason, Rect bounds) {
2473        mWindowManager.deferSurfaceLayout();
2474        try {
2475            final TaskRecord task = r.task;
2476
2477            if (r == task.stack.getVisibleBehindActivity()) {
2478                // An activity can't be pinned and visible behind at the same time. Go ahead and
2479                // release it from been visible behind before pinning.
2480                requestVisibleBehindLocked(r, false);
2481            }
2482
2483            // Need to make sure the pinned stack exist so we can resize it below...
2484            final ActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
2485
2486            // Resize the pinned stack to match the current size of the task the activity we are
2487            // going to be moving is currently contained in. We do this to have the right starting
2488            // animation bounds for the pinned stack to the desired bounds the caller wants.
2489            resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
2490                    null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
2491                    true /* allowResizeInDockedMode */);
2492
2493            if (task.mActivities.size() == 1) {
2494                // There is only one activity in the task. So, we can just move the task over to
2495                // the stack without re-parenting the activity in a different task.
2496                if (task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE) {
2497                    // Move the home stack forward if the task we just moved to the pinned stack
2498                    // was launched from home so home should be visible behind it.
2499                    moveHomeStackToFront(reason);
2500                }
2501                moveTaskToStackLocked(
2502                        task.taskId, PINNED_STACK_ID, ON_TOP, FORCE_FOCUS, reason, !ANIMATE);
2503            } else {
2504                stack.moveActivityToStack(r);
2505            }
2506        } finally {
2507            mWindowManager.continueSurfaceLayout();
2508        }
2509
2510        // The task might have already been running and its visibility needs to be synchronized
2511        // with the visibility of the stack / windows.
2512        ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
2513        resumeFocusedStackTopActivityLocked();
2514
2515        mWindowManager.animateResizePinnedStack(bounds, -1);
2516        mService.notifyActivityPinnedLocked();
2517    }
2518
2519    void positionTaskInStackLocked(int taskId, int stackId, int position) {
2520        final TaskRecord task = anyTaskForIdLocked(taskId);
2521        if (task == null) {
2522            Slog.w(TAG, "positionTaskInStackLocked: no task for id=" + taskId);
2523            return;
2524        }
2525        final ActivityStack stack = getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
2526
2527        task.updateOverrideConfigurationForStack(stack);
2528
2529        mWindowManager.positionTaskInStack(
2530                taskId, stackId, position, task.mBounds, task.mOverrideConfig);
2531        stack.positionTask(task, position);
2532        // The task might have already been running and its visibility needs to be synchronized with
2533        // the visibility of the stack / windows.
2534        stack.ensureActivityConfigurationLocked(task.topRunningActivityLocked(), 0,
2535                !PRESERVE_WINDOWS);
2536        stack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
2537        resumeFocusedStackTopActivityLocked();
2538    }
2539
2540    ActivityRecord findTaskLocked(ActivityRecord r) {
2541        mTmpFindTaskResult.r = null;
2542        mTmpFindTaskResult.matchedByRootAffinity = false;
2543        if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
2544        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2545            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2546            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2547                final ActivityStack stack = stacks.get(stackNdx);
2548                if (!r.isApplicationActivity() && !stack.isHomeStack()) {
2549                    if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (home activity) " + stack);
2550                    continue;
2551                }
2552                if (!stack.mActivityContainer.isEligibleForNewTasks()) {
2553                    if (DEBUG_TASKS) Slog.d(TAG_TASKS,
2554                            "Skipping stack: (new task not allowed) " + stack);
2555                    continue;
2556                }
2557                stack.findTaskLocked(r, mTmpFindTaskResult);
2558                // It is possible to have task in multiple stacks with the same root affinity.
2559                // If the match we found was based on root affinity we keep on looking to see if
2560                // there is a better match in another stack. We eventually return the match based
2561                // on root affinity if we don't find a better match.
2562                if (mTmpFindTaskResult.r != null && !mTmpFindTaskResult.matchedByRootAffinity) {
2563                    return mTmpFindTaskResult.r;
2564                }
2565            }
2566        }
2567        if (DEBUG_TASKS && mTmpFindTaskResult.r == null) Slog.d(TAG_TASKS, "No task found");
2568        return mTmpFindTaskResult.r;
2569    }
2570
2571    ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
2572        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2573            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2574            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2575                final ActivityRecord ar = stacks.get(stackNdx).findActivityLocked(intent, info);
2576                if (ar != null) {
2577                    return ar;
2578                }
2579            }
2580        }
2581        return null;
2582    }
2583
2584    void goingToSleepLocked() {
2585        scheduleSleepTimeout();
2586        if (!mGoingToSleep.isHeld()) {
2587            mGoingToSleep.acquire();
2588            if (mLaunchingActivity.isHeld()) {
2589                if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
2590                    throw new IllegalStateException("Calling must be system uid");
2591                }
2592                mLaunchingActivity.release();
2593                mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
2594            }
2595        }
2596        checkReadyForSleepLocked();
2597    }
2598
2599    boolean shutdownLocked(int timeout) {
2600        goingToSleepLocked();
2601
2602        boolean timedout = false;
2603        final long endTime = System.currentTimeMillis() + timeout;
2604        while (true) {
2605            boolean cantShutdown = false;
2606            for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2607                final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2608                for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2609                    cantShutdown |= stacks.get(stackNdx).checkReadyForSleepLocked();
2610                }
2611            }
2612            if (cantShutdown) {
2613                long timeRemaining = endTime - System.currentTimeMillis();
2614                if (timeRemaining > 0) {
2615                    try {
2616                        mService.wait(timeRemaining);
2617                    } catch (InterruptedException e) {
2618                    }
2619                } else {
2620                    Slog.w(TAG, "Activity manager shutdown timed out");
2621                    timedout = true;
2622                    break;
2623                }
2624            } else {
2625                break;
2626            }
2627        }
2628
2629        // Force checkReadyForSleep to complete.
2630        mSleepTimeout = true;
2631        checkReadyForSleepLocked();
2632
2633        return timedout;
2634    }
2635
2636    void comeOutOfSleepIfNeededLocked() {
2637        removeSleepTimeouts();
2638        if (mGoingToSleep.isHeld()) {
2639            mGoingToSleep.release();
2640        }
2641        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2642            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2643            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2644                final ActivityStack stack = stacks.get(stackNdx);
2645                stack.awakeFromSleepingLocked();
2646                if (isFocusedStack(stack)) {
2647                    resumeFocusedStackTopActivityLocked();
2648                }
2649            }
2650        }
2651        mGoingToSleepActivities.clear();
2652    }
2653
2654    void activitySleptLocked(ActivityRecord r) {
2655        mGoingToSleepActivities.remove(r);
2656        checkReadyForSleepLocked();
2657    }
2658
2659    void checkReadyForSleepLocked() {
2660        if (!mService.isSleepingOrShuttingDown()) {
2661            // Do not care.
2662            return;
2663        }
2664
2665        if (!mSleepTimeout) {
2666            boolean dontSleep = false;
2667            for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2668                final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2669                for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2670                    dontSleep |= stacks.get(stackNdx).checkReadyForSleepLocked();
2671                }
2672            }
2673
2674            if (mStoppingActivities.size() > 0) {
2675                // Still need to tell some activities to stop; can't sleep yet.
2676                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to stop "
2677                        + mStoppingActivities.size() + " activities");
2678                scheduleIdleLocked();
2679                dontSleep = true;
2680            }
2681
2682            if (mGoingToSleepActivities.size() > 0) {
2683                // Still need to tell some activities to sleep; can't sleep yet.
2684                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to sleep "
2685                        + mGoingToSleepActivities.size() + " activities");
2686                dontSleep = true;
2687            }
2688
2689            if (dontSleep) {
2690                return;
2691            }
2692        }
2693
2694        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2695            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2696            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2697                stacks.get(stackNdx).goToSleep();
2698            }
2699        }
2700
2701        removeSleepTimeouts();
2702
2703        if (mGoingToSleep.isHeld()) {
2704            mGoingToSleep.release();
2705        }
2706        if (mService.mShuttingDown) {
2707            mService.notifyAll();
2708        }
2709    }
2710
2711    boolean reportResumedActivityLocked(ActivityRecord r) {
2712        final ActivityStack stack = r.task.stack;
2713        if (isFocusedStack(stack)) {
2714            mService.updateUsageStats(r, true);
2715        }
2716        if (allResumedActivitiesComplete()) {
2717            ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
2718            mWindowManager.executeAppTransition();
2719            return true;
2720        }
2721        return false;
2722    }
2723
2724    void handleAppCrashLocked(ProcessRecord app) {
2725        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2726            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2727            int stackNdx = stacks.size() - 1;
2728            while (stackNdx >= 0) {
2729                stacks.get(stackNdx).handleAppCrashLocked(app);
2730                stackNdx--;
2731            }
2732        }
2733    }
2734
2735    boolean requestVisibleBehindLocked(ActivityRecord r, boolean visible) {
2736        final ActivityStack stack = r.task.stack;
2737        if (stack == null) {
2738            if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
2739                    "requestVisibleBehind: r=" + r + " visible=" + visible + " stack is null");
2740            return false;
2741        }
2742
2743        if (visible && !StackId.activitiesCanRequestVisibleBehind(stack.mStackId)) {
2744            if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND, "requestVisibleBehind: r=" + r
2745                    + " visible=" + visible + " stackId=" + stack.mStackId
2746                    + " can't contain visible behind activities");
2747            return false;
2748        }
2749
2750        final boolean isVisible = stack.hasVisibleBehindActivity();
2751        if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
2752                "requestVisibleBehind r=" + r + " visible=" + visible + " isVisible=" + isVisible);
2753
2754        final ActivityRecord top = topRunningActivityLocked();
2755        if (top == null || top == r || (visible == isVisible)) {
2756            if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND, "requestVisibleBehind: quick return");
2757            stack.setVisibleBehindActivity(visible ? r : null);
2758            return true;
2759        }
2760
2761        // A non-top activity is reporting a visibility change.
2762        if (visible && top.fullscreen) {
2763            // Let the caller know that it can't be seen.
2764            if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
2765                    "requestVisibleBehind: returning top.fullscreen=" + top.fullscreen
2766                    + " top.state=" + top.state + " top.app=" + top.app + " top.app.thread="
2767                    + top.app.thread);
2768            return false;
2769        } else if (!visible && stack.getVisibleBehindActivity() != r) {
2770            // Only the activity set as currently visible behind should actively reset its
2771            // visible behind state.
2772            if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
2773                    "requestVisibleBehind: returning visible=" + visible
2774                    + " stack.getVisibleBehindActivity()=" + stack.getVisibleBehindActivity()
2775                    + " r=" + r);
2776            return false;
2777        }
2778
2779        stack.setVisibleBehindActivity(visible ? r : null);
2780        if (!visible) {
2781            // If there is a translucent home activity, we need to force it stop being translucent,
2782            // because we can't depend on the application to necessarily perform that operation.
2783            // Check out b/14469711 for details.
2784            final ActivityRecord next = stack.findNextTranslucentActivity(r);
2785            if (next != null && next.isHomeActivity()) {
2786                mService.convertFromTranslucent(next.appToken);
2787            }
2788        }
2789        if (top.app != null && top.app.thread != null) {
2790            // Notify the top app of the change.
2791            try {
2792                top.app.thread.scheduleBackgroundVisibleBehindChanged(top.appToken, visible);
2793            } catch (RemoteException e) {
2794            }
2795        }
2796        return true;
2797    }
2798
2799    // Called when WindowManager has finished animating the launchingBehind activity to the back.
2800    void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
2801        final TaskRecord task = r.task;
2802        final ActivityStack stack = task.stack;
2803
2804        r.mLaunchTaskBehind = false;
2805        task.setLastThumbnailLocked(stack.screenshotActivitiesLocked(r));
2806        mRecentTasks.addLocked(task);
2807        mService.notifyTaskStackChangedLocked();
2808        mWindowManager.setAppVisibility(r.appToken, false);
2809
2810        // When launching tasks behind, update the last active time of the top task after the new
2811        // task has been shown briefly
2812        final ActivityRecord top = stack.topActivity();
2813        if (top != null) {
2814            top.task.touchActiveTime();
2815        }
2816    }
2817
2818    void scheduleLaunchTaskBehindComplete(IBinder token) {
2819        mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
2820    }
2821
2822    void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
2823            boolean preserveWindows) {
2824        // First the front stacks. In case any are not fullscreen and are in front of home.
2825        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2826            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2827            final int topStackNdx = stacks.size() - 1;
2828            for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
2829                final ActivityStack stack = stacks.get(stackNdx);
2830                stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
2831            }
2832        }
2833    }
2834
2835    void invalidateTaskLayers() {
2836        mTaskLayersChanged = true;
2837    }
2838
2839    void rankTaskLayersIfNeeded() {
2840        if (!mTaskLayersChanged) {
2841            return;
2842        }
2843        mTaskLayersChanged = false;
2844        for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
2845            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2846            int baseLayer = 0;
2847            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2848                baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
2849            }
2850        }
2851    }
2852
2853    void clearOtherAppTimeTrackers(AppTimeTracker except) {
2854        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2855            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2856            final int topStackNdx = stacks.size() - 1;
2857            for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
2858                final ActivityStack stack = stacks.get(stackNdx);
2859                stack.clearOtherAppTimeTrackers(except);
2860            }
2861        }
2862    }
2863
2864    void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
2865        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2866            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2867            final int numStacks = stacks.size();
2868            for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2869                final ActivityStack stack = stacks.get(stackNdx);
2870                stack.scheduleDestroyActivities(app, reason);
2871            }
2872        }
2873    }
2874
2875    void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
2876        // Examine all activities currently running in the process.
2877        TaskRecord firstTask = null;
2878        // Tasks is non-null only if two or more tasks are found.
2879        ArraySet<TaskRecord> tasks = null;
2880        if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
2881        for (int i = 0; i < app.activities.size(); i++) {
2882            ActivityRecord r = app.activities.get(i);
2883            // First, if we find an activity that is in the process of being destroyed,
2884            // then we just aren't going to do anything for now; we want things to settle
2885            // down before we try to prune more activities.
2886            if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
2887                if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
2888                return;
2889            }
2890            // Don't consider any activies that are currently not in a state where they
2891            // can be destroyed.
2892            if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
2893                    || r.state == PAUSED || r.state == STOPPING) {
2894                if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
2895                continue;
2896            }
2897            if (r.task != null) {
2898                if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + r.task
2899                        + " from " + r);
2900                if (firstTask == null) {
2901                    firstTask = r.task;
2902                } else if (firstTask != r.task) {
2903                    if (tasks == null) {
2904                        tasks = new ArraySet<>();
2905                        tasks.add(firstTask);
2906                    }
2907                    tasks.add(r.task);
2908                }
2909            }
2910        }
2911        if (tasks == null) {
2912            if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
2913            return;
2914        }
2915        // If we have activities in multiple tasks that are in a position to be destroyed,
2916        // let's iterate through the tasks and release the oldest one.
2917        final int numDisplays = mActivityDisplays.size();
2918        for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
2919            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2920            // Step through all stacks starting from behind, to hit the oldest things first.
2921            for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
2922                final ActivityStack stack = stacks.get(stackNdx);
2923                // Try to release activities in this stack; if we manage to, we are done.
2924                if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
2925                    return;
2926                }
2927            }
2928        }
2929    }
2930
2931    boolean switchUserLocked(int userId, UserState uss) {
2932        mUserStackInFront.put(mCurrentUser, mFocusedStack.getStackId());
2933        final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
2934        mCurrentUser = userId;
2935
2936        mStartingUsers.add(uss);
2937        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2938            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2939            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2940                final ActivityStack stack = stacks.get(stackNdx);
2941                stack.switchUserLocked(userId);
2942                TaskRecord task = stack.topTask();
2943                if (task != null) {
2944                    mWindowManager.moveTaskToTop(task.taskId);
2945                }
2946            }
2947        }
2948
2949        ActivityStack stack = getStack(restoreStackId);
2950        if (stack == null) {
2951            stack = mHomeStack;
2952        }
2953        final boolean homeInFront = stack.isHomeStack();
2954        if (stack.isOnHomeDisplay()) {
2955            stack.moveToFront("switchUserOnHomeDisplay");
2956        } else {
2957            // Stack was moved to another display while user was swapped out.
2958            resumeHomeStackTask(HOME_ACTIVITY_TYPE, null, "switchUserOnOtherDisplay");
2959        }
2960        return homeInFront;
2961    }
2962
2963    /** Checks whether the userid is a profile of the current user. */
2964    boolean isCurrentProfileLocked(int userId) {
2965        if (userId == mCurrentUser) return true;
2966        return mService.mUserController.isCurrentProfileLocked(userId);
2967    }
2968
2969    /** Checks whether the activity should be shown for current user. */
2970    boolean okToShowLocked(ActivityRecord r) {
2971        return r != null && (isCurrentProfileLocked(r.userId)
2972                || (r.info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0);
2973    }
2974
2975    final ArrayList<ActivityRecord> processStoppingActivitiesLocked(boolean remove) {
2976        ArrayList<ActivityRecord> stops = null;
2977
2978        final boolean nowVisible = allResumedActivitiesVisible();
2979        for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
2980            ActivityRecord s = mStoppingActivities.get(activityNdx);
2981            final boolean waitingVisible = mWaitingVisibleActivities.contains(s);
2982            if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
2983                    + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
2984            if (waitingVisible && nowVisible) {
2985                mWaitingVisibleActivities.remove(s);
2986                if (s.finishing) {
2987                    // If this activity is finishing, it is sitting on top of
2988                    // everyone else but we now know it is no longer needed...
2989                    // so get rid of it.  Otherwise, we need to go through the
2990                    // normal flow and hide it once we determine that it is
2991                    // hidden by the activities in front of it.
2992                    if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
2993                    mWindowManager.setAppVisibility(s.appToken, false);
2994                }
2995            }
2996            if ((!waitingVisible || mService.isSleepingOrShuttingDown()) && remove) {
2997                if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
2998                if (stops == null) {
2999                    stops = new ArrayList<>();
3000                }
3001                stops.add(s);
3002                mStoppingActivities.remove(activityNdx);
3003            }
3004        }
3005
3006        return stops;
3007    }
3008
3009    void validateTopActivitiesLocked() {
3010        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3011            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3012            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3013                final ActivityStack stack = stacks.get(stackNdx);
3014                final ActivityRecord r = stack.topRunningActivityLocked();
3015                final ActivityState state = r == null ? DESTROYED : r.state;
3016                if (isFocusedStack(stack)) {
3017                    if (r == null) Slog.e(TAG,
3018                            "validateTop...: null top activity, stack=" + stack);
3019                    else {
3020                        final ActivityRecord pausing = stack.mPausingActivity;
3021                        if (pausing != null && pausing == r) Slog.e(TAG,
3022                                "validateTop...: top stack has pausing activity r=" + r
3023                                + " state=" + state);
3024                        if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3025                                "validateTop...: activity in front not resumed r=" + r
3026                                + " state=" + state);
3027                    }
3028                } else {
3029                    final ActivityRecord resumed = stack.mResumedActivity;
3030                    if (resumed != null && resumed == r) Slog.e(TAG,
3031                            "validateTop...: back stack has resumed activity r=" + r
3032                            + " state=" + state);
3033                    if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3034                            "validateTop...: activity in back resumed r=" + r + " state=" + state);
3035                }
3036            }
3037        }
3038    }
3039
3040    private String lockTaskModeToString() {
3041        switch (mLockTaskModeState) {
3042            case LOCK_TASK_MODE_LOCKED:
3043                return "LOCKED";
3044            case LOCK_TASK_MODE_PINNED:
3045                return "PINNED";
3046            case LOCK_TASK_MODE_NONE:
3047                return "NONE";
3048            default: return "unknown=" + mLockTaskModeState;
3049        }
3050    }
3051
3052    public void dump(PrintWriter pw, String prefix) {
3053        pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
3054                pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
3055        pw.print(prefix); pw.println("mSleepTimeout=" + mSleepTimeout);
3056        pw.print(prefix);
3057        pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
3058        pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
3059        pw.print(prefix); pw.println("mActivityContainers=" + mActivityContainers);
3060        pw.print(prefix); pw.print("mLockTaskModeState=" + lockTaskModeToString());
3061                final SparseArray<String[]> packages = mService.mLockTaskPackages;
3062                if (packages.size() > 0) {
3063                    pw.println(" mLockTaskPackages (userId:packages)=");
3064                    for (int i = 0; i < packages.size(); ++i) {
3065                        pw.print(prefix); pw.print(prefix); pw.print(packages.keyAt(i));
3066                        pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
3067                    }
3068                }
3069                pw.println(" mLockTaskModeTasks" + mLockTaskModeTasks);
3070    }
3071
3072    ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
3073        return mFocusedStack.getDumpActivitiesLocked(name);
3074    }
3075
3076    static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3077            boolean needSep, String prefix) {
3078        if (activity != null) {
3079            if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3080                if (needSep) {
3081                    pw.println();
3082                }
3083                pw.print(prefix);
3084                pw.println(activity);
3085                return true;
3086            }
3087        }
3088        return false;
3089    }
3090
3091    boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3092            boolean dumpClient, String dumpPackage) {
3093        boolean printed = false;
3094        boolean needSep = false;
3095        for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3096            ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
3097            pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
3098                    pw.println(" (activities from top to bottom):");
3099            ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3100            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3101                final ActivityStack stack = stacks.get(stackNdx);
3102                StringBuilder stackHeader = new StringBuilder(128);
3103                stackHeader.append("  Stack #");
3104                stackHeader.append(stack.mStackId);
3105                stackHeader.append(":");
3106                stackHeader.append("\n");
3107                stackHeader.append("  mFullscreen=" + stack.mFullscreen);
3108                stackHeader.append("\n");
3109                stackHeader.append("  mBounds=" + stack.mBounds);
3110                printed |= stack.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, dumpPackage,
3111                        needSep, stackHeader.toString());
3112                printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, "    ", "Run", false,
3113                        !dumpAll, false, dumpPackage, true,
3114                        "    Running activities (most recent first):", null);
3115
3116                needSep = printed;
3117                boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3118                        "    mPausingActivity: ");
3119                if (pr) {
3120                    printed = true;
3121                    needSep = false;
3122                }
3123                pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3124                        "    mResumedActivity: ");
3125                if (pr) {
3126                    printed = true;
3127                    needSep = false;
3128                }
3129                if (dumpAll) {
3130                    pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3131                            "    mLastPausedActivity: ");
3132                    if (pr) {
3133                        printed = true;
3134                        needSep = true;
3135                    }
3136                    printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3137                            needSep, "    mLastNoHistoryActivity: ");
3138                }
3139                needSep = printed;
3140            }
3141        }
3142
3143        printed |= dumpHistoryList(fd, pw, mFinishingActivities, "  ", "Fin", false, !dumpAll,
3144                false, dumpPackage, true, "  Activities waiting to finish:", null);
3145        printed |= dumpHistoryList(fd, pw, mStoppingActivities, "  ", "Stop", false, !dumpAll,
3146                false, dumpPackage, true, "  Activities waiting to stop:", null);
3147        printed |= dumpHistoryList(fd, pw, mWaitingVisibleActivities, "  ", "Wait", false, !dumpAll,
3148                false, dumpPackage, true, "  Activities waiting for another to become visible:",
3149                null);
3150        printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, "  ", "Sleep", false, !dumpAll,
3151                false, dumpPackage, true, "  Activities waiting to sleep:", null);
3152        printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, "  ", "Sleep", false, !dumpAll,
3153                false, dumpPackage, true, "  Activities waiting to sleep:", null);
3154
3155        return printed;
3156    }
3157
3158    static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
3159            String prefix, String label, boolean complete, boolean brief, boolean client,
3160            String dumpPackage, boolean needNL, String header1, String header2) {
3161        TaskRecord lastTask = null;
3162        String innerPrefix = null;
3163        String[] args = null;
3164        boolean printed = false;
3165        for (int i=list.size()-1; i>=0; i--) {
3166            final ActivityRecord r = list.get(i);
3167            if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3168                continue;
3169            }
3170            if (innerPrefix == null) {
3171                innerPrefix = prefix + "      ";
3172                args = new String[0];
3173            }
3174            printed = true;
3175            final boolean full = !brief && (complete || !r.isInHistory());
3176            if (needNL) {
3177                pw.println("");
3178                needNL = false;
3179            }
3180            if (header1 != null) {
3181                pw.println(header1);
3182                header1 = null;
3183            }
3184            if (header2 != null) {
3185                pw.println(header2);
3186                header2 = null;
3187            }
3188            if (lastTask != r.task) {
3189                lastTask = r.task;
3190                pw.print(prefix);
3191                pw.print(full ? "* " : "  ");
3192                pw.println(lastTask);
3193                if (full) {
3194                    lastTask.dump(pw, prefix + "  ");
3195                } else if (complete) {
3196                    // Complete + brief == give a summary.  Isn't that obvious?!?
3197                    if (lastTask.intent != null) {
3198                        pw.print(prefix); pw.print("  ");
3199                                pw.println(lastTask.intent.toInsecureStringWithClip());
3200                    }
3201                }
3202            }
3203            pw.print(prefix); pw.print(full ? "  * " : "    "); pw.print(label);
3204            pw.print(" #"); pw.print(i); pw.print(": ");
3205            pw.println(r);
3206            if (full) {
3207                r.dump(pw, innerPrefix);
3208            } else if (complete) {
3209                // Complete + brief == give a summary.  Isn't that obvious?!?
3210                pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3211                if (r.app != null) {
3212                    pw.print(innerPrefix); pw.println(r.app);
3213                }
3214            }
3215            if (client && r.app != null && r.app.thread != null) {
3216                // flush anything that is already in the PrintWriter since the thread is going
3217                // to write to the file descriptor directly
3218                pw.flush();
3219                try {
3220                    TransferPipe tp = new TransferPipe();
3221                    try {
3222                        r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
3223                                r.appToken, innerPrefix, args);
3224                        // Short timeout, since blocking here can
3225                        // deadlock with the application.
3226                        tp.go(fd, 2000);
3227                    } finally {
3228                        tp.kill();
3229                    }
3230                } catch (IOException e) {
3231                    pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3232                } catch (RemoteException e) {
3233                    pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3234                }
3235                needNL = true;
3236            }
3237        }
3238        return printed;
3239    }
3240
3241    void scheduleIdleTimeoutLocked(ActivityRecord next) {
3242        if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3243                "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
3244        Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
3245        mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
3246    }
3247
3248    final void scheduleIdleLocked() {
3249        mHandler.sendEmptyMessage(IDLE_NOW_MSG);
3250    }
3251
3252    void removeTimeoutsForActivityLocked(ActivityRecord r) {
3253        if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
3254                + Debug.getCallers(4));
3255        mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3256    }
3257
3258    final void scheduleResumeTopActivities() {
3259        if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
3260            mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
3261        }
3262    }
3263
3264    void removeSleepTimeouts() {
3265        mSleepTimeout = false;
3266        mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
3267    }
3268
3269    final void scheduleSleepTimeout() {
3270        removeSleepTimeouts();
3271        mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
3272    }
3273
3274    @Override
3275    public void onDisplayAdded(int displayId) {
3276        if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
3277        mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
3278    }
3279
3280    @Override
3281    public void onDisplayRemoved(int displayId) {
3282        if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
3283        mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
3284    }
3285
3286    @Override
3287    public void onDisplayChanged(int displayId) {
3288        if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
3289        mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
3290    }
3291
3292    private void handleDisplayAdded(int displayId) {
3293        boolean newDisplay;
3294        synchronized (mService) {
3295            newDisplay = mActivityDisplays.get(displayId) == null;
3296            if (newDisplay) {
3297                ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
3298                if (activityDisplay.mDisplay == null) {
3299                    Slog.w(TAG, "Display " + displayId + " gone before initialization complete");
3300                    return;
3301                }
3302                mActivityDisplays.put(displayId, activityDisplay);
3303                calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
3304            }
3305        }
3306        if (newDisplay) {
3307            mWindowManager.onDisplayAdded(displayId);
3308        }
3309    }
3310
3311    private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
3312        mDefaultMinimalSizeOfResizeableTask =
3313                mService.mContext.getResources().getDimensionPixelSize(
3314                        com.android.internal.R.dimen.default_minimal_size_resizable_task);
3315    }
3316
3317    private void handleDisplayRemoved(int displayId) {
3318        synchronized (mService) {
3319            ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3320            if (activityDisplay != null) {
3321                ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3322                for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3323                    stacks.get(stackNdx).mActivityContainer.detachLocked();
3324                }
3325                mActivityDisplays.remove(displayId);
3326            }
3327        }
3328        mWindowManager.onDisplayRemoved(displayId);
3329    }
3330
3331    private void handleDisplayChanged(int displayId) {
3332        synchronized (mService) {
3333            ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3334            if (activityDisplay != null) {
3335                // TODO: Update the bounds.
3336            }
3337        }
3338        mWindowManager.onDisplayChanged(displayId);
3339    }
3340
3341    private StackInfo getStackInfoLocked(ActivityStack stack) {
3342        StackInfo info = new StackInfo();
3343        mWindowManager.getStackBounds(stack.mStackId, info.bounds);
3344        info.displayId = Display.DEFAULT_DISPLAY;
3345        info.stackId = stack.mStackId;
3346        info.userId = stack.mCurrentUser;
3347
3348        ArrayList<TaskRecord> tasks = stack.getAllTasks();
3349        final int numTasks = tasks.size();
3350        int[] taskIds = new int[numTasks];
3351        String[] taskNames = new String[numTasks];
3352        Rect[] taskBounds = new Rect[numTasks];
3353        int[] taskUserIds = new int[numTasks];
3354        for (int i = 0; i < numTasks; ++i) {
3355            final TaskRecord task = tasks.get(i);
3356            taskIds[i] = task.taskId;
3357            taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
3358                    : task.realActivity != null ? task.realActivity.flattenToString()
3359                    : task.getTopActivity() != null ? task.getTopActivity().packageName
3360                    : "unknown";
3361            taskBounds[i] = new Rect();
3362            mWindowManager.getTaskBounds(task.taskId, taskBounds[i]);
3363            taskUserIds[i] = task.userId;
3364        }
3365        info.taskIds = taskIds;
3366        info.taskNames = taskNames;
3367        info.taskBounds = taskBounds;
3368        info.taskUserIds = taskUserIds;
3369        return info;
3370    }
3371
3372    StackInfo getStackInfoLocked(int stackId) {
3373        ActivityStack stack = getStack(stackId);
3374        if (stack != null) {
3375            return getStackInfoLocked(stack);
3376        }
3377        return null;
3378    }
3379
3380    ArrayList<StackInfo> getAllStackInfosLocked() {
3381        ArrayList<StackInfo> list = new ArrayList<>();
3382        for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3383            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3384            for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
3385                list.add(getStackInfoLocked(stacks.get(ndx)));
3386            }
3387        }
3388        return list;
3389    }
3390
3391    TaskRecord getLockedTaskLocked() {
3392        final int top = mLockTaskModeTasks.size() - 1;
3393        if (top >= 0) {
3394            return mLockTaskModeTasks.get(top);
3395        }
3396        return null;
3397    }
3398
3399    boolean isLockedTask(TaskRecord task) {
3400        return mLockTaskModeTasks.contains(task);
3401    }
3402
3403    boolean isLastLockedTask(TaskRecord task) {
3404        return mLockTaskModeTasks.size() == 1 && mLockTaskModeTasks.contains(task);
3405    }
3406
3407    void removeLockedTaskLocked(final TaskRecord task) {
3408        if (!mLockTaskModeTasks.remove(task)) {
3409            return;
3410        }
3411        if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "removeLockedTaskLocked: removed " + task);
3412        if (mLockTaskModeTasks.isEmpty()) {
3413            // Last one.
3414            if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
3415                    " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
3416            final Message lockTaskMsg = Message.obtain();
3417            lockTaskMsg.arg1 = task.userId;
3418            lockTaskMsg.what = LOCK_TASK_END_MSG;
3419            mHandler.sendMessage(lockTaskMsg);
3420        }
3421    }
3422
3423    void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId, int actualStackId) {
3424        handleNonResizableTaskIfNeeded(task, preferredStackId, actualStackId,
3425                false /* forceNonResizable */);
3426    }
3427
3428    void handleNonResizableTaskIfNeeded(
3429            TaskRecord task, int preferredStackId, int actualStackId, boolean forceNonResizable) {
3430        if ((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
3431                || task.isHomeTask()) {
3432            return;
3433        }
3434
3435        if (!task.canGoInDockedStack() || forceNonResizable) {
3436            // Display a warning toast that we tried to put a non-dockable task in the docked stack.
3437            mService.mHandler.sendEmptyMessage(NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG);
3438
3439            // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
3440            // we need to move it to top of fullscreen stack, otherwise it will be covered.
3441            mService.moveTasksToFullscreenStack(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
3442        } else if (task.mResizeMode == RESIZE_MODE_FORCE_RESIZEABLE) {
3443            String packageName = task.getTopActivity() != null
3444                    ? task.getTopActivity().appInfo.packageName : null;
3445            mService.mHandler.obtainMessage(NOTIFY_FORCED_RESIZABLE_MSG, task.taskId, 0,
3446                    packageName).sendToTarget();
3447        }
3448    }
3449
3450    void showLockTaskToast() {
3451        mLockTaskNotify.showToast(mLockTaskModeState);
3452    }
3453
3454    void showLockTaskEscapeMessageLocked(TaskRecord task) {
3455        if (mLockTaskModeTasks.contains(task)) {
3456            mHandler.sendEmptyMessage(SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG);
3457        }
3458    }
3459
3460    void setLockTaskModeLocked(TaskRecord task, int lockTaskModeState, String reason,
3461            boolean andResume) {
3462        if (task == null) {
3463            // Take out of lock task mode if necessary
3464            final TaskRecord lockedTask = getLockedTaskLocked();
3465            if (lockedTask != null) {
3466                removeLockedTaskLocked(lockedTask);
3467                if (!mLockTaskModeTasks.isEmpty()) {
3468                    // There are locked tasks remaining, can only finish this task, not unlock it.
3469                    if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
3470                            "setLockTaskModeLocked: Tasks remaining, can't unlock");
3471                    lockedTask.performClearTaskLocked();
3472                    resumeFocusedStackTopActivityLocked();
3473                    return;
3474                }
3475            }
3476            if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
3477                    "setLockTaskModeLocked: No tasks to unlock. Callers=" + Debug.getCallers(4));
3478            return;
3479        }
3480
3481        // Should have already been checked, but do it again.
3482        if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
3483            if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
3484                    "setLockTaskModeLocked: Can't lock due to auth");
3485            return;
3486        }
3487        if (isLockTaskModeViolation(task)) {
3488            Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
3489            return;
3490        }
3491
3492        if (mLockTaskModeTasks.isEmpty()) {
3493            // First locktask.
3494            final Message lockTaskMsg = Message.obtain();
3495            lockTaskMsg.obj = task.intent.getComponent().getPackageName();
3496            lockTaskMsg.arg1 = task.userId;
3497            lockTaskMsg.what = LOCK_TASK_START_MSG;
3498            lockTaskMsg.arg2 = lockTaskModeState;
3499            mHandler.sendMessage(lockTaskMsg);
3500        }
3501        // Add it or move it to the top.
3502        if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskModeLocked: Locking to " + task +
3503                " Callers=" + Debug.getCallers(4));
3504        mLockTaskModeTasks.remove(task);
3505        mLockTaskModeTasks.add(task);
3506
3507        if (task.mLockTaskUid == -1) {
3508            task.mLockTaskUid = task.effectiveUid;
3509        }
3510
3511        if (andResume) {
3512            findTaskToMoveToFrontLocked(task, 0, null, reason,
3513                    lockTaskModeState != LOCK_TASK_MODE_NONE);
3514            resumeFocusedStackTopActivityLocked();
3515        } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
3516            handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, task.stack.mStackId,
3517                    true /* forceNonResizable */);
3518        }
3519    }
3520
3521    boolean isLockTaskModeViolation(TaskRecord task) {
3522        return isLockTaskModeViolation(task, false);
3523    }
3524
3525    boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) {
3526        if (getLockedTaskLocked() == task && !isNewClearTask) {
3527            return false;
3528        }
3529        final int lockTaskAuth = task.mLockTaskAuth;
3530        switch (lockTaskAuth) {
3531            case LOCK_TASK_AUTH_DONT_LOCK:
3532                return !mLockTaskModeTasks.isEmpty();
3533            case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
3534            case LOCK_TASK_AUTH_LAUNCHABLE:
3535            case LOCK_TASK_AUTH_WHITELISTED:
3536                return false;
3537            case LOCK_TASK_AUTH_PINNABLE:
3538                // Pinnable tasks can't be launched on top of locktask tasks.
3539                return !mLockTaskModeTasks.isEmpty();
3540            default:
3541                Slog.w(TAG, "isLockTaskModeViolation: invalid lockTaskAuth value=" + lockTaskAuth);
3542                return true;
3543        }
3544    }
3545
3546    void onLockTaskPackagesUpdatedLocked() {
3547        boolean didSomething = false;
3548        for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
3549            final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx);
3550            final boolean wasWhitelisted =
3551                    (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
3552                    (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
3553            lockedTask.setLockTaskAuth();
3554            final boolean isWhitelisted =
3555                    (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
3556                    (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
3557            if (wasWhitelisted && !isWhitelisted) {
3558                // Lost whitelisting authorization. End it now.
3559                if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "onLockTaskPackagesUpdated: removing " +
3560                        lockedTask + " mLockTaskAuth=" + lockedTask.lockTaskAuthToString());
3561                removeLockedTaskLocked(lockedTask);
3562                lockedTask.performClearTaskLocked();
3563                didSomething = true;
3564            }
3565        }
3566        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3567            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3568            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3569                final ActivityStack stack = stacks.get(stackNdx);
3570                stack.onLockTaskPackagesUpdatedLocked();
3571            }
3572        }
3573        final ActivityRecord r = topRunningActivityLocked();
3574        final TaskRecord task = r != null ? r.task : null;
3575        if (mLockTaskModeTasks.isEmpty() && task != null
3576                && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
3577            // This task must have just been authorized.
3578            if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK,
3579                    "onLockTaskPackagesUpdated: starting new locktask task=" + task);
3580            setLockTaskModeLocked(task, ActivityManager.LOCK_TASK_MODE_LOCKED, "package updated",
3581                    false);
3582            didSomething = true;
3583        }
3584        if (didSomething) {
3585            resumeFocusedStackTopActivityLocked();
3586        }
3587    }
3588
3589    int getLockTaskModeState() {
3590        return mLockTaskModeState;
3591    }
3592
3593    void activityRelaunchedLocked(IBinder token) {
3594        mWindowManager.notifyAppRelaunchingFinished(token);
3595    }
3596
3597    void activityRelaunchingLocked(ActivityRecord r) {
3598        mWindowManager.notifyAppRelaunching(r.appToken);
3599    }
3600
3601    void logStackState() {
3602        mActivityMetricsLogger.logWindowState();
3603    }
3604
3605    void scheduleReportMultiWindowModeChanged(TaskRecord task) {
3606        for (int i = task.mActivities.size() - 1; i >= 0; i--) {
3607            final ActivityRecord r = task.mActivities.get(i);
3608            if (r.app != null && r.app.thread != null) {
3609                mMultiWindowModeChangedActivities.add(r);
3610            }
3611        }
3612
3613        if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
3614            mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
3615        }
3616    }
3617
3618    void scheduleReportPictureInPictureModeChangedIfNeeded(TaskRecord task, ActivityStack prevStack) {
3619        final ActivityStack stack = task.stack;
3620        if (prevStack == null || prevStack == stack
3621                || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
3622            return;
3623        }
3624
3625        for (int i = task.mActivities.size() - 1; i >= 0; i--) {
3626            final ActivityRecord r = task.mActivities.get(i);
3627            if (r.app != null && r.app.thread != null) {
3628                mPipModeChangedActivities.add(r);
3629            }
3630        }
3631
3632        if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
3633            mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
3634        }
3635    }
3636
3637    void setDockedStackMinimized(boolean minimized) {
3638        mIsDockMinimized = minimized;
3639        if (minimized) {
3640            // Docked stack is not visible, no need to confirm credentials for its top activity.
3641            return;
3642        }
3643        final ActivityStack dockedStack = getStack(StackId.DOCKED_STACK_ID);
3644        if (dockedStack == null) {
3645            return;
3646        }
3647        final ActivityRecord top = dockedStack.topRunningActivityLocked();
3648        if (top != null && mService.mUserController.shouldConfirmCredentials(top.userId)) {
3649            mService.mActivityStarter.showConfirmDeviceCredential(top.userId);
3650        }
3651    }
3652
3653    private final class ActivityStackSupervisorHandler extends Handler {
3654
3655        public ActivityStackSupervisorHandler(Looper looper) {
3656            super(looper);
3657        }
3658
3659        void activityIdleInternal(ActivityRecord r) {
3660            synchronized (mService) {
3661                activityIdleInternalLocked(r != null ? r.appToken : null, true, null);
3662            }
3663        }
3664
3665        @Override
3666        public void handleMessage(Message msg) {
3667            switch (msg.what) {
3668                case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
3669                    synchronized (mService) {
3670                        for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
3671                            final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
3672                            r.scheduleMultiWindowModeChanged();
3673                        }
3674                    }
3675                } break;
3676                case REPORT_PIP_MODE_CHANGED_MSG: {
3677                    synchronized (mService) {
3678                        for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
3679                            final ActivityRecord r = mPipModeChangedActivities.remove(i);
3680                            r.schedulePictureInPictureModeChanged();
3681                        }
3682                    }
3683                } break;
3684                case IDLE_TIMEOUT_MSG: {
3685                    if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3686                            "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
3687                    if (mService.mDidDexOpt) {
3688                        mService.mDidDexOpt = false;
3689                        Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
3690                        nmsg.obj = msg.obj;
3691                        mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
3692                        return;
3693                    }
3694                    // We don't at this point know if the activity is fullscreen,
3695                    // so we need to be conservative and assume it isn't.
3696                    activityIdleInternal((ActivityRecord)msg.obj);
3697                } break;
3698                case IDLE_NOW_MSG: {
3699                    if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
3700                    activityIdleInternal((ActivityRecord)msg.obj);
3701                } break;
3702                case RESUME_TOP_ACTIVITY_MSG: {
3703                    synchronized (mService) {
3704                        resumeFocusedStackTopActivityLocked();
3705                    }
3706                } break;
3707                case SLEEP_TIMEOUT_MSG: {
3708                    synchronized (mService) {
3709                        if (mService.isSleepingOrShuttingDown()) {
3710                            Slog.w(TAG, "Sleep timeout!  Sleeping now.");
3711                            mSleepTimeout = true;
3712                            checkReadyForSleepLocked();
3713                        }
3714                    }
3715                } break;
3716                case LAUNCH_TIMEOUT_MSG: {
3717                    if (mService.mDidDexOpt) {
3718                        mService.mDidDexOpt = false;
3719                        mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
3720                        return;
3721                    }
3722                    synchronized (mService) {
3723                        if (mLaunchingActivity.isHeld()) {
3724                            Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
3725                            if (VALIDATE_WAKE_LOCK_CALLER
3726                                    && Binder.getCallingUid() != Process.myUid()) {
3727                                throw new IllegalStateException("Calling must be system uid");
3728                            }
3729                            mLaunchingActivity.release();
3730                        }
3731                    }
3732                } break;
3733                case HANDLE_DISPLAY_ADDED: {
3734                    handleDisplayAdded(msg.arg1);
3735                } break;
3736                case HANDLE_DISPLAY_CHANGED: {
3737                    handleDisplayChanged(msg.arg1);
3738                } break;
3739                case HANDLE_DISPLAY_REMOVED: {
3740                    handleDisplayRemoved(msg.arg1);
3741                } break;
3742                case CONTAINER_CALLBACK_VISIBILITY: {
3743                    final ActivityContainer container = (ActivityContainer) msg.obj;
3744                    final IActivityContainerCallback callback = container.mCallback;
3745                    if (callback != null) {
3746                        try {
3747                            callback.setVisible(container.asBinder(), msg.arg1 == 1);
3748                        } catch (RemoteException e) {
3749                        }
3750                    }
3751                } break;
3752                case LOCK_TASK_START_MSG: {
3753                    // When lock task starts, we disable the status bars.
3754                    try {
3755                        if (mLockTaskNotify == null) {
3756                            mLockTaskNotify = new LockTaskNotify(mService.mContext);
3757                        }
3758                        mLockTaskNotify.show(true);
3759                        mLockTaskModeState = msg.arg2;
3760                        if (getStatusBarService() != null) {
3761                            int flags = 0;
3762                            if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
3763                                flags = StatusBarManager.DISABLE_MASK
3764                                        & (~StatusBarManager.DISABLE_BACK);
3765                            } else if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
3766                                flags = StatusBarManager.DISABLE_MASK
3767                                        & (~StatusBarManager.DISABLE_BACK)
3768                                        & (~StatusBarManager.DISABLE_HOME)
3769                                        & (~StatusBarManager.DISABLE_RECENT);
3770                            }
3771                            getStatusBarService().disable(flags, mToken,
3772                                    mService.mContext.getPackageName());
3773                        }
3774                        mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
3775                        if (getDevicePolicyManager() != null) {
3776                            getDevicePolicyManager().notifyLockTaskModeChanged(true,
3777                                    (String)msg.obj, msg.arg1);
3778                        }
3779                    } catch (RemoteException ex) {
3780                        throw new RuntimeException(ex);
3781                    }
3782                } break;
3783                case LOCK_TASK_END_MSG: {
3784                    // When lock task ends, we enable the status bars.
3785                    try {
3786                        if (getStatusBarService() != null) {
3787                            getStatusBarService().disable(StatusBarManager.DISABLE_NONE, mToken,
3788                                    mService.mContext.getPackageName());
3789                        }
3790                        mWindowManager.reenableKeyguard(mToken);
3791                        if (getDevicePolicyManager() != null) {
3792                            getDevicePolicyManager().notifyLockTaskModeChanged(false, null,
3793                                    msg.arg1);
3794                        }
3795                        if (mLockTaskNotify == null) {
3796                            mLockTaskNotify = new LockTaskNotify(mService.mContext);
3797                        }
3798                        mLockTaskNotify.show(false);
3799                        try {
3800                            boolean shouldLockKeyguard = Settings.Secure.getInt(
3801                                    mService.mContext.getContentResolver(),
3802                                    Settings.Secure.LOCK_TO_APP_EXIT_LOCKED) != 0;
3803                            if (mLockTaskModeState == LOCK_TASK_MODE_PINNED && shouldLockKeyguard) {
3804                                mWindowManager.lockNow(null);
3805                                mWindowManager.dismissKeyguard();
3806                                new LockPatternUtils(mService.mContext)
3807                                        .requireCredentialEntry(UserHandle.USER_ALL);
3808                            }
3809                        } catch (SettingNotFoundException e) {
3810                            // No setting, don't lock.
3811                        }
3812                    } catch (RemoteException ex) {
3813                        throw new RuntimeException(ex);
3814                    } finally {
3815                        mLockTaskModeState = LOCK_TASK_MODE_NONE;
3816                    }
3817                } break;
3818                case SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG: {
3819                    if (mLockTaskNotify == null) {
3820                        mLockTaskNotify = new LockTaskNotify(mService.mContext);
3821                    }
3822                    mLockTaskNotify.showToast(LOCK_TASK_MODE_PINNED);
3823                } break;
3824                case CONTAINER_CALLBACK_TASK_LIST_EMPTY: {
3825                    final ActivityContainer container = (ActivityContainer) msg.obj;
3826                    final IActivityContainerCallback callback = container.mCallback;
3827                    if (callback != null) {
3828                        try {
3829                            callback.onAllActivitiesComplete(container.asBinder());
3830                        } catch (RemoteException e) {
3831                        }
3832                    }
3833                } break;
3834                case LAUNCH_TASK_BEHIND_COMPLETE: {
3835                    synchronized (mService) {
3836                        ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
3837                        if (r != null) {
3838                            handleLaunchTaskBehindCompleteLocked(r);
3839                        }
3840                    }
3841                } break;
3842
3843            }
3844        }
3845    }
3846
3847    class ActivityContainer extends android.app.IActivityContainer.Stub {
3848        final static int FORCE_NEW_TASK_FLAGS = FLAG_ACTIVITY_NEW_TASK |
3849                FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION;
3850        final int mStackId;
3851        IActivityContainerCallback mCallback = null;
3852        final ActivityStack mStack;
3853        ActivityRecord mParentActivity = null;
3854        String mIdString;
3855
3856        boolean mVisible = true;
3857
3858        /** Display this ActivityStack is currently on. Null if not attached to a Display. */
3859        ActivityDisplay mActivityDisplay;
3860
3861        final static int CONTAINER_STATE_HAS_SURFACE = 0;
3862        final static int CONTAINER_STATE_NO_SURFACE = 1;
3863        final static int CONTAINER_STATE_FINISHING = 2;
3864        int mContainerState = CONTAINER_STATE_HAS_SURFACE;
3865
3866        ActivityContainer(int stackId) {
3867            synchronized (mService) {
3868                mStackId = stackId;
3869                mStack = new ActivityStack(this, mRecentTasks);
3870                mIdString = "ActivtyContainer{" + mStackId + "}";
3871                if (DEBUG_STACK) Slog.d(TAG_STACK, "Creating " + this);
3872            }
3873        }
3874
3875        void attachToDisplayLocked(ActivityDisplay activityDisplay, boolean onTop) {
3876            if (DEBUG_STACK) Slog.d(TAG_STACK, "attachToDisplayLocked: " + this
3877                    + " to display=" + activityDisplay + " onTop=" + onTop);
3878            mActivityDisplay = activityDisplay;
3879            mStack.attachDisplay(activityDisplay, onTop);
3880            activityDisplay.attachActivities(mStack, onTop);
3881        }
3882
3883        @Override
3884        public void attachToDisplay(int displayId) {
3885            synchronized (mService) {
3886                ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3887                if (activityDisplay == null) {
3888                    return;
3889                }
3890                attachToDisplayLocked(activityDisplay, true);
3891            }
3892        }
3893
3894        @Override
3895        public int getDisplayId() {
3896            synchronized (mService) {
3897                if (mActivityDisplay != null) {
3898                    return mActivityDisplay.mDisplayId;
3899                }
3900            }
3901            return -1;
3902        }
3903
3904        @Override
3905        public int getStackId() {
3906            synchronized (mService) {
3907                return mStackId;
3908            }
3909        }
3910
3911        @Override
3912        public boolean injectEvent(InputEvent event) {
3913            final long origId = Binder.clearCallingIdentity();
3914            try {
3915                synchronized (mService) {
3916                    if (mActivityDisplay != null) {
3917                        return mInputManagerInternal.injectInputEvent(event,
3918                                mActivityDisplay.mDisplayId,
3919                                InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
3920                    }
3921                }
3922                return false;
3923            } finally {
3924                Binder.restoreCallingIdentity(origId);
3925            }
3926        }
3927
3928        @Override
3929        public void release() {
3930            synchronized (mService) {
3931                if (mContainerState == CONTAINER_STATE_FINISHING) {
3932                    return;
3933                }
3934                mContainerState = CONTAINER_STATE_FINISHING;
3935
3936                long origId = Binder.clearCallingIdentity();
3937                try {
3938                    mStack.finishAllActivitiesLocked(false);
3939                    mService.mActivityStarter.removePendingActivityLaunchesLocked(mStack);
3940                } finally {
3941                    Binder.restoreCallingIdentity(origId);
3942                }
3943            }
3944        }
3945
3946        protected void detachLocked() {
3947            if (DEBUG_STACK) Slog.d(TAG_STACK, "detachLocked: " + this + " from display="
3948                    + mActivityDisplay + " Callers=" + Debug.getCallers(2));
3949            if (mActivityDisplay != null) {
3950                mActivityDisplay.detachActivitiesLocked(mStack);
3951                mActivityDisplay = null;
3952                mStack.detachDisplay();
3953            }
3954        }
3955
3956        @Override
3957        public final int startActivity(Intent intent) {
3958            return mService.startActivity(intent, this);
3959        }
3960
3961        @Override
3962        public final int startActivityIntentSender(IIntentSender intentSender)
3963                throws TransactionTooLargeException {
3964            mService.enforceNotIsolatedCaller("ActivityContainer.startActivityIntentSender");
3965
3966            if (!(intentSender instanceof PendingIntentRecord)) {
3967                throw new IllegalArgumentException("Bad PendingIntent object");
3968            }
3969
3970            final int userId = mService.mUserController.handleIncomingUser(Binder.getCallingPid(),
3971                    Binder.getCallingUid(), mCurrentUser, false,
3972                    ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null);
3973
3974            final PendingIntentRecord pendingIntent = (PendingIntentRecord) intentSender;
3975            checkEmbeddedAllowedInner(userId, pendingIntent.key.requestIntent,
3976                    pendingIntent.key.requestResolvedType);
3977
3978            return pendingIntent.sendInner(0, null, null, null, null, null, null, 0,
3979                    FORCE_NEW_TASK_FLAGS, FORCE_NEW_TASK_FLAGS, null, this);
3980        }
3981
3982        void checkEmbeddedAllowedInner(int userId, Intent intent, String resolvedType) {
3983            ActivityInfo aInfo = resolveActivity(intent, resolvedType, 0, null, userId);
3984            if (aInfo != null && (aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
3985                throw new SecurityException(
3986                        "Attempt to embed activity that has not set allowEmbedded=\"true\"");
3987            }
3988        }
3989
3990        @Override
3991        public IBinder asBinder() {
3992            return this;
3993        }
3994
3995        @Override
3996        public void setSurface(Surface surface, int width, int height, int density) {
3997            mService.enforceNotIsolatedCaller("ActivityContainer.attachToSurface");
3998        }
3999
4000        ActivityStackSupervisor getOuter() {
4001            return ActivityStackSupervisor.this;
4002        }
4003
4004        boolean isAttachedLocked() {
4005            return mActivityDisplay != null;
4006        }
4007
4008        // TODO: Make sure every change to ActivityRecord.visible results in a call to this.
4009        void setVisible(boolean visible) {
4010            if (mVisible != visible) {
4011                mVisible = visible;
4012                if (mCallback != null) {
4013                    mHandler.obtainMessage(CONTAINER_CALLBACK_VISIBILITY, visible ? 1 : 0,
4014                            0 /* unused */, this).sendToTarget();
4015                }
4016            }
4017        }
4018
4019        void setDrawn() {
4020        }
4021
4022        // You can always start a new task on a regular ActivityStack.
4023        boolean isEligibleForNewTasks() {
4024            return true;
4025        }
4026
4027        void onTaskListEmptyLocked() {
4028            detachLocked();
4029            deleteActivityContainer(this);
4030            mHandler.obtainMessage(CONTAINER_CALLBACK_TASK_LIST_EMPTY, this).sendToTarget();
4031        }
4032
4033        @Override
4034        public String toString() {
4035            return mIdString + (mActivityDisplay == null ? "N" : "A");
4036        }
4037    }
4038
4039    private class VirtualActivityContainer extends ActivityContainer {
4040        Surface mSurface;
4041        boolean mDrawn = false;
4042
4043        VirtualActivityContainer(ActivityRecord parent, IActivityContainerCallback callback) {
4044            super(getNextStackId());
4045            mParentActivity = parent;
4046            mCallback = callback;
4047            mContainerState = CONTAINER_STATE_NO_SURFACE;
4048            mIdString = "VirtualActivityContainer{" + mStackId + ", parent=" + mParentActivity + "}";
4049        }
4050
4051        @Override
4052        public void setSurface(Surface surface, int width, int height, int density) {
4053            super.setSurface(surface, width, height, density);
4054
4055            synchronized (mService) {
4056                final long origId = Binder.clearCallingIdentity();
4057                try {
4058                    setSurfaceLocked(surface, width, height, density);
4059                } finally {
4060                    Binder.restoreCallingIdentity(origId);
4061                }
4062            }
4063        }
4064
4065        private void setSurfaceLocked(Surface surface, int width, int height, int density) {
4066            if (mContainerState == CONTAINER_STATE_FINISHING) {
4067                return;
4068            }
4069            VirtualActivityDisplay virtualActivityDisplay =
4070                    (VirtualActivityDisplay) mActivityDisplay;
4071            if (virtualActivityDisplay == null) {
4072                virtualActivityDisplay =
4073                        new VirtualActivityDisplay(width, height, density);
4074                mActivityDisplay = virtualActivityDisplay;
4075                mActivityDisplays.put(virtualActivityDisplay.mDisplayId, virtualActivityDisplay);
4076                attachToDisplayLocked(virtualActivityDisplay, true);
4077            }
4078
4079            if (mSurface != null) {
4080                mSurface.release();
4081            }
4082
4083            mSurface = surface;
4084            if (surface != null) {
4085                resumeFocusedStackTopActivityLocked();
4086            } else {
4087                mContainerState = CONTAINER_STATE_NO_SURFACE;
4088                ((VirtualActivityDisplay) mActivityDisplay).setSurface(null);
4089                if (mStack.mPausingActivity == null && mStack.mResumedActivity != null) {
4090                    mStack.startPausingLocked(false, true, false, false);
4091                }
4092            }
4093
4094            setSurfaceIfReadyLocked();
4095
4096            if (DEBUG_STACK) Slog.d(TAG_STACK,
4097                    "setSurface: " + this + " to display=" + virtualActivityDisplay);
4098        }
4099
4100        @Override
4101        boolean isAttachedLocked() {
4102            return mSurface != null && super.isAttachedLocked();
4103        }
4104
4105        @Override
4106        void setDrawn() {
4107            synchronized (mService) {
4108                mDrawn = true;
4109                setSurfaceIfReadyLocked();
4110            }
4111        }
4112
4113        // Never start a new task on an ActivityView if it isn't explicitly specified.
4114        @Override
4115        boolean isEligibleForNewTasks() {
4116            return false;
4117        }
4118
4119        private void setSurfaceIfReadyLocked() {
4120            if (DEBUG_STACK) Slog.v(TAG_STACK, "setSurfaceIfReadyLocked: mDrawn=" + mDrawn +
4121                    " mContainerState=" + mContainerState + " mSurface=" + mSurface);
4122            if (mDrawn && mSurface != null && mContainerState == CONTAINER_STATE_NO_SURFACE) {
4123                ((VirtualActivityDisplay) mActivityDisplay).setSurface(mSurface);
4124                mContainerState = CONTAINER_STATE_HAS_SURFACE;
4125            }
4126        }
4127    }
4128
4129    /** Exactly one of these classes per Display in the system. Capable of holding zero or more
4130     * attached {@link ActivityStack}s */
4131    class ActivityDisplay {
4132        /** Actual Display this object tracks. */
4133        int mDisplayId;
4134        Display mDisplay;
4135        DisplayInfo mDisplayInfo = new DisplayInfo();
4136
4137        /** All of the stacks on this display. Order matters, topmost stack is in front of all other
4138         * stacks, bottommost behind. Accessed directly by ActivityManager package classes */
4139        final ArrayList<ActivityStack> mStacks = new ArrayList<>();
4140
4141        ActivityRecord mVisibleBehindActivity;
4142
4143        ActivityDisplay() {
4144        }
4145
4146        // After instantiation, check that mDisplay is not null before using this. The alternative
4147        // is for this to throw an exception if mDisplayManager.getDisplay() returns null.
4148        ActivityDisplay(int displayId) {
4149            final Display display = mDisplayManager.getDisplay(displayId);
4150            if (display == null) {
4151                return;
4152            }
4153            init(display);
4154        }
4155
4156        void init(Display display) {
4157            mDisplay = display;
4158            mDisplayId = display.getDisplayId();
4159            mDisplay.getDisplayInfo(mDisplayInfo);
4160        }
4161
4162        void attachActivities(ActivityStack stack, boolean onTop) {
4163            if (DEBUG_STACK) Slog.v(TAG_STACK,
4164                    "attachActivities: attaching " + stack + " to displayId=" + mDisplayId
4165                    + " onTop=" + onTop);
4166            if (onTop) {
4167                mStacks.add(stack);
4168            } else {
4169                mStacks.add(0, stack);
4170            }
4171        }
4172
4173        void detachActivitiesLocked(ActivityStack stack) {
4174            if (DEBUG_STACK) Slog.v(TAG_STACK, "detachActivitiesLocked: detaching " + stack
4175                    + " from displayId=" + mDisplayId);
4176            mStacks.remove(stack);
4177        }
4178
4179        void setVisibleBehindActivity(ActivityRecord r) {
4180            mVisibleBehindActivity = r;
4181        }
4182
4183        boolean hasVisibleBehindActivity() {
4184            return mVisibleBehindActivity != null;
4185        }
4186
4187        @Override
4188        public String toString() {
4189            return "ActivityDisplay={" + mDisplayId + " numStacks=" + mStacks.size() + "}";
4190        }
4191    }
4192
4193    class VirtualActivityDisplay extends ActivityDisplay {
4194        VirtualDisplay mVirtualDisplay;
4195
4196        VirtualActivityDisplay(int width, int height, int density) {
4197            DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
4198            mVirtualDisplay = dm.createVirtualDisplay(mService.mContext, null,
4199                    VIRTUAL_DISPLAY_BASE_NAME, width, height, density, null,
4200                    DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC |
4201                    DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY, null, null);
4202
4203            init(mVirtualDisplay.getDisplay());
4204
4205            mWindowManager.handleDisplayAdded(mDisplayId);
4206        }
4207
4208        void setSurface(Surface surface) {
4209            if (mVirtualDisplay != null) {
4210                mVirtualDisplay.setSurface(surface);
4211            }
4212        }
4213
4214        @Override
4215        void detachActivitiesLocked(ActivityStack stack) {
4216            super.detachActivitiesLocked(stack);
4217            if (mVirtualDisplay != null) {
4218                mVirtualDisplay.release();
4219                mVirtualDisplay = null;
4220            }
4221        }
4222
4223        @Override
4224        public String toString() {
4225            return "VirtualActivityDisplay={" + mDisplayId + "}";
4226        }
4227    }
4228
4229    /**
4230     * Adjust bounds to stay within stack bounds.
4231     *
4232     * Since bounds might be outside of stack bounds, this method tries to move the bounds in a way
4233     * that keep them unchanged, but be contained within the stack bounds.
4234     *
4235     * @param bounds Bounds to be adjusted.
4236     * @param stackBounds Bounds within which the other bounds should remain.
4237     */
4238    private static void fitWithinBounds(Rect bounds, Rect stackBounds) {
4239        if (stackBounds == null || stackBounds.contains(bounds)) {
4240            return;
4241        }
4242
4243        if (bounds.left < stackBounds.left || bounds.right > stackBounds.right) {
4244            final int maxRight = stackBounds.right
4245                    - (stackBounds.width() / FIT_WITHIN_BOUNDS_DIVIDER);
4246            int horizontalDiff = stackBounds.left - bounds.left;
4247            if ((horizontalDiff < 0 && bounds.left >= maxRight)
4248                    || (bounds.left + horizontalDiff >= maxRight)) {
4249                horizontalDiff = maxRight - bounds.left;
4250            }
4251            bounds.left += horizontalDiff;
4252            bounds.right += horizontalDiff;
4253        }
4254
4255        if (bounds.top < stackBounds.top || bounds.bottom > stackBounds.bottom) {
4256            final int maxBottom = stackBounds.bottom
4257                    - (stackBounds.height() / FIT_WITHIN_BOUNDS_DIVIDER);
4258            int verticalDiff = stackBounds.top - bounds.top;
4259            if ((verticalDiff < 0 && bounds.top >= maxBottom)
4260                    || (bounds.top + verticalDiff >= maxBottom)) {
4261                verticalDiff = maxBottom - bounds.top;
4262            }
4263            bounds.top += verticalDiff;
4264            bounds.bottom += verticalDiff;
4265        }
4266    }
4267
4268    ActivityStack findStackBehind(ActivityStack stack) {
4269        // TODO(multi-display): We are only looking for stacks on the default display.
4270        final ActivityDisplay display = mActivityDisplays.get(Display.DEFAULT_DISPLAY);
4271        if (display == null) {
4272            return null;
4273        }
4274        final ArrayList<ActivityStack> stacks = display.mStacks;
4275        for (int i = stacks.size() - 1; i >= 0; i--) {
4276            if (stacks.get(i) == stack && i > 0) {
4277                return stacks.get(i - 1);
4278            }
4279        }
4280        throw new IllegalStateException("Failed to find a stack behind stack=" + stack
4281                + " in=" + stacks);
4282    }
4283
4284    /**
4285     * Puts a task into resizing mode during the next app transition.
4286     *
4287     * @param taskId the id of the task to put into resizing mode
4288     */
4289    private void setResizingDuringAnimation(int taskId) {
4290        mResizingTasksDuringAnimation.add(taskId);
4291        mWindowManager.setTaskDockedResizing(taskId, true);
4292    }
4293
4294    final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
4295        final TaskRecord task;
4296        final int callingUid;
4297        final String callingPackage;
4298        final Intent intent;
4299        final int userId;
4300        final ActivityOptions activityOptions = (bOptions != null)
4301                ? new ActivityOptions(bOptions) : null;
4302        final int launchStackId = (activityOptions != null)
4303                ? activityOptions.getLaunchStackId() : INVALID_STACK_ID;
4304
4305        if (launchStackId == HOME_STACK_ID) {
4306            throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
4307                    + taskId + " can't be launch in the home stack.");
4308        }
4309        task = anyTaskForIdLocked(taskId, RESTORE_FROM_RECENTS, launchStackId);
4310        if (task == null) {
4311            throw new IllegalArgumentException(
4312                    "startActivityFromRecentsInner: Task " + taskId + " not found.");
4313        }
4314
4315        if (launchStackId != INVALID_STACK_ID) {
4316            if (launchStackId == DOCKED_STACK_ID) {
4317                mWindowManager.setDockedStackCreateState(
4318                        activityOptions.getDockCreateMode(), null /* initialBounds */);
4319
4320                // Defer updating the stack in which recents is until the app transition is done, to
4321                // not run into issues where we still need to draw the task in recents but the
4322                // docked stack is already created.
4323                deferUpdateBounds(HOME_STACK_ID);
4324                mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
4325            }
4326            if (task.stack.mStackId != launchStackId) {
4327                moveTaskToStackLocked(
4328                        taskId, launchStackId, ON_TOP, FORCE_FOCUS, "startActivityFromRecents",
4329                        ANIMATE);
4330            }
4331        }
4332
4333        // If the user must confirm credentials (e.g. when first launching a work app and the
4334        // Work Challenge is present) let startActivityInPackage handle the intercepting.
4335        if (!mService.mUserController.shouldConfirmCredentials(task.userId)
4336                && task.getRootActivity() != null) {
4337            mActivityMetricsLogger.notifyActivityLaunching();
4338            mService.moveTaskToFrontLocked(task.taskId, 0, bOptions);
4339
4340            // If we are launching the task in the docked stack, put it into resizing mode so
4341            // the window renders full-screen with the background filling the void. Also only
4342            // call this at the end to make sure that tasks exists on the window manager side.
4343            if (launchStackId == DOCKED_STACK_ID) {
4344                setResizingDuringAnimation(taskId);
4345            }
4346            return ActivityManager.START_TASK_TO_FRONT;
4347        }
4348        callingUid = task.mCallingUid;
4349        callingPackage = task.mCallingPackage;
4350        intent = task.intent;
4351        intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4352        userId = task.userId;
4353            int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
4354                    null, null, 0, 0, bOptions, userId, null, task);
4355            if (launchStackId == DOCKED_STACK_ID) {
4356                setResizingDuringAnimation(task.taskId);
4357            }
4358            return result;
4359    }
4360
4361    /**
4362     * @return a list of activities which are the top ones in each visible stack. The first
4363     * entry will be the focused activity.
4364     */
4365    public List<IBinder> getTopVisibleActivities() {
4366        final ActivityDisplay display = mActivityDisplays.get(Display.DEFAULT_DISPLAY);
4367        if (display == null) {
4368            return Collections.EMPTY_LIST;
4369        }
4370        ArrayList<IBinder> topActivityTokens = new ArrayList<>();
4371        final ArrayList<ActivityStack> stacks = display.mStacks;
4372        for (int i = stacks.size() - 1; i >= 0; i--) {
4373            ActivityStack stack = stacks.get(i);
4374            if (stack.getStackVisibilityLocked(null) == ActivityStack.STACK_VISIBLE) {
4375                ActivityRecord top = stack.topActivity();
4376                if (top != null) {
4377                    if (stack == mFocusedStack) {
4378                        topActivityTokens.add(0, top.appToken);
4379                    } else {
4380                        topActivityTokens.add(top.appToken);
4381                    }
4382                }
4383            }
4384        }
4385        return topActivityTokens;
4386    }
4387}
4388