2 * Copyright (C) 2013 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.am;
19 import android.Manifest;
20 import android.annotation.UserIdInt;
21 import android.app.Activity;
22 import android.app.ActivityManager;
23 import android.app.ActivityManager.RunningTaskInfo;
24 import android.app.ActivityManager.StackId;
25 import android.app.ActivityManager.StackInfo;
26 import android.app.ActivityOptions;
27 import android.app.AppGlobals;
28 import android.app.AppOpsManager;
29 import android.app.IActivityContainer;
30 import android.app.IActivityContainerCallback;
31 import android.app.IActivityManager;
32 import android.app.IActivityManager.WaitResult;
33 import android.app.ProfilerInfo;
34 import android.app.ResultInfo;
35 import android.app.StatusBarManager;
36 import android.app.admin.IDevicePolicyManager;
37 import android.content.ComponentName;
38 import android.content.Context;
39 import android.content.IIntentSender;
40 import android.content.Intent;
41 import android.content.pm.ActivityInfo;
42 import android.content.pm.ApplicationInfo;
43 import android.content.pm.PackageInfo;
44 import android.content.pm.PackageManager;
45 import android.content.pm.ResolveInfo;
46 import android.content.pm.UserInfo;
47 import android.content.res.Configuration;
48 import android.graphics.Rect;
49 import android.hardware.display.DisplayManager;
50 import android.hardware.display.DisplayManager.DisplayListener;
51 import android.hardware.display.DisplayManagerGlobal;
52 import android.hardware.display.VirtualDisplay;
53 import android.hardware.input.InputManager;
54 import android.hardware.input.InputManagerInternal;
55 import android.os.Binder;
56 import android.os.Bundle;
57 import android.os.Debug;
58 import android.os.Handler;
59 import android.os.IBinder;
60 import android.os.Looper;
61 import android.os.Message;
62 import android.os.ParcelFileDescriptor;
63 import android.os.PowerManager;
64 import android.os.Process;
65 import android.os.RemoteException;
66 import android.os.ServiceManager;
67 import android.os.SystemClock;
68 import android.os.Trace;
69 import android.os.TransactionTooLargeException;
70 import android.os.UserHandle;
71 import android.os.UserManager;
72 import android.os.WorkSource;
73 import android.provider.MediaStore;
74 import android.provider.Settings;
75 import android.provider.Settings.SettingNotFoundException;
76 import android.service.voice.IVoiceInteractionSession;
77 import android.util.ArrayMap;
78 import android.util.ArraySet;
79 import android.util.EventLog;
80 import android.util.Slog;
81 import android.util.SparseArray;
82 import android.util.SparseIntArray;
83 import android.view.Display;
84 import android.view.DisplayInfo;
85 import android.view.InputEvent;
86 import android.view.Surface;
88 import com.android.internal.content.ReferrerIntent;
89 import com.android.internal.os.TransferPipe;
90 import com.android.internal.statusbar.IStatusBarService;
91 import com.android.internal.util.ArrayUtils;
92 import com.android.internal.widget.LockPatternUtils;
93 import com.android.server.LocalServices;
94 import com.android.server.am.ActivityStack.ActivityState;
95 import com.android.server.wm.WindowManagerService;
97 import java.io.FileDescriptor;
98 import java.io.IOException;
99 import java.io.PrintWriter;
100 import java.util.ArrayList;
101 import java.util.Arrays;
102 import java.util.Collections;
103 import java.util.List;
104 import java.util.Objects;
105 import java.util.Set;
107 import static android.Manifest.permission.START_ANY_ACTIVITY;
108 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
109 import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
110 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
111 import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
112 import static android.app.ActivityManager.RESIZE_MODE_FORCED;
113 import static android.app.ActivityManager.RESIZE_MODE_SYSTEM;
114 import static android.app.ActivityManager.START_TASK_TO_FRONT;
115 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
116 import static android.app.ActivityManager.StackId.FIRST_DYNAMIC_STACK_ID;
117 import static android.app.ActivityManager.StackId.FIRST_STATIC_STACK_ID;
118 import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
119 import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
120 import static android.app.ActivityManager.StackId.HOME_STACK_ID;
121 import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
122 import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
123 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
124 import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
125 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
126 import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS;
127 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
128 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
129 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
130 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONTAINERS;
131 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
132 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKSCREEN;
133 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
134 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
135 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
136 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
137 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
138 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
139 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
140 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
141 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBLE_BEHIND;
142 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONTAINERS;
143 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IDLE;
144 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
145 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
146 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
147 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
148 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
149 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
150 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
151 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
152 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBLE_BEHIND;
153 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
154 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
155 import static com.android.server.am.ActivityManagerService.ANIMATE;
156 import static com.android.server.am.ActivityManagerService.FIRST_SUPERVISOR_STACK_MSG;
157 import static com.android.server.am.ActivityManagerService.NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG;
158 import static com.android.server.am.ActivityManagerService.NOTIFY_FORCED_RESIZABLE_MSG;
159 import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
160 import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
161 import static com.android.server.am.ActivityRecord.RECENTS_ACTIVITY_TYPE;
162 import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
163 import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
164 import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
165 import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
166 import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
167 import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
168 import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
169 import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
170 import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
171 import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
172 import static com.android.server.am.ActivityStack.STACK_VISIBLE;
173 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
174 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
175 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
176 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
177 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
178 import static com.android.server.wm.AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS;
180 public final class ActivityStackSupervisor implements DisplayListener {
181 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_AM;
182 private static final String TAG_CONTAINERS = TAG + POSTFIX_CONTAINERS;
183 private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
184 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
185 private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
186 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
187 private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
188 private static final String TAG_STACK = TAG + POSTFIX_STACK;
189 private static final String TAG_STATES = TAG + POSTFIX_STATES;
190 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
191 static final String TAG_TASKS = TAG + POSTFIX_TASKS;
192 private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND;
194 /** How long we wait until giving up on the last activity telling us it is idle. */
195 static final int IDLE_TIMEOUT = 10 * 1000;
197 /** How long we can hold the sleep wake lock before giving up. */
198 static final int SLEEP_TIMEOUT = 5 * 1000;
200 // How long we can hold the launch wake lock before giving up.
201 static final int LAUNCH_TIMEOUT = 10 * 1000;
203 static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
204 static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
205 static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
206 static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
207 static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
208 static final int HANDLE_DISPLAY_ADDED = FIRST_SUPERVISOR_STACK_MSG + 5;
209 static final int HANDLE_DISPLAY_CHANGED = FIRST_SUPERVISOR_STACK_MSG + 6;
210 static final int HANDLE_DISPLAY_REMOVED = FIRST_SUPERVISOR_STACK_MSG + 7;
211 static final int CONTAINER_CALLBACK_VISIBILITY = FIRST_SUPERVISOR_STACK_MSG + 8;
212 static final int LOCK_TASK_START_MSG = FIRST_SUPERVISOR_STACK_MSG + 9;
213 static final int LOCK_TASK_END_MSG = FIRST_SUPERVISOR_STACK_MSG + 10;
214 static final int CONTAINER_CALLBACK_TASK_LIST_EMPTY = FIRST_SUPERVISOR_STACK_MSG + 11;
215 static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
216 static final int SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG = FIRST_SUPERVISOR_STACK_MSG + 13;
217 static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
218 static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
220 private static final String VIRTUAL_DISPLAY_BASE_NAME = "ActivityViewVirtualDisplay";
222 private static final String LOCK_TASK_TAG = "Lock-to-App";
224 // Used to indicate if an object (e.g. stack) that we are trying to get
225 // should be created if it doesn't exist already.
226 static final boolean CREATE_IF_NEEDED = true;
228 // Used to indicate that windows of activities should be preserved during the resize.
229 static final boolean PRESERVE_WINDOWS = true;
231 // Used to indicate if an object (e.g. task) should be moved/created
232 // at the top of its container (e.g. stack).
233 static final boolean ON_TOP = true;
235 // Used to indicate that an objects (e.g. task) removal from its container
236 // (e.g. stack) is due to it moving to another container.
237 static final boolean MOVING = true;
239 // Force the focus to change to the stack we are moving a task to..
240 static final boolean FORCE_FOCUS = true;
242 // Restore task from the saved recents if it can't be found in any live stack.
243 static final boolean RESTORE_FROM_RECENTS = true;
245 // Don't execute any calls to resume.
246 static final boolean DEFER_RESUME = true;
248 // Activity actions an app cannot start if it uses a permission which is not granted.
249 private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION =
253 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE,
254 Manifest.permission.CAMERA);
255 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE,
256 Manifest.permission.CAMERA);
257 ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL,
258 Manifest.permission.CALL_PHONE);
261 /** Action restriction: launching the activity is not restricted. */
262 private static final int ACTIVITY_RESTRICTION_NONE = 0;
263 /** Action restriction: launching the activity is restricted by a permission. */
264 private static final int ACTIVITY_RESTRICTION_PERMISSION = 1;
265 /** Action restriction: launching the activity is restricted by an app op. */
266 private static final int ACTIVITY_RESTRICTION_APPOP = 2;
268 // The height/width divide used when fitting a task within a bounds with method
269 // {@link #fitWithinBounds}.
270 // We always want the task to to be visible in the bounds without affecting its size when
271 // fitting. To make sure this is the case, we don't adjust the task left or top side pass
272 // the input bounds right or bottom side minus the width or height divided by this value.
273 private static final int FIT_WITHIN_BOUNDS_DIVIDER = 3;
275 /** Status Bar Service **/
276 private IBinder mToken = new Binder();
277 private IStatusBarService mStatusBarService;
278 private IDevicePolicyManager mDevicePolicyManager;
280 // For debugging to make sure the caller when acquiring/releasing our
281 // wake lock is the system process.
282 static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
283 /** The number of distinct task ids that can be assigned to the tasks of a single user */
284 private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
286 final ActivityManagerService mService;
288 private RecentTasks mRecentTasks;
290 final ActivityStackSupervisorHandler mHandler;
293 WindowManagerService mWindowManager;
294 DisplayManager mDisplayManager;
296 /** Counter for next free stack ID to use for dynamic activity stacks. */
297 private int mNextFreeStackId = FIRST_DYNAMIC_STACK_ID;
300 * Maps the task identifier that activities are currently being started in to the userId of the
301 * task. Each time a new task is created, the entry for the userId of the task is incremented
303 private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20);
305 /** The current user */
308 /** The stack containing the launcher app. Assumed to always be attached to
309 * Display.DEFAULT_DISPLAY. */
310 ActivityStack mHomeStack;
312 /** The stack currently receiving input or launching the next activity. */
313 ActivityStack mFocusedStack;
315 /** If this is the same as mFocusedStack then the activity on the top of the focused stack has
316 * been resumed. If stacks are changing position this will hold the old stack until the new
317 * stack becomes resumed after which it will be set to mFocusedStack. */
318 private ActivityStack mLastFocusedStack;
320 /** List of activities that are waiting for a new activity to become visible before completing
321 * whatever operation they are supposed to do. */
322 final ArrayList<ActivityRecord> mWaitingVisibleActivities = new ArrayList<>();
324 /** List of processes waiting to find out about the next visible activity. */
325 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible = new ArrayList<>();
327 /** List of processes waiting to find out about the next launched activity. */
328 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched = new ArrayList<>();
330 /** List of activities that are ready to be stopped, but waiting for the next activity to
331 * settle down before doing so. */
332 final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>();
334 /** List of activities that are ready to be finished, but waiting for the previous activity to
335 * settle down before doing so. It contains ActivityRecord objects. */
336 final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>();
338 /** List of activities that are in the process of going to sleep. */
339 final ArrayList<ActivityRecord> mGoingToSleepActivities = new ArrayList<>();
341 /** List of activities whose multi-window mode changed that we need to report to the
343 final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
345 /** List of activities whose picture-in-picture mode changed that we need to report to the
347 final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
349 /** Used on user changes */
350 final ArrayList<UserState> mStartingUsers = new ArrayList<>();
352 /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity
353 * is being brought in front of us. */
354 boolean mUserLeaving = false;
356 /** Set when we have taken too long waiting to go to sleep. */
357 boolean mSleepTimeout = false;
360 * We don't want to allow the device to go to sleep while in the process
361 * of launching an activity. This is primarily to allow alarm intent
362 * receivers to launch an activity and get that to run before the device
363 * goes back to sleep.
365 PowerManager.WakeLock mLaunchingActivity;
368 * Set when the system is going to sleep, until we have
369 * successfully paused the current activity and released our wake lock.
370 * At that point the system is allowed to actually sleep.
372 PowerManager.WakeLock mGoingToSleep;
374 /** Stack id of the front stack when user switched, indexed by userId. */
375 SparseIntArray mUserStackInFront = new SparseIntArray(2);
377 // TODO: Add listener for removal of references.
378 /** Mapping from (ActivityStack/TaskStack).mStackId to their current state */
379 private SparseArray<ActivityContainer> mActivityContainers = new SparseArray<>();
381 /** Mapping from displayId to display current state */
382 private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();
384 InputManagerInternal mInputManagerInternal;
386 /** The chain of tasks in lockTask mode. The current frontmost task is at the top, and tasks
387 * may be finished until there is only one entry left. If this is empty the system is not
388 * in lockTask mode. */
389 ArrayList<TaskRecord> mLockTaskModeTasks = new ArrayList<>();
390 /** Store the current lock task mode. Possible values:
391 * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
392 * {@link ActivityManager#LOCK_TASK_MODE_PINNED}
394 private int mLockTaskModeState;
396 * Notifies the user when entering/exiting lock-task.
398 private LockTaskNotify mLockTaskNotify;
400 /** Used to keep resumeTopActivityUncheckedLocked() from being entered recursively */
401 boolean inResumeTopActivity;
403 // temp. rects used during resize calculation so we don't need to create a new object each time.
404 private final Rect tempRect = new Rect();
405 private final Rect tempRect2 = new Rect();
407 private final SparseArray<Configuration> mTmpConfigs = new SparseArray<>();
408 private final SparseArray<Rect> mTmpBounds = new SparseArray<>();
409 private final SparseArray<Rect> mTmpInsetBounds = new SparseArray<>();
411 // The default minimal size that will be used if the activity doesn't specify its minimal size.
412 // It will be calculated when the default display gets added.
413 int mDefaultMinSizeOfResizeableTask = -1;
415 // Whether tasks have moved and we need to rank the tasks before next OOM scoring
416 private boolean mTaskLayersChanged = true;
418 final ActivityMetricsLogger mActivityMetricsLogger;
420 private final ResizeDockedStackTimeout mResizeDockedStackTimeout;
422 static class FindTaskResult {
424 boolean matchedByRootAffinity;
426 private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
429 * Used to keep track whether app visibilities got changed since the last pause. Useful to
430 * determine whether to invoke the task stack change listener after pausing.
432 boolean mAppVisibilitiesChangedSinceLastPause;
435 * Set of tasks that are in resizing mode during an app transition to fill the "void".
437 private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
441 * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked}
442 * will be ignored. Useful for the case where the caller is handling resizing of other stack and
443 * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger
444 * like the docked stack going empty.
446 private boolean mAllowDockedStackResize = true;
449 * Is dock currently minimized.
451 boolean mIsDockMinimized;
454 * Description of a request to start a new activity, which has been held
455 * due to app switches being disabled.
457 static class PendingActivityLaunch {
458 final ActivityRecord r;
459 final ActivityRecord sourceRecord;
460 final int startFlags;
461 final ActivityStack stack;
462 final ProcessRecord callerApp;
464 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
465 int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
467 sourceRecord = _sourceRecord;
468 startFlags = _startFlags;
470 callerApp = _callerApp;
473 void sendErrorResult(String message) {
475 if (callerApp.thread != null) {
476 callerApp.thread.scheduleCrash(message);
478 } catch (RemoteException e) {
479 Slog.e(TAG, "Exception scheduling crash of failed "
480 + "activity launcher sourceRecord=" + sourceRecord, e);
485 public ActivityStackSupervisor(ActivityManagerService service) {
487 mHandler = new ActivityStackSupervisorHandler(mService.mHandler.getLooper());
488 mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
489 mResizeDockedStackTimeout = new ResizeDockedStackTimeout(service, this, mHandler);
492 void setRecentTasks(RecentTasks recentTasks) {
493 mRecentTasks = recentTasks;
497 * At the time when the constructor runs, the power manager has not yet been
498 * initialized. So we initialize our wakelocks afterwards.
500 void initPowerManagement() {
501 PowerManager pm = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
502 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
503 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*launch*");
504 mLaunchingActivity.setReferenceCounted(false);
507 // This function returns a IStatusBarService. The value is from ServiceManager.
508 // getService and is cached.
509 private IStatusBarService getStatusBarService() {
510 synchronized (mService) {
511 if (mStatusBarService == null) {
512 mStatusBarService = IStatusBarService.Stub.asInterface(
513 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
514 if (mStatusBarService == null) {
515 Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
518 return mStatusBarService;
522 private IDevicePolicyManager getDevicePolicyManager() {
523 synchronized (mService) {
524 if (mDevicePolicyManager == null) {
525 mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
526 ServiceManager.checkService(Context.DEVICE_POLICY_SERVICE));
527 if (mDevicePolicyManager == null) {
528 Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
531 return mDevicePolicyManager;
535 void setWindowManager(WindowManagerService wm) {
536 synchronized (mService) {
540 (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
541 mDisplayManager.registerDisplayListener(this, null);
543 Display[] displays = mDisplayManager.getDisplays();
544 for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
545 final int displayId = displays[displayNdx].getDisplayId();
546 ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
547 if (activityDisplay.mDisplay == null) {
548 throw new IllegalStateException("Default Display does not exist");
550 mActivityDisplays.put(displayId, activityDisplay);
551 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
554 mHomeStack = mFocusedStack = mLastFocusedStack =
555 getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
557 mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
561 void notifyActivityDrawnForKeyguard() {
562 if (DEBUG_LOCKSCREEN) mService.logLockScreen("");
563 mWindowManager.notifyActivityDrawnForKeyguard();
566 ActivityStack getFocusedStack() {
567 return mFocusedStack;
570 ActivityStack getLastStack() {
571 return mLastFocusedStack;
574 boolean isFocusedStack(ActivityStack stack) {
579 final ActivityRecord parent = stack.mActivityContainer.mParentActivity;
580 if (parent != null) {
581 stack = parent.task.stack;
583 return stack == mFocusedStack;
586 /** The top most stack. */
587 boolean isFrontStack(ActivityStack stack) {
592 final ActivityRecord parent = stack.mActivityContainer.mParentActivity;
593 if (parent != null) {
594 stack = parent.task.stack;
596 return stack == mHomeStack.mStacks.get((mHomeStack.mStacks.size() - 1));
599 /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
600 void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
601 if (!focusCandidate.isFocusable()) {
602 // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
603 focusCandidate = focusCandidate.getNextFocusableStackLocked();
606 if (focusCandidate != mFocusedStack) {
607 mLastFocusedStack = mFocusedStack;
608 mFocusedStack = focusCandidate;
610 EventLogTags.writeAmFocusedStack(
611 mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
612 mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
615 final ActivityRecord r = topRunningActivityLocked();
616 if (!mService.mDoingSetFocusedActivity && mService.mFocusedActivity != r) {
617 // The focus activity should always be the top activity in the focused stack.
618 // There will be chaos and anarchy if it isn't...
619 mService.setFocusedActivityLocked(r, reason + " setFocusStack");
622 if (mService.mBooting || !mService.mBooted) {
623 if (r != null && r.idle) {
624 checkFinishBootingLocked();
629 void moveHomeStackToFront(String reason) {
630 mHomeStack.moveToFront(reason);
633 /** Returns true if the focus activity was adjusted to the home stack top activity. */
634 boolean moveHomeStackTaskToTop(int homeStackTaskType, String reason) {
635 if (homeStackTaskType == RECENTS_ACTIVITY_TYPE) {
636 mWindowManager.showRecentApps(false /* fromHome */);
640 mHomeStack.moveHomeStackTaskToTop(homeStackTaskType);
642 final ActivityRecord top = getHomeActivity();
646 mService.setFocusedActivityLocked(top, reason);
650 boolean resumeHomeStackTask(int homeStackTaskType, ActivityRecord prev, String reason) {
651 if (!mService.mBooting && !mService.mBooted) {
656 if (homeStackTaskType == RECENTS_ACTIVITY_TYPE) {
657 mWindowManager.showRecentApps(false /* fromHome */);
662 prev.task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
665 mHomeStack.moveHomeStackTaskToTop(homeStackTaskType);
666 ActivityRecord r = getHomeActivity();
667 final String myReason = reason + " resumeHomeStackTask";
669 // Only resume home activity if isn't finishing.
670 if (r != null && !r.finishing) {
671 mService.setFocusedActivityLocked(r, myReason);
672 return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
674 return mService.startHomeActivityLocked(mCurrentUser, myReason);
677 TaskRecord anyTaskForIdLocked(int id) {
678 return anyTaskForIdLocked(id, RESTORE_FROM_RECENTS, INVALID_STACK_ID);
682 * Returns a {@link TaskRecord} for the input id if available. Null otherwise.
683 * @param id Id of the task we would like returned.
684 * @param restoreFromRecents If the id was not in the active list, but was found in recents,
685 * restore the task from recents to the active list.
686 * @param stackId The stack to restore the task to (default launch stack will be used if
687 * stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}).
689 TaskRecord anyTaskForIdLocked(int id, boolean restoreFromRecents, int stackId) {
690 int numDisplays = mActivityDisplays.size();
691 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
692 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
693 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
694 ActivityStack stack = stacks.get(stackNdx);
695 TaskRecord task = stack.taskForIdLocked(id);
702 // Don't give up! Look in recents.
703 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
704 TaskRecord task = mRecentTasks.taskForIdLocked(id);
706 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
710 if (!restoreFromRecents) {
714 if (!restoreRecentTaskLocked(task, stackId)) {
715 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
716 "Couldn't restore task id=" + id + " found in recents");
719 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
723 ActivityRecord isInAnyStackLocked(IBinder token) {
724 int numDisplays = mActivityDisplays.size();
725 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
726 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
727 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
728 final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
738 * TODO: Handle freefom mode.
739 * @return true when credential confirmation is needed for the user and there is any
740 * activity started by the user in any visible stack.
742 boolean isUserLockedProfile(@UserIdInt int userId) {
743 if (!mService.mUserController.shouldConfirmCredentials(userId)) {
746 final ActivityStack fullScreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
747 final ActivityStack dockedStack = getStack(DOCKED_STACK_ID);
748 final ActivityStack[] activityStacks = new ActivityStack[] {fullScreenStack, dockedStack};
749 for (final ActivityStack activityStack : activityStacks) {
750 if (activityStack == null) {
753 if (activityStack.topRunningActivityLocked() == null) {
756 if (activityStack.getStackVisibilityLocked(null) == STACK_INVISIBLE) {
759 if (activityStack.isDockedStack() && mIsDockMinimized) {
762 final TaskRecord topTask = activityStack.topTask();
763 if (topTask == null) {
766 // To handle the case that work app is in the task but just is not the top one.
767 for (int i = topTask.mActivities.size() - 1; i >= 0; i--) {
768 final ActivityRecord activityRecord = topTask.mActivities.get(i);
769 if (activityRecord.userId == userId) {
777 void setNextTaskIdForUserLocked(int taskId, int userId) {
778 final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
779 if (taskId > currentTaskId) {
780 mCurTaskIdForUser.put(userId, taskId);
784 static int nextTaskIdForUser(int taskId, int userId) {
785 int nextTaskId = taskId + 1;
786 if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
787 // Wrap around as there will be smaller task ids that are available now.
788 nextTaskId -= MAX_TASK_IDS_PER_USER;
793 int getNextTaskIdForUserLocked(int userId) {
794 final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
795 // for a userId u, a taskId can only be in the range
796 // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
797 // was 10, user 0 could only have taskIds 0 to 9, user 1: 10 to 19, user 2: 20 to 29, so on.
798 int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
799 while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
800 || anyTaskForIdLocked(candidateTaskId, !RESTORE_FROM_RECENTS,
801 INVALID_STACK_ID) != null) {
802 candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
803 if (candidateTaskId == currentTaskId) {
805 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
806 throw new IllegalStateException("Cannot get an available task id."
807 + " Reached limit of " + MAX_TASK_IDS_PER_USER
808 + " running tasks per user.");
811 mCurTaskIdForUser.put(userId, candidateTaskId);
812 return candidateTaskId;
815 ActivityRecord resumedAppLocked() {
816 ActivityStack stack = mFocusedStack;
820 ActivityRecord resumedActivity = stack.mResumedActivity;
821 if (resumedActivity == null || resumedActivity.app == null) {
822 resumedActivity = stack.mPausingActivity;
823 if (resumedActivity == null || resumedActivity.app == null) {
824 resumedActivity = stack.topRunningActivityLocked();
827 return resumedActivity;
830 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
831 final String processName = app.processName;
832 boolean didSomething = false;
833 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
834 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
835 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
836 final ActivityStack stack = stacks.get(stackNdx);
837 if (!isFocusedStack(stack)) {
840 ActivityRecord hr = stack.topRunningActivityLocked();
842 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
843 && processName.equals(hr.processName)) {
845 if (realStartActivityLocked(hr, app, true, true)) {
848 } catch (RemoteException e) {
849 Slog.w(TAG, "Exception in new application when starting activity "
850 + hr.intent.getComponent().flattenToShortString(), e);
858 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
863 boolean allResumedActivitiesIdle() {
864 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
865 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
866 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
867 final ActivityStack stack = stacks.get(stackNdx);
868 if (!isFocusedStack(stack) || stack.numActivities() == 0) {
871 final ActivityRecord resumedActivity = stack.mResumedActivity;
872 if (resumedActivity == null || !resumedActivity.idle) {
873 if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
874 + stack.mStackId + " " + resumedActivity + " not idle");
879 // Send launch end powerhint when idle
880 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
884 boolean allResumedActivitiesComplete() {
885 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
886 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
887 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
888 final ActivityStack stack = stacks.get(stackNdx);
889 if (isFocusedStack(stack)) {
890 final ActivityRecord r = stack.mResumedActivity;
891 if (r != null && r.state != RESUMED) {
897 // TODO: Not sure if this should check if all Paused are complete too.
898 if (DEBUG_STACK) Slog.d(TAG_STACK,
899 "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
900 mLastFocusedStack + " to=" + mFocusedStack);
901 mLastFocusedStack = mFocusedStack;
905 boolean allResumedActivitiesVisible() {
906 boolean foundResumed = false;
907 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
908 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
909 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
910 final ActivityStack stack = stacks.get(stackNdx);
911 final ActivityRecord r = stack.mResumedActivity;
913 if (!r.nowVisible || mWaitingVisibleActivities.contains(r)) {
924 * Pause all activities in either all of the stacks or just the back stacks.
925 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
926 * @return true if any activity was paused as a result of this call.
928 boolean pauseBackStacks(boolean userLeaving, boolean resuming, boolean dontWait) {
929 boolean someActivityPaused = false;
930 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
931 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
932 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
933 final ActivityStack stack = stacks.get(stackNdx);
934 if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
935 if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
936 " mResumedActivity=" + stack.mResumedActivity);
937 someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
942 return someActivityPaused;
945 boolean allPausedActivitiesComplete() {
946 boolean pausing = true;
947 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
948 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
949 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
950 final ActivityStack stack = stacks.get(stackNdx);
951 final ActivityRecord r = stack.mPausingActivity;
952 if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
955 "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
966 void pauseChildStacks(ActivityRecord parent, boolean userLeaving, boolean uiSleeping,
967 boolean resuming, boolean dontWait) {
968 // TODO: Put all stacks in supervisor and iterate through them instead.
969 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
970 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
971 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
972 final ActivityStack stack = stacks.get(stackNdx);
973 if (stack.mResumedActivity != null &&
974 stack.mActivityContainer.mParentActivity == parent) {
975 stack.startPausingLocked(userLeaving, uiSleeping, resuming, dontWait);
981 void cancelInitializingActivities() {
982 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
983 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
984 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
985 stacks.get(stackNdx).cancelInitializingActivities();
990 void reportActivityVisibleLocked(ActivityRecord r) {
991 sendWaitingVisibleReportLocked(r);
994 void sendWaitingVisibleReportLocked(ActivityRecord r) {
995 boolean changed = false;
996 for (int i = mWaitingActivityVisible.size()-1; i >= 0; i--) {
997 WaitResult w = mWaitingActivityVisible.get(i);
1002 w.who = new ComponentName(r.info.packageName, r.info.name);
1004 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
1005 w.thisTime = w.totalTime;
1009 mService.notifyAll();
1013 void reportTaskToFrontNoLaunch(ActivityRecord r) {
1014 boolean changed = false;
1015 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1016 WaitResult w = mWaitingActivityLaunched.remove(i);
1017 if (w.who == null) {
1019 // Set result to START_TASK_TO_FRONT so that startActivityMayWait() knows that
1020 // the starting activity ends up moving another activity to front, and it should
1021 // wait for this new activity to become visible instead.
1022 // Do not modify other fields.
1023 w.result = START_TASK_TO_FRONT;
1027 mService.notifyAll();
1031 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
1032 long thisTime, long totalTime) {
1033 boolean changed = false;
1034 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1035 WaitResult w = mWaitingActivityLaunched.remove(i);
1036 if (w.who == null) {
1038 w.timeout = timeout;
1040 w.who = new ComponentName(r.info.packageName, r.info.name);
1042 w.thisTime = thisTime;
1043 w.totalTime = totalTime;
1044 // Do not modify w.result.
1048 mService.notifyAll();
1052 ActivityRecord topRunningActivityLocked() {
1053 final ActivityStack focusedStack = mFocusedStack;
1054 ActivityRecord r = focusedStack.topRunningActivityLocked();
1059 // Look in other non-focused and non-home stacks.
1060 final ArrayList<ActivityStack> stacks = mHomeStack.mStacks;
1061 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1062 final ActivityStack stack = stacks.get(stackNdx);
1063 if (stack != focusedStack && isFrontStack(stack) && stack.isFocusable()) {
1064 r = stack.topRunningActivityLocked();
1073 void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
1074 // Gather all of the running tasks for each stack into runningTaskLists.
1075 ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1076 new ArrayList<ArrayList<RunningTaskInfo>>();
1077 final int numDisplays = mActivityDisplays.size();
1078 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
1079 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1080 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1081 final ActivityStack stack = stacks.get(stackNdx);
1082 ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
1083 runningTaskLists.add(stackTaskList);
1084 stack.getTasksLocked(stackTaskList, callingUid, allowed);
1088 // The lists are already sorted from most recent to oldest. Just pull the most recent off
1089 // each list and add it to list. Stop when all lists are empty or maxNum reached.
1090 while (maxNum > 0) {
1091 long mostRecentActiveTime = Long.MIN_VALUE;
1092 ArrayList<RunningTaskInfo> selectedStackList = null;
1093 final int numTaskLists = runningTaskLists.size();
1094 for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1095 ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
1096 if (!stackTaskList.isEmpty()) {
1097 final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1098 if (lastActiveTime > mostRecentActiveTime) {
1099 mostRecentActiveTime = lastActiveTime;
1100 selectedStackList = stackTaskList;
1104 if (selectedStackList != null) {
1105 list.add(selectedStackList.remove(0));
1113 ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1114 ProfilerInfo profilerInfo) {
1115 final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
1116 if (aInfo != null) {
1117 // Store the found target back into the intent, because now that
1118 // we have it we never want to do this again. For example, if the
1119 // user navigates back to this point in the history, we should
1120 // always restart the exact same activity.
1121 intent.setComponent(new ComponentName(
1122 aInfo.applicationInfo.packageName, aInfo.name));
1124 // Don't debug things in the system process
1125 if (!aInfo.processName.equals("system")) {
1126 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
1127 mService.setDebugApp(aInfo.processName, true, false);
1130 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1131 mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1134 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1135 mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1138 if (profilerInfo != null) {
1139 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
1146 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
1147 return resolveIntent(intent, resolvedType, userId, 0);
1150 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
1152 return AppGlobals.getPackageManager().resolveIntent(intent, resolvedType,
1153 PackageManager.MATCH_DEFAULT_ONLY | flags
1154 | ActivityManagerService.STOCK_PM_FLAGS, userId);
1155 } catch (RemoteException e) {
1160 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1161 ProfilerInfo profilerInfo, int userId) {
1162 final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1163 return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1166 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1167 boolean andResume, boolean checkConfig) throws RemoteException {
1169 if (!allPausedActivitiesComplete()) {
1170 // While there are activities pausing we skipping starting any new activities until
1171 // pauses are complete. NOTE: that we also do this for activities that are starting in
1172 // the paused state because they will first be resumed then paused on the client side.
1173 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1174 "realStartActivityLocked: Skipping start of r=" + r
1175 + " some activities pausing...");
1180 r.startFreezingScreenLocked(app, 0);
1181 mWindowManager.setAppVisibility(r.appToken, true);
1183 // schedule launch ticks to collect information about slow apps.
1184 r.startLaunchTickingLocked();
1187 // Have the window manager re-evaluate the orientation of
1188 // the screen based on the new activity order. Note that
1189 // as a result of this, it can call back into the activity
1190 // manager with a new orientation. We don't care about that,
1191 // because the activity is not currently running so we are
1192 // just restarting it anyway.
1194 Configuration config = mWindowManager.updateOrientationFromAppTokens(
1195 mService.mConfiguration,
1196 r.mayFreezeScreenLocked(app) ? r.appToken : null);
1197 // Deferring resume here because we're going to launch new activity shortly.
1198 // We don't want to perform a redundant launch of the same record while ensuring
1199 // configurations and trying to resume top activity of focused stack.
1200 mService.updateConfigurationLocked(config, r, false, true /* deferResume */);
1204 app.waitingToKill = null;
1206 r.lastLaunchTime = SystemClock.uptimeMillis();
1208 if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1210 int idx = app.activities.indexOf(r);
1212 app.activities.add(r);
1214 mService.updateLruProcessLocked(app, true, null);
1215 mService.updateOomAdjLocked();
1217 final TaskRecord task = r.task;
1218 if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1219 task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
1220 setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE", false);
1223 final ActivityStack stack = task.stack;
1225 if (app.thread == null) {
1226 throw new RemoteException();
1228 List<ResultInfo> results = null;
1229 List<ReferrerIntent> newIntents = null;
1231 results = r.results;
1232 newIntents = r.newIntents;
1234 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1235 "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1236 + " newIntents=" + newIntents + " andResume=" + andResume);
1238 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
1239 r.userId, System.identityHashCode(r),
1240 task.taskId, r.shortComponentName);
1242 if (r.isHomeActivity()) {
1243 // Home process is the root process of the task.
1244 mService.mHomeProcess = task.mActivities.get(0).app;
1246 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
1247 PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
1249 r.forceNewConfig = false;
1250 mService.showUnsupportedZoomDialogIfNeededLocked(r);
1251 mService.showAskCompatModeDialogLocked(r);
1252 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1253 ProfilerInfo profilerInfo = null;
1254 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1255 if (mService.mProfileProc == null || mService.mProfileProc == app) {
1256 mService.mProfileProc = app;
1257 final String profileFile = mService.mProfileFile;
1258 if (profileFile != null) {
1259 ParcelFileDescriptor profileFd = mService.mProfileFd;
1260 if (profileFd != null) {
1262 profileFd = profileFd.dup();
1263 } catch (IOException e) {
1264 if (profileFd != null) {
1267 } catch (IOException o) {
1274 profilerInfo = new ProfilerInfo(profileFile, profileFd,
1275 mService.mSamplingInterval, mService.mAutoStopProfiler);
1281 app.hasShownUi = true;
1282 app.pendingUiClean = true;
1284 app.forceProcessStateUpTo(mService.mTopProcessState);
1285 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1286 System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
1287 new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
1288 task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
1289 newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
1291 if ((app.info.privateFlags&ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1292 // This may be a heavy-weight process! Note that the package
1293 // manager will ensure that only activity can run in the main
1294 // process of the .apk, which is the only thing that will be
1295 // considered heavy-weight.
1296 if (app.processName.equals(app.info.packageName)) {
1297 if (mService.mHeavyWeightProcess != null
1298 && mService.mHeavyWeightProcess != app) {
1299 Slog.w(TAG, "Starting new heavy weight process " + app
1300 + " when already running "
1301 + mService.mHeavyWeightProcess);
1303 mService.mHeavyWeightProcess = app;
1304 Message msg = mService.mHandler.obtainMessage(
1305 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1307 mService.mHandler.sendMessage(msg);
1311 } catch (RemoteException e) {
1312 if (r.launchFailed) {
1313 // This is the second time we failed -- finish activity
1315 Slog.e(TAG, "Second failure launching "
1316 + r.intent.getComponent().flattenToShortString()
1317 + ", giving up", e);
1318 mService.appDiedLocked(app);
1319 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1320 "2nd-crash", false);
1324 // This is the first time we failed -- restart process and
1326 app.activities.remove(r);
1330 r.launchFailed = false;
1331 if (stack.updateLRUListLocked(r)) {
1332 Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
1336 // As part of the process of launching, ActivityThread also performs
1338 stack.minimalResumeActivityLocked(r);
1340 // This activity is not starting in the resumed state... which should look like we asked
1341 // it to pause+stop (but remain visible), and it has done so and reported back the
1342 // current icicle and other state.
1343 if (DEBUG_STATES) Slog.v(TAG_STATES,
1344 "Moving to PAUSED: " + r + " (starting in paused state)");
1348 // Launch the new version setup screen if needed. We do this -after-
1349 // launching the initial activity (that is, home), so that it can have
1350 // a chance to initialize itself while in the background, making the
1351 // switch back to it faster and look better.
1352 if (isFocusedStack(stack)) {
1353 mService.startSetupActivityLocked();
1356 // Update any services we are bound to that might care about whether
1357 // their client may have activities.
1358 if (r.app != null) {
1359 mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1365 void startSpecificActivityLocked(ActivityRecord r,
1366 boolean andResume, boolean checkConfig) {
1367 // Is this activity's application already running?
1368 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1369 r.info.applicationInfo.uid, true);
1371 r.task.stack.setLaunchTime(r);
1373 if (app != null && app.thread != null) {
1375 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1376 || !"android".equals(r.info.packageName)) {
1377 // Don't add this if it is a platform component that is marked
1378 // to run in multiple processes, because this is actually
1379 // part of the framework so doesn't make sense to track as a
1380 // separate apk in the process.
1381 app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1382 mService.mProcessStats);
1384 realStartActivityLocked(r, app, andResume, checkConfig);
1386 } catch (RemoteException e) {
1387 Slog.w(TAG, "Exception when starting activity "
1388 + r.intent.getComponent().flattenToShortString(), e);
1391 // If a dead object exception was thrown -- fall through to
1392 // restart the application.
1395 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
1396 "activity", r.intent.getComponent(), false, false, true);
1399 boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
1400 String resultWho, int requestCode, int callingPid, int callingUid,
1401 String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
1402 ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
1403 final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1405 if (startAnyPerm == PERMISSION_GRANTED) {
1408 final int componentRestriction = getComponentRestrictionForCallingPackage(
1409 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1410 final int actionRestriction = getActionRestrictionForCallingPackage(
1411 intent.getAction(), callingPackage, callingPid, callingUid);
1412 if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1413 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1414 if (resultRecord != null) {
1415 resultStack.sendActivityResultLocked(-1,
1416 resultRecord, resultWho, requestCode,
1417 Activity.RESULT_CANCELED, null);
1420 if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1421 msg = "Permission Denial: starting " + intent.toString()
1422 + " from " + callerApp + " (pid=" + callingPid
1423 + ", uid=" + callingUid + ")" + " with revoked permission "
1424 + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1425 } else if (!aInfo.exported) {
1426 msg = "Permission Denial: starting " + intent.toString()
1427 + " from " + callerApp + " (pid=" + callingPid
1428 + ", uid=" + callingUid + ")"
1429 + " not exported from uid " + aInfo.applicationInfo.uid;
1431 msg = "Permission Denial: starting " + intent.toString()
1432 + " from " + callerApp + " (pid=" + callingPid
1433 + ", uid=" + callingUid + ")"
1434 + " requires " + aInfo.permission;
1437 throw new SecurityException(msg);
1440 if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1441 final String message = "Appop Denial: starting " + intent.toString()
1442 + " from " + callerApp + " (pid=" + callingPid
1443 + ", uid=" + callingUid + ")"
1444 + " requires " + AppOpsManager.permissionToOp(
1445 ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1446 Slog.w(TAG, message);
1448 } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1449 final String message = "Appop Denial: starting " + intent.toString()
1450 + " from " + callerApp + " (pid=" + callingPid
1451 + ", uid=" + callingUid + ")"
1452 + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1453 Slog.w(TAG, message);
1456 if (options != null && options.getLaunchTaskId() != -1) {
1457 final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1458 callingPid, callingUid);
1459 if (startInTaskPerm != PERMISSION_GRANTED) {
1460 final String msg = "Permission Denial: starting " + intent.toString()
1461 + " from " + callerApp + " (pid=" + callingPid
1462 + ", uid=" + callingUid + ") with launchTaskId="
1463 + options.getLaunchTaskId();
1465 throw new SecurityException(msg);
1472 UserInfo getUserInfo(int userId) {
1473 final long identity = Binder.clearCallingIdentity();
1475 return UserManager.get(mService.mContext).getUserInfo(userId);
1477 Binder.restoreCallingIdentity(identity);
1481 private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
1482 String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
1483 if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1484 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
1485 == PackageManager.PERMISSION_DENIED) {
1486 return ACTIVITY_RESTRICTION_PERMISSION;
1489 if (activityInfo.permission == null) {
1490 return ACTIVITY_RESTRICTION_NONE;
1493 final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1494 if (opCode == AppOpsManager.OP_NONE) {
1495 return ACTIVITY_RESTRICTION_NONE;
1498 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1499 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1500 if (!ignoreTargetSecurity) {
1501 return ACTIVITY_RESTRICTION_APPOP;
1505 return ACTIVITY_RESTRICTION_NONE;
1508 private int getActionRestrictionForCallingPackage(String action,
1509 String callingPackage, int callingPid, int callingUid) {
1510 if (action == null) {
1511 return ACTIVITY_RESTRICTION_NONE;
1514 String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1515 if (permission == null) {
1516 return ACTIVITY_RESTRICTION_NONE;
1519 final PackageInfo packageInfo;
1521 packageInfo = mService.mContext.getPackageManager()
1522 .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1523 } catch (PackageManager.NameNotFoundException e) {
1524 Slog.i(TAG, "Cannot find package info for " + callingPackage);
1525 return ACTIVITY_RESTRICTION_NONE;
1528 if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
1529 return ACTIVITY_RESTRICTION_NONE;
1532 if (mService.checkPermission(permission, callingPid, callingUid) ==
1533 PackageManager.PERMISSION_DENIED) {
1534 return ACTIVITY_RESTRICTION_PERMISSION;
1537 final int opCode = AppOpsManager.permissionToOpCode(permission);
1538 if (opCode == AppOpsManager.OP_NONE) {
1539 return ACTIVITY_RESTRICTION_NONE;
1542 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1543 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1544 return ACTIVITY_RESTRICTION_APPOP;
1547 return ACTIVITY_RESTRICTION_NONE;
1550 boolean moveActivityStackToFront(ActivityRecord r, String reason) {
1552 // Not sure what you are trying to do, but it is not going to work...
1555 final TaskRecord task = r.task;
1556 if (task == null || task.stack == null) {
1557 Slog.w(TAG, "Can't move stack to front for r=" + r + " task=" + task);
1560 task.stack.moveToFront(reason, task);
1564 void setLaunchSource(int uid) {
1565 mLaunchingActivity.setWorkSource(new WorkSource(uid));
1568 void acquireLaunchWakelock() {
1569 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1570 throw new IllegalStateException("Calling must be system uid");
1572 mLaunchingActivity.acquire();
1573 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1574 // To be safe, don't allow the wake lock to be held for too long.
1575 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1580 * Called when the frontmost task is idle.
1581 * @return the state of mService.mBooting before this was called.
1583 private boolean checkFinishBootingLocked() {
1584 final boolean booting = mService.mBooting;
1585 boolean enableScreen = false;
1586 mService.mBooting = false;
1587 if (!mService.mBooted) {
1588 mService.mBooted = true;
1589 enableScreen = true;
1591 if (booting || enableScreen) {
1592 mService.postFinishBooting(booting, enableScreen);
1598 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
1599 Configuration config) {
1600 if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
1602 ArrayList<ActivityRecord> finishes = null;
1603 ArrayList<UserState> startingUsers = null;
1606 boolean booting = false;
1607 boolean activityRemoved = false;
1609 ActivityRecord r = ActivityRecord.forTokenLocked(token);
1611 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1612 + Debug.getCallers(4));
1613 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1614 r.finishLaunchTickingLocked();
1616 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
1619 // This is a hack to semi-deal with a race condition
1620 // in the client where it can be constructed with a
1621 // newer configuration from when we asked it to launch.
1622 // We'll update with whatever configuration it now says
1623 // it used to launch.
1624 if (config != null) {
1625 r.configuration = config;
1628 // We are now idle. If someone is waiting for a thumbnail from
1629 // us, we can now deliver.
1632 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
1633 if (isFocusedStack(r.task.stack) || fromTimeout) {
1634 booting = checkFinishBootingLocked();
1638 if (allResumedActivitiesIdle()) {
1640 mService.scheduleAppGcsLocked();
1643 if (mLaunchingActivity.isHeld()) {
1644 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1645 if (VALIDATE_WAKE_LOCK_CALLER &&
1646 Binder.getCallingUid() != Process.myUid()) {
1647 throw new IllegalStateException("Calling must be system uid");
1649 mLaunchingActivity.release();
1651 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1654 // Atomically retrieve all of the other things to do.
1655 final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(true);
1656 NS = stops != null ? stops.size() : 0;
1657 if ((NF = mFinishingActivities.size()) > 0) {
1658 finishes = new ArrayList<>(mFinishingActivities);
1659 mFinishingActivities.clear();
1662 if (mStartingUsers.size() > 0) {
1663 startingUsers = new ArrayList<>(mStartingUsers);
1664 mStartingUsers.clear();
1667 // Stop any activities that are scheduled to do so but have been
1668 // waiting for the next one to start.
1669 for (int i = 0; i < NS; i++) {
1671 final ActivityStack stack = r.task.stack;
1672 if (stack != null) {
1674 stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1676 stack.stopActivityLocked(r);
1681 // Finish any activities that are scheduled to do so but have been
1682 // waiting for the next one to start.
1683 for (int i = 0; i < NF; i++) {
1684 r = finishes.get(i);
1685 final ActivityStack stack = r.task.stack;
1686 if (stack != null) {
1687 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1692 // Complete user switch
1693 if (startingUsers != null) {
1694 for (int i = 0; i < startingUsers.size(); i++) {
1695 mService.mUserController.finishUserSwitch(startingUsers.get(i));
1700 mService.trimApplications();
1702 //mWindowManager.dump();
1704 if (activityRemoved) {
1705 resumeFocusedStackTopActivityLocked();
1711 boolean handleAppDiedLocked(ProcessRecord app) {
1712 boolean hasVisibleActivities = false;
1713 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1714 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1715 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1716 hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
1719 return hasVisibleActivities;
1722 void closeSystemDialogsLocked() {
1723 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1724 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1725 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1726 stacks.get(stackNdx).closeSystemDialogsLocked();
1731 void removeUserLocked(int userId) {
1732 mUserStackInFront.delete(userId);
1736 * Update the last used stack id for non-current user (current user's last
1737 * used stack is the focused stack)
1739 void updateUserStackLocked(int userId, ActivityStack stack) {
1740 if (userId != mCurrentUser) {
1741 mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
1746 * @return true if some activity was finished (or would have finished if doit were true).
1748 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
1749 boolean doit, boolean evenPersistent, int userId) {
1750 boolean didSomething = false;
1751 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1752 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1753 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1754 final ActivityStack stack = stacks.get(stackNdx);
1755 if (stack.finishDisabledPackageActivitiesLocked(
1756 packageName, filterByClasses, doit, evenPersistent, userId)) {
1757 didSomething = true;
1761 return didSomething;
1764 void updatePreviousProcessLocked(ActivityRecord r) {
1765 // Now that this process has stopped, we may want to consider
1766 // it to be the previous app to try to keep around in case
1767 // the user wants to return to it.
1769 // First, found out what is currently the foreground app, so that
1770 // we don't blow away the previous app if this activity is being
1771 // hosted by the process that is actually still the foreground.
1772 ProcessRecord fgApp = null;
1773 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1774 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1775 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1776 final ActivityStack stack = stacks.get(stackNdx);
1777 if (isFocusedStack(stack)) {
1778 if (stack.mResumedActivity != null) {
1779 fgApp = stack.mResumedActivity.app;
1780 } else if (stack.mPausingActivity != null) {
1781 fgApp = stack.mPausingActivity.app;
1788 // Now set this one as the previous process, only if that really
1790 if (r.app != null && fgApp != null && r.app != fgApp
1791 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1792 && r.app != mService.mHomeProcess) {
1793 mService.mPreviousProcess = r.app;
1794 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1798 boolean resumeFocusedStackTopActivityLocked() {
1799 return resumeFocusedStackTopActivityLocked(null, null, null);
1802 boolean resumeFocusedStackTopActivityLocked(
1803 ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
1804 if (targetStack != null && isFocusedStack(targetStack)) {
1805 return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
1807 final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
1808 if (r == null || r.state != RESUMED) {
1809 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
1814 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
1815 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1816 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1817 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1818 stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
1823 TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
1824 TaskRecord finishedTask = null;
1825 ActivityStack focusedStack = getFocusedStack();
1826 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1827 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1828 final int numStacks = stacks.size();
1829 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
1830 final ActivityStack stack = stacks.get(stackNdx);
1831 TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
1832 if (stack == focusedStack || finishedTask == null) {
1837 return finishedTask;
1840 void finishVoiceTask(IVoiceInteractionSession session) {
1841 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1842 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1843 final int numStacks = stacks.size();
1844 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
1845 final ActivityStack stack = stacks.get(stackNdx);
1846 stack.finishVoiceTask(session);
1851 void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
1852 String reason, boolean forceNonResizeable) {
1853 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
1854 mUserLeaving = true;
1856 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
1857 // Caller wants the home activity moved with it. To accomplish this,
1858 // we'll just indicate that this task returns to the home task.
1859 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
1861 if (task.stack == null) {
1862 Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
1863 + task + " to front. Stack is null");
1867 if (task.isResizeable() && options != null) {
1868 int stackId = options.getLaunchStackId();
1869 if (canUseActivityOptionsLaunchBounds(options, stackId)) {
1870 final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
1871 task.updateOverrideConfiguration(bounds);
1872 if (stackId == INVALID_STACK_ID) {
1873 stackId = task.getLaunchStackId();
1875 if (stackId != task.stack.mStackId) {
1876 final ActivityStack stack = moveTaskToStackUncheckedLocked(
1877 task, stackId, ON_TOP, !FORCE_FOCUS, reason);
1878 stackId = stack.mStackId;
1879 // moveTaskToStackUncheckedLocked() should already placed the task on top,
1880 // still need moveTaskToFrontLocked() below for any transition settings.
1882 if (StackId.resizeStackWithLaunchBounds(stackId)) {
1883 resizeStackLocked(stackId, bounds,
1884 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
1885 !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */, !DEFER_RESUME);
1887 // WM resizeTask must be done after the task is moved to the correct stack,
1888 // because Task's setBounds() also updates dim layer's bounds, but that has
1889 // dependency on the stack.
1890 mWindowManager.resizeTask(task.taskId, task.mBounds, task.mOverrideConfig,
1891 false /* relayout */, false /* forced */);
1896 final ActivityRecord r = task.getTopActivity();
1897 task.stack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
1898 r == null ? null : r.appTimeTracker, reason);
1900 if (DEBUG_STACK) Slog.d(TAG_STACK,
1901 "findTaskToMoveToFront: moved to front of stack=" + task.stack);
1903 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, task.stack.mStackId,
1904 forceNonResizeable);
1907 boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
1908 // We use the launch bounds in the activity options is the device supports freeform
1909 // window management or is launching into the pinned stack.
1910 if (options.getLaunchBounds() == null) {
1913 return (mService.mSupportsPictureInPicture && launchStackId == PINNED_STACK_ID)
1914 || mService.mSupportsFreeformWindowManagement;
1917 ActivityStack getStack(int stackId) {
1918 return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
1921 ActivityStack getStack(int stackId, boolean createStaticStackIfNeeded, boolean createOnTop) {
1922 ActivityContainer activityContainer = mActivityContainers.get(stackId);
1923 if (activityContainer != null) {
1924 return activityContainer.mStack;
1926 if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
1929 return createStackOnDisplay(stackId, Display.DEFAULT_DISPLAY, createOnTop);
1932 ArrayList<ActivityStack> getStacks() {
1933 ArrayList<ActivityStack> allStacks = new ArrayList<>();
1934 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1935 allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
1940 IBinder getHomeActivityToken() {
1941 ActivityRecord homeActivity = getHomeActivity();
1942 if (homeActivity != null) {
1943 return homeActivity.appToken;
1948 ActivityRecord getHomeActivity() {
1949 return getHomeActivityForUser(mCurrentUser);
1952 ActivityRecord getHomeActivityForUser(int userId) {
1953 final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
1954 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
1955 final TaskRecord task = tasks.get(taskNdx);
1956 if (task.isHomeTask()) {
1957 final ArrayList<ActivityRecord> activities = task.mActivities;
1958 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1959 final ActivityRecord r = activities.get(activityNdx);
1960 if (r.isHomeActivity()
1961 && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
1971 * Returns if a stack should be treated as if it's docked. Returns true if the stack is
1972 * the docked stack itself, or if it's side-by-side to the docked stack.
1974 boolean isStackDockedInEffect(int stackId) {
1975 return stackId == DOCKED_STACK_ID ||
1976 (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
1979 ActivityContainer createVirtualActivityContainer(ActivityRecord parentActivity,
1980 IActivityContainerCallback callback) {
1981 ActivityContainer activityContainer =
1982 new VirtualActivityContainer(parentActivity, callback);
1983 mActivityContainers.put(activityContainer.mStackId, activityContainer);
1984 if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS,
1985 "createActivityContainer: " + activityContainer);
1986 parentActivity.mChildContainers.add(activityContainer);
1987 return activityContainer;
1990 void removeChildActivityContainers(ActivityRecord parentActivity) {
1991 final ArrayList<ActivityContainer> childStacks = parentActivity.mChildContainers;
1992 for (int containerNdx = childStacks.size() - 1; containerNdx >= 0; --containerNdx) {
1993 ActivityContainer container = childStacks.remove(containerNdx);
1994 if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS, "removeChildActivityContainers: removing "
1996 container.release();
2000 void deleteActivityContainer(IActivityContainer container) {
2001 ActivityContainer activityContainer = (ActivityContainer)container;
2002 if (activityContainer != null) {
2003 if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS,
2004 "deleteActivityContainer: callers=" + Debug.getCallers(4));
2005 final int stackId = activityContainer.mStackId;
2006 mActivityContainers.remove(stackId);
2007 mWindowManager.removeStack(stackId);
2011 void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
2012 boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
2013 if (stackId == DOCKED_STACK_ID) {
2014 resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
2015 preserveWindows, deferResume);
2018 final ActivityStack stack = getStack(stackId);
2019 if (stack == null) {
2020 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2024 if (!allowResizeInDockedMode && getStack(DOCKED_STACK_ID) != null) {
2025 // If the docked stack exist we don't allow resizes of stacks not caused by the docked
2026 // stack size changing so things don't get out of sync.
2030 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
2031 mWindowManager.deferSurfaceLayout();
2033 resizeStackUncheckedLocked(stack, bounds, tempTaskBounds, tempTaskInsetBounds);
2035 stack.ensureVisibleActivitiesConfigurationLocked(
2036 stack.topRunningActivityLocked(), preserveWindows);
2039 mWindowManager.continueSurfaceLayout();
2040 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2044 void deferUpdateBounds(int stackId) {
2045 final ActivityStack stack = getStack(stackId);
2046 if (stack != null) {
2047 stack.deferUpdateBounds();
2051 void continueUpdateBounds(int stackId) {
2052 final ActivityStack stack = getStack(stackId);
2053 if (stack != null) {
2054 stack.continueUpdateBounds();
2058 void notifyAppTransitionDone() {
2059 continueUpdateBounds(HOME_STACK_ID);
2060 for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2061 final int taskId = mResizingTasksDuringAnimation.valueAt(i);
2062 if (anyTaskForIdLocked(taskId, !RESTORE_FROM_RECENTS, INVALID_STACK_ID) != null) {
2063 mWindowManager.setTaskDockedResizing(taskId, false);
2066 mResizingTasksDuringAnimation.clear();
2069 void resizeStackUncheckedLocked(ActivityStack stack, Rect bounds, Rect tempTaskBounds,
2070 Rect tempTaskInsetBounds) {
2071 bounds = TaskRecord.validateBounds(bounds);
2073 if (!stack.updateBoundsAllowed(bounds, tempTaskBounds, tempTaskInsetBounds)) {
2078 mTmpConfigs.clear();
2079 mTmpInsetBounds.clear();
2080 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2081 final Rect taskBounds = tempTaskBounds != null ? tempTaskBounds : bounds;
2082 final Rect insetBounds = tempTaskInsetBounds != null ? tempTaskInsetBounds : taskBounds;
2083 for (int i = tasks.size() - 1; i >= 0; i--) {
2084 final TaskRecord task = tasks.get(i);
2085 if (task.isResizeable()) {
2086 if (stack.mStackId == FREEFORM_WORKSPACE_STACK_ID) {
2087 // For freeform stack we don't adjust the size of the tasks to match that
2088 // of the stack, but we do try to make sure the tasks are still contained
2089 // with the bounds of the stack.
2090 tempRect2.set(task.mBounds);
2091 fitWithinBounds(tempRect2, bounds);
2092 task.updateOverrideConfiguration(tempRect2);
2094 task.updateOverrideConfiguration(taskBounds, insetBounds);
2098 mTmpConfigs.put(task.taskId, task.mOverrideConfig);
2099 mTmpBounds.put(task.taskId, task.mBounds);
2100 if (tempTaskInsetBounds != null) {
2101 mTmpInsetBounds.put(task.taskId, tempTaskInsetBounds);
2105 // We might trigger a configuration change. Save the current task bounds for freezing.
2106 mWindowManager.prepareFreezingTaskBounds(stack.mStackId);
2107 stack.mFullscreen = mWindowManager.resizeStack(stack.mStackId, bounds, mTmpConfigs,
2108 mTmpBounds, mTmpInsetBounds);
2109 stack.setBounds(bounds);
2112 void moveTasksToFullscreenStackLocked(int fromStackId, boolean onTop) {
2113 final ActivityStack stack = getStack(fromStackId);
2114 if (stack == null) {
2118 mWindowManager.deferSurfaceLayout();
2120 if (fromStackId == DOCKED_STACK_ID) {
2122 // We are moving all tasks from the docked stack to the fullscreen stack,
2123 // which is dismissing the docked stack, so resize all other stacks to
2124 // fullscreen here already so we don't end up with resize trashing.
2125 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2126 if (StackId.isResizeableByDockedStack(i)) {
2127 ActivityStack otherStack = getStack(i);
2128 if (otherStack != null) {
2129 resizeStackLocked(i, null, null, null, PRESERVE_WINDOWS,
2130 true /* allowResizeInDockedMode */, DEFER_RESUME);
2135 // Also disable docked stack resizing since we have manually adjusted the
2136 // size of other stacks above and we don't want to trigger a docked stack
2137 // resize when we remove task from it below and it is detached from the
2138 // display because it no longer contains any tasks.
2139 mAllowDockedStackResize = false;
2141 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2142 final int size = tasks.size();
2144 for (int i = 0; i < size; i++) {
2145 moveTaskToStackLocked(tasks.get(i).taskId,
2146 FULLSCREEN_WORKSPACE_STACK_ID, onTop, onTop /*forceFocus*/,
2147 "moveTasksToFullscreenStack", ANIMATE, DEFER_RESUME);
2150 ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2151 resumeFocusedStackTopActivityLocked();
2153 for (int i = size - 1; i >= 0; i--) {
2154 positionTaskInStackLocked(tasks.get(i).taskId,
2155 FULLSCREEN_WORKSPACE_STACK_ID, 0);
2159 mAllowDockedStackResize = true;
2160 mWindowManager.continueSurfaceLayout();
2164 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2165 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2166 boolean preserveWindows) {
2167 resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
2168 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows,
2169 false /* deferResume */);
2172 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2173 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2174 boolean preserveWindows, boolean deferResume) {
2176 if (!mAllowDockedStackResize) {
2177 // Docked stack resize currently disabled.
2181 final ActivityStack stack = getStack(DOCKED_STACK_ID);
2182 if (stack == null) {
2183 Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2187 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2188 mWindowManager.deferSurfaceLayout();
2190 // Don't allow re-entry while resizing. E.g. due to docked stack detaching.
2191 mAllowDockedStackResize = false;
2192 ActivityRecord r = stack.topRunningActivityLocked();
2193 resizeStackUncheckedLocked(stack, dockedBounds, tempDockedTaskBounds,
2194 tempDockedTaskInsetBounds);
2196 // TODO: Checking for isAttached might not be needed as if the user passes in null
2197 // dockedBounds then they want the docked stack to be dismissed.
2198 if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2199 // The dock stack either was dismissed or went fullscreen, which is kinda the same.
2200 // In this case we make all other static stacks fullscreen and move all
2201 // docked stack tasks to the fullscreen stack.
2202 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, ON_TOP);
2204 // stack shouldn't contain anymore activities, so nothing to resume.
2207 // Docked stacks occupy a dedicated region on screen so the size of all other
2208 // static stacks need to be adjusted so they don't overlap with the docked stack.
2209 // We get the bounds to use from window manager which has been adjusted for any
2210 // screen controls and is also the same for all stacks.
2211 mWindowManager.getStackDockedModeBounds(
2212 HOME_STACK_ID, tempRect, true /* ignoreVisibility */);
2213 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2214 if (StackId.isResizeableByDockedStack(i) && getStack(i) != null) {
2215 resizeStackLocked(i, tempRect, tempOtherTaskBounds,
2216 tempOtherTaskInsetBounds, preserveWindows,
2217 true /* allowResizeInDockedMode */, deferResume);
2222 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows);
2225 mAllowDockedStackResize = true;
2226 mWindowManager.continueSurfaceLayout();
2227 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2230 mResizeDockedStackTimeout.notifyResizing(dockedBounds,
2231 tempDockedTaskBounds != null
2232 || tempDockedTaskInsetBounds != null
2233 || tempOtherTaskBounds != null
2234 || tempOtherTaskInsetBounds != null);
2237 void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
2238 final ActivityStack stack = getStack(PINNED_STACK_ID);
2239 if (stack == null) {
2240 Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2243 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2244 mWindowManager.deferSurfaceLayout();
2246 ActivityRecord r = stack.topRunningActivityLocked();
2247 resizeStackUncheckedLocked(stack, pinnedBounds, tempPinnedTaskBounds,
2249 stack.ensureVisibleActivitiesConfigurationLocked(r, false);
2251 mWindowManager.continueSurfaceLayout();
2252 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2256 boolean resizeTaskLocked(TaskRecord task, Rect bounds, int resizeMode, boolean preserveWindow,
2257 boolean deferResume) {
2258 if (!task.isResizeable()) {
2259 Slog.w(TAG, "resizeTask: task " + task + " not resizeable.");
2263 // If this is a forced resize, let it go through even if the bounds is not changing,
2264 // as we might need a relayout due to surface size change (to/from fullscreen).
2265 final boolean forced = (resizeMode & RESIZE_MODE_FORCED) != 0;
2266 if (Objects.equals(task.mBounds, bounds) && !forced) {
2267 // Nothing to do here...
2270 bounds = TaskRecord.validateBounds(bounds);
2272 if (!mWindowManager.isValidTaskId(task.taskId)) {
2273 // Task doesn't exist in window manager yet (e.g. was restored from recents).
2274 // All we can do for now is update the bounds so it can be used when the task is
2275 // added to window manager.
2276 task.updateOverrideConfiguration(bounds);
2277 if (task.stack != null && task.stack.mStackId != FREEFORM_WORKSPACE_STACK_ID) {
2278 // re-restore the task so it can have the proper stack association.
2279 restoreRecentTaskLocked(task, FREEFORM_WORKSPACE_STACK_ID);
2284 // Do not move the task to another stack here.
2285 // This method assumes that the task is already placed in the right stack.
2286 // we do not mess with that decision and we only do the resize!
2288 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeTask_" + task.taskId);
2290 final Configuration overrideConfig = task.updateOverrideConfiguration(bounds);
2291 // This variable holds information whether the configuration didn't change in a significant
2292 // way and the activity was kept the way it was. If it's false, it means the activity had
2293 // to be relaunched due to configuration change.
2294 boolean kept = true;
2295 if (overrideConfig != null) {
2296 final ActivityRecord r = task.topRunningActivityLocked();
2298 final ActivityStack stack = task.stack;
2299 kept = stack.ensureActivityConfigurationLocked(r, 0, preserveWindow);
2303 // All other activities must be made visible with their correct configuration.
2304 ensureActivitiesVisibleLocked(r, 0, !PRESERVE_WINDOWS);
2306 resumeFocusedStackTopActivityLocked();
2311 mWindowManager.resizeTask(task.taskId, task.mBounds, task.mOverrideConfig, kept, forced);
2313 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2317 ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
2318 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
2319 if (activityDisplay == null) {
2323 ActivityContainer activityContainer = new ActivityContainer(stackId);
2324 mActivityContainers.put(stackId, activityContainer);
2325 activityContainer.attachToDisplayLocked(activityDisplay, onTop);
2326 return activityContainer.mStack;
2329 int getNextStackId() {
2331 if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2332 && getStack(mNextFreeStackId) == null) {
2337 return mNextFreeStackId;
2341 * Restores a recent task to a stack
2342 * @param task The recent task to be restored.
2343 * @param stackId The stack to restore the task to (default launch stack will be used
2344 * if stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}).
2345 * @return true if the task has been restored successfully.
2347 private boolean restoreRecentTaskLocked(TaskRecord task, int stackId) {
2348 if (stackId == INVALID_STACK_ID) {
2349 stackId = task.getLaunchStackId();
2350 } else if (stackId == DOCKED_STACK_ID && !task.canGoInDockedStack()) {
2351 // Preferred stack is the docked stack, but the task can't go in the docked stack.
2352 // Put it in the fullscreen stack.
2353 stackId = FULLSCREEN_WORKSPACE_STACK_ID;
2356 if (task.stack != null) {
2357 // Task has already been restored once. See if we need to do anything more
2358 if (task.stack.mStackId == stackId) {
2359 // Nothing else to do since it is already restored in the right stack.
2362 // Remove current stack association, so we can re-associate the task with the
2363 // right stack below.
2364 task.stack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING);
2367 final ActivityStack stack =
2368 getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
2370 if (stack == null) {
2371 // What does this mean??? Not sure how we would get here...
2372 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2373 "Unable to find/create stack to restore recent task=" + task);
2377 stack.addTask(task, false, "restoreRecentTask");
2378 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2379 "Added restored task=" + task + " to stack=" + stack);
2380 final ArrayList<ActivityRecord> activities = task.mActivities;
2381 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2382 stack.addConfigOverride(activities.get(activityNdx), task);
2388 * Moves the specified task record to the input stack id.
2389 * WARNING: This method performs an unchecked/raw move of the task and
2390 * can leave the system in an unstable state if used incorrectly.
2391 * Use {@link #moveTaskToStackLocked} to perform safe task movement to a stack.
2392 * @param task Task to move.
2393 * @param stackId Id of stack to move task to.
2394 * @param toTop True if the task should be placed at the top of the stack.
2395 * @param forceFocus if focus should be moved to the new stack
2396 * @param reason Reason the task is been moved.
2397 * @return The stack the task was moved to.
2399 ActivityStack moveTaskToStackUncheckedLocked(
2400 TaskRecord task, int stackId, boolean toTop, boolean forceFocus, String reason) {
2402 if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
2403 throw new IllegalStateException("moveTaskToStackUncheckedLocked: Device doesn't "
2404 + "support multi-window task=" + task + " to stackId=" + stackId);
2407 final ActivityRecord r = task.topRunningActivityLocked();
2408 final ActivityStack prevStack = task.stack;
2409 final boolean wasFocused = isFocusedStack(prevStack) && (topRunningActivityLocked() == r);
2410 final boolean wasResumed = prevStack.mResumedActivity == r;
2411 // In some cases the focused stack isn't the front stack. E.g. pinned stack.
2412 // Whenever we are moving the top activity from the front stack we want to make sure to move
2413 // the stack to the front.
2414 final boolean wasFront = isFrontStack(prevStack)
2415 && (prevStack.topRunningActivityLocked() == r);
2417 if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
2418 // We don't allow moving a unresizeable task to the docked stack since the docked
2419 // stack is used for split-screen mode and will cause things like the docked divider to
2420 // show up. We instead leave the task in its current stack or move it to the fullscreen
2421 // stack if it isn't currently in a stack.
2422 stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
2423 Slog.w(TAG, "Can not move unresizeable task=" + task
2424 + " to docked stack. Moving to stackId=" + stackId + " instead.");
2427 // Temporarily disable resizeablility of task we are moving. We don't want it to be resized
2428 // if a docked stack is created below which will lead to the stack we are moving from and
2429 // its resizeable tasks being resized.
2430 task.mTemporarilyUnresizable = true;
2431 final ActivityStack stack = getStack(stackId, CREATE_IF_NEEDED, toTop);
2432 task.mTemporarilyUnresizable = false;
2433 mWindowManager.moveTaskToStack(task.taskId, stack.mStackId, toTop);
2434 stack.addTask(task, toTop, reason);
2436 // If the task had focus before (or we're requested to move focus),
2437 // move focus to the new stack by moving the stack to the front.
2438 stack.moveToFrontAndResumeStateIfNeeded(
2439 r, forceFocus || wasFocused || wasFront, wasResumed, reason);
2444 boolean moveTaskToStackLocked(int taskId, int stackId, boolean toTop, boolean forceFocus,
2445 String reason, boolean animate) {
2446 return moveTaskToStackLocked(taskId, stackId, toTop, forceFocus, reason, animate,
2447 false /* deferResume */);
2450 boolean moveTaskToStackLocked(int taskId, int stackId, boolean toTop, boolean forceFocus,
2451 String reason, boolean animate, boolean deferResume) {
2452 final TaskRecord task = anyTaskForIdLocked(taskId);
2454 Slog.w(TAG, "moveTaskToStack: no task for id=" + taskId);
2458 if (task.stack != null && task.stack.mStackId == stackId) {
2459 // You are already in the right stack silly...
2460 Slog.i(TAG, "moveTaskToStack: taskId=" + taskId + " already in stackId=" + stackId);
2464 if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
2465 throw new IllegalArgumentException("moveTaskToStack:"
2466 + "Attempt to move task " + taskId + " to unsupported freeform stack");
2469 final ActivityRecord topActivity = task.getTopActivity();
2470 final int sourceStackId = task.stack != null ? task.stack.mStackId : INVALID_STACK_ID;
2471 final boolean mightReplaceWindow =
2472 StackId.replaceWindowsOnTaskMove(sourceStackId, stackId) && topActivity != null;
2473 if (mightReplaceWindow) {
2474 // We are about to relaunch the activity because its configuration changed due to
2475 // being maximized, i.e. size change. The activity will first remove the old window
2476 // and then add a new one. This call will tell window manager about this, so it can
2477 // preserve the old window until the new one is drawn. This prevents having a gap
2478 // between the removal and addition, in which no window is visible. We also want the
2479 // entrance of the new window to be properly animated.
2480 // Note here we always set the replacing window first, as the flags might be needed
2481 // during the relaunch. If we end up not doing any relaunch, we clear the flags later.
2482 mWindowManager.setReplacingWindow(topActivity.appToken, animate);
2485 mWindowManager.deferSurfaceLayout();
2486 final int preferredLaunchStackId = stackId;
2487 boolean kept = true;
2489 final ActivityStack stack = moveTaskToStackUncheckedLocked(
2490 task, stackId, toTop, forceFocus, reason + " moveTaskToStack");
2491 stackId = stack.mStackId;
2494 stack.mNoAnimActivities.add(topActivity);
2497 // We might trigger a configuration change. Save the current task bounds for freezing.
2498 mWindowManager.prepareFreezingTaskBounds(stack.mStackId);
2500 // Make sure the task has the appropriate bounds/size for the stack it is in.
2501 if (stackId == FULLSCREEN_WORKSPACE_STACK_ID && task.mBounds != null) {
2502 kept = resizeTaskLocked(task, stack.mBounds, RESIZE_MODE_SYSTEM,
2503 !mightReplaceWindow, deferResume);
2504 } else if (stackId == FREEFORM_WORKSPACE_STACK_ID) {
2505 Rect bounds = task.getLaunchBounds();
2506 if (bounds == null) {
2507 stack.layoutTaskInStack(task, null);
2508 bounds = task.mBounds;
2510 kept = resizeTaskLocked(task, bounds, RESIZE_MODE_FORCED, !mightReplaceWindow,
2512 } else if (stackId == DOCKED_STACK_ID || stackId == PINNED_STACK_ID) {
2513 kept = resizeTaskLocked(task, stack.mBounds, RESIZE_MODE_SYSTEM,
2514 !mightReplaceWindow, deferResume);
2517 mWindowManager.continueSurfaceLayout();
2520 if (mightReplaceWindow) {
2521 // If we didn't actual do a relaunch (indicated by kept==true meaning we kept the old
2522 // window), we need to clear the replace window settings. Otherwise, we schedule a
2523 // timeout to remove the old window if the replacing window is not coming in time.
2524 mWindowManager.scheduleClearReplacingWindowIfNeeded(topActivity.appToken, !kept);
2529 // The task might have already been running and its visibility needs to be synchronized with
2530 // the visibility of the stack / windows.
2531 ensureActivitiesVisibleLocked(null, 0, !mightReplaceWindow);
2532 resumeFocusedStackTopActivityLocked();
2535 handleNonResizableTaskIfNeeded(task, preferredLaunchStackId, stackId);
2537 return (preferredLaunchStackId == stackId);
2540 boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect bounds) {
2541 final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2542 if (stack == null) {
2543 throw new IllegalArgumentException(
2544 "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
2547 final ActivityRecord r = stack.topRunningActivityLocked();
2549 Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
2550 + " in stack=" + stack);
2554 if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
2556 "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
2561 moveActivityToPinnedStackLocked(r, "moveTopActivityToPinnedStack", bounds);
2565 void moveActivityToPinnedStackLocked(ActivityRecord r, String reason, Rect bounds) {
2566 mWindowManager.deferSurfaceLayout();
2568 final TaskRecord task = r.task;
2570 if (r == task.stack.getVisibleBehindActivity()) {
2571 // An activity can't be pinned and visible behind at the same time. Go ahead and
2572 // release it from been visible behind before pinning.
2573 requestVisibleBehindLocked(r, false);
2576 // Need to make sure the pinned stack exist so we can resize it below...
2577 final ActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
2579 // Resize the pinned stack to match the current size of the task the activity we are
2580 // going to be moving is currently contained in. We do this to have the right starting
2581 // animation bounds for the pinned stack to the desired bounds the caller wants.
2582 resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
2583 null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
2584 true /* allowResizeInDockedMode */, !DEFER_RESUME);
2586 if (task.mActivities.size() == 1) {
2587 // There is only one activity in the task. So, we can just move the task over to
2588 // the stack without re-parenting the activity in a different task.
2589 if (task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE) {
2590 // Move the home stack forward if the task we just moved to the pinned stack
2591 // was launched from home so home should be visible behind it.
2592 moveHomeStackToFront(reason);
2594 moveTaskToStackLocked(
2595 task.taskId, PINNED_STACK_ID, ON_TOP, FORCE_FOCUS, reason, !ANIMATE);
2597 stack.moveActivityToStack(r);
2600 mWindowManager.continueSurfaceLayout();
2603 // The task might have already been running and its visibility needs to be synchronized
2604 // with the visibility of the stack / windows.
2605 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
2606 resumeFocusedStackTopActivityLocked();
2608 mWindowManager.animateResizePinnedStack(bounds, -1);
2609 mService.notifyActivityPinnedLocked();
2612 void positionTaskInStackLocked(int taskId, int stackId, int position) {
2613 final TaskRecord task = anyTaskForIdLocked(taskId);
2615 Slog.w(TAG, "positionTaskInStackLocked: no task for id=" + taskId);
2618 final ActivityStack stack = getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
2620 task.updateOverrideConfigurationForStack(stack);
2622 mWindowManager.positionTaskInStack(
2623 taskId, stackId, position, task.mBounds, task.mOverrideConfig);
2624 stack.positionTask(task, position);
2625 // The task might have already been running and its visibility needs to be synchronized with
2626 // the visibility of the stack / windows.
2627 stack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
2628 resumeFocusedStackTopActivityLocked();
2631 ActivityRecord findTaskLocked(ActivityRecord r) {
2632 mTmpFindTaskResult.r = null;
2633 mTmpFindTaskResult.matchedByRootAffinity = false;
2634 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
2635 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2636 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2637 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2638 final ActivityStack stack = stacks.get(stackNdx);
2639 if (!r.isApplicationActivity() && !stack.isHomeStack()) {
2640 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (home activity) " + stack);
2643 if (!stack.mActivityContainer.isEligibleForNewTasks()) {
2644 if (DEBUG_TASKS) Slog.d(TAG_TASKS,
2645 "Skipping stack: (new task not allowed) " + stack);
2648 stack.findTaskLocked(r, mTmpFindTaskResult);
2649 // It is possible to have task in multiple stacks with the same root affinity.
2650 // If the match we found was based on root affinity we keep on looking to see if
2651 // there is a better match in another stack. We eventually return the match based
2652 // on root affinity if we don't find a better match.
2653 if (mTmpFindTaskResult.r != null && !mTmpFindTaskResult.matchedByRootAffinity) {
2654 return mTmpFindTaskResult.r;
2658 if (DEBUG_TASKS && mTmpFindTaskResult.r == null) Slog.d(TAG_TASKS, "No task found");
2659 return mTmpFindTaskResult.r;
2662 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
2663 boolean compareIntentFilters) {
2664 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2665 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2666 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2667 final ActivityRecord ar = stacks.get(stackNdx)
2668 .findActivityLocked(intent, info, compareIntentFilters);
2677 void goingToSleepLocked() {
2678 scheduleSleepTimeout();
2679 if (!mGoingToSleep.isHeld()) {
2680 mGoingToSleep.acquire();
2681 if (mLaunchingActivity.isHeld()) {
2682 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
2683 throw new IllegalStateException("Calling must be system uid");
2685 mLaunchingActivity.release();
2686 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
2689 checkReadyForSleepLocked();
2692 boolean shutdownLocked(int timeout) {
2693 goingToSleepLocked();
2695 boolean timedout = false;
2696 final long endTime = System.currentTimeMillis() + timeout;
2698 boolean cantShutdown = false;
2699 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2700 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2701 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2702 cantShutdown |= stacks.get(stackNdx).checkReadyForSleepLocked();
2706 long timeRemaining = endTime - System.currentTimeMillis();
2707 if (timeRemaining > 0) {
2709 mService.wait(timeRemaining);
2710 } catch (InterruptedException e) {
2713 Slog.w(TAG, "Activity manager shutdown timed out");
2722 // Force checkReadyForSleep to complete.
2723 mSleepTimeout = true;
2724 checkReadyForSleepLocked();
2729 void comeOutOfSleepIfNeededLocked() {
2730 removeSleepTimeouts();
2731 if (mGoingToSleep.isHeld()) {
2732 mGoingToSleep.release();
2734 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2735 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2736 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2737 final ActivityStack stack = stacks.get(stackNdx);
2738 stack.awakeFromSleepingLocked();
2739 if (isFocusedStack(stack)) {
2740 resumeFocusedStackTopActivityLocked();
2744 mGoingToSleepActivities.clear();
2747 void activitySleptLocked(ActivityRecord r) {
2748 mGoingToSleepActivities.remove(r);
2749 checkReadyForSleepLocked();
2752 void checkReadyForSleepLocked() {
2753 if (!mService.isSleepingOrShuttingDownLocked()) {
2758 if (!mSleepTimeout) {
2759 boolean dontSleep = false;
2760 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2761 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2762 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2763 dontSleep |= stacks.get(stackNdx).checkReadyForSleepLocked();
2767 if (mStoppingActivities.size() > 0) {
2768 // Still need to tell some activities to stop; can't sleep yet.
2769 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to stop "
2770 + mStoppingActivities.size() + " activities");
2771 scheduleIdleLocked();
2775 if (mGoingToSleepActivities.size() > 0) {
2776 // Still need to tell some activities to sleep; can't sleep yet.
2777 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to sleep "
2778 + mGoingToSleepActivities.size() + " activities");
2787 // Send launch end powerhint before going sleep
2788 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
2790 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2791 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2792 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2793 stacks.get(stackNdx).goToSleep();
2797 removeSleepTimeouts();
2799 if (mGoingToSleep.isHeld()) {
2800 mGoingToSleep.release();
2802 if (mService.mShuttingDown) {
2803 mService.notifyAll();
2807 boolean reportResumedActivityLocked(ActivityRecord r) {
2808 final ActivityStack stack = r.task.stack;
2809 if (isFocusedStack(stack)) {
2810 mService.updateUsageStats(r, true);
2812 if (allResumedActivitiesComplete()) {
2813 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
2814 mWindowManager.executeAppTransition();
2820 void handleAppCrashLocked(ProcessRecord app) {
2821 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2822 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2823 int stackNdx = stacks.size() - 1;
2824 while (stackNdx >= 0) {
2825 stacks.get(stackNdx).handleAppCrashLocked(app);
2831 boolean requestVisibleBehindLocked(ActivityRecord r, boolean visible) {
2832 final ActivityStack stack = r.task.stack;
2833 if (stack == null) {
2834 if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
2835 "requestVisibleBehind: r=" + r + " visible=" + visible + " stack is null");
2839 if (visible && !StackId.activitiesCanRequestVisibleBehind(stack.mStackId)) {
2840 if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND, "requestVisibleBehind: r=" + r
2841 + " visible=" + visible + " stackId=" + stack.mStackId
2842 + " can't contain visible behind activities");
2846 final boolean isVisible = stack.hasVisibleBehindActivity();
2847 if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
2848 "requestVisibleBehind r=" + r + " visible=" + visible + " isVisible=" + isVisible);
2850 final ActivityRecord top = topRunningActivityLocked();
2851 if (top == null || top == r || (visible == isVisible)) {
2852 if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND, "requestVisibleBehind: quick return");
2853 stack.setVisibleBehindActivity(visible ? r : null);
2857 // A non-top activity is reporting a visibility change.
2858 if (visible && top.fullscreen) {
2859 // Let the caller know that it can't be seen.
2860 if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
2861 "requestVisibleBehind: returning top.fullscreen=" + top.fullscreen
2862 + " top.state=" + top.state + " top.app=" + top.app + " top.app.thread="
2865 } else if (!visible && stack.getVisibleBehindActivity() != r) {
2866 // Only the activity set as currently visible behind should actively reset its
2867 // visible behind state.
2868 if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND,
2869 "requestVisibleBehind: returning visible=" + visible
2870 + " stack.getVisibleBehindActivity()=" + stack.getVisibleBehindActivity()
2875 stack.setVisibleBehindActivity(visible ? r : null);
2877 // If there is a translucent home activity, we need to force it stop being translucent,
2878 // because we can't depend on the application to necessarily perform that operation.
2879 // Check out b/14469711 for details.
2880 final ActivityRecord next = stack.findNextTranslucentActivity(r);
2881 if (next != null && next.isHomeActivity()) {
2882 mService.convertFromTranslucent(next.appToken);
2885 if (top.app != null && top.app.thread != null) {
2886 // Notify the top app of the change.
2888 top.app.thread.scheduleBackgroundVisibleBehindChanged(top.appToken, visible);
2889 } catch (RemoteException e) {
2895 // Called when WindowManager has finished animating the launchingBehind activity to the back.
2896 void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
2897 final TaskRecord task = r.task;
2898 final ActivityStack stack = task.stack;
2900 r.mLaunchTaskBehind = false;
2901 task.setLastThumbnailLocked(stack.screenshotActivitiesLocked(r));
2902 mRecentTasks.addLocked(task);
2903 mService.notifyTaskStackChangedLocked();
2904 mWindowManager.setAppVisibility(r.appToken, false);
2906 // When launching tasks behind, update the last active time of the top task after the new
2907 // task has been shown briefly
2908 final ActivityRecord top = stack.topActivity();
2910 top.task.touchActiveTime();
2914 void scheduleLaunchTaskBehindComplete(IBinder token) {
2915 mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
2918 void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
2919 boolean preserveWindows) {
2920 // First the front stacks. In case any are not fullscreen and are in front of home.
2921 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2922 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2923 final int topStackNdx = stacks.size() - 1;
2924 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
2925 final ActivityStack stack = stacks.get(stackNdx);
2926 stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
2931 void invalidateTaskLayers() {
2932 mTaskLayersChanged = true;
2935 void rankTaskLayersIfNeeded() {
2936 if (!mTaskLayersChanged) {
2939 mTaskLayersChanged = false;
2940 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
2941 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2943 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2944 baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
2949 void clearOtherAppTimeTrackers(AppTimeTracker except) {
2950 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2951 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2952 final int topStackNdx = stacks.size() - 1;
2953 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
2954 final ActivityStack stack = stacks.get(stackNdx);
2955 stack.clearOtherAppTimeTrackers(except);
2960 void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
2961 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2962 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2963 final int numStacks = stacks.size();
2964 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2965 final ActivityStack stack = stacks.get(stackNdx);
2966 stack.scheduleDestroyActivities(app, reason);
2971 void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
2972 // Examine all activities currently running in the process.
2973 TaskRecord firstTask = null;
2974 // Tasks is non-null only if two or more tasks are found.
2975 ArraySet<TaskRecord> tasks = null;
2976 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
2977 for (int i = 0; i < app.activities.size(); i++) {
2978 ActivityRecord r = app.activities.get(i);
2979 // First, if we find an activity that is in the process of being destroyed,
2980 // then we just aren't going to do anything for now; we want things to settle
2981 // down before we try to prune more activities.
2982 if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
2983 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
2986 // Don't consider any activies that are currently not in a state where they
2987 // can be destroyed.
2988 if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
2989 || r.state == PAUSED || r.state == STOPPING) {
2990 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
2993 if (r.task != null) {
2994 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + r.task
2996 if (firstTask == null) {
2998 } else if (firstTask != r.task) {
2999 if (tasks == null) {
3000 tasks = new ArraySet<>();
3001 tasks.add(firstTask);
3007 if (tasks == null) {
3008 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
3011 // If we have activities in multiple tasks that are in a position to be destroyed,
3012 // let's iterate through the tasks and release the oldest one.
3013 final int numDisplays = mActivityDisplays.size();
3014 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3015 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3016 // Step through all stacks starting from behind, to hit the oldest things first.
3017 for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
3018 final ActivityStack stack = stacks.get(stackNdx);
3019 // Try to release activities in this stack; if we manage to, we are done.
3020 if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
3027 boolean switchUserLocked(int userId, UserState uss) {
3028 final int focusStackId = mFocusedStack.getStackId();
3029 // We dismiss the docked stack whenever we switch users.
3030 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, focusStackId == DOCKED_STACK_ID);
3032 mUserStackInFront.put(mCurrentUser, focusStackId);
3033 final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
3034 mCurrentUser = userId;
3036 mStartingUsers.add(uss);
3037 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3038 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3039 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3040 final ActivityStack stack = stacks.get(stackNdx);
3041 stack.switchUserLocked(userId);
3042 TaskRecord task = stack.topTask();
3044 mWindowManager.moveTaskToTop(task.taskId);
3049 ActivityStack stack = getStack(restoreStackId);
3050 if (stack == null) {
3053 final boolean homeInFront = stack.isHomeStack();
3054 if (stack.isOnHomeDisplay()) {
3055 stack.moveToFront("switchUserOnHomeDisplay");
3057 // Stack was moved to another display while user was swapped out.
3058 resumeHomeStackTask(HOME_ACTIVITY_TYPE, null, "switchUserOnOtherDisplay");
3063 /** Checks whether the userid is a profile of the current user. */
3064 boolean isCurrentProfileLocked(int userId) {
3065 if (userId == mCurrentUser) return true;
3066 return mService.mUserController.isCurrentProfileLocked(userId);
3069 /** Checks whether the activity should be shown for current user. */
3070 boolean okToShowLocked(ActivityRecord r) {
3071 return r != null && ((r.info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0
3072 || (isCurrentProfileLocked(r.userId)
3073 && !mService.mUserController.isUserStoppingOrShuttingDownLocked(r.userId)));
3076 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(boolean remove) {
3077 ArrayList<ActivityRecord> stops = null;
3079 final boolean nowVisible = allResumedActivitiesVisible();
3080 for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3081 ActivityRecord s = mStoppingActivities.get(activityNdx);
3082 boolean waitingVisible = mWaitingVisibleActivities.contains(s);
3083 if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
3084 + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
3085 if (waitingVisible && nowVisible) {
3086 mWaitingVisibleActivities.remove(s);
3088 // If this activity is finishing, it is sitting on top of
3089 // everyone else but we now know it is no longer needed...
3090 // so get rid of it. Otherwise, we need to go through the
3091 // normal flow and hide it once we determine that it is
3092 // hidden by the activities in front of it.
3093 if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
3094 mWindowManager.setAppVisibility(s.appToken, false);
3095 waitingVisible = false;
3098 if ((!waitingVisible || mService.isSleepingOrShuttingDownLocked()) && remove) {
3099 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
3100 if (stops == null) {
3101 stops = new ArrayList<>();
3104 mStoppingActivities.remove(activityNdx);
3111 void validateTopActivitiesLocked() {
3112 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3113 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3114 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3115 final ActivityStack stack = stacks.get(stackNdx);
3116 final ActivityRecord r = stack.topRunningActivityLocked();
3117 final ActivityState state = r == null ? DESTROYED : r.state;
3118 if (isFocusedStack(stack)) {
3119 if (r == null) Slog.e(TAG,
3120 "validateTop...: null top activity, stack=" + stack);
3122 final ActivityRecord pausing = stack.mPausingActivity;
3123 if (pausing != null && pausing == r) Slog.e(TAG,
3124 "validateTop...: top stack has pausing activity r=" + r
3125 + " state=" + state);
3126 if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3127 "validateTop...: activity in front not resumed r=" + r
3128 + " state=" + state);
3131 final ActivityRecord resumed = stack.mResumedActivity;
3132 if (resumed != null && resumed == r) Slog.e(TAG,
3133 "validateTop...: back stack has resumed activity r=" + r
3134 + " state=" + state);
3135 if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3136 "validateTop...: activity in back resumed r=" + r + " state=" + state);
3142 private String lockTaskModeToString() {
3143 switch (mLockTaskModeState) {
3144 case LOCK_TASK_MODE_LOCKED:
3146 case LOCK_TASK_MODE_PINNED:
3148 case LOCK_TASK_MODE_NONE:
3150 default: return "unknown=" + mLockTaskModeState;
3154 public void dump(PrintWriter pw, String prefix) {
3155 pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
3156 pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
3157 pw.print(prefix); pw.println("mSleepTimeout=" + mSleepTimeout);
3159 pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
3160 pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
3161 pw.print(prefix); pw.println("mActivityContainers=" + mActivityContainers);
3162 pw.print(prefix); pw.print("mLockTaskModeState=" + lockTaskModeToString());
3163 final SparseArray<String[]> packages = mService.mLockTaskPackages;
3164 if (packages.size() > 0) {
3165 pw.println(" mLockTaskPackages (userId:packages)=");
3166 for (int i = 0; i < packages.size(); ++i) {
3167 pw.print(prefix); pw.print(prefix); pw.print(packages.keyAt(i));
3168 pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
3171 pw.println(" mLockTaskModeTasks" + mLockTaskModeTasks);
3174 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
3175 return mFocusedStack.getDumpActivitiesLocked(name);
3178 static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3179 boolean needSep, String prefix) {
3180 if (activity != null) {
3181 if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3186 pw.println(activity);
3193 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3194 boolean dumpClient, String dumpPackage) {
3195 boolean printed = false;
3196 boolean needSep = false;
3197 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3198 ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
3199 pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
3200 pw.println(" (activities from top to bottom):");
3201 ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3202 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3203 final ActivityStack stack = stacks.get(stackNdx);
3204 StringBuilder stackHeader = new StringBuilder(128);
3205 stackHeader.append(" Stack #");
3206 stackHeader.append(stack.mStackId);
3207 stackHeader.append(":");
3208 stackHeader.append("\n");
3209 stackHeader.append(" mFullscreen=" + stack.mFullscreen);
3210 stackHeader.append("\n");
3211 stackHeader.append(" mBounds=" + stack.mBounds);
3212 printed |= stack.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, dumpPackage,
3213 needSep, stackHeader.toString());
3214 printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, " ", "Run", false,
3215 !dumpAll, false, dumpPackage, true,
3216 " Running activities (most recent first):", null);
3219 boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3220 " mPausingActivity: ");
3225 pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3226 " mResumedActivity: ");
3232 pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3233 " mLastPausedActivity: ");
3238 printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3239 needSep, " mLastNoHistoryActivity: ");
3245 printed |= dumpHistoryList(fd, pw, mFinishingActivities, " ", "Fin", false, !dumpAll,
3246 false, dumpPackage, true, " Activities waiting to finish:", null);
3247 printed |= dumpHistoryList(fd, pw, mStoppingActivities, " ", "Stop", false, !dumpAll,
3248 false, dumpPackage, true, " Activities waiting to stop:", null);
3249 printed |= dumpHistoryList(fd, pw, mWaitingVisibleActivities, " ", "Wait", false, !dumpAll,
3250 false, dumpPackage, true, " Activities waiting for another to become visible:",
3252 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3253 false, dumpPackage, true, " Activities waiting to sleep:", null);
3254 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3255 false, dumpPackage, true, " Activities waiting to sleep:", null);
3260 static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
3261 String prefix, String label, boolean complete, boolean brief, boolean client,
3262 String dumpPackage, boolean needNL, String header1, String header2) {
3263 TaskRecord lastTask = null;
3264 String innerPrefix = null;
3265 String[] args = null;
3266 boolean printed = false;
3267 for (int i=list.size()-1; i>=0; i--) {
3268 final ActivityRecord r = list.get(i);
3269 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3272 if (innerPrefix == null) {
3273 innerPrefix = prefix + " ";
3274 args = new String[0];
3277 final boolean full = !brief && (complete || !r.isInHistory());
3282 if (header1 != null) {
3283 pw.println(header1);
3286 if (header2 != null) {
3287 pw.println(header2);
3290 if (lastTask != r.task) {
3293 pw.print(full ? "* " : " ");
3294 pw.println(lastTask);
3296 lastTask.dump(pw, prefix + " ");
3297 } else if (complete) {
3298 // Complete + brief == give a summary. Isn't that obvious?!?
3299 if (lastTask.intent != null) {
3300 pw.print(prefix); pw.print(" ");
3301 pw.println(lastTask.intent.toInsecureStringWithClip());
3305 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
3306 pw.print(" #"); pw.print(i); pw.print(": ");
3309 r.dump(pw, innerPrefix);
3310 } else if (complete) {
3311 // Complete + brief == give a summary. Isn't that obvious?!?
3312 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3313 if (r.app != null) {
3314 pw.print(innerPrefix); pw.println(r.app);
3317 if (client && r.app != null && r.app.thread != null) {
3318 // flush anything that is already in the PrintWriter since the thread is going
3319 // to write to the file descriptor directly
3322 TransferPipe tp = new TransferPipe();
3324 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
3325 r.appToken, innerPrefix, args);
3326 // Short timeout, since blocking here can
3327 // deadlock with the application.
3332 } catch (IOException e) {
3333 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3334 } catch (RemoteException e) {
3335 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3343 void scheduleIdleTimeoutLocked(ActivityRecord next) {
3344 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3345 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
3346 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
3347 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
3350 final void scheduleIdleLocked() {
3351 mHandler.sendEmptyMessage(IDLE_NOW_MSG);
3354 void removeTimeoutsForActivityLocked(ActivityRecord r) {
3355 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
3356 + Debug.getCallers(4));
3357 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3360 final void scheduleResumeTopActivities() {
3361 if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
3362 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
3366 void removeSleepTimeouts() {
3367 mSleepTimeout = false;
3368 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
3371 final void scheduleSleepTimeout() {
3372 removeSleepTimeouts();
3373 mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
3377 public void onDisplayAdded(int displayId) {
3378 if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
3379 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
3383 public void onDisplayRemoved(int displayId) {
3384 if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
3385 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
3389 public void onDisplayChanged(int displayId) {
3390 if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
3391 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
3394 private void handleDisplayAdded(int displayId) {
3396 synchronized (mService) {
3397 newDisplay = mActivityDisplays.get(displayId) == null;
3399 ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
3400 if (activityDisplay.mDisplay == null) {
3401 Slog.w(TAG, "Display " + displayId + " gone before initialization complete");
3404 mActivityDisplays.put(displayId, activityDisplay);
3405 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
3409 mWindowManager.onDisplayAdded(displayId);
3413 private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
3414 mDefaultMinSizeOfResizeableTask =
3415 mService.mContext.getResources().getDimensionPixelSize(
3416 com.android.internal.R.dimen.default_minimal_size_resizable_task);
3419 private void handleDisplayRemoved(int displayId) {
3420 synchronized (mService) {
3421 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3422 if (activityDisplay != null) {
3423 ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3424 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3425 stacks.get(stackNdx).mActivityContainer.detachLocked();
3427 mActivityDisplays.remove(displayId);
3430 mWindowManager.onDisplayRemoved(displayId);
3433 private void handleDisplayChanged(int displayId) {
3434 synchronized (mService) {
3435 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3436 if (activityDisplay != null) {
3437 // TODO: Update the bounds.
3440 mWindowManager.onDisplayChanged(displayId);
3443 private StackInfo getStackInfoLocked(ActivityStack stack) {
3444 final ActivityDisplay display = mActivityDisplays.get(Display.DEFAULT_DISPLAY);
3445 StackInfo info = new StackInfo();
3446 mWindowManager.getStackBounds(stack.mStackId, info.bounds);
3447 info.displayId = Display.DEFAULT_DISPLAY;
3448 info.stackId = stack.mStackId;
3449 info.userId = stack.mCurrentUser;
3450 info.visible = stack.getStackVisibilityLocked(null) == STACK_VISIBLE;
3451 info.position = display != null
3452 ? display.mStacks.indexOf(stack)
3455 ArrayList<TaskRecord> tasks = stack.getAllTasks();
3456 final int numTasks = tasks.size();
3457 int[] taskIds = new int[numTasks];
3458 String[] taskNames = new String[numTasks];
3459 Rect[] taskBounds = new Rect[numTasks];
3460 int[] taskUserIds = new int[numTasks];
3461 for (int i = 0; i < numTasks; ++i) {
3462 final TaskRecord task = tasks.get(i);
3463 taskIds[i] = task.taskId;
3464 taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
3465 : task.realActivity != null ? task.realActivity.flattenToString()
3466 : task.getTopActivity() != null ? task.getTopActivity().packageName
3468 taskBounds[i] = new Rect();
3469 mWindowManager.getTaskBounds(task.taskId, taskBounds[i]);
3470 taskUserIds[i] = task.userId;
3472 info.taskIds = taskIds;
3473 info.taskNames = taskNames;
3474 info.taskBounds = taskBounds;
3475 info.taskUserIds = taskUserIds;
3477 final ActivityRecord top = stack.topRunningActivityLocked();
3478 info.topActivity = top != null ? top.intent.getComponent() : null;
3482 StackInfo getStackInfoLocked(int stackId) {
3483 ActivityStack stack = getStack(stackId);
3484 if (stack != null) {
3485 return getStackInfoLocked(stack);
3490 ArrayList<StackInfo> getAllStackInfosLocked() {
3491 ArrayList<StackInfo> list = new ArrayList<>();
3492 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3493 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3494 for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
3495 list.add(getStackInfoLocked(stacks.get(ndx)));
3501 TaskRecord getLockedTaskLocked() {
3502 final int top = mLockTaskModeTasks.size() - 1;
3504 return mLockTaskModeTasks.get(top);
3509 boolean isLockedTask(TaskRecord task) {
3510 return mLockTaskModeTasks.contains(task);
3513 boolean isLastLockedTask(TaskRecord task) {
3514 return mLockTaskModeTasks.size() == 1 && mLockTaskModeTasks.contains(task);
3517 void removeLockedTaskLocked(final TaskRecord task) {
3518 if (!mLockTaskModeTasks.remove(task)) {
3521 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "removeLockedTaskLocked: removed " + task);
3522 if (mLockTaskModeTasks.isEmpty()) {
3524 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
3525 " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
3526 final Message lockTaskMsg = Message.obtain();
3527 lockTaskMsg.arg1 = task.userId;
3528 lockTaskMsg.what = LOCK_TASK_END_MSG;
3529 mHandler.sendMessage(lockTaskMsg);
3533 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId, int actualStackId) {
3534 handleNonResizableTaskIfNeeded(task, preferredStackId, actualStackId,
3535 false /* forceNonResizable */);
3538 void handleNonResizableTaskIfNeeded(
3539 TaskRecord task, int preferredStackId, int actualStackId, boolean forceNonResizable) {
3540 if ((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
3541 || task.isHomeTask()) {
3545 final ActivityRecord topActivity = task.getTopActivity();
3546 if (!task.canGoInDockedStack() || forceNonResizable) {
3547 // Display a warning toast that we tried to put a non-dockable task in the docked stack.
3548 mService.mHandler.sendEmptyMessage(NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG);
3550 // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
3551 // we need to move it to top of fullscreen stack, otherwise it will be covered.
3552 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
3553 } else if (topActivity != null && topActivity.isNonResizableOrForced()
3554 && !topActivity.noDisplay) {
3555 String packageName = topActivity.appInfo.packageName;
3556 mService.mHandler.obtainMessage(NOTIFY_FORCED_RESIZABLE_MSG, task.taskId, 0,
3557 packageName).sendToTarget();
3561 void showLockTaskToast() {
3562 if (mLockTaskNotify != null) {
3563 mLockTaskNotify.showToast(mLockTaskModeState);
3567 void showLockTaskEscapeMessageLocked(TaskRecord task) {
3568 if (mLockTaskModeTasks.contains(task)) {
3569 mHandler.sendEmptyMessage(SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG);
3573 void setLockTaskModeLocked(TaskRecord task, int lockTaskModeState, String reason,
3574 boolean andResume) {
3576 // Take out of lock task mode if necessary
3577 final TaskRecord lockedTask = getLockedTaskLocked();
3578 if (lockedTask != null) {
3579 removeLockedTaskLocked(lockedTask);
3580 if (!mLockTaskModeTasks.isEmpty()) {
3581 // There are locked tasks remaining, can only finish this task, not unlock it.
3582 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
3583 "setLockTaskModeLocked: Tasks remaining, can't unlock");
3584 lockedTask.performClearTaskLocked();
3585 resumeFocusedStackTopActivityLocked();
3589 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
3590 "setLockTaskModeLocked: No tasks to unlock. Callers=" + Debug.getCallers(4));
3594 // Should have already been checked, but do it again.
3595 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
3596 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
3597 "setLockTaskModeLocked: Can't lock due to auth");
3600 if (isLockTaskModeViolation(task)) {
3601 Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
3605 if (mLockTaskModeTasks.isEmpty()) {
3607 final Message lockTaskMsg = Message.obtain();
3608 lockTaskMsg.obj = task.intent.getComponent().getPackageName();
3609 lockTaskMsg.arg1 = task.userId;
3610 lockTaskMsg.what = LOCK_TASK_START_MSG;
3611 lockTaskMsg.arg2 = lockTaskModeState;
3612 mHandler.sendMessage(lockTaskMsg);
3614 // Add it or move it to the top.
3615 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskModeLocked: Locking to " + task +
3616 " Callers=" + Debug.getCallers(4));
3617 mLockTaskModeTasks.remove(task);
3618 mLockTaskModeTasks.add(task);
3620 if (task.mLockTaskUid == -1) {
3621 task.mLockTaskUid = task.effectiveUid;
3625 findTaskToMoveToFrontLocked(task, 0, null, reason,
3626 lockTaskModeState != LOCK_TASK_MODE_NONE);
3627 resumeFocusedStackTopActivityLocked();
3628 } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
3629 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, task.stack.mStackId,
3630 true /* forceNonResizable */);
3634 boolean isLockTaskModeViolation(TaskRecord task) {
3635 return isLockTaskModeViolation(task, false);
3638 boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) {
3639 if (getLockedTaskLocked() == task && !isNewClearTask) {
3642 final int lockTaskAuth = task.mLockTaskAuth;
3643 switch (lockTaskAuth) {
3644 case LOCK_TASK_AUTH_DONT_LOCK:
3645 return !mLockTaskModeTasks.isEmpty();
3646 case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
3647 case LOCK_TASK_AUTH_LAUNCHABLE:
3648 case LOCK_TASK_AUTH_WHITELISTED:
3650 case LOCK_TASK_AUTH_PINNABLE:
3651 // Pinnable tasks can't be launched on top of locktask tasks.
3652 return !mLockTaskModeTasks.isEmpty();
3654 Slog.w(TAG, "isLockTaskModeViolation: invalid lockTaskAuth value=" + lockTaskAuth);
3659 void onLockTaskPackagesUpdatedLocked() {
3660 boolean didSomething = false;
3661 for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
3662 final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx);
3663 final boolean wasWhitelisted =
3664 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
3665 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
3666 lockedTask.setLockTaskAuth();
3667 final boolean isWhitelisted =
3668 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
3669 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
3670 if (wasWhitelisted && !isWhitelisted) {
3671 // Lost whitelisting authorization. End it now.
3672 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "onLockTaskPackagesUpdated: removing " +
3673 lockedTask + " mLockTaskAuth=" + lockedTask.lockTaskAuthToString());
3674 removeLockedTaskLocked(lockedTask);
3675 lockedTask.performClearTaskLocked();
3676 didSomething = true;
3679 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3680 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3681 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3682 final ActivityStack stack = stacks.get(stackNdx);
3683 stack.onLockTaskPackagesUpdatedLocked();
3686 final ActivityRecord r = topRunningActivityLocked();
3687 final TaskRecord task = r != null ? r.task : null;
3688 if (mLockTaskModeTasks.isEmpty() && task != null
3689 && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
3690 // This task must have just been authorized.
3691 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK,
3692 "onLockTaskPackagesUpdated: starting new locktask task=" + task);
3693 setLockTaskModeLocked(task, ActivityManager.LOCK_TASK_MODE_LOCKED, "package updated",
3695 didSomething = true;
3698 resumeFocusedStackTopActivityLocked();
3702 int getLockTaskModeState() {
3703 return mLockTaskModeState;
3706 void activityRelaunchedLocked(IBinder token) {
3707 mWindowManager.notifyAppRelaunchingFinished(token);
3710 void activityRelaunchingLocked(ActivityRecord r) {
3711 mWindowManager.notifyAppRelaunching(r.appToken);
3714 void logStackState() {
3715 mActivityMetricsLogger.logWindowState();
3718 void scheduleReportMultiWindowModeChanged(TaskRecord task) {
3719 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
3720 final ActivityRecord r = task.mActivities.get(i);
3721 if (r.app != null && r.app.thread != null) {
3722 mMultiWindowModeChangedActivities.add(r);
3726 if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
3727 mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
3731 void scheduleReportPictureInPictureModeChangedIfNeeded(TaskRecord task, ActivityStack prevStack) {
3732 final ActivityStack stack = task.stack;
3733 if (prevStack == null || prevStack == stack
3734 || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
3738 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
3739 final ActivityRecord r = task.mActivities.get(i);
3740 if (r.app != null && r.app.thread != null) {
3741 mPipModeChangedActivities.add(r);
3745 if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
3746 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
3750 void setDockedStackMinimized(boolean minimized) {
3751 mIsDockMinimized = minimized;
3753 // Docked stack is not visible, no need to confirm credentials for its top activity.
3756 final ActivityStack dockedStack = getStack(StackId.DOCKED_STACK_ID);
3757 if (dockedStack == null) {
3760 final ActivityRecord top = dockedStack.topRunningActivityLocked();
3761 if (top != null && mService.mUserController.shouldConfirmCredentials(top.userId)) {
3762 mService.mActivityStarter.showConfirmDeviceCredential(top.userId);
3766 private final class ActivityStackSupervisorHandler extends Handler {
3768 public ActivityStackSupervisorHandler(Looper looper) {
3772 void activityIdleInternal(ActivityRecord r) {
3773 synchronized (mService) {
3774 activityIdleInternalLocked(r != null ? r.appToken : null, true, null);
3779 public void handleMessage(Message msg) {
3781 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
3782 synchronized (mService) {
3783 for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
3784 final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
3785 r.scheduleMultiWindowModeChanged();
3789 case REPORT_PIP_MODE_CHANGED_MSG: {
3790 synchronized (mService) {
3791 for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
3792 final ActivityRecord r = mPipModeChangedActivities.remove(i);
3793 r.schedulePictureInPictureModeChanged();
3797 case IDLE_TIMEOUT_MSG: {
3798 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3799 "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
3800 if (mService.mDidDexOpt) {
3801 mService.mDidDexOpt = false;
3802 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
3804 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
3807 // We don't at this point know if the activity is fullscreen,
3808 // so we need to be conservative and assume it isn't.
3809 activityIdleInternal((ActivityRecord)msg.obj);
3811 case IDLE_NOW_MSG: {
3812 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
3813 activityIdleInternal((ActivityRecord)msg.obj);
3815 case RESUME_TOP_ACTIVITY_MSG: {
3816 synchronized (mService) {
3817 resumeFocusedStackTopActivityLocked();
3820 case SLEEP_TIMEOUT_MSG: {
3821 synchronized (mService) {
3822 if (mService.isSleepingOrShuttingDownLocked()) {
3823 Slog.w(TAG, "Sleep timeout! Sleeping now.");
3824 mSleepTimeout = true;
3825 checkReadyForSleepLocked();
3829 case LAUNCH_TIMEOUT_MSG: {
3830 if (mService.mDidDexOpt) {
3831 mService.mDidDexOpt = false;
3832 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
3835 synchronized (mService) {
3836 if (mLaunchingActivity.isHeld()) {
3837 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
3838 if (VALIDATE_WAKE_LOCK_CALLER
3839 && Binder.getCallingUid() != Process.myUid()) {
3840 throw new IllegalStateException("Calling must be system uid");
3842 mLaunchingActivity.release();
3846 case HANDLE_DISPLAY_ADDED: {
3847 handleDisplayAdded(msg.arg1);
3849 case HANDLE_DISPLAY_CHANGED: {
3850 handleDisplayChanged(msg.arg1);
3852 case HANDLE_DISPLAY_REMOVED: {
3853 handleDisplayRemoved(msg.arg1);
3855 case CONTAINER_CALLBACK_VISIBILITY: {
3856 final ActivityContainer container = (ActivityContainer) msg.obj;
3857 final IActivityContainerCallback callback = container.mCallback;
3858 if (callback != null) {
3860 callback.setVisible(container.asBinder(), msg.arg1 == 1);
3861 } catch (RemoteException e) {
3865 case LOCK_TASK_START_MSG: {
3866 // When lock task starts, we disable the status bars.
3868 if (mLockTaskNotify == null) {
3869 mLockTaskNotify = new LockTaskNotify(mService.mContext);
3871 mLockTaskNotify.show(true);
3872 mLockTaskModeState = msg.arg2;
3873 if (getStatusBarService() != null) {
3875 if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
3876 flags = StatusBarManager.DISABLE_MASK
3877 & (~StatusBarManager.DISABLE_BACK);
3878 } else if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
3879 flags = StatusBarManager.DISABLE_MASK
3880 & (~StatusBarManager.DISABLE_BACK)
3881 & (~StatusBarManager.DISABLE_HOME)
3882 & (~StatusBarManager.DISABLE_RECENT);
3884 getStatusBarService().disable(flags, mToken,
3885 mService.mContext.getPackageName());
3887 mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
3888 if (getDevicePolicyManager() != null) {
3889 getDevicePolicyManager().notifyLockTaskModeChanged(true,
3890 (String)msg.obj, msg.arg1);
3892 } catch (RemoteException ex) {
3893 throw new RuntimeException(ex);
3896 case LOCK_TASK_END_MSG: {
3897 // When lock task ends, we enable the status bars.
3899 if (getStatusBarService() != null) {
3900 getStatusBarService().disable(StatusBarManager.DISABLE_NONE, mToken,
3901 mService.mContext.getPackageName());
3903 mWindowManager.reenableKeyguard(mToken);
3904 if (getDevicePolicyManager() != null) {
3905 getDevicePolicyManager().notifyLockTaskModeChanged(false, null,
3908 if (mLockTaskNotify == null) {
3909 mLockTaskNotify = new LockTaskNotify(mService.mContext);
3911 mLockTaskNotify.show(false);
3913 boolean shouldLockKeyguard = Settings.Secure.getInt(
3914 mService.mContext.getContentResolver(),
3915 Settings.Secure.LOCK_TO_APP_EXIT_LOCKED) != 0;
3916 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED && shouldLockKeyguard) {
3917 mWindowManager.lockNow(null);
3918 mWindowManager.dismissKeyguard();
3919 new LockPatternUtils(mService.mContext)
3920 .requireCredentialEntry(UserHandle.USER_ALL);
3922 } catch (SettingNotFoundException e) {
3923 // No setting, don't lock.
3925 } catch (RemoteException ex) {
3926 throw new RuntimeException(ex);
3928 mLockTaskModeState = LOCK_TASK_MODE_NONE;
3931 case SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG: {
3932 if (mLockTaskNotify == null) {
3933 mLockTaskNotify = new LockTaskNotify(mService.mContext);
3935 mLockTaskNotify.showToast(LOCK_TASK_MODE_PINNED);
3937 case CONTAINER_CALLBACK_TASK_LIST_EMPTY: {
3938 final ActivityContainer container = (ActivityContainer) msg.obj;
3939 final IActivityContainerCallback callback = container.mCallback;
3940 if (callback != null) {
3942 callback.onAllActivitiesComplete(container.asBinder());
3943 } catch (RemoteException e) {
3947 case LAUNCH_TASK_BEHIND_COMPLETE: {
3948 synchronized (mService) {
3949 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
3951 handleLaunchTaskBehindCompleteLocked(r);
3960 class ActivityContainer extends android.app.IActivityContainer.Stub {
3961 final static int FORCE_NEW_TASK_FLAGS = FLAG_ACTIVITY_NEW_TASK |
3962 FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION;
3964 IActivityContainerCallback mCallback = null;
3965 final ActivityStack mStack;
3966 ActivityRecord mParentActivity = null;
3969 boolean mVisible = true;
3971 /** Display this ActivityStack is currently on. Null if not attached to a Display. */
3972 ActivityDisplay mActivityDisplay;
3974 final static int CONTAINER_STATE_HAS_SURFACE = 0;
3975 final static int CONTAINER_STATE_NO_SURFACE = 1;
3976 final static int CONTAINER_STATE_FINISHING = 2;
3977 int mContainerState = CONTAINER_STATE_HAS_SURFACE;
3979 ActivityContainer(int stackId) {
3980 synchronized (mService) {
3982 mStack = new ActivityStack(this, mRecentTasks);
3983 mIdString = "ActivtyContainer{" + mStackId + "}";
3984 if (DEBUG_STACK) Slog.d(TAG_STACK, "Creating " + this);
3988 void attachToDisplayLocked(ActivityDisplay activityDisplay, boolean onTop) {
3989 if (DEBUG_STACK) Slog.d(TAG_STACK, "attachToDisplayLocked: " + this
3990 + " to display=" + activityDisplay + " onTop=" + onTop);
3991 mActivityDisplay = activityDisplay;
3992 mStack.attachDisplay(activityDisplay, onTop);
3993 activityDisplay.attachActivities(mStack, onTop);
3997 public void attachToDisplay(int displayId) {
3998 synchronized (mService) {
3999 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
4000 if (activityDisplay == null) {
4003 attachToDisplayLocked(activityDisplay, true);
4008 public int getDisplayId() {
4009 synchronized (mService) {
4010 if (mActivityDisplay != null) {
4011 return mActivityDisplay.mDisplayId;
4018 public int getStackId() {
4019 synchronized (mService) {
4025 public boolean injectEvent(InputEvent event) {
4026 final long origId = Binder.clearCallingIdentity();
4028 synchronized (mService) {
4029 if (mActivityDisplay != null) {
4030 return mInputManagerInternal.injectInputEvent(event,
4031 mActivityDisplay.mDisplayId,
4032 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
4037 Binder.restoreCallingIdentity(origId);
4042 public void release() {
4043 synchronized (mService) {
4044 if (mContainerState == CONTAINER_STATE_FINISHING) {
4047 mContainerState = CONTAINER_STATE_FINISHING;
4049 long origId = Binder.clearCallingIdentity();
4051 mStack.finishAllActivitiesLocked(false);
4052 mService.mActivityStarter.removePendingActivityLaunchesLocked(mStack);
4054 Binder.restoreCallingIdentity(origId);
4059 protected void detachLocked() {
4060 if (DEBUG_STACK) Slog.d(TAG_STACK, "detachLocked: " + this + " from display="
4061 + mActivityDisplay + " Callers=" + Debug.getCallers(2));
4062 if (mActivityDisplay != null) {
4063 mActivityDisplay.detachActivitiesLocked(mStack);
4064 mActivityDisplay = null;
4065 mStack.detachDisplay();
4070 public final int startActivity(Intent intent) {
4071 return mService.startActivity(intent, this);
4075 public final int startActivityIntentSender(IIntentSender intentSender)
4076 throws TransactionTooLargeException {
4077 mService.enforceNotIsolatedCaller("ActivityContainer.startActivityIntentSender");
4079 if (!(intentSender instanceof PendingIntentRecord)) {
4080 throw new IllegalArgumentException("Bad PendingIntent object");
4083 final int userId = mService.mUserController.handleIncomingUser(Binder.getCallingPid(),
4084 Binder.getCallingUid(), mCurrentUser, false,
4085 ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null);
4087 final PendingIntentRecord pendingIntent = (PendingIntentRecord) intentSender;
4088 checkEmbeddedAllowedInner(userId, pendingIntent.key.requestIntent,
4089 pendingIntent.key.requestResolvedType);
4091 return pendingIntent.sendInner(0, null, null, null, null, null, null, 0,
4092 FORCE_NEW_TASK_FLAGS, FORCE_NEW_TASK_FLAGS, null, this);
4095 void checkEmbeddedAllowedInner(int userId, Intent intent, String resolvedType) {
4096 ActivityInfo aInfo = resolveActivity(intent, resolvedType, 0, null, userId);
4097 if (aInfo != null && (aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
4098 throw new SecurityException(
4099 "Attempt to embed activity that has not set allowEmbedded=\"true\"");
4104 public IBinder asBinder() {
4109 public void setSurface(Surface surface, int width, int height, int density) {
4110 mService.enforceNotIsolatedCaller("ActivityContainer.attachToSurface");
4113 ActivityStackSupervisor getOuter() {
4114 return ActivityStackSupervisor.this;
4117 boolean isAttachedLocked() {
4118 return mActivityDisplay != null;
4121 // TODO: Make sure every change to ActivityRecord.visible results in a call to this.
4122 void setVisible(boolean visible) {
4123 if (mVisible != visible) {
4125 if (mCallback != null) {
4126 mHandler.obtainMessage(CONTAINER_CALLBACK_VISIBILITY, visible ? 1 : 0,
4127 0 /* unused */, this).sendToTarget();
4135 // You can always start a new task on a regular ActivityStack.
4136 boolean isEligibleForNewTasks() {
4140 void onTaskListEmptyLocked() {
4142 deleteActivityContainer(this);
4143 mHandler.obtainMessage(CONTAINER_CALLBACK_TASK_LIST_EMPTY, this).sendToTarget();
4147 public String toString() {
4148 return mIdString + (mActivityDisplay == null ? "N" : "A");
4152 private class VirtualActivityContainer extends ActivityContainer {
4154 boolean mDrawn = false;
4156 VirtualActivityContainer(ActivityRecord parent, IActivityContainerCallback callback) {
4157 super(getNextStackId());
4158 mParentActivity = parent;
4159 mCallback = callback;
4160 mContainerState = CONTAINER_STATE_NO_SURFACE;
4161 mIdString = "VirtualActivityContainer{" + mStackId + ", parent=" + mParentActivity + "}";
4165 public void setSurface(Surface surface, int width, int height, int density) {
4166 super.setSurface(surface, width, height, density);
4168 synchronized (mService) {
4169 final long origId = Binder.clearCallingIdentity();
4171 setSurfaceLocked(surface, width, height, density);
4173 Binder.restoreCallingIdentity(origId);
4178 private void setSurfaceLocked(Surface surface, int width, int height, int density) {
4179 if (mContainerState == CONTAINER_STATE_FINISHING) {
4182 VirtualActivityDisplay virtualActivityDisplay =
4183 (VirtualActivityDisplay) mActivityDisplay;
4184 if (virtualActivityDisplay == null) {
4185 virtualActivityDisplay =
4186 new VirtualActivityDisplay(width, height, density);
4187 mActivityDisplay = virtualActivityDisplay;
4188 mActivityDisplays.put(virtualActivityDisplay.mDisplayId, virtualActivityDisplay);
4189 attachToDisplayLocked(virtualActivityDisplay, true);
4192 if (mSurface != null) {
4197 if (surface != null) {
4198 resumeFocusedStackTopActivityLocked();
4200 mContainerState = CONTAINER_STATE_NO_SURFACE;
4201 ((VirtualActivityDisplay) mActivityDisplay).setSurface(null);
4202 if (mStack.mPausingActivity == null && mStack.mResumedActivity != null) {
4203 mStack.startPausingLocked(false, true, false, false);
4207 setSurfaceIfReadyLocked();
4209 if (DEBUG_STACK) Slog.d(TAG_STACK,
4210 "setSurface: " + this + " to display=" + virtualActivityDisplay);
4214 boolean isAttachedLocked() {
4215 return mSurface != null && super.isAttachedLocked();
4220 synchronized (mService) {
4222 setSurfaceIfReadyLocked();
4226 // Never start a new task on an ActivityView if it isn't explicitly specified.
4228 boolean isEligibleForNewTasks() {
4232 private void setSurfaceIfReadyLocked() {
4233 if (DEBUG_STACK) Slog.v(TAG_STACK, "setSurfaceIfReadyLocked: mDrawn=" + mDrawn +
4234 " mContainerState=" + mContainerState + " mSurface=" + mSurface);
4235 if (mDrawn && mSurface != null && mContainerState == CONTAINER_STATE_NO_SURFACE) {
4236 ((VirtualActivityDisplay) mActivityDisplay).setSurface(mSurface);
4237 mContainerState = CONTAINER_STATE_HAS_SURFACE;
4242 /** Exactly one of these classes per Display in the system. Capable of holding zero or more
4243 * attached {@link ActivityStack}s */
4244 class ActivityDisplay {
4245 /** Actual Display this object tracks. */
4248 DisplayInfo mDisplayInfo = new DisplayInfo();
4250 /** All of the stacks on this display. Order matters, topmost stack is in front of all other
4251 * stacks, bottommost behind. Accessed directly by ActivityManager package classes */
4252 final ArrayList<ActivityStack> mStacks = new ArrayList<>();
4254 ActivityRecord mVisibleBehindActivity;
4259 // After instantiation, check that mDisplay is not null before using this. The alternative
4260 // is for this to throw an exception if mDisplayManager.getDisplay() returns null.
4261 ActivityDisplay(int displayId) {
4262 final Display display = mDisplayManager.getDisplay(displayId);
4263 if (display == null) {
4269 void init(Display display) {
4271 mDisplayId = display.getDisplayId();
4272 mDisplay.getDisplayInfo(mDisplayInfo);
4275 void attachActivities(ActivityStack stack, boolean onTop) {
4276 if (DEBUG_STACK) Slog.v(TAG_STACK,
4277 "attachActivities: attaching " + stack + " to displayId=" + mDisplayId
4278 + " onTop=" + onTop);
4282 mStacks.add(0, stack);
4286 void detachActivitiesLocked(ActivityStack stack) {
4287 if (DEBUG_STACK) Slog.v(TAG_STACK, "detachActivitiesLocked: detaching " + stack
4288 + " from displayId=" + mDisplayId);
4289 mStacks.remove(stack);
4292 void setVisibleBehindActivity(ActivityRecord r) {
4293 mVisibleBehindActivity = r;
4296 boolean hasVisibleBehindActivity() {
4297 return mVisibleBehindActivity != null;
4301 public String toString() {
4302 return "ActivityDisplay={" + mDisplayId + " numStacks=" + mStacks.size() + "}";
4306 class VirtualActivityDisplay extends ActivityDisplay {
4307 VirtualDisplay mVirtualDisplay;
4309 VirtualActivityDisplay(int width, int height, int density) {
4310 DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
4311 mVirtualDisplay = dm.createVirtualDisplay(mService.mContext, null,
4312 VIRTUAL_DISPLAY_BASE_NAME, width, height, density, null,
4313 DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC |
4314 DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY, null, null);
4316 init(mVirtualDisplay.getDisplay());
4318 mWindowManager.handleDisplayAdded(mDisplayId);
4321 void setSurface(Surface surface) {
4322 if (mVirtualDisplay != null) {
4323 mVirtualDisplay.setSurface(surface);
4328 void detachActivitiesLocked(ActivityStack stack) {
4329 super.detachActivitiesLocked(stack);
4330 if (mVirtualDisplay != null) {
4331 mVirtualDisplay.release();
4332 mVirtualDisplay = null;
4337 public String toString() {
4338 return "VirtualActivityDisplay={" + mDisplayId + "}";
4343 * Adjust bounds to stay within stack bounds.
4345 * Since bounds might be outside of stack bounds, this method tries to move the bounds in a way
4346 * that keep them unchanged, but be contained within the stack bounds.
4348 * @param bounds Bounds to be adjusted.
4349 * @param stackBounds Bounds within which the other bounds should remain.
4351 private static void fitWithinBounds(Rect bounds, Rect stackBounds) {
4352 if (stackBounds == null || stackBounds.contains(bounds)) {
4356 if (bounds.left < stackBounds.left || bounds.right > stackBounds.right) {
4357 final int maxRight = stackBounds.right
4358 - (stackBounds.width() / FIT_WITHIN_BOUNDS_DIVIDER);
4359 int horizontalDiff = stackBounds.left - bounds.left;
4360 if ((horizontalDiff < 0 && bounds.left >= maxRight)
4361 || (bounds.left + horizontalDiff >= maxRight)) {
4362 horizontalDiff = maxRight - bounds.left;
4364 bounds.left += horizontalDiff;
4365 bounds.right += horizontalDiff;
4368 if (bounds.top < stackBounds.top || bounds.bottom > stackBounds.bottom) {
4369 final int maxBottom = stackBounds.bottom
4370 - (stackBounds.height() / FIT_WITHIN_BOUNDS_DIVIDER);
4371 int verticalDiff = stackBounds.top - bounds.top;
4372 if ((verticalDiff < 0 && bounds.top >= maxBottom)
4373 || (bounds.top + verticalDiff >= maxBottom)) {
4374 verticalDiff = maxBottom - bounds.top;
4376 bounds.top += verticalDiff;
4377 bounds.bottom += verticalDiff;
4381 ActivityStack findStackBehind(ActivityStack stack) {
4382 // TODO(multi-display): We are only looking for stacks on the default display.
4383 final ActivityDisplay display = mActivityDisplays.get(Display.DEFAULT_DISPLAY);
4384 if (display == null) {
4387 final ArrayList<ActivityStack> stacks = display.mStacks;
4388 for (int i = stacks.size() - 1; i >= 0; i--) {
4389 if (stacks.get(i) == stack && i > 0) {
4390 return stacks.get(i - 1);
4393 throw new IllegalStateException("Failed to find a stack behind stack=" + stack
4398 * Puts a task into resizing mode during the next app transition.
4400 * @param taskId the id of the task to put into resizing mode
4402 private void setResizingDuringAnimation(int taskId) {
4403 mResizingTasksDuringAnimation.add(taskId);
4404 mWindowManager.setTaskDockedResizing(taskId, true);
4407 final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
4408 final TaskRecord task;
4409 final int callingUid;
4410 final String callingPackage;
4411 final Intent intent;
4413 final ActivityOptions activityOptions = (bOptions != null)
4414 ? new ActivityOptions(bOptions) : null;
4415 final int launchStackId = (activityOptions != null)
4416 ? activityOptions.getLaunchStackId() : INVALID_STACK_ID;
4417 if (launchStackId == HOME_STACK_ID) {
4418 throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
4419 + taskId + " can't be launch in the home stack.");
4422 if (launchStackId == DOCKED_STACK_ID) {
4423 mWindowManager.setDockedStackCreateState(
4424 activityOptions.getDockCreateMode(), null /* initialBounds */);
4426 // Defer updating the stack in which recents is until the app transition is done, to
4427 // not run into issues where we still need to draw the task in recents but the
4428 // docked stack is already created.
4429 deferUpdateBounds(HOME_STACK_ID);
4430 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
4433 task = anyTaskForIdLocked(taskId, RESTORE_FROM_RECENTS, launchStackId);
4435 continueUpdateBounds(HOME_STACK_ID);
4436 mWindowManager.executeAppTransition();
4437 throw new IllegalArgumentException(
4438 "startActivityFromRecentsInner: Task " + taskId + " not found.");
4441 // Since we don't have an actual source record here, we assume that the currently focused
4442 // activity was the source.
4443 final ActivityStack focusedStack = getFocusedStack();
4444 final ActivityRecord sourceRecord =
4445 focusedStack != null ? focusedStack.topActivity() : null;
4447 if (launchStackId != INVALID_STACK_ID) {
4448 if (task.stack.mStackId != launchStackId) {
4449 moveTaskToStackLocked(
4450 taskId, launchStackId, ON_TOP, FORCE_FOCUS, "startActivityFromRecents",
4455 // If the user must confirm credentials (e.g. when first launching a work app and the
4456 // Work Challenge is present) let startActivityInPackage handle the intercepting.
4457 if (!mService.mUserController.shouldConfirmCredentials(task.userId)
4458 && task.getRootActivity() != null) {
4459 mService.mActivityStarter.sendPowerHintForLaunchStartIfNeeded(true /* forceSend */);
4460 mActivityMetricsLogger.notifyActivityLaunching();
4461 mService.moveTaskToFrontLocked(task.taskId, 0, bOptions);
4462 mActivityMetricsLogger.notifyActivityLaunched(ActivityManager.START_TASK_TO_FRONT,
4463 task.getTopActivity());
4465 // If we are launching the task in the docked stack, put it into resizing mode so
4466 // the window renders full-screen with the background filling the void. Also only
4467 // call this at the end to make sure that tasks exists on the window manager side.
4468 if (launchStackId == DOCKED_STACK_ID) {
4469 setResizingDuringAnimation(taskId);
4472 mService.mActivityStarter.postStartActivityUncheckedProcessing(task.getTopActivity(),
4473 ActivityManager.START_TASK_TO_FRONT,
4474 sourceRecord != null ? sourceRecord.task.stack.mStackId : INVALID_STACK_ID,
4475 sourceRecord, task.stack);
4476 return ActivityManager.START_TASK_TO_FRONT;
4478 callingUid = task.mCallingUid;
4479 callingPackage = task.mCallingPackage;
4480 intent = task.intent;
4481 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4482 userId = task.userId;
4483 int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
4484 null, null, 0, 0, bOptions, userId, null, task);
4485 if (launchStackId == DOCKED_STACK_ID) {
4486 setResizingDuringAnimation(task.taskId);
4492 * @return a list of activities which are the top ones in each visible stack. The first
4493 * entry will be the focused activity.
4495 public List<IBinder> getTopVisibleActivities() {
4496 final ActivityDisplay display = mActivityDisplays.get(Display.DEFAULT_DISPLAY);
4497 if (display == null) {
4498 return Collections.EMPTY_LIST;
4500 ArrayList<IBinder> topActivityTokens = new ArrayList<>();
4501 final ArrayList<ActivityStack> stacks = display.mStacks;
4502 for (int i = stacks.size() - 1; i >= 0; i--) {
4503 ActivityStack stack = stacks.get(i);
4504 if (stack.getStackVisibilityLocked(null) == ActivityStack.STACK_VISIBLE) {
4505 ActivityRecord top = stack.topActivity();
4507 if (stack == mFocusedStack) {
4508 topActivityTokens.add(0, top.appToken);
4510 topActivityTokens.add(top.appToken);
4515 return topActivityTokens;