blob: 744a4f67ed1bcae023200d3081c24adc546a913c [file] [log] [blame]
Craig Mautner27084302013-03-25 08:05:25 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Andrii Kulian3c9ad072017-08-01 11:45:22 -070019import static android.Manifest.permission.ACTIVITY_EMBEDDING;
Andrii Kulian3a95edc2017-06-28 16:21:07 -070020import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Jorim Jaggife762342016-10-13 14:33:27 +020021import static android.Manifest.permission.START_ANY_ACTIVITY;
22import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Jorim Jaggife762342016-10-13 14:33:27 +020023import static android.app.ActivityManager.START_TASK_TO_FRONT;
24import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
25import static android.app.ActivityManager.StackId.FIRST_DYNAMIC_STACK_ID;
26import static android.app.ActivityManager.StackId.FIRST_STATIC_STACK_ID;
27import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
28import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
29import static android.app.ActivityManager.StackId.HOME_STACK_ID;
30import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
31import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
32import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
Matthew Ng330757d2017-02-28 14:19:17 -080033import static android.app.ActivityManager.StackId.RECENTS_STACK_ID;
Andrii Kulian036e3ad2017-04-19 10:55:10 -070034import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
35import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Andrii Kulian3c9ad072017-08-01 11:45:22 -070036import static android.content.pm.PackageManager.PERMISSION_DENIED;
Jorim Jaggife762342016-10-13 14:33:27 +020037import static android.content.pm.PackageManager.PERMISSION_GRANTED;
chaviw59b98852017-06-13 12:05:44 -070038import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
Benjamin Franza83859f2017-07-03 16:34:14 +010039import static android.os.Process.SYSTEM_UID;
Jorim Jaggife762342016-10-13 14:33:27 +020040import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
41import static android.view.Display.DEFAULT_DISPLAY;
Andrii Kulian16802aa2016-11-02 12:21:33 -070042import static android.view.Display.FLAG_PRIVATE;
43import static android.view.Display.INVALID_DISPLAY;
Andrii Kulian250d6532017-02-08 23:30:45 -080044import static android.view.Display.REMOVE_MODE_DESTROY_CONTENT;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070045import static android.view.Display.TYPE_VIRTUAL;
Winson Chung47900652017-04-06 18:44:25 -070046import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN;
Jorim Jaggife762342016-10-13 14:33:27 +020047import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
Jorim Jaggife762342016-10-13 14:33:27 +020048import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
49import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
Jorim Jaggife762342016-10-13 14:33:27 +020050import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
51import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
52import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
53import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
54import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
55import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
56import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020057import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
58import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IDLE;
Jorim Jaggife762342016-10-13 14:33:27 +020059import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
60import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
61import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
62import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
63import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
64import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
65import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020066import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
67import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
68import static com.android.server.am.ActivityManagerService.ANIMATE;
69import static com.android.server.am.ActivityManagerService.FIRST_SUPERVISOR_STACK_MSG;
70import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
71import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
Jorim Jaggife762342016-10-13 14:33:27 +020072import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
73import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
74import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
75import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
76import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
77import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
78import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
79import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
80import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
81import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
82import static com.android.server.am.ActivityStack.STACK_VISIBLE;
Jorim Jaggife762342016-10-13 14:33:27 +020083import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
84import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
Winson Chung74666102017-02-22 17:49:24 -080085import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
86import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
87import static com.android.server.am.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
Jorim Jaggife762342016-10-13 14:33:27 +020088import static com.android.server.wm.AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS;
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -080089import static java.lang.Integer.MAX_VALUE;
Jorim Jaggife762342016-10-13 14:33:27 +020090
Svetoslav7008b512015-06-24 18:47:07 -070091import android.Manifest;
Winson Chung7900bee2017-03-10 08:59:25 -080092import android.annotation.IntDef;
Andrii Kulian16802aa2016-11-02 12:21:33 -070093import android.annotation.NonNull;
Tony Mak853304c2016-04-18 15:17:41 +010094import android.annotation.UserIdInt;
Craig Mautner2420ead2013-04-01 17:13:20 -070095import android.app.Activity;
Craig Mautner23ac33b2013-04-01 16:26:35 -070096import android.app.ActivityManager;
Filip Gruszczynski80e29f12015-12-14 14:58:30 -080097import android.app.ActivityManager.RunningTaskInfo;
Wale Ogunwale3797c222015-10-27 14:21:58 -070098import android.app.ActivityManager.StackId;
Craig Mautnered6649f2013-12-02 14:08:25 -080099import android.app.ActivityManager.StackInfo;
David Stevens9440dc82017-03-16 19:00:20 -0700100import android.app.ActivityManagerInternal.SleepToken;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700101import android.app.ActivityOptions;
Svetoslav7008b512015-06-24 18:47:07 -0700102import android.app.AppOpsManager;
Jeff Hao1b012d32014-08-20 10:35:34 -0700103import android.app.ProfilerInfo;
Craig Mautner2420ead2013-04-01 17:13:20 -0700104import android.app.ResultInfo;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700105import android.app.WaitResult;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700106import android.content.ComponentName;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700107import android.content.Context;
108import android.content.Intent;
109import android.content.pm.ActivityInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700110import android.content.pm.ApplicationInfo;
Svetoslav7008b512015-06-24 18:47:07 -0700111import android.content.pm.PackageInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700112import android.content.pm.PackageManager;
113import android.content.pm.ResolveInfo;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100114import android.content.pm.UserInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700115import android.content.res.Configuration;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800116import android.graphics.Rect;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800117import android.hardware.display.DisplayManager;
118import android.hardware.display.DisplayManager.DisplayListener;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800119import android.hardware.display.DisplayManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800120import android.hardware.input.InputManagerInternal;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700121import android.os.Binder;
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100122import android.os.Bundle;
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700123import android.os.Debug;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700124import android.os.Handler;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700125import android.os.IBinder;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700126import android.os.Looper;
Craig Mautner2420ead2013-04-01 17:13:20 -0700127import android.os.Message;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700128import android.os.PowerManager;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700129import android.os.Process;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700130import android.os.RemoteException;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700131import android.os.SystemClock;
Wale Ogunwalecad05a02015-09-25 10:41:44 -0700132import android.os.Trace;
Craig Mautner6170f732013-04-02 13:05:23 -0700133import android.os.UserHandle;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100134import android.os.UserManager;
Dianne Hackborn3d07c942015-03-13 18:02:54 -0700135import android.os.WorkSource;
Svetoslav7008b512015-06-24 18:47:07 -0700136import android.provider.MediaStore;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700137import android.service.voice.IVoiceInteractionSession;
Svetoslav7008b512015-06-24 18:47:07 -0700138import android.util.ArrayMap;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700139import android.util.ArraySet;
Craig Mautner2420ead2013-04-01 17:13:20 -0700140import android.util.EventLog;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800141import android.util.IntArray;
Wale Ogunwalee610d3d2017-04-25 10:23:48 -0700142import android.util.MergedConfiguration;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700143import android.util.Slog;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800144import android.util.SparseArray;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800145import android.util.SparseIntArray;
David Stevens9440dc82017-03-16 19:00:20 -0700146import android.util.TimeUtils;
Craig Mautnered6649f2013-12-02 14:08:25 -0800147import android.view.Display;
Chong Zhangb15758a2015-11-17 12:12:03 -0800148
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700149import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800150import com.android.internal.content.ReferrerIntent;
Winson Chung14fbe142016-12-19 16:18:24 -0800151import com.android.internal.logging.MetricsLogger;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -0700152import com.android.internal.os.TransferPipe;
Svetoslav7008b512015-06-24 18:47:07 -0700153import com.android.internal.util.ArrayUtils;
Jeff Brownca9bc702014-02-11 14:32:56 -0800154import com.android.server.LocalServices;
Craig Mautner2420ead2013-04-01 17:13:20 -0700155import com.android.server.am.ActivityStack.ActivityState;
Wale Ogunwale98d62312017-07-12 09:24:56 -0700156import com.android.server.wm.ConfigurationContainer;
Winson Chung19953ca2017-04-11 11:19:23 -0700157import com.android.server.wm.PinnedStackWindowController;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700158import com.android.server.wm.WindowManagerService;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700159
Craig Mautner8d341ef2013-03-26 09:03:27 -0700160import java.io.FileDescriptor;
161import java.io.IOException;
Craig Mautner27084302013-03-25 08:05:25 -0700162import java.io.PrintWriter;
Winson Chung7900bee2017-03-10 08:59:25 -0800163import java.lang.annotation.Retention;
164import java.lang.annotation.RetentionPolicy;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700165import java.util.ArrayList;
Craig Mautnere0570202015-05-13 13:06:11 -0700166import java.util.Arrays;
David Stevens9440dc82017-03-16 19:00:20 -0700167import java.util.Iterator;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700168import java.util.List;
Wale Ogunwale540e1232015-05-01 15:35:39 -0700169import java.util.Set;
Craig Mautner27084302013-03-25 08:05:25 -0700170
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -0800171public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener {
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800172 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_AM;
Chong Zhang6cda19c2016-06-14 19:07:56 -0700173 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700174 private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700175 private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700176 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700177 private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700178 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700179 private static final String TAG_STATES = TAG + POSTFIX_STATES;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700180 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800181 static final String TAG_TASKS = TAG + POSTFIX_TASKS;
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800182
Craig Mautnerf3333272013-04-22 10:55:53 -0700183 /** How long we wait until giving up on the last activity telling us it is idle. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700184 static final int IDLE_TIMEOUT = 10 * 1000;
Craig Mautnerf3333272013-04-22 10:55:53 -0700185
Craig Mautner0eea92c2013-05-16 13:35:39 -0700186 /** How long we can hold the sleep wake lock before giving up. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700187 static final int SLEEP_TIMEOUT = 5 * 1000;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700188
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700189 // How long we can hold the launch wake lock before giving up.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700190 static final int LAUNCH_TIMEOUT = 10 * 1000;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700191
Craig Mautner05d29032013-05-03 13:40:13 -0700192 static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
193 static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
194 static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700195 static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700196 static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800197 static final int HANDLE_DISPLAY_ADDED = FIRST_SUPERVISOR_STACK_MSG + 5;
198 static final int HANDLE_DISPLAY_CHANGED = FIRST_SUPERVISOR_STACK_MSG + 6;
199 static final int HANDLE_DISPLAY_REMOVED = FIRST_SUPERVISOR_STACK_MSG + 7;
Wale Ogunwale73eba742015-04-07 14:23:14 -0700200 static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
Wale Ogunwale22e25262016-02-01 10:32:02 -0800201 static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
202 static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800203
Wale Ogunwale040b4702015-08-06 18:10:50 -0700204 private static final String VIRTUAL_DISPLAY_BASE_NAME = "ActivityViewVirtualDisplay";
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700205
Wale Ogunwale040b4702015-08-06 18:10:50 -0700206 // Used to indicate if an object (e.g. stack) that we are trying to get
207 // should be created if it doesn't exist already.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800208 static final boolean CREATE_IF_NEEDED = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700209
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700210 // Used to indicate that windows of activities should be preserved during the resize.
211 static final boolean PRESERVE_WINDOWS = true;
212
Wale Ogunwale040b4702015-08-06 18:10:50 -0700213 // Used to indicate if an object (e.g. task) should be moved/created
214 // at the top of its container (e.g. stack).
Wale Ogunwaleb30daaa2015-08-07 21:50:49 -0700215 static final boolean ON_TOP = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700216
217 // Used to indicate that an objects (e.g. task) removal from its container
218 // (e.g. stack) is due to it moving to another container.
219 static final boolean MOVING = true;
220
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700221 // Force the focus to change to the stack we are moving a task to..
222 static final boolean FORCE_FOCUS = true;
223
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700224 // Don't execute any calls to resume.
225 static final boolean DEFER_RESUME = true;
226
Winson Chung010927a2016-12-15 16:12:35 -0800227 // Used to indicate that a task is removed it should also be removed from recents.
228 static final boolean REMOVE_FROM_RECENTS = true;
229
Winson Chung6954fc92017-03-24 16:22:12 -0700230 // Used to indicate that pausing an activity should occur immediately without waiting for
231 // the activity callback indicating that it has completed pausing
232 static final boolean PAUSE_IMMEDIATELY = true;
233
Winson Chung7900bee2017-03-10 08:59:25 -0800234 /**
235 * The modes which affect which tasks are returned when calling
236 * {@link ActivityStackSupervisor#anyTaskForIdLocked(int)}.
237 */
238 @Retention(RetentionPolicy.SOURCE)
239 @IntDef({
240 MATCH_TASK_IN_STACKS_ONLY,
241 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
242 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
243 })
244 public @interface AnyTaskForIdMatchTaskMode {}
245 // Match only tasks in the current stacks
246 static final int MATCH_TASK_IN_STACKS_ONLY = 0;
247 // Match either tasks in the current stacks, or in the recent tasks if not found in the stacks
248 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS = 1;
249 // Match either tasks in the current stacks, or in the recent tasks, restoring it to the
250 // provided stack id
251 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE = 2;
252
Svetoslav7008b512015-06-24 18:47:07 -0700253 // Activity actions an app cannot start if it uses a permission which is not granted.
254 private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION =
255 new ArrayMap<>();
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700256
Svetoslav7008b512015-06-24 18:47:07 -0700257 static {
258 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE,
259 Manifest.permission.CAMERA);
260 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE,
261 Manifest.permission.CAMERA);
262 ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL,
263 Manifest.permission.CALL_PHONE);
264 }
265
Svet Ganov99b60432015-06-27 13:15:22 -0700266 /** Action restriction: launching the activity is not restricted. */
267 private static final int ACTIVITY_RESTRICTION_NONE = 0;
268 /** Action restriction: launching the activity is restricted by a permission. */
269 private static final int ACTIVITY_RESTRICTION_PERMISSION = 1;
270 /** Action restriction: launching the activity is restricted by an app op. */
271 private static final int ACTIVITY_RESTRICTION_APPOP = 2;
Svetoslav7008b512015-06-24 18:47:07 -0700272
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700273 // For debugging to make sure the caller when acquiring/releasing our
274 // wake lock is the system process.
275 static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800276 /** The number of distinct task ids that can be assigned to the tasks of a single user */
277 private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
Craig Mautnerf3333272013-04-22 10:55:53 -0700278
Craig Mautner27084302013-03-25 08:05:25 -0700279 final ActivityManagerService mService;
280
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800281 private RecentTasks mRecentTasks;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800282
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700283 final ActivityStackSupervisorHandler mHandler;
284
285 /** Short cut */
286 WindowManagerService mWindowManager;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800287 DisplayManager mDisplayManager;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700288
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -0700289 /** Counter for next free stack ID to use for dynamic activity stacks. */
290 private int mNextFreeStackId = FIRST_DYNAMIC_STACK_ID;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700291
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800292 /**
293 * Maps the task identifier that activities are currently being started in to the userId of the
294 * task. Each time a new task is created, the entry for the userId of the task is incremented
295 */
296 private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20);
Craig Mautner8d341ef2013-03-26 09:03:27 -0700297
Craig Mautner2420ead2013-04-01 17:13:20 -0700298 /** The current user */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800299 int mCurrentUser;
Craig Mautner2420ead2013-04-01 17:13:20 -0700300
Craig Mautnere0a38842013-12-16 16:14:02 -0800301 /** The stack containing the launcher app. Assumed to always be attached to
302 * Display.DEFAULT_DISPLAY. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800303 ActivityStack mHomeStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700304
Craig Mautnere0a38842013-12-16 16:14:02 -0800305 /** The stack currently receiving input or launching the next activity. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800306 ActivityStack mFocusedStack;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700307
Craig Mautner4a1cb222013-12-04 16:14:06 -0800308 /** If this is the same as mFocusedStack then the activity on the top of the focused stack has
309 * been resumed. If stacks are changing position this will hold the old stack until the new
Craig Mautnere0a38842013-12-16 16:14:02 -0800310 * stack becomes resumed after which it will be set to mFocusedStack. */
Craig Mautner4a1cb222013-12-04 16:14:06 -0800311 private ActivityStack mLastFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -0700312
313 /** List of activities that are waiting for a new activity to become visible before completing
314 * whatever operation they are supposed to do. */
Bryce Lee4a194382017-04-04 14:32:48 -0700315 // TODO: Remove mActivitiesWaitingForVisibleActivity list and just remove activity from
316 // mStoppingActivities when something else comes up.
317 final ArrayList<ActivityRecord> mActivitiesWaitingForVisibleActivity = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700318
Bryce Lee4a194382017-04-04 14:32:48 -0700319 /** List of processes waiting to find out when a specific activity becomes visible. */
320 private final ArrayList<WaitInfo> mWaitingForActivityVisible = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700321
322 /** List of processes waiting to find out about the next launched activity. */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700323 final ArrayList<WaitResult> mWaitingActivityLaunched = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700324
Craig Mautnerde4ef022013-04-07 19:01:33 -0700325 /** List of activities that are ready to be stopped, but waiting for the next activity to
326 * settle down before doing so. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800327 final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700328
Craig Mautnerf3333272013-04-22 10:55:53 -0700329 /** List of activities that are ready to be finished, but waiting for the previous activity to
330 * settle down before doing so. It contains ActivityRecord objects. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800331 final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700332
Craig Mautner0eea92c2013-05-16 13:35:39 -0700333 /** List of activities that are in the process of going to sleep. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800334 final ArrayList<ActivityRecord> mGoingToSleepActivities = new ArrayList<>();
Craig Mautner0eea92c2013-05-16 13:35:39 -0700335
Wale Ogunwale22e25262016-02-01 10:32:02 -0800336 /** List of activities whose multi-window mode changed that we need to report to the
337 * application */
338 final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
339
340 /** List of activities whose picture-in-picture mode changed that we need to report to the
341 * application */
342 final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
343
Winson Chung5af42fc2017-03-24 17:11:33 -0700344 /** The target stack bounds for the picture-in-picture mode changed that we need to report to
345 * the application */
346 Rect mPipModeChangedTargetStackBounds;
347
Craig Mautnerf3333272013-04-22 10:55:53 -0700348 /** Used on user changes */
Amith Yamasani37a40c22015-06-17 13:25:42 -0700349 final ArrayList<UserState> mStartingUsers = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700350
Craig Mautnerde4ef022013-04-07 19:01:33 -0700351 /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity
352 * is being brought in front of us. */
353 boolean mUserLeaving = false;
354
Craig Mautner0eea92c2013-05-16 13:35:39 -0700355 /**
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700356 * We don't want to allow the device to go to sleep while in the process
357 * of launching an activity. This is primarily to allow alarm intent
358 * receivers to launch an activity and get that to run before the device
359 * goes back to sleep.
360 */
Jeff Brown2c43c332014-06-12 22:38:59 -0700361 PowerManager.WakeLock mLaunchingActivity;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700362
363 /**
Craig Mautner0eea92c2013-05-16 13:35:39 -0700364 * Set when the system is going to sleep, until we have
365 * successfully paused the current activity and released our wake lock.
366 * At that point the system is allowed to actually sleep.
367 */
Jeff Brown2c43c332014-06-12 22:38:59 -0700368 PowerManager.WakeLock mGoingToSleep;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700369
David Stevens9440dc82017-03-16 19:00:20 -0700370 /**
371 * A list of tokens that cause the top activity to be put to sleep.
372 * They are used by components that may hide and block interaction with underlying
373 * activities.
374 */
375 final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>();
376
Craig Mautner4f1df4f2013-10-15 15:44:14 -0700377 /** Stack id of the front stack when user switched, indexed by userId. */
378 SparseIntArray mUserStackInFront = new SparseIntArray(2);
Craig Mautner93529a42013-10-04 15:03:13 -0700379
Craig Mautner4504de52013-12-20 09:06:56 -0800380 // TODO: Add listener for removal of references.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800381 /** Mapping from (ActivityStack/TaskStack).mStackId to their current state */
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700382 SparseArray<ActivityStack> mStacks = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800383
Bryce Leeaf3a4002017-03-20 10:37:12 -0700384 // TODO: There should be an ActivityDisplayController coordinating am/wm interaction.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800385 /** Mapping from displayId to display current state */
Craig Mautner15df08a2015-04-01 12:17:18 -0700386 private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800387
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800388 private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>();
389
390 private DisplayManagerInternal mDisplayManagerInternal;
391 private InputManagerInternal mInputManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800392
Wale Ogunwaled046a012015-12-24 13:05:59 -0800393 /** Used to keep resumeTopActivityUncheckedLocked() from being entered recursively */
Craig Mautner42d04db2014-11-06 12:13:23 -0800394 boolean inResumeTopActivity;
395
Andrii Kulian1e32e022016-09-16 15:29:34 -0700396 /**
397 * Temporary rect used during docked stack resize calculation so we don't need to create a new
398 * object each time.
399 */
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700400 private final Rect tempRect = new Rect();
Filip Gruszczynskiebcc8752015-08-25 16:51:05 -0700401
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700402 // The default minimal size that will be used if the activity doesn't specify its minimal size.
403 // It will be calculated when the default display gets added.
Andrii Kulianf66a83d2016-05-17 12:17:44 -0700404 int mDefaultMinSizeOfResizeableTask = -1;
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700405
Chong Zhangfdcc4d42015-10-14 16:50:12 -0700406 // Whether tasks have moved and we need to rank the tasks before next OOM scoring
407 private boolean mTaskLayersChanged = true;
408
Jorim Jaggi275561a2016-02-23 10:11:02 -0500409 final ActivityMetricsLogger mActivityMetricsLogger;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800410
Jorim Jaggiea039a82017-08-02 14:37:49 +0200411 private final ArrayList<ActivityRecord> mTmpActivityList = new ArrayList<>();
412
Andrii Kulian1779e612016-10-12 21:58:25 -0700413 @Override
414 protected int getChildCount() {
415 return mActivityDisplays.size();
416 }
417
418 @Override
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700419 protected ActivityDisplay getChildAt(int index) {
Andrii Kulian1779e612016-10-12 21:58:25 -0700420 return mActivityDisplays.valueAt(index);
421 }
422
423 @Override
424 protected ConfigurationContainer getParent() {
425 return null;
426 }
427
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700428 Configuration getDisplayOverrideConfiguration(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700429 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700430 if (activityDisplay == null) {
431 throw new IllegalArgumentException("No display found with id: " + displayId);
432 }
433
434 return activityDisplay.getOverrideConfiguration();
435 }
436
437 void setDisplayOverrideConfiguration(Configuration overrideConfiguration, int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700438 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700439 if (activityDisplay == null) {
440 throw new IllegalArgumentException("No display found with id: " + displayId);
441 }
442
443 activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
444 }
445
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700446 /** Check if placing task or activity on specified display is allowed. */
Andrii Kulian02689a72017-07-06 14:28:59 -0700447 boolean canPlaceEntityOnDisplay(int displayId, boolean resizeable, int callingPid,
448 int callingUid, ActivityInfo activityInfo) {
449 if (displayId == DEFAULT_DISPLAY) {
450 // No restrictions for the default display.
451 return true;
452 }
453 if (!mService.mSupportsMultiDisplay) {
454 // Can't launch on secondary displays if feature is not supported.
455 return false;
456 }
457 if (!resizeable && !displayConfigMatchesGlobal(displayId)) {
458 // Can't apply wrong configuration to non-resizeable activities.
459 return false;
460 }
461 if (!isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, displayId, activityInfo)) {
462 // Can't place activities to a display that has restricted launch rules.
463 // In this case the request should be made by explicitly adding target display id and
464 // by caller with corresponding permissions. See #isCallerAllowedToLaunchOnDisplay().
465 return false;
466 }
467 return true;
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700468 }
469
470 /**
471 * Check if configuration of specified display matches current global config.
472 * Used to check if we can put a non-resizeable activity on a secondary display and it will get
473 * the same config as on the default display.
474 * @param displayId Id of the display to check.
475 * @return {@code true} if configuration matches.
476 */
477 private boolean displayConfigMatchesGlobal(int displayId) {
478 if (displayId == DEFAULT_DISPLAY) {
479 return true;
480 }
481 if (displayId == INVALID_DISPLAY) {
482 return false;
483 }
Andrii Kulian62e6f252017-05-30 22:46:53 -0700484 final ActivityDisplay targetDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700485 if (targetDisplay == null) {
486 throw new IllegalArgumentException("No display found with id: " + displayId);
487 }
488 return getConfiguration().equals(targetDisplay.getConfiguration());
489 }
490
Wale Ogunwale39381972015-12-17 17:15:29 -0800491 static class FindTaskResult {
492 ActivityRecord r;
493 boolean matchedByRootAffinity;
494 }
495 private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
496
Craig Mautneree36c772014-07-16 14:56:05 -0700497 /**
Andrii Kulian7fc22812016-12-28 13:04:11 -0800498 * Temp storage for display ids sorted in focus order.
499 * Maps position to id. Using {@link SparseIntArray} instead of {@link ArrayList} because
500 * it's more efficient, as the number of displays is usually small.
501 */
502 private SparseIntArray mTmpOrderedDisplayIds = new SparseIntArray();
503
504 /**
Jorim Jaggia0fdeec2016-01-07 14:42:28 +0100505 * Used to keep track whether app visibilities got changed since the last pause. Useful to
506 * determine whether to invoke the task stack change listener after pausing.
507 */
508 boolean mAppVisibilitiesChangedSinceLastPause;
509
510 /**
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100511 * Set of tasks that are in resizing mode during an app transition to fill the "void".
512 */
513 private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
514
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700515
516 /**
517 * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked}
518 * will be ignored. Useful for the case where the caller is handling resizing of other stack and
519 * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger
520 * like the docked stack going empty.
521 */
522 private boolean mAllowDockedStackResize = true;
523
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100524 /**
Tony Mak853304c2016-04-18 15:17:41 +0100525 * Is dock currently minimized.
526 */
527 boolean mIsDockMinimized;
528
Jorim Jaggife762342016-10-13 14:33:27 +0200529 final KeyguardController mKeyguardController;
530
chaviw59b98852017-06-13 12:05:44 -0700531 private PowerManager mPowerManager;
532 private int mDeferResumeCount;
533
Tony Mak853304c2016-04-18 15:17:41 +0100534 /**
Craig Mautneree36c772014-07-16 14:56:05 -0700535 * Description of a request to start a new activity, which has been held
536 * due to app switches being disabled.
537 */
538 static class PendingActivityLaunch {
539 final ActivityRecord r;
540 final ActivityRecord sourceRecord;
541 final int startFlags;
542 final ActivityStack stack;
Robert Carr13997f52015-10-23 13:13:39 -0700543 final ProcessRecord callerApp;
Craig Mautneree36c772014-07-16 14:56:05 -0700544
545 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
Robert Carr13997f52015-10-23 13:13:39 -0700546 int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
Craig Mautneree36c772014-07-16 14:56:05 -0700547 r = _r;
548 sourceRecord = _sourceRecord;
549 startFlags = _startFlags;
550 stack = _stack;
Robert Carr13997f52015-10-23 13:13:39 -0700551 callerApp = _callerApp;
552 }
553
554 void sendErrorResult(String message) {
555 try {
556 if (callerApp.thread != null) {
557 callerApp.thread.scheduleCrash(message);
558 }
559 } catch (RemoteException e) {
560 Slog.e(TAG, "Exception scheduling crash of failed "
561 + "activity launcher sourceRecord=" + sourceRecord, e);
562 }
Craig Mautneree36c772014-07-16 14:56:05 -0700563 }
564 }
565
Bryce Leeaf691c02017-03-20 14:20:22 -0700566 public ActivityStackSupervisor(ActivityManagerService service, Looper looper) {
Craig Mautner27084302013-03-25 08:05:25 -0700567 mService = service;
Bryce Leeaf691c02017-03-20 14:20:22 -0700568 mHandler = new ActivityStackSupervisorHandler(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800569 mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
Jorim Jaggife762342016-10-13 14:33:27 +0200570 mKeyguardController = new KeyguardController(service, this);
Jeff Brown2c43c332014-06-12 22:38:59 -0700571 }
572
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800573 void setRecentTasks(RecentTasks recentTasks) {
574 mRecentTasks = recentTasks;
575 }
576
Jeff Brown2c43c332014-06-12 22:38:59 -0700577 /**
578 * At the time when the constructor runs, the power manager has not yet been
579 * initialized. So we initialize our wakelocks afterwards.
580 */
581 void initPowerManagement() {
chaviw59b98852017-06-13 12:05:44 -0700582 mPowerManager = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
583 mGoingToSleep = mPowerManager
584 .newWakeLock(PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
585 mLaunchingActivity = mPowerManager.newWakeLock(PARTIAL_WAKE_LOCK, "*launch*");
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700586 mLaunchingActivity.setReferenceCounted(false);
Craig Mautner2219a1b2013-03-25 09:44:30 -0700587 }
588
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700589 void setWindowManager(WindowManagerService wm) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800590 synchronized (mService) {
591 mWindowManager = wm;
Jorim Jaggife762342016-10-13 14:33:27 +0200592 mKeyguardController.setWindowManager(wm);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800593
594 mDisplayManager =
595 (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
596 mDisplayManager.registerDisplayListener(this, null);
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800597 mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800598
599 Display[] displays = mDisplayManager.getDisplays();
600 for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
601 final int displayId = displays[displayNdx].getDisplayId();
Craig Mautnere0a38842013-12-16 16:14:02 -0800602 ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
Craig Mautner1a70a162014-09-13 12:09:31 -0700603 if (activityDisplay.mDisplay == null) {
604 throw new IllegalStateException("Default Display does not exist");
605 }
Craig Mautnere0a38842013-12-16 16:14:02 -0800606 mActivityDisplays.put(displayId, activityDisplay);
Filip Gruszczynski7be9a8c2015-10-15 18:20:30 -0700607 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800608 }
609
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800610 mHomeStack = mFocusedStack = mLastFocusedStack =
611 getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Jeff Brownca9bc702014-02-11 14:32:56 -0800612
613 mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800614 }
Craig Mautner27084302013-03-25 08:05:25 -0700615 }
616
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700617 ActivityStack getFocusedStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800618 return mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700619 }
620
Craig Mautnerde4ef022013-04-07 19:01:33 -0700621 ActivityStack getLastStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800622 return mLastFocusedStack;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700623 }
624
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700625 boolean isFocusedStack(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700626 return stack != null && stack == mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700627 }
628
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800629 /** The top most stack on its display. */
630 boolean isFrontStackOnDisplay(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700631 return isFrontOfStackList(stack, stack.getDisplay().mStacks);
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800632 }
633
634 private boolean isFrontOfStackList(ActivityStack stack, List<ActivityStack> stackList) {
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800635 return stack == stackList.get((stackList.size() - 1));
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700636 }
637
Wale Ogunwaled046a012015-12-24 13:05:59 -0800638 /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800639 void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
640 if (!focusCandidate.isFocusable()) {
641 // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
Andrii Kulian7fc22812016-12-28 13:04:11 -0800642 focusCandidate = getNextFocusableStackLocked(focusCandidate);
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800643 }
644
645 if (focusCandidate != mFocusedStack) {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800646 mLastFocusedStack = mFocusedStack;
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800647 mFocusedStack = focusCandidate;
Wale Ogunwalecb82f302015-02-25 07:53:40 -0800648
Wale Ogunwaled046a012015-12-24 13:05:59 -0800649 EventLogTags.writeAmFocusedStack(
650 mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
651 mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
652 }
653
654 final ActivityRecord r = topRunningActivityLocked();
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800655 if (mService.mBooting || !mService.mBooted) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800656 if (r != null && r.idle) {
657 checkFinishBootingLocked();
658 }
659 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700660 }
661
Wale Ogunwale925d0d12015-09-23 15:40:07 -0700662 void moveHomeStackToFront(String reason) {
663 mHomeStack.moveToFront(reason);
664 }
665
Matthew Ng330757d2017-02-28 14:19:17 -0800666 void moveRecentsStackToFront(String reason) {
667 final ActivityStack recentsStack = getStack(RECENTS_STACK_ID);
668 if (recentsStack != null) {
669 recentsStack.moveToFront(reason);
670 }
671 }
672
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700673 /** Returns true if the focus activity was adjusted to the home stack top activity. */
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800674 boolean moveHomeStackTaskToTop(String reason) {
675 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700676
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700677 final ActivityRecord top = getHomeActivity();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700678 if (top == null) {
679 return false;
680 }
Chong Zhang6cda19c2016-06-14 19:07:56 -0700681 moveFocusableActivityStackToFrontLocked(top, reason);
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700682 return true;
Craig Mautner8e569572013-10-11 17:36:59 -0700683 }
684
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800685 boolean resumeHomeStackTask(ActivityRecord prev, String reason) {
Dianne Hackborn7622a0f2014-09-30 14:31:42 -0700686 if (!mService.mBooting && !mService.mBooted) {
687 // Not ready yet!
688 return false;
689 }
690
Craig Mautner84984fa2014-06-19 11:19:20 -0700691 if (prev != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -0700692 prev.getTask().setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
Craig Mautner84984fa2014-06-19 11:19:20 -0700693 }
694
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800695 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700696 ActivityRecord r = getHomeActivity();
Wale Ogunwaled046a012015-12-24 13:05:59 -0800697 final String myReason = reason + " resumeHomeStackTask";
698
Mark Lua56ea122015-10-08 13:31:01 +0800699 // Only resume home activity if isn't finishing.
700 if (r != null && !r.finishing) {
Chong Zhang6cda19c2016-06-14 19:07:56 -0700701 moveFocusableActivityStackToFrontLocked(r, myReason);
Wale Ogunwaled046a012015-12-24 13:05:59 -0800702 return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
Craig Mautner69ada552013-04-18 13:51:51 -0700703 }
Wale Ogunwaled046a012015-12-24 13:05:59 -0800704 return mService.startHomeActivityLocked(mCurrentUser, myReason);
Craig Mautner69ada552013-04-18 13:51:51 -0700705 }
706
Craig Mautner8d341ef2013-03-26 09:03:27 -0700707 TaskRecord anyTaskForIdLocked(int id) {
Winson Chung7900bee2017-03-10 08:59:25 -0800708 return anyTaskForIdLocked(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
709 INVALID_STACK_ID);
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700710 }
711
712 /**
Bryce Lee92b7b652017-04-03 08:33:11 -0700713 * Returns a {@link TaskRecord} for the input id if available. {@code null} otherwise.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700714 * @param id Id of the task we would like returned.
Winson Chung7900bee2017-03-10 08:59:25 -0800715 * @param matchMode The mode to match the given task id in.
Wale Ogunwale3797c222015-10-27 14:21:58 -0700716 * @param stackId The stack to restore the task to (default launch stack will be used if
Winson Chung7900bee2017-03-10 08:59:25 -0800717 * stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}). Only
718 * valid if the matchMode is
719 * {@link #MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE}.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700720 */
Winson Chung7900bee2017-03-10 08:59:25 -0800721 TaskRecord anyTaskForIdLocked(int id, @AnyTaskForIdMatchTaskMode int matchMode, int stackId) {
722 // If there is a stack id set, ensure that we are attempting to actually restore a task
723 if (matchMode != MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE &&
724 stackId != INVALID_STACK_ID) {
725 throw new IllegalArgumentException("Should not specify stackId for non-restore lookup");
726 }
727
Craig Mautnere0a38842013-12-16 16:14:02 -0800728 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800729 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800730 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800731 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
732 ActivityStack stack = stacks.get(stackNdx);
Bryce Lee92b7b652017-04-03 08:33:11 -0700733 final TaskRecord task = stack.taskForIdLocked(id);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800734 if (task != null) {
735 return task;
736 }
Craig Mautner8d341ef2013-03-26 09:03:27 -0700737 }
738 }
Wale Ogunwale7de05352014-12-12 15:21:33 -0800739
Winson Chung7900bee2017-03-10 08:59:25 -0800740 // If we are matching stack tasks only, return now
741 if (matchMode == MATCH_TASK_IN_STACKS_ONLY) {
Wale Ogunwale7de05352014-12-12 15:21:33 -0800742 return null;
743 }
744
Winson Chung7900bee2017-03-10 08:59:25 -0800745 // Otherwise, check the recent tasks and return if we find it there and we are not restoring
746 // the task from recents
747 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
Bryce Lee92b7b652017-04-03 08:33:11 -0700748 final TaskRecord task = mRecentTasks.taskForIdLocked(id);
749
750 if (task == null) {
751 if (DEBUG_RECENTS) {
Winson Chung7900bee2017-03-10 08:59:25 -0800752 Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
753 }
Bryce Lee92b7b652017-04-03 08:33:11 -0700754
755 return null;
756 }
757
758 if (matchMode == MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) {
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700759 return task;
760 }
761
Winson Chung7900bee2017-03-10 08:59:25 -0800762 // Implicitly, this case is MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
Wale Ogunwale7e8184b2015-10-05 14:37:03 -0700763 if (!restoreRecentTaskLocked(task, stackId)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700764 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
765 "Couldn't restore task id=" + id + " found in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800766 return null;
767 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700768 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800769 return task;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700770 }
771
Craig Mautner6170f732013-04-02 13:05:23 -0700772 ActivityRecord isInAnyStackLocked(IBinder token) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800773 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800774 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800775 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800776 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
777 final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
778 if (r != null) {
779 return r;
780 }
Craig Mautner6170f732013-04-02 13:05:23 -0700781 }
782 }
783 return null;
784 }
785
Tony Mak853304c2016-04-18 15:17:41 +0100786 /**
Robin Lee3fef1f22016-12-20 14:50:13 +0000787 * Detects whether we should show a lock screen in front of this task for a locked user.
788 * <p>
789 * We'll do this if either of the following holds:
790 * <ul>
791 * <li>The top activity explicitly belongs to {@param userId}.</li>
792 * <li>The top activity returns a result to an activity belonging to {@param userId}.</li>
793 * </ul>
794 *
795 * @return {@code true} if the top activity looks like it belongs to {@param userId}.
Tony Mak853304c2016-04-18 15:17:41 +0100796 */
Robin Lee3fef1f22016-12-20 14:50:13 +0000797 private boolean taskTopActivityIsUser(TaskRecord task, @UserIdInt int userId) {
798 // To handle the case that work app is in the task but just is not the top one.
799 final ActivityRecord activityRecord = task.getTopActivity();
800 final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null);
801
802 return (activityRecord != null && activityRecord.userId == userId)
803 || (resultTo != null && resultTo.userId == userId);
804 }
805
806 /**
807 * Find all visible task stacks containing {@param userId} and intercept them with an activity
808 * to block out the contents and possibly start a credential-confirming intent.
809 *
810 * @param userId user handle for the locked managed profile.
811 */
812 void lockAllProfileTasks(@UserIdInt int userId) {
813 mWindowManager.deferSurfaceLayout();
814 try {
815 final List<ActivityStack> stacks = getStacks();
816 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; stackNdx--) {
817 final List<TaskRecord> tasks = stacks.get(stackNdx).getAllTasks();
818 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) {
819 final TaskRecord task = tasks.get(taskNdx);
820
821 // Check the task for a top activity belonging to userId, or returning a result
822 // to an activity belonging to userId. Example case: a document picker for
823 // personal files, opened by a work app, should still get locked.
824 if (taskTopActivityIsUser(task, userId)) {
Robin Leec41f6ec2017-01-10 17:02:34 +0000825 mService.mTaskChangeNotificationController.notifyTaskProfileLocked(
826 task.taskId, userId);
Robin Lee3fef1f22016-12-20 14:50:13 +0000827 }
Tony Mak853304c2016-04-18 15:17:41 +0100828 }
829 }
Robin Lee3fef1f22016-12-20 14:50:13 +0000830 } finally {
831 mWindowManager.continueSurfaceLayout();
Tony Mak853304c2016-04-18 15:17:41 +0100832 }
Clara Bayarrif0649ce2016-01-14 12:30:42 +0000833 }
834
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800835 void setNextTaskIdForUserLocked(int taskId, int userId) {
836 final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
837 if (taskId > currentTaskId) {
838 mCurTaskIdForUser.put(userId, taskId);
Craig Mautneref73ee12014-04-23 11:45:37 -0700839 }
840 }
841
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700842 static int nextTaskIdForUser(int taskId, int userId) {
843 int nextTaskId = taskId + 1;
844 if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
845 // Wrap around as there will be smaller task ids that are available now.
846 nextTaskId -= MAX_TASK_IDS_PER_USER;
847 }
848 return nextTaskId;
849 }
850
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800851 int getNextTaskIdForUserLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800852 final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
853 // for a userId u, a taskId can only be in the range
854 // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
855 // was 10, user 0 could only have taskIds 0 to 9, user 1: 10 to 19, user 2: 20 to 29, so on.
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700856 int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800857 while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
Winson Chung7900bee2017-03-10 08:59:25 -0800858 || anyTaskForIdLocked(candidateTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800859 INVALID_STACK_ID) != null) {
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700860 candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800861 if (candidateTaskId == currentTaskId) {
862 // Something wrong!
863 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
864 throw new IllegalStateException("Cannot get an available task id."
865 + " Reached limit of " + MAX_TASK_IDS_PER_USER
866 + " running tasks per user.");
867 }
868 }
869 mCurTaskIdForUser.put(userId, candidateTaskId);
870 return candidateTaskId;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700871 }
872
Chong Zhang6cda19c2016-06-14 19:07:56 -0700873 ActivityRecord getResumedActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -0800874 ActivityStack stack = mFocusedStack;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700875 if (stack == null) {
876 return null;
877 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700878 ActivityRecord resumedActivity = stack.mResumedActivity;
879 if (resumedActivity == null || resumedActivity.app == null) {
880 resumedActivity = stack.mPausingActivity;
881 if (resumedActivity == null || resumedActivity.app == null) {
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -0700882 resumedActivity = stack.topRunningActivityLocked();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700883 }
884 }
885 return resumedActivity;
886 }
887
Dianne Hackbornff072722014-09-24 10:56:28 -0700888 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
Craig Mautner20e72272013-04-01 13:45:53 -0700889 final String processName = app.processName;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800890 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800891 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
892 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800893 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
894 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700895 if (!isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800896 continue;
897 }
Jorim Jaggiea039a82017-08-02 14:37:49 +0200898 stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
899 final ActivityRecord top = stack.topRunningActivityLocked();
900 final int size = mTmpActivityList.size();
901 for (int i = 0; i < size; i++) {
902 final ActivityRecord activity = mTmpActivityList.get(i);
903 if (activity.app == null && app.uid == activity.info.applicationInfo.uid
904 && processName.equals(activity.processName)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800905 try {
Jorim Jaggiea039a82017-08-02 14:37:49 +0200906 if (realStartActivityLocked(activity, app,
907 top == activity /* andResume */, true /* checkConfig */)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800908 didSomething = true;
909 }
Dianne Hackbornff072722014-09-24 10:56:28 -0700910 } catch (RemoteException e) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800911 Slog.w(TAG, "Exception in new application when starting activity "
Jorim Jaggiea039a82017-08-02 14:37:49 +0200912 + top.intent.getComponent().flattenToShortString(), e);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800913 throw e;
Craig Mautner20e72272013-04-01 13:45:53 -0700914 }
Craig Mautner20e72272013-04-01 13:45:53 -0700915 }
Craig Mautner20e72272013-04-01 13:45:53 -0700916 }
917 }
918 }
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700919 if (!didSomething) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700920 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700921 }
Craig Mautner20e72272013-04-01 13:45:53 -0700922 return didSomething;
923 }
924
925 boolean allResumedActivitiesIdle() {
Craig Mautnere0a38842013-12-16 16:14:02 -0800926 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
927 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800928 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
929 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700930 if (!isFocusedStack(stack) || stack.numActivities() == 0) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800931 continue;
932 }
933 final ActivityRecord resumedActivity = stack.mResumedActivity;
934 if (resumedActivity == null || !resumedActivity.idle) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700935 if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
Craig Mautner34b73df2014-01-12 21:11:08 -0800936 + stack.mStackId + " " + resumedActivity + " not idle");
Craig Mautner4a1cb222013-12-04 16:14:06 -0800937 return false;
938 }
Craig Mautner20e72272013-04-01 13:45:53 -0700939 }
940 }
Wei Wang65c7a152016-06-02 18:51:22 -0700941 // Send launch end powerhint when idle
942 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
Craig Mautner20e72272013-04-01 13:45:53 -0700943 return true;
944 }
945
Craig Mautnerde4ef022013-04-07 19:01:33 -0700946 boolean allResumedActivitiesComplete() {
Craig Mautnere0a38842013-12-16 16:14:02 -0800947 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
948 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800949 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
950 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700951 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800952 final ActivityRecord r = stack.mResumedActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700953 if (r != null && r.state != RESUMED) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800954 return false;
955 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700956 }
957 }
958 }
959 // TODO: Not sure if this should check if all Paused are complete too.
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700960 if (DEBUG_STACK) Slog.d(TAG_STACK,
Craig Mautner4a1cb222013-12-04 16:14:06 -0800961 "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
962 mLastFocusedStack + " to=" + mFocusedStack);
963 mLastFocusedStack = mFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -0700964 return true;
965 }
966
967 boolean allResumedActivitiesVisible() {
riddle_hsudb46d6b2015-04-01 18:58:07 +0800968 boolean foundResumed = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800969 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
970 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800971 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
972 final ActivityStack stack = stacks.get(stackNdx);
973 final ActivityRecord r = stack.mResumedActivity;
riddle_hsudb46d6b2015-04-01 18:58:07 +0800974 if (r != null) {
Bryce Lee4a194382017-04-04 14:32:48 -0700975 if (!r.nowVisible || mActivitiesWaitingForVisibleActivity.contains(r)) {
riddle_hsudb46d6b2015-04-01 18:58:07 +0800976 return false;
977 }
978 foundResumed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800979 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700980 }
981 }
riddle_hsudb46d6b2015-04-01 18:58:07 +0800982 return foundResumed;
Craig Mautnerde4ef022013-04-07 19:01:33 -0700983 }
984
Craig Mautner2acc3892013-09-23 10:28:14 -0700985 /**
986 * Pause all activities in either all of the stacks or just the back stacks.
987 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
Wale Ogunwale950faff2016-08-08 09:51:04 -0700988 * @param resuming The resuming activity.
989 * @param dontWait The resuming activity isn't going to wait for all activities to be paused
990 * before resuming.
Craig Mautner2acc3892013-09-23 10:28:14 -0700991 * @return true if any activity was paused as a result of this call.
992 */
Wale Ogunwale950faff2016-08-08 09:51:04 -0700993 boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
Craig Mautnercf910b02013-04-23 11:23:27 -0700994 boolean someActivityPaused = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800995 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
996 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800997 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
998 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700999 if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001000 if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
Craig Mautner4a1cb222013-12-04 16:14:06 -08001001 " mResumedActivity=" + stack.mResumedActivity);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001002 someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
1003 dontWait);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001004 }
Craig Mautnercf910b02013-04-23 11:23:27 -07001005 }
1006 }
1007 return someActivityPaused;
1008 }
1009
Craig Mautnerde4ef022013-04-07 19:01:33 -07001010 boolean allPausedActivitiesComplete() {
Craig Mautnerac6f8432013-07-17 13:24:59 -07001011 boolean pausing = true;
Craig Mautnere0a38842013-12-16 16:14:02 -08001012 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1013 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001014 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1015 final ActivityStack stack = stacks.get(stackNdx);
1016 final ActivityRecord r = stack.mPausingActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001017 if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001018 if (DEBUG_STATES) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001019 Slog.d(TAG_STATES,
1020 "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001021 pausing = false;
1022 } else {
1023 return false;
1024 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001025 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001026 }
1027 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001028 return pausing;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001029 }
1030
Wale Ogunwale2be760d2016-02-17 11:16:10 -08001031 void cancelInitializingActivities() {
1032 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1033 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1034 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1035 stacks.get(stackNdx).cancelInitializingActivities();
1036 }
1037 }
1038 }
1039
Bryce Lee4a194382017-04-04 14:32:48 -07001040 void waitActivityVisible(ComponentName name, WaitResult result) {
1041 final WaitInfo waitInfo = new WaitInfo(name, result);
1042 mWaitingForActivityVisible.add(waitInfo);
1043 }
1044
1045 void cleanupActivity(ActivityRecord r) {
1046 // Make sure this record is no longer in the pending finishes list.
1047 // This could happen, for example, if we are trimming activities
1048 // down to the max limit while they are still waiting to finish.
1049 mFinishingActivities.remove(r);
1050 mActivitiesWaitingForVisibleActivity.remove(r);
1051
1052 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
Wale Ogunwale3270f172017-04-26 07:29:42 -07001053 if (mWaitingForActivityVisible.get(i).matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001054 mWaitingForActivityVisible.remove(i);
1055 }
1056 }
1057 }
1058
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001059 void reportActivityVisibleLocked(ActivityRecord r) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001060 sendWaitingVisibleReportLocked(r);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001061 }
1062
1063 void sendWaitingVisibleReportLocked(ActivityRecord r) {
1064 boolean changed = false;
Bryce Lee4a194382017-04-04 14:32:48 -07001065 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
1066 final WaitInfo w = mWaitingForActivityVisible.get(i);
Wale Ogunwale3270f172017-04-26 07:29:42 -07001067 if (w.matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001068 final WaitResult result = w.getResult();
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001069 changed = true;
Bryce Lee4a194382017-04-04 14:32:48 -07001070 result.timeout = false;
1071 result.who = w.getComponent();
1072 result.totalTime = SystemClock.uptimeMillis() - result.thisTime;
1073 result.thisTime = result.totalTime;
1074 mWaitingForActivityVisible.remove(w);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001075 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001076 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001077 if (changed) {
1078 mService.notifyAll();
1079 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001080 }
1081
Chong Zhang5022da32016-06-21 16:31:37 -07001082 void reportTaskToFrontNoLaunch(ActivityRecord r) {
1083 boolean changed = false;
1084 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1085 WaitResult w = mWaitingActivityLaunched.remove(i);
1086 if (w.who == null) {
1087 changed = true;
1088 // Set result to START_TASK_TO_FRONT so that startActivityMayWait() knows that
1089 // the starting activity ends up moving another activity to front, and it should
1090 // wait for this new activity to become visible instead.
1091 // Do not modify other fields.
1092 w.result = START_TASK_TO_FRONT;
1093 }
1094 }
1095 if (changed) {
1096 mService.notifyAll();
1097 }
1098 }
1099
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001100 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
1101 long thisTime, long totalTime) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001102 boolean changed = false;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001103 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
Craig Mautnerc64f73e2013-04-24 16:44:56 -07001104 WaitResult w = mWaitingActivityLaunched.remove(i);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001105 if (w.who == null) {
1106 changed = true;
1107 w.timeout = timeout;
1108 if (r != null) {
1109 w.who = new ComponentName(r.info.packageName, r.info.name);
1110 }
1111 w.thisTime = thisTime;
1112 w.totalTime = totalTime;
Chong Zhang5022da32016-06-21 16:31:37 -07001113 // Do not modify w.result.
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001114 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001115 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001116 if (changed) {
1117 mService.notifyAll();
1118 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001119 }
1120
Craig Mautner29219d92013-04-16 20:19:12 -07001121 ActivityRecord topRunningActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -08001122 final ActivityStack focusedStack = mFocusedStack;
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07001123 ActivityRecord r = focusedStack.topRunningActivityLocked();
Craig Mautner1602ec22013-05-12 10:24:27 -07001124 if (r != null) {
1125 return r;
Craig Mautner29219d92013-04-16 20:19:12 -07001126 }
Craig Mautner1602ec22013-05-12 10:24:27 -07001127
Andrii Kulian7318d632016-07-20 18:59:28 -07001128 // Look in other non-focused and non-home stacks.
Andrii Kulian7d95df42017-02-15 10:11:48 -08001129 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
1130
1131 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
1132 final int displayId = mTmpOrderedDisplayIds.get(i);
1133 final List<ActivityStack> stacks = mActivityDisplays.get(displayId).mStacks;
1134 if (stacks == null) {
1135 continue;
1136 }
1137 for (int j = stacks.size() - 1; j >= 0; --j) {
1138 final ActivityStack stack = stacks.get(j);
1139 if (stack != focusedStack && isFrontStackOnDisplay(stack) && stack.isFocusable()) {
1140 r = stack.topRunningActivityLocked();
1141 if (r != null) {
1142 return r;
1143 }
Craig Mautner29219d92013-04-16 20:19:12 -07001144 }
1145 }
1146 }
1147 return null;
1148 }
1149
Dianne Hackborn09233282014-04-30 11:33:59 -07001150 void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001151 // Gather all of the running tasks for each stack into runningTaskLists.
Craig Mautner4a1cb222013-12-04 16:14:06 -08001152 ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1153 new ArrayList<ArrayList<RunningTaskInfo>>();
Craig Mautnere0a38842013-12-16 16:14:02 -08001154 final int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001155 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08001156 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001157 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1158 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautner15df08a2015-04-01 12:17:18 -07001159 ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001160 runningTaskLists.add(stackTaskList);
Dianne Hackborn09233282014-04-30 11:33:59 -07001161 stack.getTasksLocked(stackTaskList, callingUid, allowed);
Craig Mautner20e72272013-04-01 13:45:53 -07001162 }
1163 }
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001164
1165 // The lists are already sorted from most recent to oldest. Just pull the most recent off
1166 // each list and add it to list. Stop when all lists are empty or maxNum reached.
1167 while (maxNum > 0) {
1168 long mostRecentActiveTime = Long.MIN_VALUE;
1169 ArrayList<RunningTaskInfo> selectedStackList = null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001170 final int numTaskLists = runningTaskLists.size();
1171 for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1172 ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001173 if (!stackTaskList.isEmpty()) {
1174 final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1175 if (lastActiveTime > mostRecentActiveTime) {
1176 mostRecentActiveTime = lastActiveTime;
1177 selectedStackList = stackTaskList;
1178 }
1179 }
1180 }
1181 if (selectedStackList != null) {
1182 list.add(selectedStackList.remove(0));
1183 --maxNum;
1184 } else {
1185 break;
1186 }
1187 }
Craig Mautner20e72272013-04-01 13:45:53 -07001188 }
1189
Todd Kennedy7440f172015-12-09 14:31:22 -08001190 ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1191 ProfilerInfo profilerInfo) {
1192 final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
Craig Mautner23ac33b2013-04-01 16:26:35 -07001193 if (aInfo != null) {
1194 // Store the found target back into the intent, because now that
1195 // we have it we never want to do this again. For example, if the
1196 // user navigates back to this point in the history, we should
1197 // always restart the exact same activity.
1198 intent.setComponent(new ComponentName(
1199 aInfo.applicationInfo.packageName, aInfo.name));
1200
1201 // Don't debug things in the system process
Man Caocfa78b22015-06-11 20:14:34 -07001202 if (!aInfo.processName.equals("system")) {
1203 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
Chong Zhangd25944e2016-06-09 16:15:27 -07001204 mService.setDebugApp(aInfo.processName, true, false);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001205 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001206
Tamas Berghammerdf6cb282016-01-29 12:07:00 +00001207 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1208 mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1209 }
1210
Man Caocfa78b22015-06-11 20:14:34 -07001211 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1212 mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1213 }
1214
1215 if (profilerInfo != null) {
Jeff Hao1b012d32014-08-20 10:35:34 -07001216 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001217 }
1218 }
Todd Kennedyb3b431302017-03-20 16:05:48 -07001219 final String intentLaunchToken = intent.getLaunchToken();
1220 if (aInfo.launchToken == null && intentLaunchToken != null) {
1221 aInfo.launchToken = intentLaunchToken;
1222 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001223 }
1224 return aInfo;
1225 }
1226
Todd Kennedy7440f172015-12-09 14:31:22 -08001227 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
Kenny Guyb1b30262016-02-09 16:02:35 +00001228 return resolveIntent(intent, resolvedType, userId, 0);
1229 }
1230
1231 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
Todd Kennedy4d1de7d2017-02-23 10:32:18 -08001232 synchronized (mService) {
1233 return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001234 PackageManager.MATCH_INSTANT | PackageManager.MATCH_DEFAULT_ONLY | flags
Kenny Guyb1b30262016-02-09 16:02:35 +00001235 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Todd Kennedy7440f172015-12-09 14:31:22 -08001236 }
Todd Kennedy7440f172015-12-09 14:31:22 -08001237 }
1238
1239 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1240 ProfilerInfo profilerInfo, int userId) {
1241 final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1242 return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1243 }
1244
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001245 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1246 boolean andResume, boolean checkConfig) throws RemoteException {
1247
1248 if (!allPausedActivitiesComplete()) {
1249 // While there are activities pausing we skipping starting any new activities until
1250 // pauses are complete. NOTE: that we also do this for activities that are starting in
1251 // the paused state because they will first be resumed then paused on the client side.
1252 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1253 "realStartActivityLocked: Skipping start of r=" + r
1254 + " some activities pausing...");
1255 return false;
1256 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001257
Bryce Leeaf691c02017-03-20 14:20:22 -07001258 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07001259 final ActivityStack stack = task.getStack();
chaviw59b98852017-06-13 12:05:44 -07001260
1261 beginDeferResume();
1262
Craig Mautner2420ead2013-04-01 17:13:20 -07001263 try {
chaviw59b98852017-06-13 12:05:44 -07001264 r.startFreezingScreenLocked(app, 0);
1265
1266 // schedule launch ticks to collect information about slow apps.
1267 r.startLaunchTickingLocked();
1268
1269 r.app = app;
1270
Jorim Jaggi838c2452017-08-28 15:44:43 +02001271 if (mKeyguardController.isKeyguardLocked()) {
1272 r.notifyUnknownVisibilityLaunched();
1273 }
1274
chaviw59b98852017-06-13 12:05:44 -07001275 // Have the window manager re-evaluate the orientation of the screen based on the new
1276 // activity order. Note that as a result of this, it can call back into the activity
1277 // manager with a new orientation. We don't care about that, because the activity is
1278 // not currently running so we are just restarting it anyway.
1279 if (checkConfig) {
1280 final int displayId = r.getDisplayId();
1281 final Configuration config = mWindowManager.updateOrientationFromAppTokens(
1282 getDisplayOverrideConfiguration(displayId),
1283 r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
1284 // Deferring resume here because we're going to launch new activity shortly.
1285 // We don't want to perform a redundant launch of the same record while ensuring
1286 // configurations and trying to resume top activity of focused stack.
1287 mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
1288 displayId);
Craig Mautner2420ead2013-04-01 17:13:20 -07001289 }
chaviw59b98852017-06-13 12:05:44 -07001290
1291 if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */,
1292 true /* isTop */)) {
1293 // We only set the visibility to true if the activity is allowed to be visible
1294 // based on
1295 // keyguard state. This avoids setting this into motion in window manager that is
1296 // later cancelled due to later calls to ensure visible activities that set
1297 // visibility back to false.
1298 r.setVisibility(true);
Craig Mautner2420ead2013-04-01 17:13:20 -07001299 }
chaviw59b98852017-06-13 12:05:44 -07001300
chaviw59b98852017-06-13 12:05:44 -07001301 final int applicationInfoUid =
1302 (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
1303 if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
1304 Slog.wtf(TAG,
1305 "User ID for activity changing for " + r
1306 + " appInfo.uid=" + r.appInfo.uid
1307 + " info.ai.uid=" + applicationInfoUid
1308 + " old=" + r.app + " new=" + app);
1309 }
1310
1311 app.waitingToKill = null;
1312 r.launchCount++;
1313 r.lastLaunchTime = SystemClock.uptimeMillis();
1314
1315 if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1316
1317 int idx = app.activities.indexOf(r);
1318 if (idx < 0) {
1319 app.activities.add(r);
1320 }
1321 mService.updateLruProcessLocked(app, true, null);
1322 mService.updateOomAdjLocked();
1323
1324 if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1325 task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
Benjamin Franza83859f2017-07-03 16:34:14 +01001326 mService.mLockTaskController.startLockTaskMode(task, false, 0 /* blank UID */);
chaviw59b98852017-06-13 12:05:44 -07001327 }
1328
1329 try {
1330 if (app.thread == null) {
1331 throw new RemoteException();
1332 }
1333 List<ResultInfo> results = null;
1334 List<ReferrerIntent> newIntents = null;
1335 if (andResume) {
1336 // We don't need to deliver new intents and/or set results if activity is going
1337 // to pause immediately after launch.
1338 results = r.results;
1339 newIntents = r.newIntents;
1340 }
1341 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1342 "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1343 + " newIntents=" + newIntents + " andResume=" + andResume);
1344 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
1345 System.identityHashCode(r), task.taskId, r.shortComponentName);
1346 if (r.isHomeActivity()) {
1347 // Home process is the root process of the task.
1348 mService.mHomeProcess = task.mActivities.get(0).app;
1349 }
1350 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
1351 PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
1352 r.sleeping = false;
1353 r.forceNewConfig = false;
1354 mService.showUnsupportedZoomDialogIfNeededLocked(r);
1355 mService.showAskCompatModeDialogLocked(r);
1356 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1357 ProfilerInfo profilerInfo = null;
1358 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1359 if (mService.mProfileProc == null || mService.mProfileProc == app) {
1360 mService.mProfileProc = app;
Andreas Gampe2b073a02017-06-22 17:28:57 -07001361 ProfilerInfo profilerInfoSvc = mService.mProfilerInfo;
1362 if (profilerInfoSvc != null && profilerInfoSvc.profileFile != null) {
1363 if (profilerInfoSvc.profileFd != null) {
chaviw59b98852017-06-13 12:05:44 -07001364 try {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001365 profilerInfoSvc.profileFd = profilerInfoSvc.profileFd.dup();
chaviw59b98852017-06-13 12:05:44 -07001366 } catch (IOException e) {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001367 profilerInfoSvc.closeFd();
Craig Mautner2568c3a2015-03-26 14:22:34 -07001368 }
1369 }
chaviw59b98852017-06-13 12:05:44 -07001370
Andreas Gampe2b073a02017-06-22 17:28:57 -07001371 profilerInfo = new ProfilerInfo(profilerInfoSvc);
Craig Mautner2420ead2013-04-01 17:13:20 -07001372 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001373 }
1374 }
Adam Powellcfbe9be2013-11-06 14:58:58 -08001375
chaviw59b98852017-06-13 12:05:44 -07001376 app.hasShownUi = true;
1377 app.pendingUiClean = true;
1378 app.forceProcessStateUpTo(mService.mTopProcessState);
1379 // Because we could be starting an Activity in the system process this may not go
1380 // across a Binder interface which would create a new Configuration. Consequently
1381 // we have to always create a new Configuration here.
Bryce Leea163b762017-01-24 11:05:01 -08001382
chaviw59b98852017-06-13 12:05:44 -07001383 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
1384 mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
1385 r.setLastReportedConfiguration(mergedConfiguration);
Bryce Leea163b762017-01-24 11:05:01 -08001386
chaviw59b98852017-06-13 12:05:44 -07001387 logIfTransactionTooLarge(r.intent, r.icicle);
1388 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1389 System.identityHashCode(r), r.info,
1390 // TODO: Have this take the merged configuration instead of separate global
1391 // and override configs.
1392 mergedConfiguration.getGlobalConfiguration(),
1393 mergedConfiguration.getOverrideConfiguration(), r.compat,
1394 r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1395 r.persistentState, results, newIntents, !andResume,
1396 mService.isNextTransitionForward(), profilerInfo);
Craig Mautner2420ead2013-04-01 17:13:20 -07001397
chaviw59b98852017-06-13 12:05:44 -07001398 if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1399 // This may be a heavy-weight process! Note that the package
1400 // manager will ensure that only activity can run in the main
1401 // process of the .apk, which is the only thing that will be
1402 // considered heavy-weight.
1403 if (app.processName.equals(app.info.packageName)) {
1404 if (mService.mHeavyWeightProcess != null
1405 && mService.mHeavyWeightProcess != app) {
1406 Slog.w(TAG, "Starting new heavy weight process " + app
1407 + " when already running "
1408 + mService.mHeavyWeightProcess);
1409 }
1410 mService.mHeavyWeightProcess = app;
1411 Message msg = mService.mHandler.obtainMessage(
1412 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1413 msg.obj = r;
1414 mService.mHandler.sendMessage(msg);
Craig Mautner2420ead2013-04-01 17:13:20 -07001415 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001416 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001417
chaviw59b98852017-06-13 12:05:44 -07001418 } catch (RemoteException e) {
1419 if (r.launchFailed) {
1420 // This is the second time we failed -- finish activity
1421 // and give up.
1422 Slog.e(TAG, "Second failure launching "
1423 + r.intent.getComponent().flattenToShortString()
1424 + ", giving up", e);
1425 mService.appDiedLocked(app);
1426 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1427 "2nd-crash", false);
1428 return false;
1429 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001430
chaviw59b98852017-06-13 12:05:44 -07001431 // This is the first time we failed -- restart process and
1432 // retry.
1433 r.launchFailed = true;
1434 app.activities.remove(r);
1435 throw e;
1436 }
1437 } finally {
1438 endDeferResume();
Craig Mautner2420ead2013-04-01 17:13:20 -07001439 }
1440
1441 r.launchFailed = false;
1442 if (stack.updateLRUListLocked(r)) {
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07001443 Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
Craig Mautner2420ead2013-04-01 17:13:20 -07001444 }
1445
chaviw59b98852017-06-13 12:05:44 -07001446 if (andResume && readyToResume()) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001447 // As part of the process of launching, ActivityThread also performs
1448 // a resume.
1449 stack.minimalResumeActivityLocked(r);
1450 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001451 // This activity is not starting in the resumed state... which should look like we asked
Wale Ogunwale919a05d2017-04-13 00:36:34 +00001452 // it to pause+stop (but remain visible), and it has done so and reported back the
Wale Ogunwaled046a012015-12-24 13:05:59 -08001453 // current icicle and other state.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001454 if (DEBUG_STATES) Slog.v(TAG_STATES,
Wale Ogunwaled046a012015-12-24 13:05:59 -08001455 "Moving to PAUSED: " + r + " (starting in paused state)");
1456 r.state = PAUSED;
Craig Mautner2420ead2013-04-01 17:13:20 -07001457 }
1458
1459 // Launch the new version setup screen if needed. We do this -after-
1460 // launching the initial activity (that is, home), so that it can have
1461 // a chance to initialize itself while in the background, making the
1462 // switch back to it faster and look better.
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001463 if (isFocusedStack(stack)) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001464 mService.startSetupActivityLocked();
1465 }
1466
Dianne Hackborn465fa392014-09-14 14:21:18 -07001467 // Update any services we are bound to that might care about whether
1468 // their client may have activities.
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001469 if (r.app != null) {
1470 mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1471 }
Dianne Hackborn465fa392014-09-14 14:21:18 -07001472
Craig Mautner2420ead2013-04-01 17:13:20 -07001473 return true;
1474 }
1475
Sudheer Shankafab200f2017-05-17 20:41:53 -07001476 private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
1477 int extrasSize = 0;
1478 if (intent != null) {
1479 final Bundle extras = intent.getExtras();
1480 if (extras != null) {
1481 extrasSize = extras.getSize();
1482 }
1483 }
1484 int icicleSize = (icicle == null ? 0 : icicle.getSize());
1485 if (extrasSize + icicleSize > 200000) {
1486 Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
1487 + ", icicle size: " + icicleSize);
1488 }
1489 }
1490
Craig Mautnere79d42682013-04-01 19:01:53 -07001491 void startSpecificActivityLocked(ActivityRecord r,
George Mount2c92c972014-03-20 09:38:23 -07001492 boolean andResume, boolean checkConfig) {
Craig Mautnere79d42682013-04-01 19:01:53 -07001493 // Is this activity's application already running?
1494 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001495 r.info.applicationInfo.uid, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001496
Andrii Kulian02b7a832016-10-06 23:11:56 -07001497 r.getStack().setLaunchTime(r);
Craig Mautnere79d42682013-04-01 19:01:53 -07001498
1499 if (app != null && app.thread != null) {
1500 try {
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001501 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1502 || !"android".equals(r.info.packageName)) {
1503 // Don't add this if it is a platform component that is marked
1504 // to run in multiple processes, because this is actually
1505 // part of the framework so doesn't make sense to track as a
1506 // separate apk in the process.
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001507 app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1508 mService.mProcessStats);
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001509 }
George Mount2c92c972014-03-20 09:38:23 -07001510 realStartActivityLocked(r, app, andResume, checkConfig);
Craig Mautnere79d42682013-04-01 19:01:53 -07001511 return;
1512 } catch (RemoteException e) {
1513 Slog.w(TAG, "Exception when starting activity "
1514 + r.intent.getComponent().flattenToShortString(), e);
1515 }
1516
1517 // If a dead object exception was thrown -- fall through to
1518 // restart the application.
1519 }
1520
1521 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001522 "activity", r.intent.getComponent(), false, false, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001523 }
1524
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001525 boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001526 String resultWho, int requestCode, int callingPid, int callingUid,
1527 String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
Jorim Jaggi2adba072016-03-03 13:43:39 +01001528 ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001529 final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1530 callingUid);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001531 if (startAnyPerm == PERMISSION_GRANTED) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001532 return true;
1533 }
1534 final int componentRestriction = getComponentRestrictionForCallingPackage(
1535 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1536 final int actionRestriction = getActionRestrictionForCallingPackage(
1537 intent.getAction(), callingPackage, callingPid, callingUid);
1538 if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1539 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1540 if (resultRecord != null) {
1541 resultStack.sendActivityResultLocked(-1,
1542 resultRecord, resultWho, requestCode,
1543 Activity.RESULT_CANCELED, null);
1544 }
1545 final String msg;
1546 if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1547 msg = "Permission Denial: starting " + intent.toString()
1548 + " from " + callerApp + " (pid=" + callingPid
1549 + ", uid=" + callingUid + ")" + " with revoked permission "
1550 + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1551 } else if (!aInfo.exported) {
1552 msg = "Permission Denial: starting " + intent.toString()
1553 + " from " + callerApp + " (pid=" + callingPid
1554 + ", uid=" + callingUid + ")"
1555 + " not exported from uid " + aInfo.applicationInfo.uid;
1556 } else {
1557 msg = "Permission Denial: starting " + intent.toString()
1558 + " from " + callerApp + " (pid=" + callingPid
1559 + ", uid=" + callingUid + ")"
1560 + " requires " + aInfo.permission;
1561 }
1562 Slog.w(TAG, msg);
1563 throw new SecurityException(msg);
1564 }
1565
1566 if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1567 final String message = "Appop Denial: starting " + intent.toString()
1568 + " from " + callerApp + " (pid=" + callingPid
1569 + ", uid=" + callingUid + ")"
1570 + " requires " + AppOpsManager.permissionToOp(
1571 ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1572 Slog.w(TAG, message);
1573 return false;
1574 } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1575 final String message = "Appop Denial: starting " + intent.toString()
1576 + " from " + callerApp + " (pid=" + callingPid
1577 + ", uid=" + callingUid + ")"
1578 + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1579 Slog.w(TAG, message);
1580 return false;
1581 }
Andrii Kulian16802aa2016-11-02 12:21:33 -07001582 if (options != null) {
1583 if (options.getLaunchTaskId() != INVALID_STACK_ID) {
1584 final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1585 callingPid, callingUid);
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001586 if (startInTaskPerm == PERMISSION_DENIED) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07001587 final String msg = "Permission Denial: starting " + intent.toString()
1588 + " from " + callerApp + " (pid=" + callingPid
1589 + ", uid=" + callingUid + ") with launchTaskId="
1590 + options.getLaunchTaskId();
1591 Slog.w(TAG, msg);
1592 throw new SecurityException(msg);
1593 }
1594 }
1595 // Check if someone tries to launch an activity on a private display with a different
1596 // owner.
1597 final int launchDisplayId = options.getLaunchDisplayId();
Andrii Kulian02689a72017-07-06 14:28:59 -07001598 if (launchDisplayId != INVALID_DISPLAY && !isCallerAllowedToLaunchOnDisplay(callingPid,
1599 callingUid, launchDisplayId, aInfo)) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001600 final String msg = "Permission Denial: starting " + intent.toString()
1601 + " from " + callerApp + " (pid=" + callingPid
1602 + ", uid=" + callingUid + ") with launchDisplayId="
1603 + launchDisplayId;
1604 Slog.w(TAG, msg);
1605 throw new SecurityException(msg);
Jorim Jaggi2adba072016-03-03 13:43:39 +01001606 }
1607 }
1608
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001609 return true;
1610 }
1611
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001612 /** Check if caller is allowed to launch activities on specified display. */
Andrii Kulian02689a72017-07-06 14:28:59 -07001613 boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId,
1614 ActivityInfo aInfo) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001615 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId
1616 + " callingPid=" + callingPid + " callingUid=" + callingUid);
1617
Andrii Kulian02689a72017-07-06 14:28:59 -07001618 if (callingPid == -1 && callingUid == -1) {
1619 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: no caller info, skip check");
1620 return true;
1621 }
1622
Andrii Kulian62e6f252017-05-30 22:46:53 -07001623 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(launchDisplayId);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001624 if (activityDisplay == null) {
1625 Slog.w(TAG, "Launch on display check: display not found");
1626 return false;
1627 }
1628
Andrii Kulian02689a72017-07-06 14:28:59 -07001629 // Check if the caller has enough privileges to embed activities and launch to private
1630 // displays.
Andrii Kulian3a95edc2017-06-28 16:21:07 -07001631 final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001632 callingUid);
1633 if (startAnyPerm == PERMISSION_GRANTED) {
1634 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1635 + " allow launch any on display");
1636 return true;
1637 }
1638
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001639 final int displayOwnerUid = activityDisplay.mDisplay.getOwnerUid();
1640 if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL && displayOwnerUid != SYSTEM_UID
1641 && displayOwnerUid != aInfo.applicationInfo.uid) {
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001642 // Limit launching on virtual displays, because their contents can be read from Surface
1643 // by apps that created them.
Andrii Kulian02689a72017-07-06 14:28:59 -07001644 if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
1645 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1646 + " disallow launch on virtual display for not-embedded activity.");
1647 return false;
1648 }
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001649 // Check if the caller is allowed to embed activities from other apps.
1650 if (mService.checkPermission(ACTIVITY_EMBEDDING, callingPid, callingUid)
1651 == PERMISSION_DENIED) {
1652 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1653 + " disallow activity embedding without permission.");
1654 return false;
1655 }
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001656 }
1657
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001658 if (!activityDisplay.isPrivate()) {
1659 // Anyone can launch on a public display.
1660 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1661 + " allow launch on public display");
1662 return true;
1663 }
1664
1665 // Check if the caller is the owner of the display.
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001666 if (displayOwnerUid == callingUid) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001667 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1668 + " allow launch for owner of the display");
1669 return true;
1670 }
1671
1672 // Check if caller is present on display
1673 if (activityDisplay.isUidPresent(callingUid)) {
1674 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1675 + " allow launch for caller present on the display");
1676 return true;
1677 }
1678
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001679 Slog.w(TAG, "Launch on display check: denied");
1680 return false;
1681 }
1682
1683 /** Update lists of UIDs that are present on displays and have access to them. */
1684 void updateUIDsPresentOnDisplay() {
1685 mDisplayAccessUIDs.clear();
1686 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1687 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
David Stevens82ea6cb2017-03-03 16:18:50 -08001688 // Only bother calculating the whitelist for private displays
1689 if (activityDisplay.isPrivate()) {
1690 mDisplayAccessUIDs.append(
1691 activityDisplay.mDisplayId, activityDisplay.getPresentUIDs());
1692 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001693 }
1694 // Store updated lists in DisplayManager. Callers from outside of AM should get them there.
1695 mDisplayManagerInternal.setDisplayAccessUIDs(mDisplayAccessUIDs);
1696 }
1697
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001698 UserInfo getUserInfo(int userId) {
Clara Bayarrif7fea162015-10-22 16:09:52 +01001699 final long identity = Binder.clearCallingIdentity();
1700 try {
1701 return UserManager.get(mService.mContext).getUserInfo(userId);
1702 } finally {
1703 Binder.restoreCallingIdentity(identity);
1704 }
1705 }
1706
Svet Ganov99b60432015-06-27 13:15:22 -07001707 private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001708 String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001709 if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1710 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001711 == PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001712 return ACTIVITY_RESTRICTION_PERMISSION;
1713 }
1714
Christopher Tateff7add02015-08-17 10:23:22 -07001715 if (activityInfo.permission == null) {
1716 return ACTIVITY_RESTRICTION_NONE;
1717 }
1718
Svet Ganov99b60432015-06-27 13:15:22 -07001719 final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1720 if (opCode == AppOpsManager.OP_NONE) {
1721 return ACTIVITY_RESTRICTION_NONE;
1722 }
1723
1724 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1725 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001726 if (!ignoreTargetSecurity) {
1727 return ACTIVITY_RESTRICTION_APPOP;
1728 }
Svet Ganov99b60432015-06-27 13:15:22 -07001729 }
1730
1731 return ACTIVITY_RESTRICTION_NONE;
1732 }
1733
Svetoslav7008b512015-06-24 18:47:07 -07001734 private int getActionRestrictionForCallingPackage(String action,
1735 String callingPackage, int callingPid, int callingUid) {
1736 if (action == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001737 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001738 }
1739
1740 String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1741 if (permission == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001742 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001743 }
1744
1745 final PackageInfo packageInfo;
1746 try {
1747 packageInfo = mService.mContext.getPackageManager()
1748 .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1749 } catch (PackageManager.NameNotFoundException e) {
1750 Slog.i(TAG, "Cannot find package info for " + callingPackage);
Svet Ganov99b60432015-06-27 13:15:22 -07001751 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001752 }
1753
1754 if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
Svet Ganov99b60432015-06-27 13:15:22 -07001755 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001756 }
1757
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001758 if (mService.checkPermission(permission, callingPid, callingUid) == PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001759 return ACTIVITY_RESTRICTION_PERMISSION;
Svetoslav7008b512015-06-24 18:47:07 -07001760 }
1761
1762 final int opCode = AppOpsManager.permissionToOpCode(permission);
1763 if (opCode == AppOpsManager.OP_NONE) {
Svet Ganov99b60432015-06-27 13:15:22 -07001764 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001765 }
1766
1767 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1768 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001769 return ACTIVITY_RESTRICTION_APPOP;
Svetoslav7008b512015-06-24 18:47:07 -07001770 }
1771
Svet Ganov99b60432015-06-27 13:15:22 -07001772 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001773 }
1774
Dianne Hackborn3d07c942015-03-13 18:02:54 -07001775 void setLaunchSource(int uid) {
1776 mLaunchingActivity.setWorkSource(new WorkSource(uid));
1777 }
1778
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001779 void acquireLaunchWakelock() {
1780 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1781 throw new IllegalStateException("Calling must be system uid");
1782 }
1783 mLaunchingActivity.acquire();
1784 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1785 // To be safe, don't allow the wake lock to be held for too long.
1786 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1787 }
1788 }
1789
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001790 /**
1791 * Called when the frontmost task is idle.
1792 * @return the state of mService.mBooting before this was called.
1793 */
1794 private boolean checkFinishBootingLocked() {
1795 final boolean booting = mService.mBooting;
1796 boolean enableScreen = false;
1797 mService.mBooting = false;
1798 if (!mService.mBooted) {
1799 mService.mBooted = true;
1800 enableScreen = true;
1801 }
1802 if (booting || enableScreen) {
1803 mService.postFinishBooting(booting, enableScreen);
1804 }
1805 return booting;
1806 }
1807
Craig Mautnerf3333272013-04-22 10:55:53 -07001808 // Checked.
1809 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
Winson Chung4dabf232017-01-25 13:25:22 -08001810 boolean processPausingActivities, Configuration config) {
Wale Ogunwalee23149f2015-03-06 15:39:44 -08001811 if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001812
Craig Mautnerf3333272013-04-22 10:55:53 -07001813 ArrayList<ActivityRecord> finishes = null;
Amith Yamasani37a40c22015-06-17 13:25:42 -07001814 ArrayList<UserState> startingUsers = null;
Craig Mautnerf3333272013-04-22 10:55:53 -07001815 int NS = 0;
1816 int NF = 0;
Craig Mautnerf3333272013-04-22 10:55:53 -07001817 boolean booting = false;
Craig Mautnerf3333272013-04-22 10:55:53 -07001818 boolean activityRemoved = false;
1819
Wale Ogunwale7d701172015-03-11 15:36:30 -07001820 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001821 if (r != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001822 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1823 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07001824 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1825 r.finishLaunchTickingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001826 if (fromTimeout) {
1827 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
Craig Mautnerf3333272013-04-22 10:55:53 -07001828 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001829
1830 // This is a hack to semi-deal with a race condition
1831 // in the client where it can be constructed with a
1832 // newer configuration from when we asked it to launch.
1833 // We'll update with whatever configuration it now says
1834 // it used to launch.
1835 if (config != null) {
Bryce Leea163b762017-01-24 11:05:01 -08001836 r.setLastReportedGlobalConfiguration(config);
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001837 }
1838
1839 // We are now idle. If someone is waiting for a thumbnail from
1840 // us, we can now deliver.
1841 r.idle = true;
1842
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001843 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001844 if (isFocusedStack(r.getStack()) || fromTimeout) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001845 booting = checkFinishBootingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001846 }
1847 }
1848
1849 if (allResumedActivitiesIdle()) {
1850 if (r != null) {
1851 mService.scheduleAppGcsLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001852 }
1853
1854 if (mLaunchingActivity.isHeld()) {
1855 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1856 if (VALIDATE_WAKE_LOCK_CALLER &&
1857 Binder.getCallingUid() != Process.myUid()) {
1858 throw new IllegalStateException("Calling must be system uid");
1859 }
1860 mLaunchingActivity.release();
1861 }
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07001862 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerf3333272013-04-22 10:55:53 -07001863 }
1864
1865 // Atomically retrieve all of the other things to do.
Winson Chung4dabf232017-01-25 13:25:22 -08001866 final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
1867 true /* remove */, processPausingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001868 NS = stops != null ? stops.size() : 0;
Wale Ogunwale7d701172015-03-11 15:36:30 -07001869 if ((NF = mFinishingActivities.size()) > 0) {
1870 finishes = new ArrayList<>(mFinishingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001871 mFinishingActivities.clear();
1872 }
1873
Craig Mautnerf3333272013-04-22 10:55:53 -07001874 if (mStartingUsers.size() > 0) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07001875 startingUsers = new ArrayList<>(mStartingUsers);
Craig Mautnerf3333272013-04-22 10:55:53 -07001876 mStartingUsers.clear();
1877 }
1878
Craig Mautnerf3333272013-04-22 10:55:53 -07001879 // Stop any activities that are scheduled to do so but have been
1880 // waiting for the next one to start.
1881 for (int i = 0; i < NS; i++) {
1882 r = stops.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001883 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001884 if (stack != null) {
1885 if (r.finishing) {
1886 stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1887 } else {
1888 stack.stopActivityLocked(r);
1889 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001890 }
1891 }
1892
1893 // Finish any activities that are scheduled to do so but have been
1894 // waiting for the next one to start.
1895 for (int i = 0; i < NF; i++) {
1896 r = finishes.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001897 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001898 if (stack != null) {
1899 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1900 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001901 }
1902
Dianne Hackborn7622a0f2014-09-30 14:31:42 -07001903 if (!booting) {
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001904 // Complete user switch
1905 if (startingUsers != null) {
1906 for (int i = 0; i < startingUsers.size(); i++) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001907 mService.mUserController.finishUserSwitch(startingUsers.get(i));
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001908 }
1909 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001910 }
1911
1912 mService.trimApplications();
1913 //dump();
1914 //mWindowManager.dump();
1915
Craig Mautnerf3333272013-04-22 10:55:53 -07001916 if (activityRemoved) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001917 resumeFocusedStackTopActivityLocked();
Craig Mautnerf3333272013-04-22 10:55:53 -07001918 }
1919
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001920 return r;
Craig Mautnerf3333272013-04-22 10:55:53 -07001921 }
1922
Craig Mautner8e569572013-10-11 17:36:59 -07001923 boolean handleAppDiedLocked(ProcessRecord app) {
Craig Mautner19091252013-10-05 00:03:53 -07001924 boolean hasVisibleActivities = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001925 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1926 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001927 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1928 hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
1929 }
Craig Mautner6b74cb52013-09-27 17:02:21 -07001930 }
Craig Mautner19091252013-10-05 00:03:53 -07001931 return hasVisibleActivities;
Craig Mautner8d341ef2013-03-26 09:03:27 -07001932 }
1933
1934 void closeSystemDialogsLocked() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001935 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1936 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001937 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1938 stacks.get(stackNdx).closeSystemDialogsLocked();
1939 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07001940 }
1941 }
1942
Craig Mautner93529a42013-10-04 15:03:13 -07001943 void removeUserLocked(int userId) {
Craig Mautner4f1df4f2013-10-15 15:44:14 -07001944 mUserStackInFront.delete(userId);
Craig Mautner93529a42013-10-04 15:03:13 -07001945 }
1946
Craig Mautner8d341ef2013-03-26 09:03:27 -07001947 /**
Chong Zhang45c25ce2015-08-10 22:18:26 -07001948 * Update the last used stack id for non-current user (current user's last
1949 * used stack is the focused stack)
1950 */
1951 void updateUserStackLocked(int userId, ActivityStack stack) {
1952 if (userId != mCurrentUser) {
1953 mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
1954 }
1955 }
1956
1957 /**
Craig Mautner8d341ef2013-03-26 09:03:27 -07001958 * @return true if some activity was finished (or would have finished if doit were true).
1959 */
Wale Ogunwale540e1232015-05-01 15:35:39 -07001960 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
1961 boolean doit, boolean evenPersistent, int userId) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07001962 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001963 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1964 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
louis_chang8f0555a2015-10-27 10:45:53 +08001965 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001966 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale540e1232015-05-01 15:35:39 -07001967 if (stack.finishDisabledPackageActivitiesLocked(
1968 packageName, filterByClasses, doit, evenPersistent, userId)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001969 didSomething = true;
1970 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07001971 }
1972 }
1973 return didSomething;
1974 }
1975
Dianne Hackborna413dc02013-07-12 12:02:55 -07001976 void updatePreviousProcessLocked(ActivityRecord r) {
1977 // Now that this process has stopped, we may want to consider
1978 // it to be the previous app to try to keep around in case
1979 // the user wants to return to it.
1980
1981 // First, found out what is currently the foreground app, so that
1982 // we don't blow away the previous app if this activity is being
1983 // hosted by the process that is actually still the foreground.
1984 ProcessRecord fgApp = null;
Craig Mautnere0a38842013-12-16 16:14:02 -08001985 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1986 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001987 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1988 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001989 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001990 if (stack.mResumedActivity != null) {
1991 fgApp = stack.mResumedActivity.app;
1992 } else if (stack.mPausingActivity != null) {
1993 fgApp = stack.mPausingActivity.app;
1994 }
1995 break;
Dianne Hackborna413dc02013-07-12 12:02:55 -07001996 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001997 }
1998 }
1999
2000 // Now set this one as the previous process, only if that really
2001 // makes sense to.
2002 if (r.app != null && fgApp != null && r.app != fgApp
2003 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
Craig Mautner4ef26932013-09-18 15:15:52 -07002004 && r.app != mService.mHomeProcess) {
Dianne Hackborna413dc02013-07-12 12:02:55 -07002005 mService.mPreviousProcess = r.app;
2006 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
2007 }
2008 }
2009
Wale Ogunwaled046a012015-12-24 13:05:59 -08002010 boolean resumeFocusedStackTopActivityLocked() {
2011 return resumeFocusedStackTopActivityLocked(null, null, null);
Craig Mautner05d29032013-05-03 13:40:13 -07002012 }
2013
Wale Ogunwaled046a012015-12-24 13:05:59 -08002014 boolean resumeFocusedStackTopActivityLocked(
Chong Zhang280d3322015-11-03 17:27:26 -08002015 ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
chaviw59b98852017-06-13 12:05:44 -07002016
2017 if (!readyToResume()) {
2018 return false;
2019 }
2020
Wale Ogunwaled046a012015-12-24 13:05:59 -08002021 if (targetStack != null && isFocusedStack(targetStack)) {
2022 return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
Craig Mautner05d29032013-05-03 13:40:13 -07002023 }
chaviw59b98852017-06-13 12:05:44 -07002024
Wale Ogunwale06579d62016-04-30 15:29:06 -07002025 final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2026 if (r == null || r.state != RESUMED) {
2027 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
skuhne@google.com1b974dc2016-12-09 13:41:29 -08002028 } else if (r.state == RESUMED) {
2029 // Kick off any lingering app transitions form the MoveTaskToFront operation.
2030 mFocusedStack.executeAppTransition(targetOptions);
Wale Ogunwale06579d62016-04-30 15:29:06 -07002031 }
chaviw59b98852017-06-13 12:05:44 -07002032
Wale Ogunwaled046a012015-12-24 13:05:59 -08002033 return false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002034 }
2035
Todd Kennedy39bfee52016-02-24 10:28:21 -08002036 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
2037 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2038 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2039 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2040 stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
2041 }
2042 }
2043 }
2044
Adrian Roos20d7df32016-01-12 18:59:43 +01002045 TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
2046 TaskRecord finishedTask = null;
2047 ActivityStack focusedStack = getFocusedStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08002048 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2049 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002050 final int numStacks = stacks.size();
2051 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2052 final ActivityStack stack = stacks.get(stackNdx);
Adrian Roos20d7df32016-01-12 18:59:43 +01002053 TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
2054 if (stack == focusedStack || finishedTask == null) {
2055 finishedTask = t;
2056 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08002057 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002058 }
Adrian Roos20d7df32016-01-12 18:59:43 +01002059 return finishedTask;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002060 }
2061
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07002062 void finishVoiceTask(IVoiceInteractionSession session) {
2063 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2064 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2065 final int numStacks = stacks.size();
2066 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2067 final ActivityStack stack = stacks.get(stackNdx);
2068 stack.finishVoiceTask(session);
2069 }
2070 }
2071 }
2072
Andrii Kulianc27916642016-04-12 17:59:27 -07002073 void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
2074 String reason, boolean forceNonResizeable) {
Craig Mautneraea74a52014-03-08 14:23:10 -08002075 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
2076 mUserLeaving = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002077 }
Craig Mautneraea74a52014-03-08 14:23:10 -08002078 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
2079 // Caller wants the home activity moved with it. To accomplish this,
2080 // we'll just indicate that this task returns to the home task.
Craig Mautner84984fa2014-06-19 11:19:20 -07002081 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
Craig Mautneraea74a52014-03-08 14:23:10 -08002082 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002083 ActivityStack currentStack = task.getStack();
2084 if (currentStack == null) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07002085 Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
2086 + task + " to front. Stack is null");
2087 return;
2088 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002089
Wale Ogunwaleb1faf602016-01-27 09:12:31 -08002090 if (task.isResizeable() && options != null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002091 int stackId = options.getLaunchStackId();
2092 if (canUseActivityOptionsLaunchBounds(options, stackId)) {
Filip Gruszczynskidce2d162016-01-12 15:40:13 -08002093 final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
Chong Zhang0fa656b2015-08-31 15:17:21 -07002094 task.updateOverrideConfiguration(bounds);
Wale Ogunwale854809c2015-12-27 16:18:19 -08002095 if (stackId == INVALID_STACK_ID) {
2096 stackId = task.getLaunchStackId();
2097 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002098 if (stackId != currentStack.mStackId) {
Winson Chung74666102017-02-22 17:49:24 -08002099 task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE,
2100 DEFER_RESUME, "findTaskToMoveToFrontLocked");
Andrii Kulian02b7a832016-10-06 23:11:56 -07002101 stackId = currentStack.mStackId;
Chong Zhang112eb8c2015-11-02 11:17:00 -08002102 // moveTaskToStackUncheckedLocked() should already placed the task on top,
2103 // still need moveTaskToFrontLocked() below for any transition settings.
2104 }
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002105 if (StackId.resizeStackWithLaunchBounds(stackId)) {
2106 resizeStackLocked(stackId, bounds,
2107 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002108 !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002109 } else {
2110 // WM resizeTask must be done after the task is moved to the correct stack,
2111 // because Task's setBounds() also updates dim layer's bounds, but that has
2112 // dependency on the stack.
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002113 task.resizeWindowContainer();
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002114 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002115 }
2116 }
2117
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002118 final ActivityRecord r = task.getTopActivity();
Andrii Kulian02b7a832016-10-06 23:11:56 -07002119 currentStack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002120 r == null ? null : r.appTimeTracker, reason);
2121
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002122 if (DEBUG_STACK) Slog.d(TAG_STACK,
Andrii Kulian02b7a832016-10-06 23:11:56 -07002123 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
Jorim Jaggi2adba072016-03-03 13:43:39 +01002124
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002125 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
2126 currentStack.mStackId, forceNonResizeable);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002127 }
2128
Wale Ogunwale854809c2015-12-27 16:18:19 -08002129 boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002130 // We use the launch bounds in the activity options is the device supports freeform
Wale Ogunwale854809c2015-12-27 16:18:19 -08002131 // window management or is launching into the pinned stack.
Wale Ogunwale5122df02016-01-29 22:33:38 -08002132 if (options.getLaunchBounds() == null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002133 return false;
2134 }
2135 return (mService.mSupportsPictureInPicture && launchStackId == PINNED_STACK_ID)
2136 || mService.mSupportsFreeformWindowManagement;
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002137 }
2138
Winson Chung55893332017-02-17 17:13:10 -08002139 protected <T extends ActivityStack> T getStack(int stackId) {
Wale Ogunwale040b4702015-08-06 18:10:50 -07002140 return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002141 }
2142
Winson Chung55893332017-02-17 17:13:10 -08002143 protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
2144 boolean createOnTop) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002145 final ActivityStack stack = mStacks.get(stackId);
2146 if (stack != null) {
2147 return (T) stack;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002148 }
Wale Ogunwale3797c222015-10-27 14:21:58 -07002149 if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002150 return null;
2151 }
Matthew Ng330757d2017-02-28 14:19:17 -08002152 if (stackId == DOCKED_STACK_ID) {
2153 // Make sure recents stack exist when creating a dock stack as it normally need to be on
2154 // the other side of the docked stack and we make visibility decisions based on that.
2155 getStack(RECENTS_STACK_ID, CREATE_IF_NEEDED, createOnTop);
2156 }
Winson Chung55893332017-02-17 17:13:10 -08002157 return (T) createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002158 }
2159
Andrii Kulian16802aa2016-11-02 12:21:33 -07002160 /**
2161 * Get a topmost stack on the display, that is a valid launch stack for specified activity.
2162 * If there is no such stack, new dynamic stack can be created.
2163 * @param displayId Target display.
2164 * @param r Activity that should be launched there.
2165 * @return Existing stack if there is a valid one, new dynamic stack if it is valid or null.
2166 */
2167 ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002168 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian16802aa2016-11-02 12:21:33 -07002169 if (activityDisplay == null) {
2170 throw new IllegalArgumentException(
2171 "Display with displayId=" + displayId + " not found.");
2172 }
2173
2174 // Return the topmost valid stack on the display.
2175 for (int i = activityDisplay.mStacks.size() - 1; i >= 0; --i) {
2176 final ActivityStack stack = activityDisplay.mStacks.get(i);
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002177 if (mService.mActivityStarter.isValidLaunchStackId(stack.mStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002178 return stack;
2179 }
2180 }
2181
2182 // If there is no valid stack on the external display - check if new dynamic stack will do.
2183 if (displayId != Display.DEFAULT_DISPLAY) {
2184 final int newDynamicStackId = getNextStackId();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002185 if (mService.mActivityStarter.isValidLaunchStackId(newDynamicStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002186 return createStackOnDisplay(newDynamicStackId, displayId, true /*onTop*/);
2187 }
2188 }
2189
2190 Slog.w(TAG, "getValidLaunchStackOnDisplay: can't launch on displayId " + displayId);
2191 return null;
2192 }
2193
Craig Mautner967212c2013-04-13 21:10:58 -07002194 ArrayList<ActivityStack> getStacks() {
Wale Ogunwale3797c222015-10-27 14:21:58 -07002195 ArrayList<ActivityStack> allStacks = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08002196 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2197 allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002198 }
2199 return allStacks;
Craig Mautner967212c2013-04-13 21:10:58 -07002200 }
2201
Jorim Jaggife762342016-10-13 14:33:27 +02002202 ArrayList<ActivityStack> getStacksOnDefaultDisplay() {
2203 return mActivityDisplays.valueAt(DEFAULT_DISPLAY).mStacks;
2204 }
2205
Andrii Kulian7fc22812016-12-28 13:04:11 -08002206 /**
2207 * Get next focusable stack in the system. This will search across displays and stacks
2208 * in last-focused order for a focusable and visible stack, different from the target stack.
2209 *
2210 * @param currentFocus The stack that previously had focus and thus needs to be ignored when
2211 * searching for next candidate.
2212 * @return Next focusable {@link ActivityStack}, null if not found.
2213 */
2214 ActivityStack getNextFocusableStackLocked(ActivityStack currentFocus) {
2215 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2216
2217 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2218 final int displayId = mTmpOrderedDisplayIds.get(i);
Andrii Kulian62e6f252017-05-30 22:46:53 -07002219 // If a display is registered in WM, it must also be available in AM.
2220 @SuppressWarnings("ConstantConditions")
2221 final List<ActivityStack> stacks = getActivityDisplayOrCreateLocked(displayId).mStacks;
Andrii Kulian7fc22812016-12-28 13:04:11 -08002222 for (int j = stacks.size() - 1; j >= 0; --j) {
2223 final ActivityStack stack = stacks.get(j);
2224 if (stack != currentFocus && stack.isFocusable()
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002225 && stack.shouldBeVisible(null) != STACK_INVISIBLE) {
Andrii Kulian7fc22812016-12-28 13:04:11 -08002226 return stack;
2227 }
2228 }
2229 }
2230
2231 return null;
2232 }
2233
Andrii Kuliana8fe3df2017-06-16 15:29:26 -07002234 /**
2235 * Get next valid stack for launching provided activity in the system. This will search across
2236 * displays and stacks in last-focused order for a focusable and visible stack, except those
2237 * that are on a currently focused display.
2238 *
2239 * @param r The activity that is being launched.
2240 * @param currentFocus The display that previously had focus and thus needs to be ignored when
2241 * searching for the next candidate.
2242 * @return Next valid {@link ActivityStack}, null if not found.
2243 */
2244 ActivityStack getNextValidLaunchStackLocked(@NonNull ActivityRecord r, int currentFocus) {
2245 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2246 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2247 final int displayId = mTmpOrderedDisplayIds.get(i);
2248 if (displayId == currentFocus) {
2249 continue;
2250 }
2251 final ActivityStack stack = getValidLaunchStackOnDisplay(displayId, r);
2252 if (stack != null) {
2253 return stack;
2254 }
2255 }
2256 return null;
2257 }
2258
Craig Mautneree2e45a2014-06-27 12:10:03 -07002259 ActivityRecord getHomeActivity() {
Craig Mautnerdb49fec2015-05-21 15:33:30 -07002260 return getHomeActivityForUser(mCurrentUser);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002261 }
2262
2263 ActivityRecord getHomeActivityForUser(int userId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002264 final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
2265 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
2266 final TaskRecord task = tasks.get(taskNdx);
2267 if (task.isHomeTask()) {
2268 final ArrayList<ActivityRecord> activities = task.mActivities;
2269 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2270 final ActivityRecord r = activities.get(activityNdx);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002271 if (r.isHomeActivity()
2272 && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
Craig Mautneree2e45a2014-06-27 12:10:03 -07002273 return r;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002274 }
2275 }
2276 }
2277 }
2278 return null;
2279 }
2280
Chong Zhangb15758a2015-11-17 12:12:03 -08002281 /**
2282 * Returns if a stack should be treated as if it's docked. Returns true if the stack is
2283 * the docked stack itself, or if it's side-by-side to the docked stack.
2284 */
2285 boolean isStackDockedInEffect(int stackId) {
2286 return stackId == DOCKED_STACK_ID ||
2287 (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
2288 }
2289
Jorim Jaggidc249c42015-12-15 14:57:31 -08002290 void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002291 boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
Jorim Jaggidc249c42015-12-15 14:57:31 -08002292 if (stackId == DOCKED_STACK_ID) {
2293 resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002294 preserveWindows, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002295 return;
2296 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08002297 final ActivityStack stack = getStack(stackId);
2298 if (stack == null) {
2299 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2300 return;
2301 }
Wale Ogunwale9d3de4c2015-02-01 16:49:44 -08002302
Wale Ogunwale3382ab12017-07-27 08:55:03 -07002303 if (!allowResizeInDockedMode
2304 && !stack.getWindowConfiguration().tasksAreFloating()
2305 && getStack(DOCKED_STACK_ID) != null) {
Winson Chunga2249ac2017-03-30 18:15:30 -07002306 // If the docked stack exists, don't resize non-floating stacks independently of the
2307 // size computed from the docked stack size (otherwise they will be out of sync)
Wale Ogunwaleffc11bb2015-10-10 13:05:45 -07002308 return;
2309 }
2310
Wale Ogunwalecad05a02015-09-25 10:41:44 -07002311 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
Jorim Jaggic4025202015-10-22 16:43:34 +02002312 mWindowManager.deferSurfaceLayout();
2313 try {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002314 stack.resize(bounds, tempTaskBounds, tempTaskInsetBounds);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002315 if (!deferResume) {
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002316 stack.ensureVisibleActivitiesConfigurationLocked(
2317 stack.topRunningActivityLocked(), preserveWindows);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002318 }
Jorim Jaggic4025202015-10-22 16:43:34 +02002319 } finally {
2320 mWindowManager.continueSurfaceLayout();
2321 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07002322 }
2323 }
2324
Jorim Jaggi192086e2016-03-11 17:17:03 +01002325 void deferUpdateBounds(int stackId) {
2326 final ActivityStack stack = getStack(stackId);
2327 if (stack != null) {
2328 stack.deferUpdateBounds();
2329 }
2330 }
2331
2332 void continueUpdateBounds(int stackId) {
2333 final ActivityStack stack = getStack(stackId);
2334 if (stack != null) {
2335 stack.continueUpdateBounds();
2336 }
2337 }
2338
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002339 void notifyAppTransitionDone() {
Matthew Ng606dd802017-06-05 14:06:32 -07002340 continueUpdateBounds(RECENTS_STACK_ID);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002341 for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2342 final int taskId = mResizingTasksDuringAnimation.valueAt(i);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002343 final TaskRecord task =
Winson Chung7900bee2017-03-10 08:59:25 -08002344 anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002345 if (task != null) {
2346 task.setTaskDockedResizing(false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002347 }
2348 }
2349 mResizingTasksDuringAnimation.clear();
2350 }
2351
Robert Carre7cc44d2017-03-20 19:04:30 -07002352 private void moveTasksToFullscreenStackInSurfaceTransaction(int fromStackId,
2353 boolean onTop) {
Robert Carr6914f082017-03-20 19:04:30 -07002354
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002355 final ActivityStack stack = getStack(fromStackId);
2356 if (stack == null) {
2357 return;
2358 }
2359
2360 mWindowManager.deferSurfaceLayout();
2361 try {
2362 if (fromStackId == DOCKED_STACK_ID) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002363 // We are moving all tasks from the docked stack to the fullscreen stack,
2364 // which is dismissing the docked stack, so resize all other stacks to
2365 // fullscreen here already so we don't end up with resize trashing.
2366 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2367 if (StackId.isResizeableByDockedStack(i)) {
2368 ActivityStack otherStack = getStack(i);
2369 if (otherStack != null) {
2370 resizeStackLocked(i, null, null, null, PRESERVE_WINDOWS,
2371 true /* allowResizeInDockedMode */, DEFER_RESUME);
2372 }
2373 }
2374 }
2375
2376 // Also disable docked stack resizing since we have manually adjusted the
2377 // size of other stacks above and we don't want to trigger a docked stack
2378 // resize when we remove task from it below and it is detached from the
2379 // display because it no longer contains any tasks.
2380 mAllowDockedStackResize = false;
Winson Chung47900652017-04-06 18:44:25 -07002381 } else if (fromStackId == PINNED_STACK_ID) {
2382 if (onTop) {
2383 // Log if we are expanding the PiP to fullscreen
2384 MetricsLogger.action(mService.mContext,
2385 ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN);
2386 }
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002387 }
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002388 ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
Winson Chungc85d9ce2017-01-03 11:59:52 -08002389 final boolean isFullscreenStackVisible = fullscreenStack != null &&
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002390 fullscreenStack.shouldBeVisible(null) == STACK_VISIBLE;
Winson Chung5af42fc2017-03-24 17:11:33 -07002391 // If we are moving from the pinned stack, then the animation takes care of updating
2392 // the picture-in-picture mode.
Winson Chung47900652017-04-06 18:44:25 -07002393 final boolean schedulePictureInPictureModeChange = (fromStackId == PINNED_STACK_ID);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002394 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2395 final int size = tasks.size();
2396 if (onTop) {
2397 for (int i = 0; i < size; i++) {
Winson Chung0c1ca092016-11-10 17:40:34 -08002398 final TaskRecord task = tasks.get(i);
Winson Chung74666102017-02-22 17:49:24 -08002399 final boolean isTopTask = i == (size - 1);
Winson Chung0c1ca092016-11-10 17:40:34 -08002400 if (fromStackId == PINNED_STACK_ID) {
2401 // Update the return-to to reflect where the pinned stack task was moved
2402 // from so that we retain the stack that was previously visible if the
2403 // pinned stack is recreated. See moveActivityToPinnedStackLocked().
Winson Chungc85d9ce2017-01-03 11:59:52 -08002404 task.setTaskToReturnTo(isFullscreenStackVisible && onTop ?
2405 APPLICATION_ACTIVITY_TYPE : HOME_ACTIVITY_TYPE);
Winson Chung0c1ca092016-11-10 17:40:34 -08002406 }
Winson Chung74666102017-02-22 17:49:24 -08002407 // Defer resume until all the tasks have been moved to the fullscreen stack
2408 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
2409 REPARENT_MOVE_STACK_TO_FRONT, isTopTask /* animate */, DEFER_RESUME,
Winson Chung5af42fc2017-03-24 17:11:33 -07002410 schedulePictureInPictureModeChange,
Winson Chung74666102017-02-22 17:49:24 -08002411 "moveTasksToFullscreenStack - onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002412 }
2413 } else {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002414 for (int i = 0; i < size; i++) {
Wale Ogunwalec5cc3012017-01-13 13:26:16 -08002415 final TaskRecord task = tasks.get(i);
Winson Chung3a649982017-04-19 10:16:17 -07002416 // Position the tasks in the fullscreen stack in order at the bottom of the
2417 // stack. Also defer resume until all the tasks have been moved to the
2418 // fullscreen stack.
2419 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, i /* position */,
Winson Chung5af42fc2017-03-24 17:11:33 -07002420 REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME,
2421 schedulePictureInPictureModeChange,
2422 "moveTasksToFullscreenStack - NOT_onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002423 }
2424 }
Winson Chung74666102017-02-22 17:49:24 -08002425
2426 ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2427 resumeFocusedStackTopActivityLocked();
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002428 } finally {
2429 mAllowDockedStackResize = true;
2430 mWindowManager.continueSurfaceLayout();
2431 }
2432 }
2433
Robert Carr6914f082017-03-20 19:04:30 -07002434 void moveTasksToFullscreenStackLocked(int fromStackId, boolean onTop) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002435 mWindowManager.inSurfaceTransaction(
2436 () -> moveTasksToFullscreenStackInSurfaceTransaction(fromStackId, onTop));
Robert Carr6914f082017-03-20 19:04:30 -07002437 }
2438
Jorim Jaggidc249c42015-12-15 14:57:31 -08002439 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002440 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2441 boolean preserveWindows) {
2442 resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
2443 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows,
2444 false /* deferResume */);
2445 }
2446
2447 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2448 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2449 boolean preserveWindows, boolean deferResume) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002450
2451 if (!mAllowDockedStackResize) {
2452 // Docked stack resize currently disabled.
2453 return;
2454 }
2455
Jorim Jaggidc249c42015-12-15 14:57:31 -08002456 final ActivityStack stack = getStack(DOCKED_STACK_ID);
2457 if (stack == null) {
2458 Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2459 return;
2460 }
2461
2462 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2463 mWindowManager.deferSurfaceLayout();
2464 try {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002465 // Don't allow re-entry while resizing. E.g. due to docked stack detaching.
2466 mAllowDockedStackResize = false;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002467 ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwale1666e312016-12-16 11:27:18 -08002468 stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002469
Andrii Kulian69fb5e42016-04-05 16:47:29 -07002470 // TODO: Checking for isAttached might not be needed as if the user passes in null
2471 // dockedBounds then they want the docked stack to be dismissed.
2472 if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2473 // The dock stack either was dismissed or went fullscreen, which is kinda the same.
Jorim Jaggidc249c42015-12-15 14:57:31 -08002474 // In this case we make all other static stacks fullscreen and move all
2475 // docked stack tasks to the fullscreen stack.
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002476 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, ON_TOP);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002477
2478 // stack shouldn't contain anymore activities, so nothing to resume.
2479 r = null;
2480 } else {
2481 // Docked stacks occupy a dedicated region on screen so the size of all other
2482 // static stacks need to be adjusted so they don't overlap with the docked stack.
2483 // We get the bounds to use from window manager which has been adjusted for any
2484 // screen controls and is also the same for all stacks.
Matthew Ngaa2b6202017-02-10 14:48:21 -08002485 final Rect otherTaskRect = new Rect();
Jorim Jaggidc249c42015-12-15 14:57:31 -08002486 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002487 final ActivityStack current = getStack(i);
2488 if (current != null && StackId.isResizeableByDockedStack(i)) {
Matthew Ngaa2b6202017-02-10 14:48:21 -08002489 current.getStackDockedModeBounds(
2490 tempOtherTaskBounds /* currentTempTaskBounds */,
2491 tempRect /* outStackBounds */,
2492 otherTaskRect /* outTempTaskBounds */, true /* ignoreVisibility */);
2493
Andrii Kuliane48b7d82017-04-28 14:51:05 -07002494 resizeStackLocked(i, !tempRect.isEmpty() ? tempRect : null,
Matthew Ngaa2b6202017-02-10 14:48:21 -08002495 !otherTaskRect.isEmpty() ? otherTaskRect : tempOtherTaskBounds,
2496 tempOtherTaskInsetBounds, preserveWindows,
2497 true /* allowResizeInDockedMode */, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002498 }
2499 }
2500 }
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002501 if (!deferResume) {
2502 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows);
2503 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002504 } finally {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002505 mAllowDockedStackResize = true;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002506 mWindowManager.continueSurfaceLayout();
2507 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2508 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002509 }
2510
Robert Carr0d00c2e2016-02-29 17:45:02 -08002511 void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Winson Chung19953ca2017-04-11 11:19:23 -07002512 final PinnedActivityStack stack = getStack(PINNED_STACK_ID);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002513 if (stack == null) {
2514 Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2515 return;
2516 }
Winson Chung19953ca2017-04-11 11:19:23 -07002517
2518 // It is possible for the bounds animation from the WM to call this but be delayed by
2519 // another AM call that is holding the AMS lock. In such a case, the pinnedBounds may be
2520 // incorrect if AMS.resizeStackWithBoundsFromWindowManager() is already called while waiting
2521 // for the AMS lock to be freed. So check and make sure these bounds are still good.
2522 final PinnedStackWindowController stackController = stack.getWindowContainerController();
Winson Chung8bca9e42017-04-16 15:59:43 -07002523 if (stackController.pinnedStackResizeDisallowed()) {
Winson Chung19953ca2017-04-11 11:19:23 -07002524 return;
2525 }
2526
Robert Carr0d00c2e2016-02-29 17:45:02 -08002527 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2528 mWindowManager.deferSurfaceLayout();
2529 try {
2530 ActivityRecord r = stack.topRunningActivityLocked();
Robert Carr7e4c90e2017-02-15 19:52:38 -08002531 Rect insetBounds = null;
2532 if (tempPinnedTaskBounds != null) {
2533 // We always use 0,0 as the position for the inset rect because
2534 // if we are getting insets at all in the pinned stack it must mean
2535 // we are headed for fullscreen.
2536 insetBounds = tempRect;
2537 insetBounds.top = 0;
2538 insetBounds.left = 0;
2539 insetBounds.right = tempPinnedTaskBounds.width();
2540 insetBounds.bottom = tempPinnedTaskBounds.height();
2541 }
2542 stack.resize(pinnedBounds, tempPinnedTaskBounds, insetBounds);
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002543 stack.ensureVisibleActivitiesConfigurationLocked(r, false);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002544 } finally {
2545 mWindowManager.continueSurfaceLayout();
2546 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2547 }
2548 }
2549
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002550 ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002551 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Craig Mautnere0a38842013-12-16 16:14:02 -08002552 if (activityDisplay == null) {
Todd Kennedy4900bf92015-01-16 16:05:14 -08002553 return null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002554 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002555 return createStack(stackId, activityDisplay, onTop);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002556
Craig Mautner4a1cb222013-12-04 16:14:06 -08002557 }
2558
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002559 ActivityStack createStack(int stackId, ActivityDisplay display, boolean onTop) {
2560 switch (stackId) {
2561 case PINNED_STACK_ID:
2562 return new PinnedActivityStack(display, stackId, this, mRecentTasks, onTop);
2563 default:
2564 return new ActivityStack(display, stackId, this, mRecentTasks, onTop);
2565 }
2566 }
Robert Carr6914f082017-03-20 19:04:30 -07002567
Robert Carre7cc44d2017-03-20 19:04:30 -07002568 void removeStackInSurfaceTransaction(int stackId) {
Winson Chung010927a2016-12-15 16:12:35 -08002569 final ActivityStack stack = getStack(stackId);
2570 if (stack == null) {
2571 return;
2572 }
2573
2574 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2575 if (stack.getStackId() == PINNED_STACK_ID) {
Winson Chung47900652017-04-06 18:44:25 -07002576 /**
2577 * Workaround: Force-stop all the activities in the pinned stack before we reparent them
2578 * to the fullscreen stack. This is to guarantee that when we are removing a stack,
2579 * that the client receives onStop() before it is reparented. We do this by detaching
2580 * the stack from the display so that it will be considered invisible when
2581 * ensureActivitiesVisibleLocked() is called, and all of its activitys will be marked
2582 * invisible as well and added to the stopping list. After which we process the
2583 * stopping list by handling the idle.
2584 */
2585 final PinnedActivityStack pinnedStack = (PinnedActivityStack) stack;
2586 pinnedStack.mForceHidden = true;
2587 pinnedStack.ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2588 pinnedStack.mForceHidden = false;
2589 activityIdleInternalLocked(null, false /* fromTimeout */,
2590 true /* processPausingActivites */, null /* configuration */);
2591
2592 // Move all the tasks to the bottom of the fullscreen stack
2593 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
Winson Chung010927a2016-12-15 16:12:35 -08002594 } else {
2595 for (int i = tasks.size() - 1; i >= 0; i--) {
2596 removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */,
2597 REMOVE_FROM_RECENTS);
2598 }
2599 }
2600 }
2601
2602 /**
Robert Carr6914f082017-03-20 19:04:30 -07002603 * Removes the stack associated with the given {@param stackId}. If the {@param stackId} is the
2604 * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
2605 * instead moved back onto the fullscreen stack.
2606 */
2607 void removeStackLocked(int stackId) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002608 mWindowManager.inSurfaceTransaction(
2609 () -> removeStackInSurfaceTransaction(stackId));
Robert Carr6914f082017-03-20 19:04:30 -07002610 }
2611
2612 /**
Winson Chung6954fc92017-03-24 16:22:12 -07002613 * See {@link #removeTaskByIdLocked(int, boolean, boolean, boolean)}
2614 */
2615 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents) {
2616 return removeTaskByIdLocked(taskId, killProcess, removeFromRecents, !PAUSE_IMMEDIATELY);
2617 }
2618
2619 /**
Winson Chung010927a2016-12-15 16:12:35 -08002620 * Removes the task with the specified task id.
2621 *
2622 * @param taskId Identifier of the task to be removed.
2623 * @param killProcess Kill any process associated with the task if possible.
2624 * @param removeFromRecents Whether to also remove the task from recents.
Winson Chung6954fc92017-03-24 16:22:12 -07002625 * @param pauseImmediately Pauses all task activities immediately without waiting for the
2626 * pause-complete callback from the activity.
Winson Chung010927a2016-12-15 16:12:35 -08002627 * @return Returns true if the given task was found and removed.
2628 */
Winson Chung6954fc92017-03-24 16:22:12 -07002629 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents,
2630 boolean pauseImmediately) {
Winson Chung7900bee2017-03-10 08:59:25 -08002631 final TaskRecord tr = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
2632 INVALID_STACK_ID);
Winson Chung010927a2016-12-15 16:12:35 -08002633 if (tr != null) {
Winson Chung6954fc92017-03-24 16:22:12 -07002634 tr.removeTaskActivitiesLocked(pauseImmediately);
Winson Chung010927a2016-12-15 16:12:35 -08002635 cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents);
2636 if (tr.isPersistable) {
2637 mService.notifyTaskPersisterLocked(null, true);
2638 }
2639 return true;
2640 }
2641 Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
2642 return false;
2643 }
2644
2645 void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) {
2646 if (removeFromRecents) {
2647 mRecentTasks.remove(tr);
2648 tr.removedFromRecents();
2649 }
2650 ComponentName component = tr.getBaseIntent().getComponent();
2651 if (component == null) {
2652 Slog.w(TAG, "No component for base intent of task: " + tr);
2653 return;
2654 }
2655
2656 // Find any running services associated with this app and stop if needed.
2657 mService.mServices.cleanUpRemovedTaskLocked(tr, component, new Intent(tr.getBaseIntent()));
2658
2659 if (!killProcess) {
2660 return;
2661 }
2662
2663 // Determine if the process(es) for this task should be killed.
2664 final String pkg = component.getPackageName();
2665 ArrayList<ProcessRecord> procsToKill = new ArrayList<>();
2666 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mService.mProcessNames.getMap();
2667 for (int i = 0; i < pmap.size(); i++) {
2668
2669 SparseArray<ProcessRecord> uids = pmap.valueAt(i);
2670 for (int j = 0; j < uids.size(); j++) {
2671 ProcessRecord proc = uids.valueAt(j);
2672 if (proc.userId != tr.userId) {
2673 // Don't kill process for a different user.
2674 continue;
2675 }
2676 if (proc == mService.mHomeProcess) {
2677 // Don't kill the home process along with tasks from the same package.
2678 continue;
2679 }
2680 if (!proc.pkgList.containsKey(pkg)) {
2681 // Don't kill process that is not associated with this task.
2682 continue;
2683 }
2684
2685 for (int k = 0; k < proc.activities.size(); k++) {
Bryce Leeaf691c02017-03-20 14:20:22 -07002686 TaskRecord otherTask = proc.activities.get(k).getTask();
Winson Chung010927a2016-12-15 16:12:35 -08002687 if (tr.taskId != otherTask.taskId && otherTask.inRecents) {
2688 // Don't kill process(es) that has an activity in a different task that is
2689 // also in recents.
2690 return;
2691 }
2692 }
2693
2694 if (proc.foregroundServices) {
2695 // Don't kill process(es) with foreground service.
2696 return;
2697 }
2698
2699 // Add process to kill list.
2700 procsToKill.add(proc);
2701 }
2702 }
2703
2704 // Kill the running processes.
2705 for (int i = 0; i < procsToKill.size(); i++) {
2706 ProcessRecord pr = procsToKill.get(i);
2707 if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
2708 && pr.curReceivers.isEmpty()) {
2709 pr.kill("remove task", true);
2710 } else {
2711 // We delay killing processes that are not in the background or running a receiver.
2712 pr.waitingToKill = "remove task";
2713 }
2714 }
2715 }
2716
Craig Mautner4a1cb222013-12-04 16:14:06 -08002717 int getNextStackId() {
Craig Mautner858d8a62013-04-23 17:08:34 -07002718 while (true) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002719 if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2720 && getStack(mNextFreeStackId) == null) {
Craig Mautner858d8a62013-04-23 17:08:34 -07002721 break;
2722 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002723 mNextFreeStackId++;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002724 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002725 return mNextFreeStackId;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002726 }
2727
Chong Zhang5dcb2752015-08-18 13:50:26 -07002728 /**
2729 * Restores a recent task to a stack
2730 * @param task The recent task to be restored.
2731 * @param stackId The stack to restore the task to (default launch stack will be used
Andrii Kulian16802aa2016-11-02 12:21:33 -07002732 * if stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}
2733 * or is not a static stack).
Chong Zhang5dcb2752015-08-18 13:50:26 -07002734 * @return true if the task has been restored successfully.
2735 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002736 boolean restoreRecentTaskLocked(TaskRecord task, int stackId) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002737 if (!StackId.isStaticStack(stackId)) {
2738 // If stack is not static (or stack id is invalid) - use the default one.
2739 // This means that tasks that were on external displays will be restored on the
2740 // primary display.
Wale Ogunwale8b06a582015-10-22 14:38:21 -07002741 stackId = task.getLaunchStackId();
Winson Chungd3395382016-12-13 11:49:09 -08002742 } else if (stackId == DOCKED_STACK_ID && !task.supportsSplitScreen()) {
Wale Ogunwale513346d2016-01-27 10:55:01 -08002743 // Preferred stack is the docked stack, but the task can't go in the docked stack.
2744 // Put it in the fullscreen stack.
2745 stackId = FULLSCREEN_WORKSPACE_STACK_ID;
Chong Zhang5dcb2752015-08-18 13:50:26 -07002746 }
Wale Ogunwale513346d2016-01-27 10:55:01 -08002747
Andrii Kulian02b7a832016-10-06 23:11:56 -07002748 final ActivityStack currentStack = task.getStack();
2749 if (currentStack != null) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002750 // Task has already been restored once. See if we need to do anything more
Andrii Kulian02b7a832016-10-06 23:11:56 -07002751 if (currentStack.mStackId == stackId) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002752 // Nothing else to do since it is already restored in the right stack.
2753 return true;
2754 }
2755 // Remove current stack association, so we can re-associate the task with the
2756 // right stack below.
Andrii Kulian02b7a832016-10-06 23:11:56 -07002757 currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING);
Wale Ogunwale706ed792015-08-02 10:29:44 -07002758 }
2759
Wale Ogunwale6c5eb1c2015-11-10 07:52:22 -08002760 final ActivityStack stack =
Wale Ogunwale040b4702015-08-06 18:10:50 -07002761 getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002762
2763 if (stack == null) {
2764 // What does this mean??? Not sure how we would get here...
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002765 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2766 "Unable to find/create stack to restore recent task=" + task);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002767 return false;
2768 }
2769
Wale Ogunwale72919d22016-12-08 18:58:50 -08002770 stack.addTask(task, false /* toTop */, "restoreRecentTask");
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002771 // TODO: move call for creation here and other place into Stack.addTask()
2772 task.createWindowContainer(false /* toTop */, true /* showForAllUsers */);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002773 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2774 "Added restored task=" + task + " to stack=" + stack);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002775 final ArrayList<ActivityRecord> activities = task.mActivities;
2776 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002777 activities.get(activityNdx).createWindowContainer();
Wale Ogunwale7de05352014-12-12 15:21:33 -08002778 }
2779 return true;
Craig Mautneref73ee12014-04-23 11:45:37 -07002780 }
2781
Wale Ogunwale040b4702015-08-06 18:10:50 -07002782 /**
Andrii Kulian839def92016-11-02 10:58:58 -07002783 * Move stack with all its existing content to specified display.
2784 * @param stackId Id of stack to move.
2785 * @param displayId Id of display to move stack to.
Andrii Kulian250d6532017-02-08 23:30:45 -08002786 * @param onTop Indicates whether container should be place on top or on bottom.
Andrii Kulian839def92016-11-02 10:58:58 -07002787 */
Andrii Kulian250d6532017-02-08 23:30:45 -08002788 void moveStackToDisplayLocked(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002789 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian839def92016-11-02 10:58:58 -07002790 if (activityDisplay == null) {
2791 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown displayId="
2792 + displayId);
2793 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002794 final ActivityStack stack = mStacks.get(stackId);
2795 if (stack == null) {
Andrii Kulian839def92016-11-02 10:58:58 -07002796 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
2797 + stackId);
2798 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002799
2800 final ActivityDisplay currentDisplay = stack.getDisplay();
2801 if (currentDisplay == null) {
2802 throw new IllegalStateException("moveStackToDisplayLocked: Stack with stack=" + stack
2803 + " is not attached to any display.");
2804 }
2805
2806 if (currentDisplay.mDisplayId == displayId) {
2807 throw new IllegalArgumentException("Trying to move stack=" + stack
2808 + " to its current displayId=" + displayId);
2809 }
2810
2811 stack.reparent(activityDisplay, onTop);
Andrii Kulian839def92016-11-02 10:58:58 -07002812 // TODO(multi-display): resize stacks properly if moved from split-screen.
2813 }
2814
2815 /**
Winson Chung74666102017-02-22 17:49:24 -08002816 * Returns the reparent target stack, creating the stack if necessary. This call also enforces
2817 * the various checks on tasks that are going to be reparented from one stack to another.
Wale Ogunwale040b4702015-08-06 18:10:50 -07002818 */
Winson Chung74666102017-02-22 17:49:24 -08002819 ActivityStack getReparentTargetStack(TaskRecord task, int stackId, boolean toTop) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07002820 final ActivityStack prevStack = task.getStack();
Chong Zhang02898352015-08-21 17:27:14 -07002821
Winson Chung74666102017-02-22 17:49:24 -08002822 // Check that we aren't reparenting to the same stack that the task is already in
2823 if (prevStack != null && prevStack.mStackId == stackId) {
2824 Slog.w(TAG, "Can not reparent to same stack, task=" + task
2825 + " already in stackId=" + stackId);
2826 return prevStack;
Wale Ogunwale513346d2016-01-27 10:55:01 -08002827 }
2828
Winson Chung74666102017-02-22 17:49:24 -08002829 // Ensure that we aren't trying to move into a multi-window stack without multi-window
2830 // support
2831 if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
2832 throw new IllegalArgumentException("Device doesn't support multi-window, can not"
2833 + " reparent task=" + task + " to stackId=" + stackId);
Winson Chungc2baac02017-01-11 13:34:47 -08002834 }
2835
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002836 // Ensure that we're not moving a task to a dynamic stack if device doesn't support
2837 // multi-display.
2838 // TODO(multi-display): Support non-dynamic stacks on secondary displays.
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002839 if (StackId.isDynamicStack(stackId) && !mService.mSupportsMultiDisplay) {
2840 throw new IllegalArgumentException("Device doesn't support multi-display, can not"
2841 + " reparent task=" + task + " to stackId=" + stackId);
2842 }
2843
Winson Chung74666102017-02-22 17:49:24 -08002844 // Ensure that we aren't trying to move into a freeform stack without freeform
2845 // support
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002846 if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
Winson Chung74666102017-02-22 17:49:24 -08002847 throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
2848 + " task=" + task);
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002849 }
2850
Winson Chung74666102017-02-22 17:49:24 -08002851 // We don't allow moving a unresizeable task to the docked stack since the docked stack is
2852 // used for split-screen mode and will cause things like the docked divider to show up. We
2853 // instead leave the task in its current stack or move it to the fullscreen stack if it
2854 // isn't currently in a stack.
2855 if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
2856 stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
2857 Slog.w(TAG, "Can not move unresizeable task=" + task + " to docked stack."
2858 + " Moving to stackId=" + stackId + " instead.");
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07002859 }
Wale Ogunwale961f4852016-02-01 20:25:54 -08002860
Winson Chung74666102017-02-22 17:49:24 -08002861 // Temporarily disable resizeablility of the task as we don't want it to be resized if, for
2862 // example, a docked stack is created which will lead to the stack we are moving from being
2863 // resized and and its resizeable tasks being resized.
Wale Ogunwale961f4852016-02-01 20:25:54 -08002864 try {
Winson Chung74666102017-02-22 17:49:24 -08002865 task.mTemporarilyUnresizable = true;
2866 return getStack(stackId, CREATE_IF_NEEDED, toTop);
Wale Ogunwale961f4852016-02-01 20:25:54 -08002867 } finally {
Winson Chung74666102017-02-22 17:49:24 -08002868 task.mTemporarilyUnresizable = false;
Chong Zhangf596cd52016-01-05 13:42:44 -08002869 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002870 }
2871
Winson Chung08f81892017-03-02 15:40:51 -08002872 boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect destBounds) {
Wale Ogunwale079a0042015-10-24 11:44:07 -07002873 final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2874 if (stack == null) {
2875 throw new IllegalArgumentException(
2876 "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
2877 }
2878
2879 final ActivityRecord r = stack.topRunningActivityLocked();
2880 if (r == null) {
2881 Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
2882 + " in stack=" + stack);
2883 return false;
2884 }
2885
Wale Ogunwale6cae7652015-12-26 07:36:26 -08002886 if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
Wale Ogunwaleb60692e2015-10-24 12:35:56 -07002887 Slog.w(TAG,
2888 "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
Filip Gruszczynski77d94482015-12-11 13:59:52 -08002889 + " r=" + r);
Wale Ogunwale079a0042015-10-24 11:44:07 -07002890 return false;
2891 }
2892
Winson Chung3a682872017-04-10 14:38:05 -07002893 moveActivityToPinnedStackLocked(r, null /* sourceBounds */, 0f /* aspectRatio */,
Winson Chung08f81892017-03-02 15:40:51 -08002894 true /* moveHomeStackToFront */, "moveTopActivityToPinnedStack");
Wale Ogunwale9c604c72015-12-06 18:42:57 -08002895 return true;
2896 }
2897
Winson Chung8bca9e42017-04-16 15:59:43 -07002898 void moveActivityToPinnedStackLocked(ActivityRecord r, Rect sourceHintBounds, float aspectRatio,
Winson Chung08f81892017-03-02 15:40:51 -08002899 boolean moveHomeStackToFront, String reason) {
2900
Wale Ogunwale480dca02016-02-06 13:58:29 -08002901 mWindowManager.deferSurfaceLayout();
Winson Chung74666102017-02-22 17:49:24 -08002902
Bryce Lee04ab3462017-04-10 15:06:33 -07002903 // This will clear the pinned stack by moving an existing task to the full screen stack,
2904 // ensuring only one task is present.
2905 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
2906
Wale Ogunwale1666e312016-12-16 11:27:18 -08002907 // Need to make sure the pinned stack exist so we can resize it below...
Winson Chung55893332017-02-17 17:13:10 -08002908 final PinnedActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Wale Ogunwale1666e312016-12-16 11:27:18 -08002909
Wale Ogunwale480dca02016-02-06 13:58:29 -08002910 try {
Bryce Leeaf691c02017-03-20 14:20:22 -07002911 final TaskRecord task = r.getTask();
Wale Ogunwale480dca02016-02-06 13:58:29 -08002912 // Resize the pinned stack to match the current size of the task the activity we are
2913 // going to be moving is currently contained in. We do this to have the right starting
2914 // animation bounds for the pinned stack to the desired bounds the caller wants.
2915 resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
2916 null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002917 true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002918
2919 if (task.mActivities.size() == 1) {
2920 // There is only one activity in the task. So, we can just move the task over to
Winson Chungc2baac02017-01-11 13:34:47 -08002921 // the stack without re-parenting the activity in a different task. We don't
2922 // move the home stack forward if we are currently entering picture-in-picture
2923 // while pausing because that changes the focused stack and may prevent the new
2924 // starting activity from resuming.
2925 if (moveHomeStackToFront && task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE
Winson Chungf7e03e12017-08-22 11:32:16 -07002926 && (r.state == RESUMED || !r.supportsEnterPipOnTaskSwitch)) {
Wale Ogunwaleda4ba962016-03-11 09:33:17 -08002927 // Move the home stack forward if the task we just moved to the pinned stack
2928 // was launched from home so home should be visible behind it.
2929 moveHomeStackToFront(reason);
2930 }
Winson Chung5af42fc2017-03-24 17:11:33 -07002931 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08002932 task.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07002933 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002934 } else {
Winson Chungb5c41b72016-12-07 15:00:47 -08002935 // There are multiple activities in the task and moving the top activity should
Winson Chung74666102017-02-22 17:49:24 -08002936 // reveal/leave the other activities in their original task.
2937
2938 // Currently, we don't support reparenting activities across tasks in two different
2939 // stacks, so instead, just create a new task in the same stack, reparent the
2940 // activity into that task, and then reparent the whole task to the new stack. This
2941 // ensures that all the necessary work to migrate states in the old and new stacks
2942 // is also done.
2943 final TaskRecord newTask = task.getStack().createTaskRecord(
2944 getNextTaskIdForUserLocked(r.userId), r.info, r.intent, null, null, true,
2945 r.mActivityType);
2946 r.reparent(newTask, MAX_VALUE, "moveActivityToStack");
2947
Winson Chung5af42fc2017-03-24 17:11:33 -07002948 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08002949 newTask.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07002950 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002951 }
Winson Chungc2baac02017-01-11 13:34:47 -08002952
2953 // Reset the state that indicates it can enter PiP while pausing after we've moved it
2954 // to the pinned stack
Winson Chungf7e03e12017-08-22 11:32:16 -07002955 r.supportsEnterPipOnTaskSwitch = false;
Wale Ogunwale480dca02016-02-06 13:58:29 -08002956 } finally {
2957 mWindowManager.continueSurfaceLayout();
Wale Ogunwale079a0042015-10-24 11:44:07 -07002958 }
2959
Winson Chunge7ba6862017-05-24 12:13:33 -07002960 // Calculate the default bounds (don't use existing stack bounds as we may have just created
2961 // the stack, and schedule the start of the animation into PiP (the bounds animator that
2962 // is triggered by this is posted on another thread)
Winson Chunga71febe2017-05-22 11:14:22 -07002963 final Rect destBounds = stack.getDefaultPictureInPictureBounds(aspectRatio);
2964
Winson Chunge7ba6862017-05-24 12:13:33 -07002965 stack.animateResizePinnedStack(sourceHintBounds, destBounds, -1 /* animationDuration */,
2966 true /* fromFullscreen */);
2967
2968 // Update the visibility of all activities after the they have been reparented to the new
2969 // stack. This MUST run after the animation above is scheduled to ensure that the windows
2970 // drawn signal is scheduled after the bounds animation start call on the bounds animator
2971 // thread.
Wale Ogunwale079a0042015-10-24 11:44:07 -07002972 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwaled046a012015-12-24 13:05:59 -08002973 resumeFocusedStackTopActivityLocked();
Wale Ogunwale03ce8632015-12-29 16:15:22 -08002974
Winson Chungb5026902017-05-03 12:45:13 -07002975 mService.mTaskChangeNotificationController.notifyActivityPinned(r.packageName,
2976 r.getTask().taskId);
Wale Ogunwale079a0042015-10-24 11:44:07 -07002977 }
2978
Andrii Kulian0864bbb2017-02-16 15:45:58 -08002979 /** Move activity with its stack to front and make the stack focused. */
Chong Zhang6cda19c2016-06-14 19:07:56 -07002980 boolean moveFocusableActivityStackToFrontLocked(ActivityRecord r, String reason) {
2981 if (r == null || !r.isFocusable()) {
2982 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
2983 "moveActivityStackToFront: unfocusable r=" + r);
2984 return false;
2985 }
2986
Bryce Leeaf691c02017-03-20 14:20:22 -07002987 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07002988 final ActivityStack stack = r.getStack();
2989 if (stack == null) {
Chong Zhang6cda19c2016-06-14 19:07:56 -07002990 Slog.w(TAG, "moveActivityStackToFront: invalid task or stack: r="
2991 + r + " task=" + task);
2992 return false;
2993 }
2994
Chong Zhang6cda19c2016-06-14 19:07:56 -07002995 if (stack == mFocusedStack && stack.topRunningActivityLocked() == r) {
2996 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
2997 "moveActivityStackToFront: already on top, r=" + r);
2998 return false;
2999 }
3000
3001 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3002 "moveActivityStackToFront: r=" + r);
3003
3004 stack.moveToFront(reason, task);
3005 return true;
3006 }
3007
David Stevensc6b91c62017-02-08 14:23:58 -08003008 ActivityRecord findTaskLocked(ActivityRecord r, int displayId) {
Wale Ogunwale39381972015-12-17 17:15:29 -08003009 mTmpFindTaskResult.r = null;
3010 mTmpFindTaskResult.matchedByRootAffinity = false;
David Stevensc6b91c62017-02-08 14:23:58 -08003011 ActivityRecord affinityMatch = null;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003012 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
Craig Mautnere0a38842013-12-16 16:14:02 -08003013 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3014 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003015 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3016 final ActivityStack stack = stacks.get(stackNdx);
Winson Chung91e5c882017-04-21 14:44:38 -07003017 if (!checkActivityBelongsInStack(r, stack)) {
3018 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) "
3019 + stack);
Craig Mautner1b4bf852014-05-26 15:06:32 -07003020 continue;
3021 }
Wale Ogunwale39381972015-12-17 17:15:29 -08003022 stack.findTaskLocked(r, mTmpFindTaskResult);
David Stevensc6b91c62017-02-08 14:23:58 -08003023 // It is possible to have tasks in multiple stacks with the same root affinity, so
3024 // we should keep looking after finding an affinity match to see if there is a
3025 // better match in another stack. Also, task affinity isn't a good enough reason
3026 // to target a display which isn't the source of the intent, so skip any affinity
3027 // matches not on the specified display.
3028 if (mTmpFindTaskResult.r != null) {
3029 if (!mTmpFindTaskResult.matchedByRootAffinity) {
3030 return mTmpFindTaskResult.r;
3031 } else if (mTmpFindTaskResult.r.getDisplayId() == displayId) {
Winson Chung5b895b72017-05-01 13:46:25 -07003032 // Note: since the traversing through the stacks is top down, the floating
3033 // tasks should always have lower priority than any affinity-matching tasks
3034 // in the fullscreen stacks
David Stevensc6b91c62017-02-08 14:23:58 -08003035 affinityMatch = mTmpFindTaskResult.r;
3036 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003037 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003038 }
3039 }
Winson Chung5b895b72017-05-01 13:46:25 -07003040
David Stevensc6b91c62017-02-08 14:23:58 -08003041 if (DEBUG_TASKS && affinityMatch == null) Slog.d(TAG_TASKS, "No task found");
3042 return affinityMatch;
Craig Mautner8849a5e2013-04-02 16:41:03 -07003043 }
3044
Winson Chung91e5c882017-04-21 14:44:38 -07003045 /**
3046 * Checks that for the given activity {@param r}, its activity type matches the {@param stack}
3047 * type.
3048 */
3049 private boolean checkActivityBelongsInStack(ActivityRecord r, ActivityStack stack) {
3050 if (r.isHomeActivity()) {
3051 return stack.isHomeStack();
3052 } else if (r.isRecentsActivity()) {
3053 return stack.isRecentsStack();
3054 } else if (r.isAssistantActivity()) {
3055 return stack.isAssistantStack();
3056 }
3057 return true;
3058 }
3059
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003060 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
3061 boolean compareIntentFilters) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003062 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3063 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003064 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003065 final ActivityRecord ar = stacks.get(stackNdx)
3066 .findActivityLocked(intent, info, compareIntentFilters);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003067 if (ar != null) {
3068 return ar;
3069 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003070 }
3071 }
3072 return null;
3073 }
3074
David Stevens9440dc82017-03-16 19:00:20 -07003075 boolean hasAwakeDisplay() {
3076 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3077 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3078 if (!display.shouldSleep()) {
3079 return true;
3080 }
3081 }
3082 return false;
3083 }
3084
Craig Mautner8d341ef2013-03-26 09:03:27 -07003085 void goingToSleepLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003086 scheduleSleepTimeout();
3087 if (!mGoingToSleep.isHeld()) {
3088 mGoingToSleep.acquire();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003089 if (mLaunchingActivity.isHeld()) {
3090 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
3091 throw new IllegalStateException("Calling must be system uid");
Craig Mautner0eea92c2013-05-16 13:35:39 -07003092 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003093 mLaunchingActivity.release();
3094 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003095 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003096 }
David Stevens9440dc82017-03-16 19:00:20 -07003097
3098 applySleepTokensLocked(false /* applyToStacks */);
3099
3100 checkReadyForSleepLocked(true /* allowDelay */);
3101 }
3102
3103 void prepareForShutdownLocked() {
3104 for (int i = 0; i < mActivityDisplays.size(); i++) {
3105 createSleepTokenLocked("shutdown", mActivityDisplays.keyAt(i));
3106 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003107 }
3108
3109 boolean shutdownLocked(int timeout) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003110 goingToSleepLocked();
Craig Mautner0eea92c2013-05-16 13:35:39 -07003111
Craig Mautnerf4c909b2014-04-17 18:39:38 -07003112 boolean timedout = false;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003113 final long endTime = System.currentTimeMillis() + timeout;
3114 while (true) {
David Stevens18abd0e2017-08-17 14:55:47 -07003115 if (!putStacksToSleepLocked(true /* allowDelay */, true /* shuttingDown */)) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003116 long timeRemaining = endTime - System.currentTimeMillis();
3117 if (timeRemaining > 0) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003118 try {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003119 mService.wait(timeRemaining);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003120 } catch (InterruptedException e) {
3121 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003122 } else {
3123 Slog.w(TAG, "Activity manager shutdown timed out");
3124 timedout = true;
3125 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003126 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003127 } else {
3128 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003129 }
3130 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003131
3132 // Force checkReadyForSleep to complete.
David Stevens9440dc82017-03-16 19:00:20 -07003133 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003134
Craig Mautner8d341ef2013-03-26 09:03:27 -07003135 return timedout;
3136 }
3137
3138 void comeOutOfSleepIfNeededLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003139 removeSleepTimeouts();
3140 if (mGoingToSleep.isHeld()) {
3141 mGoingToSleep.release();
3142 }
David Stevens9440dc82017-03-16 19:00:20 -07003143 }
3144
3145 void applySleepTokensLocked(boolean applyToStacks) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003146 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
David Stevens9440dc82017-03-16 19:00:20 -07003147 // Set the sleeping state of the display.
3148 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3149 final boolean displayShouldSleep = display.shouldSleep();
3150 if (displayShouldSleep == display.isSleeping()) {
3151 continue;
3152 }
3153 display.setIsSleeping(displayShouldSleep);
3154
3155 if (!applyToStacks) {
3156 continue;
3157 }
3158
3159 // Set the sleeping state of the stacks on the display.
3160 final ArrayList<ActivityStack> stacks = display.mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003161 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3162 final ActivityStack stack = stacks.get(stackNdx);
David Stevens9440dc82017-03-16 19:00:20 -07003163 if (displayShouldSleep) {
3164 stack.goToSleepIfPossible(false /* shuttingDown */);
3165 } else {
3166 stack.awakeFromSleepingLocked();
3167 if (isFocusedStack(stack)) {
3168 resumeFocusedStackTopActivityLocked();
3169 }
3170 }
3171 }
3172
3173 if (displayShouldSleep || mGoingToSleepActivities.isEmpty()) {
3174 continue;
3175 }
3176 // The display is awake now, so clean up the going to sleep list.
3177 for (Iterator<ActivityRecord> it = mGoingToSleepActivities.iterator(); it.hasNext(); ) {
3178 final ActivityRecord r = it.next();
3179 if (r.getDisplayId() == display.mDisplayId) {
3180 it.remove();
Craig Mautner4a1cb222013-12-04 16:14:06 -08003181 }
Craig Mautner5314a402013-09-26 12:40:16 -07003182 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003183 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003184 }
3185
3186 void activitySleptLocked(ActivityRecord r) {
3187 mGoingToSleepActivities.remove(r);
David Stevens9440dc82017-03-16 19:00:20 -07003188 final ActivityStack s = r.getStack();
3189 if (s != null) {
3190 s.checkReadyForSleep();
3191 } else {
3192 checkReadyForSleepLocked(true);
3193 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003194 }
3195
David Stevens9440dc82017-03-16 19:00:20 -07003196 void checkReadyForSleepLocked(boolean allowDelay) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07003197 if (!mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003198 // Do not care.
3199 return;
3200 }
3201
David Stevens18abd0e2017-08-17 14:55:47 -07003202 if (!putStacksToSleepLocked(allowDelay, false /* shuttingDown */)) {
3203 return;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003204 }
3205
Wei Wang65c7a152016-06-02 18:51:22 -07003206 // Send launch end powerhint before going sleep
3207 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
3208
Craig Mautner0eea92c2013-05-16 13:35:39 -07003209 removeSleepTimeouts();
3210
3211 if (mGoingToSleep.isHeld()) {
3212 mGoingToSleep.release();
3213 }
3214 if (mService.mShuttingDown) {
3215 mService.notifyAll();
3216 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003217 }
3218
David Stevens18abd0e2017-08-17 14:55:47 -07003219 // Tries to put all activity stacks to sleep. Returns true if all stacks were
3220 // successfully put to sleep.
3221 private boolean putStacksToSleepLocked(boolean allowDelay, boolean shuttingDown) {
3222 boolean allSleep = true;
3223 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3224 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3225 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3226 if (allowDelay) {
3227 allSleep &= stacks.get(stackNdx).goToSleepIfPossible(shuttingDown);
3228 } else {
3229 stacks.get(stackNdx).goToSleep();
3230 }
3231 }
3232 }
3233 return allSleep;
3234 }
3235
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003236 boolean reportResumedActivityLocked(ActivityRecord r) {
Bryce Lee29a649d2017-08-18 13:52:31 -07003237 // A resumed activity cannot be stopping. remove from list
3238 mStoppingActivities.remove(r);
3239
Andrii Kulian02b7a832016-10-06 23:11:56 -07003240 final ActivityStack stack = r.getStack();
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003241 if (isFocusedStack(stack)) {
Jeff Sharkey5782da72013-04-25 14:32:30 -07003242 mService.updateUsageStats(r, true);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003243 }
3244 if (allResumedActivitiesComplete()) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003245 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003246 mWindowManager.executeAppTransition();
3247 return true;
3248 }
3249 return false;
3250 }
3251
Craig Mautner8d341ef2013-03-26 09:03:27 -07003252 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003253 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3254 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Wale Ogunwale28b23972015-07-29 16:01:50 -07003255 int stackNdx = stacks.size() - 1;
3256 while (stackNdx >= 0) {
3257 stacks.get(stackNdx).handleAppCrashLocked(app);
3258 stackNdx--;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003259 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003260 }
3261 }
3262
Craig Mautnerbb742462014-07-07 15:28:55 -07003263 // Called when WindowManager has finished animating the launchingBehind activity to the back.
Andrii Kulian21713ac2016-10-12 22:05:05 -07003264 private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003265 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003266 final ActivityStack stack = task.getStack();
Winson730bf062016-03-31 18:04:56 -07003267
3268 r.mLaunchTaskBehind = false;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08003269 mRecentTasks.addLocked(task);
Yorke Leebd54c2a2016-10-25 13:49:23 -07003270 mService.mTaskChangeNotificationController.notifyTaskStackChanged();
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003271 r.setVisibility(false);
Winson730bf062016-03-31 18:04:56 -07003272
3273 // When launching tasks behind, update the last active time of the top task after the new
3274 // task has been shown briefly
3275 final ActivityRecord top = stack.topActivity();
3276 if (top != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003277 top.getTask().touchActiveTime();
Winson730bf062016-03-31 18:04:56 -07003278 }
Craig Mautnerbb742462014-07-07 15:28:55 -07003279 }
3280
3281 void scheduleLaunchTaskBehindComplete(IBinder token) {
3282 mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
3283 }
3284
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003285 void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
3286 boolean preserveWindows) {
Jorim Jaggife762342016-10-13 14:33:27 +02003287 mKeyguardController.beginActivityVisibilityUpdate();
3288 try {
3289 // First the front stacks. In case any are not fullscreen and are in front of home.
3290 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3291 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3292 final int topStackNdx = stacks.size() - 1;
3293 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3294 final ActivityStack stack = stacks.get(stackNdx);
3295 stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
3296 }
Craig Mautner580ea812013-04-25 12:58:38 -07003297 }
Jorim Jaggife762342016-10-13 14:33:27 +02003298 } finally {
3299 mKeyguardController.endActivityVisibilityUpdate();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003300 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003301 }
3302
Jorim Jaggi8b702ed2017-01-20 16:59:03 +01003303 void addStartingWindowsForVisibleActivities(boolean taskSwitch) {
3304 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3305 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3306 final int topStackNdx = stacks.size() - 1;
3307 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3308 final ActivityStack stack = stacks.get(stackNdx);
3309 stack.addStartingWindowsForVisibleActivities(taskSwitch);
3310 }
3311 }
3312 }
3313
Chong Zhangfdcc4d42015-10-14 16:50:12 -07003314 void invalidateTaskLayers() {
3315 mTaskLayersChanged = true;
3316 }
3317
3318 void rankTaskLayersIfNeeded() {
3319 if (!mTaskLayersChanged) {
3320 return;
3321 }
3322 mTaskLayersChanged = false;
3323 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
3324 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3325 int baseLayer = 0;
3326 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3327 baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
3328 }
3329 }
3330 }
3331
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07003332 void clearOtherAppTimeTrackers(AppTimeTracker except) {
3333 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3334 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3335 final int topStackNdx = stacks.size() - 1;
3336 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3337 final ActivityStack stack = stacks.get(stackNdx);
3338 stack.clearOtherAppTimeTrackers(except);
3339 }
3340 }
3341 }
3342
Craig Mautner8d341ef2013-03-26 09:03:27 -07003343 void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003344 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3345 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003346 final int numStacks = stacks.size();
3347 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
3348 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003349 stack.scheduleDestroyActivities(app, reason);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003350 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003351 }
3352 }
3353
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003354 void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
3355 // Examine all activities currently running in the process.
3356 TaskRecord firstTask = null;
3357 // Tasks is non-null only if two or more tasks are found.
3358 ArraySet<TaskRecord> tasks = null;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003359 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
3360 for (int i = 0; i < app.activities.size(); i++) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003361 ActivityRecord r = app.activities.get(i);
3362 // First, if we find an activity that is in the process of being destroyed,
3363 // then we just aren't going to do anything for now; we want things to settle
3364 // down before we try to prune more activities.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003365 if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003366 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003367 return;
3368 }
3369 // Don't consider any activies that are currently not in a state where they
3370 // can be destroyed.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003371 if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
3372 || r.state == PAUSED || r.state == STOPPING) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003373 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003374 continue;
3375 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003376
3377 final TaskRecord task = r.getTask();
3378 if (task != null) {
3379 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + task
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003380 + " from " + r);
3381 if (firstTask == null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003382 firstTask = task;
3383 } else if (firstTask != task) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003384 if (tasks == null) {
3385 tasks = new ArraySet<>();
3386 tasks.add(firstTask);
3387 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003388 tasks.add(task);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003389 }
3390 }
3391 }
3392 if (tasks == null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003393 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003394 return;
3395 }
3396 // If we have activities in multiple tasks that are in a position to be destroyed,
3397 // let's iterate through the tasks and release the oldest one.
3398 final int numDisplays = mActivityDisplays.size();
3399 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3400 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3401 // Step through all stacks starting from behind, to hit the oldest things first.
3402 for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
3403 final ActivityStack stack = stacks.get(stackNdx);
3404 // Try to release activities in this stack; if we manage to, we are done.
3405 if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
3406 return;
3407 }
3408 }
3409 }
3410 }
3411
Amith Yamasani37a40c22015-06-17 13:25:42 -07003412 boolean switchUserLocked(int userId, UserState uss) {
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003413 final int focusStackId = mFocusedStack.getStackId();
3414 // We dismiss the docked stack whenever we switch users.
3415 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, focusStackId == DOCKED_STACK_ID);
Winson Chungc2b23a52017-01-09 15:44:55 -08003416 // Also dismiss the pinned stack whenever we switch users. Removing the pinned stack will
3417 // also cause all tasks to be moved to the fullscreen stack at a position that is
3418 // appropriate.
3419 removeStackLocked(PINNED_STACK_ID);
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003420
3421 mUserStackInFront.put(mCurrentUser, focusStackId);
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003422 final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
Craig Mautner2420ead2013-04-01 17:13:20 -07003423 mCurrentUser = userId;
Craig Mautnerac6f8432013-07-17 13:24:59 -07003424
Craig Mautner858d8a62013-04-23 17:08:34 -07003425 mStartingUsers.add(uss);
Craig Mautnere0a38842013-12-16 16:14:02 -08003426 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3427 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003428 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003429 final ActivityStack stack = stacks.get(stackNdx);
3430 stack.switchUserLocked(userId);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003431 TaskRecord task = stack.topTask();
3432 if (task != null) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08003433 stack.positionChildWindowContainerAtTop(task);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003434 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003435 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07003436 }
Craig Mautner858d8a62013-04-23 17:08:34 -07003437
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003438 ActivityStack stack = getStack(restoreStackId);
3439 if (stack == null) {
3440 stack = mHomeStack;
3441 }
3442 final boolean homeInFront = stack.isHomeStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08003443 if (stack.isOnHomeDisplay()) {
Wale Ogunwale925d0d12015-09-23 15:40:07 -07003444 stack.moveToFront("switchUserOnHomeDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003445 } else {
3446 // Stack was moved to another display while user was swapped out.
Matthew Ngae1ff4f2016-11-10 15:49:14 -08003447 resumeHomeStackTask(null, "switchUserOnOtherDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003448 }
Craig Mautner93529a42013-10-04 15:03:13 -07003449 return homeInFront;
Craig Mautner2219a1b2013-03-25 09:44:30 -07003450 }
3451
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003452 /** Checks whether the userid is a profile of the current user. */
3453 boolean isCurrentProfileLocked(int userId) {
3454 if (userId == mCurrentUser) return true;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07003455 return mService.mUserController.isCurrentProfileLocked(userId);
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003456 }
3457
Bryce Leeb7c9b802017-05-02 14:20:24 -07003458 /**
3459 * Returns whether a stopping activity is present that should be stopped after visible, rather
3460 * than idle.
3461 * @return {@code true} if such activity is present. {@code false} otherwise.
3462 */
3463 boolean isStoppingNoHistoryActivity() {
3464 // Activities that are marked as nohistory should be stopped immediately after the resumed
3465 // activity has become visible.
3466 for (ActivityRecord record : mStoppingActivities) {
3467 if (record.isNoHistory()) {
3468 return true;
3469 }
3470 }
3471
3472 return false;
3473 }
3474
Winson Chung4dabf232017-01-25 13:25:22 -08003475 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
3476 boolean remove, boolean processPausingActivities) {
Craig Mautnerde4ef022013-04-07 19:01:33 -07003477 ArrayList<ActivityRecord> stops = null;
3478
3479 final boolean nowVisible = allResumedActivitiesVisible();
Craig Mautner8c14c152015-01-15 17:32:07 -08003480 for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3481 ActivityRecord s = mStoppingActivities.get(activityNdx);
Bryce Lee4a194382017-04-04 14:32:48 -07003482 boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003483 if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
Craig Mautner8c14c152015-01-15 17:32:07 -08003484 + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
3485 if (waitingVisible && nowVisible) {
Bryce Lee4a194382017-04-04 14:32:48 -07003486 mActivitiesWaitingForVisibleActivity.remove(s);
Andrii Kulianee056812016-09-21 15:34:45 -07003487 waitingVisible = false;
Craig Mautnerde4ef022013-04-07 19:01:33 -07003488 if (s.finishing) {
3489 // If this activity is finishing, it is sitting on top of
3490 // everyone else but we now know it is no longer needed...
3491 // so get rid of it. Otherwise, we need to go through the
3492 // normal flow and hide it once we determine that it is
3493 // hidden by the activities in front of it.
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003494 if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003495 s.setVisibility(false);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003496 }
3497 }
David Stevens9440dc82017-03-16 19:00:20 -07003498 if (remove) {
3499 final ActivityStack stack = s.getStack();
3500 final boolean shouldSleepOrShutDown = stack != null
3501 ? stack.shouldSleepOrShutDownActivities()
3502 : mService.isSleepingOrShuttingDownLocked();
3503 if (!waitingVisible || shouldSleepOrShutDown) {
3504 if (!processPausingActivities && s.state == PAUSING) {
3505 // Defer processing pausing activities in this iteration and reschedule
3506 // a delayed idle to reprocess it again
3507 removeTimeoutsForActivityLocked(idleActivity);
3508 scheduleIdleTimeoutLocked(idleActivity);
3509 continue;
3510 }
Winson Chung4dabf232017-01-25 13:25:22 -08003511
David Stevens9440dc82017-03-16 19:00:20 -07003512 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
3513 if (stops == null) {
3514 stops = new ArrayList<>();
3515 }
3516 stops.add(s);
3517 mStoppingActivities.remove(activityNdx);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003518 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07003519 }
3520 }
3521
3522 return stops;
3523 }
3524
Craig Mautnercf910b02013-04-23 11:23:27 -07003525 void validateTopActivitiesLocked() {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003526 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3527 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3528 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3529 final ActivityStack stack = stacks.get(stackNdx);
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07003530 final ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003531 final ActivityState state = r == null ? DESTROYED : r.state;
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003532 if (isFocusedStack(stack)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003533 if (r == null) Slog.e(TAG,
3534 "validateTop...: null top activity, stack=" + stack);
3535 else {
3536 final ActivityRecord pausing = stack.mPausingActivity;
3537 if (pausing != null && pausing == r) Slog.e(TAG,
3538 "validateTop...: top stack has pausing activity r=" + r
3539 + " state=" + state);
3540 if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3541 "validateTop...: activity in front not resumed r=" + r
3542 + " state=" + state);
3543 }
Craig Mautnercf910b02013-04-23 11:23:27 -07003544 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003545 final ActivityRecord resumed = stack.mResumedActivity;
3546 if (resumed != null && resumed == r) Slog.e(TAG,
3547 "validateTop...: back stack has resumed activity r=" + r
3548 + " state=" + state);
3549 if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3550 "validateTop...: activity in back resumed r=" + r + " state=" + state);
Craig Mautnercf910b02013-04-23 11:23:27 -07003551 }
3552 }
3553 }
Craig Mautner76ea2242013-05-15 11:40:05 -07003554 }
3555
Craig Mautner27084302013-03-25 08:05:25 -07003556 public void dump(PrintWriter pw, String prefix) {
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003557 pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003558 pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
Suprabh Shukla09a88f52015-12-02 14:36:31 -08003559 pw.print(prefix);
3560 pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003561 pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003562 pw.print(prefix); pw.println("mStacks=" + mStacks);
Benjamin Franza83859f2017-07-03 16:34:14 +01003563 // TODO: move this to LockTaskController
Jorim Jaggi8d786932016-10-26 19:08:36 -07003564 final SparseArray<String[]> packages = mService.mLockTaskPackages;
3565 if (packages.size() > 0) {
3566 pw.print(prefix); pw.println("mLockTaskPackages (userId:packages)=");
3567 for (int i = 0; i < packages.size(); ++i) {
3568 pw.print(prefix); pw.print(prefix); pw.print(packages.keyAt(i));
3569 pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
3570 }
3571 }
Bryce Lee4a194382017-04-04 14:32:48 -07003572 if (!mWaitingForActivityVisible.isEmpty()) {
3573 pw.print(prefix); pw.println("mWaitingForActivityVisible=");
3574 for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
3575 pw.print(prefix); pw.print(prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
3576 }
3577 }
3578
Jorim Jaggi8d786932016-10-26 19:08:36 -07003579 mKeyguardController.dump(pw, prefix);
Benjamin Franza83859f2017-07-03 16:34:14 +01003580 mService.mLockTaskController.dump(pw, prefix);
Craig Mautner27084302013-03-25 08:05:25 -07003581 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003582
Winson43d1f262016-06-14 16:05:55 -07003583 /**
Andrii Kulian5406e7a2016-10-21 11:55:23 -07003584 * Dump all connected displays' configurations.
3585 * @param prefix Prefix to apply to each line of the dump.
3586 */
3587 void dumpDisplayConfigs(PrintWriter pw, String prefix) {
3588 pw.print(prefix); pw.println("Display override configurations:");
3589 final int displayCount = mActivityDisplays.size();
3590 for (int i = 0; i < displayCount; i++) {
3591 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(i);
3592 pw.print(prefix); pw.print(" "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
3593 pw.println(activityDisplay.getOverrideConfiguration());
3594 }
3595 }
3596
3597 /**
Winson43d1f262016-06-14 16:05:55 -07003598 * Dumps the activities matching the given {@param name} in the either the focused stack
3599 * or all visible stacks if {@param dumpVisibleStacks} is true.
3600 */
Winson Chung6998bc42017-02-28 17:07:05 -08003601 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name, boolean dumpVisibleStacksOnly,
3602 boolean dumpFocusedStackOnly) {
3603 if (dumpFocusedStackOnly) {
3604 return mFocusedStack.getDumpActivitiesLocked(name);
3605 } else {
Winson43d1f262016-06-14 16:05:55 -07003606 ArrayList<ActivityRecord> activities = new ArrayList<>();
3607 int numDisplays = mActivityDisplays.size();
3608 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3609 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3610 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3611 ActivityStack stack = stacks.get(stackNdx);
Winson Chung6998bc42017-02-28 17:07:05 -08003612 if (!dumpVisibleStacksOnly ||
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07003613 stack.shouldBeVisible(null) == STACK_VISIBLE) {
Winson43d1f262016-06-14 16:05:55 -07003614 activities.addAll(stack.getDumpActivitiesLocked(name));
3615 }
3616 }
3617 }
3618 return activities;
Winson43d1f262016-06-14 16:05:55 -07003619 }
Craig Mautner20e72272013-04-01 13:45:53 -07003620 }
3621
Dianne Hackborn390517b2013-05-30 15:03:32 -07003622 static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3623 boolean needSep, String prefix) {
3624 if (activity != null) {
3625 if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3626 if (needSep) {
3627 pw.println();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003628 }
3629 pw.print(prefix);
3630 pw.println(activity);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003631 return true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003632 }
3633 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003634 return false;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003635 }
3636
Craig Mautner8d341ef2013-03-26 09:03:27 -07003637 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3638 boolean dumpClient, String dumpPackage) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003639 boolean printed = false;
3640 boolean needSep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003641 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3642 ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003643 pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
Craig Mautner737fae22014-10-15 12:52:10 -07003644 pw.println(" (activities from top to bottom):");
Craig Mautnere0a38842013-12-16 16:14:02 -08003645 ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
Craig Mautner737fae22014-10-15 12:52:10 -07003646 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003647 final ActivityStack stack = stacks.get(stackNdx);
3648 StringBuilder stackHeader = new StringBuilder(128);
3649 stackHeader.append(" Stack #");
3650 stackHeader.append(stack.mStackId);
3651 stackHeader.append(":");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003652 stackHeader.append("\n");
3653 stackHeader.append(" mFullscreen=" + stack.mFullscreen);
3654 stackHeader.append("\n");
David Stevens9440dc82017-03-16 19:00:20 -07003655 stackHeader.append(" isSleeping=" + stack.shouldSleepActivities());
3656 stackHeader.append("\n");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003657 stackHeader.append(" mBounds=" + stack.mBounds);
Winson Chungabb433b2017-03-24 09:35:42 -07003658
3659 final boolean printedStackHeader = stack.dumpActivitiesLocked(fd, pw, dumpAll,
3660 dumpClient, dumpPackage, needSep, stackHeader.toString());
3661 printed |= printedStackHeader;
3662 if (!printedStackHeader) {
3663 // Ensure we always dump the stack header even if there are no activities
3664 pw.println();
3665 pw.println(stackHeader);
3666 }
3667
Craig Mautner4a1cb222013-12-04 16:14:06 -08003668 printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, " ", "Run", false,
3669 !dumpAll, false, dumpPackage, true,
3670 " Running activities (most recent first):", null);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003671
Craig Mautner4a1cb222013-12-04 16:14:06 -08003672 needSep = printed;
3673 boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3674 " mPausingActivity: ");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003675 if (pr) {
3676 printed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003677 needSep = false;
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003678 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003679 pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3680 " mResumedActivity: ");
3681 if (pr) {
3682 printed = true;
3683 needSep = false;
3684 }
3685 if (dumpAll) {
3686 pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3687 " mLastPausedActivity: ");
3688 if (pr) {
3689 printed = true;
3690 needSep = true;
3691 }
3692 printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3693 needSep, " mLastNoHistoryActivity: ");
3694 }
3695 needSep = printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003696 }
3697 }
3698
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003699 printed |= dumpHistoryList(fd, pw, mFinishingActivities, " ", "Fin", false, !dumpAll,
3700 false, dumpPackage, true, " Activities waiting to finish:", null);
3701 printed |= dumpHistoryList(fd, pw, mStoppingActivities, " ", "Stop", false, !dumpAll,
3702 false, dumpPackage, true, " Activities waiting to stop:", null);
Bryce Lee4a194382017-04-04 14:32:48 -07003703 printed |= dumpHistoryList(fd, pw, mActivitiesWaitingForVisibleActivity, " ", "Wait",
3704 false, !dumpAll, false, dumpPackage, true,
3705 " Activities waiting for another to become visible:", null);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003706 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3707 false, dumpPackage, true, " Activities waiting to sleep:", null);
Craig Mautnerf3333272013-04-22 10:55:53 -07003708
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003709 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003710 }
3711
Dianne Hackborn390517b2013-05-30 15:03:32 -07003712 static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
Craig Mautner8d341ef2013-03-26 09:03:27 -07003713 String prefix, String label, boolean complete, boolean brief, boolean client,
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003714 String dumpPackage, boolean needNL, String header1, String header2) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003715 TaskRecord lastTask = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003716 String innerPrefix = null;
3717 String[] args = null;
3718 boolean printed = false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003719 for (int i=list.size()-1; i>=0; i--) {
3720 final ActivityRecord r = list.get(i);
3721 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3722 continue;
3723 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003724 if (innerPrefix == null) {
3725 innerPrefix = prefix + " ";
3726 args = new String[0];
3727 }
3728 printed = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003729 final boolean full = !brief && (complete || !r.isInHistory());
3730 if (needNL) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003731 pw.println("");
Craig Mautner8d341ef2013-03-26 09:03:27 -07003732 needNL = false;
3733 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003734 if (header1 != null) {
3735 pw.println(header1);
3736 header1 = null;
3737 }
3738 if (header2 != null) {
3739 pw.println(header2);
3740 header2 = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003741 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003742 if (lastTask != r.getTask()) {
3743 lastTask = r.getTask();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003744 pw.print(prefix);
3745 pw.print(full ? "* " : " ");
3746 pw.println(lastTask);
3747 if (full) {
3748 lastTask.dump(pw, prefix + " ");
3749 } else if (complete) {
3750 // Complete + brief == give a summary. Isn't that obvious?!?
3751 if (lastTask.intent != null) {
3752 pw.print(prefix); pw.print(" ");
3753 pw.println(lastTask.intent.toInsecureStringWithClip());
3754 }
3755 }
3756 }
3757 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
3758 pw.print(" #"); pw.print(i); pw.print(": ");
3759 pw.println(r);
3760 if (full) {
3761 r.dump(pw, innerPrefix);
3762 } else if (complete) {
3763 // Complete + brief == give a summary. Isn't that obvious?!?
3764 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3765 if (r.app != null) {
3766 pw.print(innerPrefix); pw.println(r.app);
3767 }
3768 }
3769 if (client && r.app != null && r.app.thread != null) {
3770 // flush anything that is already in the PrintWriter since the thread is going
3771 // to write to the file descriptor directly
3772 pw.flush();
3773 try {
3774 TransferPipe tp = new TransferPipe();
3775 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003776 r.app.thread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003777 // Short timeout, since blocking here can
3778 // deadlock with the application.
3779 tp.go(fd, 2000);
3780 } finally {
3781 tp.kill();
3782 }
3783 } catch (IOException e) {
3784 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3785 } catch (RemoteException e) {
3786 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3787 }
3788 needNL = true;
3789 }
3790 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003791 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003792 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003793
Craig Mautnerf3333272013-04-22 10:55:53 -07003794 void scheduleIdleTimeoutLocked(ActivityRecord next) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003795 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3796 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
Craig Mautnerc64f73e2013-04-24 16:44:56 -07003797 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
3798 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
Craig Mautnerf3333272013-04-22 10:55:53 -07003799 }
3800
3801 final void scheduleIdleLocked() {
Craig Mautner05d29032013-05-03 13:40:13 -07003802 mHandler.sendEmptyMessage(IDLE_NOW_MSG);
Craig Mautnerf3333272013-04-22 10:55:53 -07003803 }
3804
3805 void removeTimeoutsForActivityLocked(ActivityRecord r) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003806 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
3807 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07003808 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3809 }
3810
Craig Mautner05d29032013-05-03 13:40:13 -07003811 final void scheduleResumeTopActivities() {
Craig Mautner34b73df2014-01-12 21:11:08 -08003812 if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
3813 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
3814 }
Craig Mautner05d29032013-05-03 13:40:13 -07003815 }
3816
Craig Mautner0eea92c2013-05-16 13:35:39 -07003817 void removeSleepTimeouts() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003818 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
3819 }
3820
3821 final void scheduleSleepTimeout() {
3822 removeSleepTimeouts();
3823 mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
3824 }
3825
Craig Mautner4a1cb222013-12-04 16:14:06 -08003826 @Override
3827 public void onDisplayAdded(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003828 if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003829 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
3830 }
3831
3832 @Override
3833 public void onDisplayRemoved(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003834 if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003835 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
3836 }
3837
3838 @Override
3839 public void onDisplayChanged(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003840 if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003841 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
3842 }
3843
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003844 private void handleDisplayAdded(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003845 synchronized (mService) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003846 getActivityDisplayOrCreateLocked(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003847 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003848 }
3849
Andrii Kulianca007a62016-11-22 16:33:28 -08003850 /** Check if display with specified id is added to the list. */
3851 boolean isDisplayAdded(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003852 return getActivityDisplayOrCreateLocked(displayId) != null;
3853 }
3854
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003855 ActivityDisplay getActivityDisplay(int displayId) {
3856 return mActivityDisplays.get(displayId);
3857 }
3858
Andrii Kulian62e6f252017-05-30 22:46:53 -07003859 /**
3860 * Get an existing instance of {@link ActivityDisplay} or create new if there is a
3861 * corresponding record in display manager.
3862 */
3863 private ActivityDisplay getActivityDisplayOrCreateLocked(int displayId) {
3864 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3865 if (activityDisplay != null) {
3866 return activityDisplay;
3867 }
3868 if (mDisplayManager == null) {
3869 // The system isn't fully initialized yet.
3870 return null;
3871 }
3872 final Display display = mDisplayManager.getDisplay(displayId);
3873 if (display == null) {
3874 // The display is not registered in DisplayManager.
3875 return null;
3876 }
3877 // The display hasn't been added to ActivityManager yet, create a new record now.
3878 activityDisplay = new ActivityDisplay(displayId);
3879 if (activityDisplay.mDisplay == null) {
3880 Slog.w(TAG, "Display " + displayId + " gone before initialization complete");
3881 return null;
3882 }
3883 mActivityDisplays.put(displayId, activityDisplay);
3884 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
3885 mWindowManager.onDisplayAdded(displayId);
3886 return activityDisplay;
Andrii Kulianca007a62016-11-22 16:33:28 -08003887 }
3888
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003889 private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
Andrii Kulianf66a83d2016-05-17 12:17:44 -07003890 mDefaultMinSizeOfResizeableTask =
Jorim Jaggi19cf2972016-04-07 23:26:10 -07003891 mService.mContext.getResources().getDimensionPixelSize(
3892 com.android.internal.R.dimen.default_minimal_size_resizable_task);
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003893 }
3894
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003895 private void handleDisplayRemoved(int displayId) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003896 if (displayId == DEFAULT_DISPLAY) {
3897 throw new IllegalArgumentException("Can't remove the primary display.");
3898 }
3899
Craig Mautner4a1cb222013-12-04 16:14:06 -08003900 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003901 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3902 if (activityDisplay != null) {
Andrii Kulian250d6532017-02-08 23:30:45 -08003903 final boolean destroyContentOnRemoval
3904 = activityDisplay.shouldDestroyContentOnRemove();
Andrii Kuliana33818c2017-02-16 16:11:30 -08003905 final ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3906 while (!stacks.isEmpty()) {
3907 final ActivityStack stack = stacks.get(0);
Andrii Kulian250d6532017-02-08 23:30:45 -08003908 if (destroyContentOnRemoval) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003909 moveStackToDisplayLocked(stack.mStackId, DEFAULT_DISPLAY,
3910 false /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003911 stack.finishAllActivitiesLocked(true /* immediately */);
Andrii Kuliana33818c2017-02-16 16:11:30 -08003912 } else {
3913 // Moving all tasks to fullscreen stack, because it's guaranteed to be
3914 // a valid launch stack for all activities. This way the task history from
3915 // external display will be preserved on primary after move.
3916 moveTasksToFullscreenStackLocked(stack.getStackId(), true /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003917 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003918 }
David Stevens9440dc82017-03-16 19:00:20 -07003919
3920 releaseSleepTokens(activityDisplay);
3921
Craig Mautnere0a38842013-12-16 16:14:02 -08003922 mActivityDisplays.remove(displayId);
Bryce Leeaf3a4002017-03-20 10:37:12 -07003923 mWindowManager.onDisplayRemoved(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003924 }
3925 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003926 }
3927
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003928 private void handleDisplayChanged(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003929 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003930 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3931 if (activityDisplay != null) {
David Stevens9440dc82017-03-16 19:00:20 -07003932 // The window policy is responsible for stopping activities on the default display
3933 if (displayId != Display.DEFAULT_DISPLAY) {
3934 int displayState = activityDisplay.mDisplay.getState();
3935 if (displayState == Display.STATE_OFF && activityDisplay.mOffToken == null) {
3936 activityDisplay.mOffToken =
3937 mService.acquireSleepToken("Display-off", displayId);
3938 } else if (displayState == Display.STATE_ON
3939 && activityDisplay.mOffToken != null) {
3940 activityDisplay.mOffToken.release();
3941 activityDisplay.mOffToken = null;
3942 }
3943 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003944 // TODO: Update the bounds.
3945 }
Bryce Leeaf3a4002017-03-20 10:37:12 -07003946 mWindowManager.onDisplayChanged(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003947 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003948 }
3949
David Stevens9440dc82017-03-16 19:00:20 -07003950 SleepToken createSleepTokenLocked(String tag, int displayId) {
3951 ActivityDisplay display = mActivityDisplays.get(displayId);
3952 if (display == null) {
3953 throw new IllegalArgumentException("Invalid display: " + displayId);
3954 }
3955
3956 final SleepTokenImpl token = new SleepTokenImpl(tag, displayId);
3957 mSleepTokens.add(token);
3958 display.mAllSleepTokens.add(token);
3959 return token;
3960 }
3961
3962 private void removeSleepTokenLocked(SleepTokenImpl token) {
3963 mSleepTokens.remove(token);
3964
3965 ActivityDisplay display = mActivityDisplays.get(token.mDisplayId);
3966 if (display != null) {
3967 display.mAllSleepTokens.remove(token);
3968 if (display.mAllSleepTokens.isEmpty()) {
3969 mService.updateSleepIfNeededLocked();
3970 }
3971 }
3972 }
3973
3974 private void releaseSleepTokens(ActivityDisplay display) {
3975 if (display.mAllSleepTokens.isEmpty()) {
3976 return;
3977 }
3978 for (SleepTokenImpl token : display.mAllSleepTokens) {
3979 mSleepTokens.remove(token);
3980 }
3981 display.mAllSleepTokens.clear();
3982
3983 mService.updateSleepIfNeededLocked();
3984 }
3985
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003986 private StackInfo getStackInfoLocked(ActivityStack stack) {
Andrii Kulian7e215d72017-04-26 18:33:28 -07003987 final int displayId = stack.mDisplayId;
3988 final ActivityDisplay display = mActivityDisplays.get(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003989 StackInfo info = new StackInfo();
Wale Ogunwale1666e312016-12-16 11:27:18 -08003990 stack.getWindowContainerBounds(info.bounds);
Andrii Kulian7e215d72017-04-26 18:33:28 -07003991 info.displayId = displayId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003992 info.stackId = stack.mStackId;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08003993 info.userId = stack.mCurrentUser;
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07003994 info.visible = stack.shouldBeVisible(null) == STACK_VISIBLE;
Andrii Kulian62e6f252017-05-30 22:46:53 -07003995 // A stack might be not attached to a display.
Winson529c8e42016-05-17 11:08:40 -07003996 info.position = display != null
3997 ? display.mStacks.indexOf(stack)
3998 : 0;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003999
4000 ArrayList<TaskRecord> tasks = stack.getAllTasks();
4001 final int numTasks = tasks.size();
4002 int[] taskIds = new int[numTasks];
4003 String[] taskNames = new String[numTasks];
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004004 Rect[] taskBounds = new Rect[numTasks];
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004005 int[] taskUserIds = new int[numTasks];
Craig Mautner4a1cb222013-12-04 16:14:06 -08004006 for (int i = 0; i < numTasks; ++i) {
4007 final TaskRecord task = tasks.get(i);
4008 taskIds[i] = task.taskId;
4009 taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
4010 : task.realActivity != null ? task.realActivity.flattenToString()
4011 : task.getTopActivity() != null ? task.getTopActivity().packageName
4012 : "unknown";
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004013 taskBounds[i] = new Rect();
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004014 task.getWindowContainerBounds(taskBounds[i]);
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004015 taskUserIds[i] = task.userId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004016 }
4017 info.taskIds = taskIds;
4018 info.taskNames = taskNames;
Wale Ogunwale868a5e12015-08-02 16:19:20 -07004019 info.taskBounds = taskBounds;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004020 info.taskUserIds = taskUserIds;
Winsond46b7272016-04-20 11:54:27 -07004021
4022 final ActivityRecord top = stack.topRunningActivityLocked();
4023 info.topActivity = top != null ? top.intent.getComponent() : null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004024 return info;
4025 }
4026
4027 StackInfo getStackInfoLocked(int stackId) {
4028 ActivityStack stack = getStack(stackId);
4029 if (stack != null) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004030 return getStackInfoLocked(stack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004031 }
4032 return null;
4033 }
4034
4035 ArrayList<StackInfo> getAllStackInfosLocked() {
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004036 ArrayList<StackInfo> list = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08004037 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
4038 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004039 for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004040 list.add(getStackInfoLocked(stacks.get(ndx)));
Craig Mautner4a1cb222013-12-04 16:14:06 -08004041 }
4042 }
4043 return list;
4044 }
4045
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004046 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4047 int preferredDisplayId, int actualStackId) {
4048 handleNonResizableTaskIfNeeded(task, preferredStackId, preferredDisplayId, actualStackId,
Andrii Kulianc27916642016-04-12 17:59:27 -07004049 false /* forceNonResizable */);
4050 }
4051
Benjamin Franza83859f2017-07-03 16:34:14 +01004052 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004053 int preferredDisplayId, int actualStackId, boolean forceNonResizable) {
4054 final boolean isSecondaryDisplayPreferred =
4055 (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY)
4056 || StackId.isDynamicStack(preferredStackId);
4057 if (((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
4058 && !isSecondaryDisplayPreferred) || task.isHomeTask()) {
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004059 return;
4060 }
4061
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004062 // Handle incorrect launch/move to secondary display if needed.
4063 final boolean launchOnSecondaryDisplayFailed;
4064 if (isSecondaryDisplayPreferred) {
4065 final int actualDisplayId = task.getStack().mDisplayId;
4066 if (!task.canBeLaunchedOnDisplay(actualDisplayId)) {
4067 // The task landed on an inappropriate display somehow, move it to the default
4068 // display.
4069 // TODO(multi-display): Find proper stack for the task on the default display.
4070 mService.moveTaskToStack(task.taskId, FULLSCREEN_WORKSPACE_STACK_ID,
4071 true /* toTop */);
4072 launchOnSecondaryDisplayFailed = true;
4073 } else {
4074 // The task might have landed on a display different from requested.
4075 launchOnSecondaryDisplayFailed = actualDisplayId == DEFAULT_DISPLAY
4076 || (preferredDisplayId != INVALID_DISPLAY
4077 && preferredDisplayId != actualDisplayId);
4078 }
4079 } else {
4080 // The task wasn't requested to be on a secondary display.
4081 launchOnSecondaryDisplayFailed = false;
4082 }
4083
Jorim Jaggicd13d332016-04-27 15:40:20 -07004084 final ActivityRecord topActivity = task.getTopActivity();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004085 if (launchOnSecondaryDisplayFailed || !task.supportsSplitScreen() || forceNonResizable) {
4086 if (launchOnSecondaryDisplayFailed) {
4087 // Display a warning toast that we tried to put a non-resizeable task on a secondary
4088 // display with config different from global config.
4089 mService.mTaskChangeNotificationController
4090 .notifyActivityLaunchOnSecondaryDisplayFailed();
4091 } else {
4092 // Display a warning toast that we tried to put a non-dockable task in the docked
4093 // stack.
4094 mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
4095 }
Jorim Jaggid53f0922016-04-06 22:16:23 -07004096
Andrii Kulianc27916642016-04-12 17:59:27 -07004097 // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
4098 // we need to move it to top of fullscreen stack, otherwise it will be covered.
Wale Ogunwale9a98c522016-04-27 09:23:55 -07004099 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
Winson Chungd3395382016-12-13 11:49:09 -08004100 } else if (topActivity != null && topActivity.isNonResizableOrForcedResizable()
Jorim Jaggicd13d332016-04-27 15:40:20 -07004101 && !topActivity.noDisplay) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004102 final String packageName = topActivity.appInfo.packageName;
4103 final int reason = isSecondaryDisplayPreferred
4104 ? FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY
4105 : FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Yorke Leebd54c2a2016-10-25 13:49:23 -07004106 mService.mTaskChangeNotificationController.notifyActivityForcedResizable(
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004107 task.taskId, reason, packageName);
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004108 }
Chong Zhangb15758a2015-11-17 12:12:03 -08004109 }
4110
Jorim Jaggife89d122015-12-22 16:28:44 +01004111 void activityRelaunchedLocked(IBinder token) {
4112 mWindowManager.notifyAppRelaunchingFinished(token);
David Stevens9440dc82017-03-16 19:00:20 -07004113 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4114 if (r != null) {
4115 if (r.getStack().shouldSleepOrShutDownActivities()) {
Wale Ogunwale3e997362016-09-06 10:37:56 -07004116 r.setSleeping(true, true);
4117 }
4118 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004119 }
4120
4121 void activityRelaunchingLocked(ActivityRecord r) {
4122 mWindowManager.notifyAppRelaunching(r.appToken);
4123 }
4124
Filip Gruszczynski77d94482015-12-11 13:59:52 -08004125 void logStackState() {
4126 mActivityMetricsLogger.logWindowState();
4127 }
4128
Winson Chung5af42fc2017-03-24 17:11:33 -07004129 void scheduleUpdateMultiWindowMode(TaskRecord task) {
Winson Chung8bca9e42017-04-16 15:59:43 -07004130 // If the stack is animating in a way where we will be forcing a multi-mode change at the
4131 // end, then ensure that we defer all in between multi-window mode changes
4132 if (task.getStack().deferScheduleMultiWindowModeChanged()) {
4133 return;
4134 }
4135
Wale Ogunwale22e25262016-02-01 10:32:02 -08004136 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4137 final ActivityRecord r = task.mActivities.get(i);
4138 if (r.app != null && r.app.thread != null) {
4139 mMultiWindowModeChangedActivities.add(r);
4140 }
4141 }
4142
4143 if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
4144 mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
4145 }
4146 }
4147
Winson Chung5af42fc2017-03-24 17:11:33 -07004148 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07004149 final ActivityStack stack = task.getStack();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004150 if (prevStack == null || prevStack == stack
4151 || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
4152 return;
4153 }
4154
Winson Chung5af42fc2017-03-24 17:11:33 -07004155 scheduleUpdatePictureInPictureModeIfNeeded(task, stack.mBounds, false /* immediate */);
4156 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004157
Winson Chung5af42fc2017-03-24 17:11:33 -07004158 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds,
4159 boolean immediate) {
4160
4161 if (immediate) {
4162 mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG);
4163 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4164 final ActivityRecord r = task.mActivities.get(i);
4165 if (r.app != null && r.app.thread != null) {
4166 r.updatePictureInPictureMode(targetStackBounds);
4167 }
4168 }
4169 } else {
4170 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4171 final ActivityRecord r = task.mActivities.get(i);
4172 if (r.app != null && r.app.thread != null) {
4173 mPipModeChangedActivities.add(r);
4174 }
4175 }
4176 mPipModeChangedTargetStackBounds = targetStackBounds;
4177
4178 if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
4179 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
4180 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004181 }
4182 }
4183
Tony Mak853304c2016-04-18 15:17:41 +01004184 void setDockedStackMinimized(boolean minimized) {
4185 mIsDockMinimized = minimized;
Tony Mak853304c2016-04-18 15:17:41 +01004186 }
4187
chaviw59b98852017-06-13 12:05:44 -07004188 void wakeUp(String reason) {
4189 mPowerManager.wakeUp(SystemClock.uptimeMillis(), "android.server.am:TURN_ON:" + reason);
4190 }
4191
4192 /**
4193 * Begin deferring resume to avoid duplicate resumes in one pass.
4194 */
4195 private void beginDeferResume() {
4196 mDeferResumeCount++;
4197 }
4198
4199 /**
4200 * End deferring resume and determine if resume can be called.
4201 */
4202 private void endDeferResume() {
4203 mDeferResumeCount--;
4204 }
4205
4206 /**
4207 * @return True if resume can be called.
4208 */
4209 private boolean readyToResume() {
4210 return mDeferResumeCount == 0;
4211 }
4212
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004213 private final class ActivityStackSupervisorHandler extends Handler {
Craig Mautnerf3333272013-04-22 10:55:53 -07004214
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004215 public ActivityStackSupervisorHandler(Looper looper) {
4216 super(looper);
4217 }
4218
Winson Chung4dabf232017-01-25 13:25:22 -08004219 void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) {
Craig Mautnerf3333272013-04-22 10:55:53 -07004220 synchronized (mService) {
Winson Chung4dabf232017-01-25 13:25:22 -08004221 activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */,
4222 processPausingActivities, null);
Craig Mautnerf3333272013-04-22 10:55:53 -07004223 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004224 }
4225
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004226 @Override
4227 public void handleMessage(Message msg) {
4228 switch (msg.what) {
Wale Ogunwale22e25262016-02-01 10:32:02 -08004229 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
4230 synchronized (mService) {
4231 for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
4232 final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004233 r.updateMultiWindowMode();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004234 }
4235 }
4236 } break;
4237 case REPORT_PIP_MODE_CHANGED_MSG: {
4238 synchronized (mService) {
4239 for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
4240 final ActivityRecord r = mPipModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004241 r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds);
Wale Ogunwale22e25262016-02-01 10:32:02 -08004242 }
4243 }
4244 } break;
Craig Mautnerf3333272013-04-22 10:55:53 -07004245 case IDLE_TIMEOUT_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004246 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
4247 "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
Craig Mautnerf3333272013-04-22 10:55:53 -07004248 // We don't at this point know if the activity is fullscreen,
4249 // so we need to be conservative and assume it isn't.
Winson Chung4dabf232017-01-25 13:25:22 -08004250 activityIdleInternal((ActivityRecord) msg.obj,
4251 true /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004252 } break;
4253 case IDLE_NOW_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004254 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
Winson Chung4dabf232017-01-25 13:25:22 -08004255 activityIdleInternal((ActivityRecord) msg.obj,
4256 false /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004257 } break;
Craig Mautner05d29032013-05-03 13:40:13 -07004258 case RESUME_TOP_ACTIVITY_MSG: {
4259 synchronized (mService) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004260 resumeFocusedStackTopActivityLocked();
Craig Mautner05d29032013-05-03 13:40:13 -07004261 }
4262 } break;
Craig Mautner0eea92c2013-05-16 13:35:39 -07004263 case SLEEP_TIMEOUT_MSG: {
4264 synchronized (mService) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07004265 if (mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07004266 Slog.w(TAG, "Sleep timeout! Sleeping now.");
David Stevens9440dc82017-03-16 19:00:20 -07004267 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07004268 }
4269 }
4270 } break;
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004271 case LAUNCH_TIMEOUT_MSG: {
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004272 synchronized (mService) {
4273 if (mLaunchingActivity.isHeld()) {
4274 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
4275 if (VALIDATE_WAKE_LOCK_CALLER
4276 && Binder.getCallingUid() != Process.myUid()) {
4277 throw new IllegalStateException("Calling must be system uid");
4278 }
4279 mLaunchingActivity.release();
4280 }
4281 }
4282 } break;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004283 case HANDLE_DISPLAY_ADDED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004284 handleDisplayAdded(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004285 } break;
4286 case HANDLE_DISPLAY_CHANGED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004287 handleDisplayChanged(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004288 } break;
4289 case HANDLE_DISPLAY_REMOVED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004290 handleDisplayRemoved(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004291 } break;
Craig Mautnerbb742462014-07-07 15:28:55 -07004292 case LAUNCH_TASK_BEHIND_COMPLETE: {
4293 synchronized (mService) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07004294 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
Craig Mautnerbb742462014-07-07 15:28:55 -07004295 if (r != null) {
4296 handleLaunchTaskBehindCompleteLocked(r);
4297 }
4298 }
4299 } break;
Chong Zhangc806d902015-11-30 09:44:27 -08004300
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004301 }
4302 }
4303 }
Craig Mautnered6649f2013-12-02 14:08:25 -08004304
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004305 // TODO: Move to its own file.
Craig Mautner4a1cb222013-12-04 16:14:06 -08004306 /** Exactly one of these classes per Display in the system. Capable of holding zero or more
4307 * attached {@link ActivityStack}s */
Andrii Kulian1779e612016-10-12 21:58:25 -07004308 class ActivityDisplay extends ConfigurationContainer {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004309 /** Actual Display this object tracks. */
Craig Mautner34b73df2014-01-12 21:11:08 -08004310 int mDisplayId;
4311 Display mDisplay;
Craig Mautnered6649f2013-12-02 14:08:25 -08004312
Craig Mautner4a1cb222013-12-04 16:14:06 -08004313 /** All of the stacks on this display. Order matters, topmost stack is in front of all other
4314 * stacks, bottommost behind. Accessed directly by ActivityManager package classes */
Wale Ogunwale1f544be2015-12-17 10:27:23 -08004315 final ArrayList<ActivityStack> mStacks = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004316
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004317 /** Array of all UIDs that are present on the display. */
4318 private IntArray mDisplayAccessUIDs = new IntArray();
4319
David Stevens9440dc82017-03-16 19:00:20 -07004320 /** All tokens used to put activities on this stack to sleep (including mOffToken) */
4321 final ArrayList<SleepTokenImpl> mAllSleepTokens = new ArrayList<>();
4322 /** The token acquired by ActivityStackSupervisor to put stacks on the display to sleep */
4323 SleepToken mOffToken;
4324
4325 private boolean mSleeping;
4326
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004327 @VisibleForTesting
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004328 ActivityDisplay() {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004329 mActivityDisplays.put(mDisplayId, this);
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004330 }
Craig Mautner4504de52013-12-20 09:06:56 -08004331
Craig Mautner1a70a162014-09-13 12:09:31 -07004332 // After instantiation, check that mDisplay is not null before using this. The alternative
4333 // is for this to throw an exception if mDisplayManager.getDisplay() returns null.
Craig Mautnere0a38842013-12-16 16:14:02 -08004334 ActivityDisplay(int displayId) {
Craig Mautner1a70a162014-09-13 12:09:31 -07004335 final Display display = mDisplayManager.getDisplay(displayId);
4336 if (display == null) {
4337 return;
4338 }
4339 init(display);
Craig Mautner4504de52013-12-20 09:06:56 -08004340 }
4341
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004342 void init(Display display) {
Craig Mautner4504de52013-12-20 09:06:56 -08004343 mDisplay = display;
4344 mDisplayId = display.getDisplayId();
Craig Mautnered6649f2013-12-02 14:08:25 -08004345 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004346
Winson Chung7c3ede32017-03-14 14:18:34 -07004347 void attachStack(ActivityStack stack, int position) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08004348 if (DEBUG_STACK) Slog.v(TAG_STACK, "attachStack: attaching " + stack
Winson Chung7c3ede32017-03-14 14:18:34 -07004349 + " to displayId=" + mDisplayId + " position=" + position);
4350 mStacks.add(position, stack);
David Stevens9440dc82017-03-16 19:00:20 -07004351 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004352 }
4353
Wale Ogunwale1666e312016-12-16 11:27:18 -08004354 void detachStack(ActivityStack stack) {
4355 if (DEBUG_STACK) Slog.v(TAG_STACK, "detachStack: detaching " + stack
Craig Mautnere0a38842013-12-16 16:14:02 -08004356 + " from displayId=" + mDisplayId);
4357 mStacks.remove(stack);
David Stevens9440dc82017-03-16 19:00:20 -07004358 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004359 }
4360
Craig Mautner34b73df2014-01-12 21:11:08 -08004361 @Override
4362 public String toString() {
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004363 return "ActivityDisplay={" + mDisplayId + " numStacks=" + mStacks.size() + "}";
4364 }
Andrii Kulian1779e612016-10-12 21:58:25 -07004365
4366 @Override
4367 protected int getChildCount() {
4368 return mStacks.size();
4369 }
4370
4371 @Override
4372 protected ConfigurationContainer getChildAt(int index) {
4373 return mStacks.get(index);
4374 }
4375
4376 @Override
4377 protected ConfigurationContainer getParent() {
4378 return ActivityStackSupervisor.this;
4379 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004380
4381 boolean isPrivate() {
4382 return (mDisplay.getFlags() & FLAG_PRIVATE) != 0;
4383 }
4384
4385 boolean isUidPresent(int uid) {
4386 for (ActivityStack stack : mStacks) {
4387 if (stack.isUidPresent(uid)) {
4388 return true;
4389 }
4390 }
4391 return false;
4392 }
4393
4394 /** Update and get all UIDs that are present on the display and have access to it. */
4395 private IntArray getPresentUIDs() {
4396 mDisplayAccessUIDs.clear();
4397 for (ActivityStack stack : mStacks) {
4398 stack.getPresentUIDs(mDisplayAccessUIDs);
4399 }
4400 return mDisplayAccessUIDs;
4401 }
Andrii Kulian250d6532017-02-08 23:30:45 -08004402
4403 boolean shouldDestroyContentOnRemove() {
4404 return mDisplay.getRemoveMode() == REMOVE_MODE_DESTROY_CONTENT;
4405 }
David Stevens9440dc82017-03-16 19:00:20 -07004406
4407 boolean shouldSleep() {
4408 return (mStacks.isEmpty() || !mAllSleepTokens.isEmpty())
4409 && (mService.mRunningVoice == null);
4410 }
4411
4412 boolean isSleeping() {
4413 return mSleeping;
4414 }
4415
4416 void setIsSleeping(boolean asleep) {
4417 mSleeping = asleep;
4418 }
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004419 }
4420
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004421 ActivityStack findStackBehind(ActivityStack stack) {
4422 // TODO(multi-display): We are only looking for stacks on the default display.
Jorim Jaggife762342016-10-13 14:33:27 +02004423 final ActivityDisplay display = mActivityDisplays.get(DEFAULT_DISPLAY);
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004424 if (display == null) {
4425 return null;
4426 }
4427 final ArrayList<ActivityStack> stacks = display.mStacks;
4428 for (int i = stacks.size() - 1; i >= 0; i--) {
4429 if (stacks.get(i) == stack && i > 0) {
4430 return stacks.get(i - 1);
4431 }
4432 }
4433 throw new IllegalStateException("Failed to find a stack behind stack=" + stack
4434 + " in=" + stacks);
4435 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004436
Jorim Jaggic69bd222016-03-15 14:38:37 +01004437 /**
4438 * Puts a task into resizing mode during the next app transition.
4439 *
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004440 * @param task The task to put into resizing mode
Jorim Jaggic69bd222016-03-15 14:38:37 +01004441 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004442 private void setResizingDuringAnimation(TaskRecord task) {
4443 mResizingTasksDuringAnimation.add(task.taskId);
4444 task.setTaskDockedResizing(true);
Jorim Jaggic69bd222016-03-15 14:38:37 +01004445 }
4446
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004447 final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
4448 final TaskRecord task;
4449 final int callingUid;
4450 final String callingPackage;
4451 final Intent intent;
4452 final int userId;
4453 final ActivityOptions activityOptions = (bOptions != null)
4454 ? new ActivityOptions(bOptions) : null;
4455 final int launchStackId = (activityOptions != null)
4456 ? activityOptions.getLaunchStackId() : INVALID_STACK_ID;
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004457 if (StackId.isHomeOrRecentsStack(launchStackId)) {
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004458 throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004459 + taskId + " can't be launch in the home/recents stack.");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004460 }
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004461
Matthew Ng606dd802017-06-05 14:06:32 -07004462 mWindowManager.deferSurfaceLayout();
4463 try {
4464 if (launchStackId == DOCKED_STACK_ID) {
4465 mWindowManager.setDockedStackCreateState(
4466 activityOptions.getDockCreateMode(), null /* initialBounds */);
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004467
Matthew Ng606dd802017-06-05 14:06:32 -07004468 // Defer updating the stack in which recents is until the app transition is done, to
4469 // not run into issues where we still need to draw the task in recents but the
4470 // docked stack is already created.
4471 deferUpdateBounds(RECENTS_STACK_ID);
4472 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004473 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004474
Matthew Ng606dd802017-06-05 14:06:32 -07004475 task = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
4476 launchStackId);
4477 if (task == null) {
4478 continueUpdateBounds(RECENTS_STACK_ID);
4479 mWindowManager.executeAppTransition();
4480 throw new IllegalArgumentException(
4481 "startActivityFromRecentsInner: Task " + taskId + " not found.");
4482 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004483
Matthew Ng606dd802017-06-05 14:06:32 -07004484 // Since we don't have an actual source record here, we assume that the currently
4485 // focused activity was the source.
4486 final ActivityStack focusedStack = getFocusedStack();
4487 final ActivityRecord sourceRecord =
4488 focusedStack != null ? focusedStack.topActivity() : null;
4489
4490 if (launchStackId != INVALID_STACK_ID) {
4491 if (task.getStackId() != launchStackId) {
4492 task.reparent(launchStackId, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE,
4493 DEFER_RESUME, "startActivityFromRecents");
4494 }
4495 }
4496
4497 // If the user must confirm credentials (e.g. when first launching a work app and the
4498 // Work Challenge is present) let startActivityInPackage handle the intercepting.
4499 if (!mService.mUserController.shouldConfirmCredentials(task.userId)
4500 && task.getRootActivity() != null) {
Bryce Lee28d80422017-07-21 13:25:13 -07004501 final ActivityRecord targetActivity = task.getTopActivity();
4502
4503 mService.mActivityStarter.sendPowerHintForLaunchStartIfNeeded(true /* forceSend */,
4504 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004505 mActivityMetricsLogger.notifyActivityLaunching();
Jorim Jaggi42befc62017-06-13 11:54:04 -07004506 mService.moveTaskToFrontLocked(task.taskId, 0, bOptions, true /* fromRecents */);
Matthew Ng606dd802017-06-05 14:06:32 -07004507 mActivityMetricsLogger.notifyActivityLaunched(ActivityManager.START_TASK_TO_FRONT,
Bryce Lee28d80422017-07-21 13:25:13 -07004508 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004509
4510 // If we are launching the task in the docked stack, put it into resizing mode so
4511 // the window renders full-screen with the background filling the void. Also only
4512 // call this at the end to make sure that tasks exists on the window manager side.
4513 if (launchStackId == DOCKED_STACK_ID) {
4514 setResizingDuringAnimation(task);
4515 }
4516
4517 mService.mActivityStarter.postStartActivityProcessing(task.getTopActivity(),
4518 ActivityManager.START_TASK_TO_FRONT,
4519 sourceRecord != null
4520 ? sourceRecord.getTask().getStackId() : INVALID_STACK_ID,
4521 sourceRecord, task.getStack());
4522 return ActivityManager.START_TASK_TO_FRONT;
4523 }
4524 callingUid = task.mCallingUid;
4525 callingPackage = task.mCallingPackage;
4526 intent = task.intent;
4527 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4528 userId = task.userId;
4529 int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004530 null, null, 0, 0, bOptions, userId, task, "startActivityFromRecents");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004531 if (launchStackId == DOCKED_STACK_ID) {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004532 setResizingDuringAnimation(task);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004533 }
Matthew Ng606dd802017-06-05 14:06:32 -07004534 return result;
4535 } finally {
4536 mWindowManager.continueSurfaceLayout();
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004537 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004538 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004539
4540 /**
4541 * @return a list of activities which are the top ones in each visible stack. The first
4542 * entry will be the focused activity.
4543 */
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004544 List<IBinder> getTopVisibleActivities() {
4545 final ArrayList<IBinder> topActivityTokens = new ArrayList<>();
4546 // Traverse all displays.
Robert Carr22374c02017-02-21 13:01:47 -08004547 for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004548 final ActivityDisplay display = mActivityDisplays.valueAt(i);
4549 // Traverse all stacks on a display.
4550 for (int j = display.mStacks.size() - 1; j >= 0; j--) {
4551 final ActivityStack stack = display.mStacks.get(j);
4552 // Get top activity from a visible stack and add it to the list.
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004553 if (stack.shouldBeVisible(null /* starting */)
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004554 == ActivityStack.STACK_VISIBLE) {
4555 final ActivityRecord top = stack.topActivity();
4556 if (top != null) {
4557 if (stack == mFocusedStack) {
4558 topActivityTokens.add(0, top.appToken);
4559 } else {
4560 topActivityTokens.add(top.appToken);
4561 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004562 }
4563 }
4564 }
4565 }
4566 return topActivityTokens;
4567 }
Bryce Lee4a194382017-04-04 14:32:48 -07004568
4569 /**
4570 * Internal container to store a match qualifier alongside a WaitResult.
4571 */
4572 static class WaitInfo {
4573 private final ComponentName mTargetComponent;
4574 private final WaitResult mResult;
4575
4576 public WaitInfo(ComponentName targetComponent, WaitResult result) {
4577 this.mTargetComponent = targetComponent;
4578 this.mResult = result;
4579 }
4580
Wale Ogunwale3270f172017-04-26 07:29:42 -07004581 public boolean matches(ComponentName targetComponent) {
4582 return mTargetComponent == null || mTargetComponent.equals(targetComponent);
Bryce Lee4a194382017-04-04 14:32:48 -07004583 }
4584
4585 public WaitResult getResult() {
4586 return mResult;
4587 }
4588
4589 public ComponentName getComponent() {
4590 return mTargetComponent;
4591 }
4592
4593 public void dump(PrintWriter pw, String prefix) {
4594 pw.println(prefix + "WaitInfo:");
4595 pw.println(prefix + " mTargetComponent=" + mTargetComponent);
4596 pw.println(prefix + " mResult=");
4597 mResult.dump(pw, prefix);
4598 }
4599 }
David Stevens9440dc82017-03-16 19:00:20 -07004600
4601 private final class SleepTokenImpl extends SleepToken {
4602 private final String mTag;
4603 private final long mAcquireTime;
4604 private final int mDisplayId;
4605
4606 public SleepTokenImpl(String tag, int displayId) {
4607 mTag = tag;
4608 mDisplayId = displayId;
4609 mAcquireTime = SystemClock.uptimeMillis();
4610 }
4611
4612 @Override
4613 public void release() {
4614 synchronized (mService) {
4615 removeSleepTokenLocked(this);
4616 }
4617 }
4618
4619 @Override
4620 public String toString() {
4621 return "{\"" + mTag + "\", display " + mDisplayId
4622 + ", acquire at " + TimeUtils.formatUptime(mAcquireTime) + "}";
4623 }
4624 }
4625
Craig Mautner27084302013-03-25 08:05:25 -07004626}