blob: f423ce81bd754d6fe66d5225ccc314228ace1bc3 [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;
Wale Ogunwale0568aed2017-09-08 13:29:37 -070024import static android.app.ActivityManager.StackId.ASSISTANT_STACK_ID;
Jorim Jaggife762342016-10-13 14:33:27 +020025import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
26import static android.app.ActivityManager.StackId.FIRST_DYNAMIC_STACK_ID;
27import static android.app.ActivityManager.StackId.FIRST_STATIC_STACK_ID;
28import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
29import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
30import static android.app.ActivityManager.StackId.HOME_STACK_ID;
31import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
32import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
33import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
Matthew Ng330757d2017-02-28 14:19:17 -080034import static android.app.ActivityManager.StackId.RECENTS_STACK_ID;
Wale Ogunwale0568aed2017-09-08 13:29:37 -070035import static android.app.ActivityManager.StackId.getStackIdForActivityType;
36import static android.app.ActivityManager.StackId.getStackIdForWindowingMode;
Andrii Kulian036e3ad2017-04-19 10:55:10 -070037import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
38import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -070039import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
Wale Ogunwale0568aed2017-09-08 13:29:37 -070040import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -070041import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
42import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale0568aed2017-09-08 13:29:37 -070043import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
Wale Ogunwale926aade2017-08-29 11:24:37 -070044import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale0568aed2017-09-08 13:29:37 -070045import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
46import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale926aade2017-08-29 11:24:37 -070047import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale0568aed2017-09-08 13:29:37 -070048import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Andrii Kulian3c9ad072017-08-01 11:45:22 -070049import static android.content.pm.PackageManager.PERMISSION_DENIED;
Jorim Jaggife762342016-10-13 14:33:27 +020050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
chaviw59b98852017-06-13 12:05:44 -070051import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
Benjamin Franza83859f2017-07-03 16:34:14 +010052import static android.os.Process.SYSTEM_UID;
Jorim Jaggife762342016-10-13 14:33:27 +020053import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
54import static android.view.Display.DEFAULT_DISPLAY;
Andrii Kulian16802aa2016-11-02 12:21:33 -070055import static android.view.Display.INVALID_DISPLAY;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070056import static android.view.Display.TYPE_VIRTUAL;
Winson Chung47900652017-04-06 18:44:25 -070057import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN;
Jorim Jaggife762342016-10-13 14:33:27 +020058import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
Jorim Jaggife762342016-10-13 14:33:27 +020059import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
60import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
Jorim Jaggife762342016-10-13 14:33:27 +020061import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
62import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
63import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
64import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
65import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
66import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
67import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020068import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
69import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IDLE;
Jorim Jaggife762342016-10-13 14:33:27 +020070import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
71import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
72import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
73import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
74import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
75import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
76import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020077import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
78import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
79import static com.android.server.am.ActivityManagerService.ANIMATE;
80import static com.android.server.am.ActivityManagerService.FIRST_SUPERVISOR_STACK_MSG;
Jorim Jaggife762342016-10-13 14:33:27 +020081import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
82import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
83import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
84import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
85import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
86import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
87import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
88import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
89import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
90import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
91import static com.android.server.am.ActivityStack.STACK_VISIBLE;
Wale Ogunwale0568aed2017-09-08 13:29:37 -070092import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
Jorim Jaggife762342016-10-13 14:33:27 +020093import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
94import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
Winson Chung74666102017-02-22 17:49:24 -080095import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
96import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
97import static com.android.server.am.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
Steven Timotius4346f0a2017-09-12 11:07:21 -070098import static com.android.server.am.proto.ActivityStackSupervisorProto.DISPLAYS;
99import static com.android.server.am.proto.ActivityStackSupervisorProto.FOCUSED_STACK_ID;
100import static com.android.server.am.proto.ActivityStackSupervisorProto.KEYGUARD_CONTROLLER;
101import static com.android.server.am.proto.ActivityStackSupervisorProto.RESUMED_ACTIVITY;
102import static com.android.server.am.proto.ActivityStackSupervisorProto.CONFIGURATION_CONTAINER;
103import static com.android.server.am.proto.ActivityDisplayProto.STACKS;
104import static com.android.server.am.proto.ActivityDisplayProto.ID;
Jorim Jaggife762342016-10-13 14:33:27 +0200105import static com.android.server.wm.AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS;
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -0800106import static java.lang.Integer.MAX_VALUE;
Jorim Jaggife762342016-10-13 14:33:27 +0200107
Svetoslav7008b512015-06-24 18:47:07 -0700108import android.Manifest;
Winson Chung7900bee2017-03-10 08:59:25 -0800109import android.annotation.IntDef;
Andrii Kulian16802aa2016-11-02 12:21:33 -0700110import android.annotation.NonNull;
Wale Ogunwale0568aed2017-09-08 13:29:37 -0700111import android.annotation.Nullable;
Tony Mak853304c2016-04-18 15:17:41 +0100112import android.annotation.UserIdInt;
Craig Mautner2420ead2013-04-01 17:13:20 -0700113import android.app.Activity;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700114import android.app.ActivityManager;
Filip Gruszczynski80e29f12015-12-14 14:58:30 -0800115import android.app.ActivityManager.RunningTaskInfo;
Wale Ogunwale3797c222015-10-27 14:21:58 -0700116import android.app.ActivityManager.StackId;
Craig Mautnered6649f2013-12-02 14:08:25 -0800117import android.app.ActivityManager.StackInfo;
David Stevens9440dc82017-03-16 19:00:20 -0700118import android.app.ActivityManagerInternal.SleepToken;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700119import android.app.ActivityOptions;
Svetoslav7008b512015-06-24 18:47:07 -0700120import android.app.AppOpsManager;
Jeff Hao1b012d32014-08-20 10:35:34 -0700121import android.app.ProfilerInfo;
Craig Mautner2420ead2013-04-01 17:13:20 -0700122import android.app.ResultInfo;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700123import android.app.WaitResult;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700124import android.content.ComponentName;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700125import android.content.Context;
126import android.content.Intent;
127import android.content.pm.ActivityInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700128import android.content.pm.ApplicationInfo;
Svetoslav7008b512015-06-24 18:47:07 -0700129import android.content.pm.PackageInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700130import android.content.pm.PackageManager;
131import android.content.pm.ResolveInfo;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100132import android.content.pm.UserInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700133import android.content.res.Configuration;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800134import android.graphics.Rect;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800135import android.hardware.display.DisplayManager;
136import android.hardware.display.DisplayManager.DisplayListener;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800137import android.hardware.display.DisplayManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800138import android.hardware.input.InputManagerInternal;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700139import android.os.Binder;
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100140import android.os.Bundle;
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700141import android.os.Debug;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700142import android.os.Handler;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700143import android.os.IBinder;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700144import android.os.Looper;
Craig Mautner2420ead2013-04-01 17:13:20 -0700145import android.os.Message;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700146import android.os.PowerManager;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700147import android.os.Process;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700148import android.os.RemoteException;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700149import android.os.SystemClock;
Wale Ogunwalecad05a02015-09-25 10:41:44 -0700150import android.os.Trace;
Craig Mautner6170f732013-04-02 13:05:23 -0700151import android.os.UserHandle;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100152import android.os.UserManager;
Dianne Hackborn3d07c942015-03-13 18:02:54 -0700153import android.os.WorkSource;
Svetoslav7008b512015-06-24 18:47:07 -0700154import android.provider.MediaStore;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700155import android.service.voice.IVoiceInteractionSession;
Svetoslav7008b512015-06-24 18:47:07 -0700156import android.util.ArrayMap;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700157import android.util.ArraySet;
Craig Mautner2420ead2013-04-01 17:13:20 -0700158import android.util.EventLog;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800159import android.util.IntArray;
Wale Ogunwalee610d3d2017-04-25 10:23:48 -0700160import android.util.MergedConfiguration;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700161import android.util.Slog;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800162import android.util.SparseArray;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800163import android.util.SparseIntArray;
David Stevens9440dc82017-03-16 19:00:20 -0700164import android.util.TimeUtils;
Steven Timotius4346f0a2017-09-12 11:07:21 -0700165import android.util.proto.ProtoOutputStream;
Craig Mautnered6649f2013-12-02 14:08:25 -0800166import android.view.Display;
Chong Zhangb15758a2015-11-17 12:12:03 -0800167
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700168import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800169import com.android.internal.content.ReferrerIntent;
Winson Chung14fbe142016-12-19 16:18:24 -0800170import com.android.internal.logging.MetricsLogger;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -0700171import com.android.internal.os.TransferPipe;
Svetoslav7008b512015-06-24 18:47:07 -0700172import com.android.internal.util.ArrayUtils;
Jeff Brownca9bc702014-02-11 14:32:56 -0800173import com.android.server.LocalServices;
Craig Mautner2420ead2013-04-01 17:13:20 -0700174import com.android.server.am.ActivityStack.ActivityState;
Steven Timotius4346f0a2017-09-12 11:07:21 -0700175import com.android.server.am.proto.ActivityDisplayProto;
Wale Ogunwale98d62312017-07-12 09:24:56 -0700176import com.android.server.wm.ConfigurationContainer;
Winson Chung19953ca2017-04-11 11:19:23 -0700177import com.android.server.wm.PinnedStackWindowController;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700178import com.android.server.wm.WindowManagerService;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700179
Craig Mautner8d341ef2013-03-26 09:03:27 -0700180import java.io.FileDescriptor;
181import java.io.IOException;
Craig Mautner27084302013-03-25 08:05:25 -0700182import java.io.PrintWriter;
Winson Chung7900bee2017-03-10 08:59:25 -0800183import java.lang.annotation.Retention;
184import java.lang.annotation.RetentionPolicy;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700185import java.util.ArrayList;
David Stevens9440dc82017-03-16 19:00:20 -0700186import java.util.Iterator;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700187import java.util.List;
Wale Ogunwale540e1232015-05-01 15:35:39 -0700188import java.util.Set;
Craig Mautner27084302013-03-25 08:05:25 -0700189
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -0800190public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener {
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800191 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_AM;
Chong Zhang6cda19c2016-06-14 19:07:56 -0700192 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700193 private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700194 private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700195 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700196 private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700197 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700198 private static final String TAG_STATES = TAG + POSTFIX_STATES;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700199 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800200 static final String TAG_TASKS = TAG + POSTFIX_TASKS;
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800201
Craig Mautnerf3333272013-04-22 10:55:53 -0700202 /** How long we wait until giving up on the last activity telling us it is idle. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700203 static final int IDLE_TIMEOUT = 10 * 1000;
Craig Mautnerf3333272013-04-22 10:55:53 -0700204
Craig Mautner0eea92c2013-05-16 13:35:39 -0700205 /** How long we can hold the sleep wake lock before giving up. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700206 static final int SLEEP_TIMEOUT = 5 * 1000;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700207
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700208 // How long we can hold the launch wake lock before giving up.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700209 static final int LAUNCH_TIMEOUT = 10 * 1000;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700210
Craig Mautner05d29032013-05-03 13:40:13 -0700211 static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
212 static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
213 static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700214 static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700215 static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800216 static final int HANDLE_DISPLAY_ADDED = FIRST_SUPERVISOR_STACK_MSG + 5;
217 static final int HANDLE_DISPLAY_CHANGED = FIRST_SUPERVISOR_STACK_MSG + 6;
218 static final int HANDLE_DISPLAY_REMOVED = FIRST_SUPERVISOR_STACK_MSG + 7;
Wale Ogunwale73eba742015-04-07 14:23:14 -0700219 static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
Wale Ogunwale22e25262016-02-01 10:32:02 -0800220 static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
221 static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800222
Wale Ogunwale040b4702015-08-06 18:10:50 -0700223 private static final String VIRTUAL_DISPLAY_BASE_NAME = "ActivityViewVirtualDisplay";
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700224
Wale Ogunwale040b4702015-08-06 18:10:50 -0700225 // Used to indicate if an object (e.g. stack) that we are trying to get
226 // should be created if it doesn't exist already.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800227 static final boolean CREATE_IF_NEEDED = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700228
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700229 // Used to indicate that windows of activities should be preserved during the resize.
230 static final boolean PRESERVE_WINDOWS = true;
231
Wale Ogunwale040b4702015-08-06 18:10:50 -0700232 // Used to indicate if an object (e.g. task) should be moved/created
233 // at the top of its container (e.g. stack).
Wale Ogunwaleb30daaa2015-08-07 21:50:49 -0700234 static final boolean ON_TOP = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700235
236 // Used to indicate that an objects (e.g. task) removal from its container
237 // (e.g. stack) is due to it moving to another container.
238 static final boolean MOVING = true;
239
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700240 // Force the focus to change to the stack we are moving a task to..
241 static final boolean FORCE_FOCUS = true;
242
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700243 // Don't execute any calls to resume.
244 static final boolean DEFER_RESUME = true;
245
Winson Chung010927a2016-12-15 16:12:35 -0800246 // Used to indicate that a task is removed it should also be removed from recents.
247 static final boolean REMOVE_FROM_RECENTS = true;
248
Winson Chung6954fc92017-03-24 16:22:12 -0700249 // Used to indicate that pausing an activity should occur immediately without waiting for
250 // the activity callback indicating that it has completed pausing
251 static final boolean PAUSE_IMMEDIATELY = true;
252
Winson Chung7900bee2017-03-10 08:59:25 -0800253 /**
254 * The modes which affect which tasks are returned when calling
255 * {@link ActivityStackSupervisor#anyTaskForIdLocked(int)}.
256 */
257 @Retention(RetentionPolicy.SOURCE)
258 @IntDef({
259 MATCH_TASK_IN_STACKS_ONLY,
260 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
261 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
262 })
263 public @interface AnyTaskForIdMatchTaskMode {}
264 // Match only tasks in the current stacks
265 static final int MATCH_TASK_IN_STACKS_ONLY = 0;
266 // Match either tasks in the current stacks, or in the recent tasks if not found in the stacks
267 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS = 1;
268 // Match either tasks in the current stacks, or in the recent tasks, restoring it to the
269 // provided stack id
270 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE = 2;
271
Svetoslav7008b512015-06-24 18:47:07 -0700272 // Activity actions an app cannot start if it uses a permission which is not granted.
273 private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION =
274 new ArrayMap<>();
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700275
Svetoslav7008b512015-06-24 18:47:07 -0700276 static {
277 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE,
278 Manifest.permission.CAMERA);
279 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE,
280 Manifest.permission.CAMERA);
281 ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL,
282 Manifest.permission.CALL_PHONE);
283 }
284
Svet Ganov99b60432015-06-27 13:15:22 -0700285 /** Action restriction: launching the activity is not restricted. */
286 private static final int ACTIVITY_RESTRICTION_NONE = 0;
287 /** Action restriction: launching the activity is restricted by a permission. */
288 private static final int ACTIVITY_RESTRICTION_PERMISSION = 1;
289 /** Action restriction: launching the activity is restricted by an app op. */
290 private static final int ACTIVITY_RESTRICTION_APPOP = 2;
Svetoslav7008b512015-06-24 18:47:07 -0700291
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700292 // For debugging to make sure the caller when acquiring/releasing our
293 // wake lock is the system process.
294 static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800295 /** The number of distinct task ids that can be assigned to the tasks of a single user */
296 private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
Craig Mautnerf3333272013-04-22 10:55:53 -0700297
Craig Mautner27084302013-03-25 08:05:25 -0700298 final ActivityManagerService mService;
299
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800300 private RecentTasks mRecentTasks;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800301
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700302 final ActivityStackSupervisorHandler mHandler;
303
304 /** Short cut */
305 WindowManagerService mWindowManager;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800306 DisplayManager mDisplayManager;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700307
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -0700308 /** Counter for next free stack ID to use for dynamic activity stacks. */
309 private int mNextFreeStackId = FIRST_DYNAMIC_STACK_ID;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700310
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800311 /**
312 * Maps the task identifier that activities are currently being started in to the userId of the
313 * task. Each time a new task is created, the entry for the userId of the task is incremented
314 */
315 private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20);
Craig Mautner8d341ef2013-03-26 09:03:27 -0700316
Craig Mautner2420ead2013-04-01 17:13:20 -0700317 /** The current user */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800318 int mCurrentUser;
Craig Mautner2420ead2013-04-01 17:13:20 -0700319
Craig Mautnere0a38842013-12-16 16:14:02 -0800320 /** The stack containing the launcher app. Assumed to always be attached to
321 * Display.DEFAULT_DISPLAY. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800322 ActivityStack mHomeStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700323
Craig Mautnere0a38842013-12-16 16:14:02 -0800324 /** The stack currently receiving input or launching the next activity. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800325 ActivityStack mFocusedStack;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700326
Craig Mautner4a1cb222013-12-04 16:14:06 -0800327 /** If this is the same as mFocusedStack then the activity on the top of the focused stack has
328 * been resumed. If stacks are changing position this will hold the old stack until the new
Craig Mautnere0a38842013-12-16 16:14:02 -0800329 * stack becomes resumed after which it will be set to mFocusedStack. */
Craig Mautner4a1cb222013-12-04 16:14:06 -0800330 private ActivityStack mLastFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -0700331
332 /** List of activities that are waiting for a new activity to become visible before completing
333 * whatever operation they are supposed to do. */
Bryce Lee4a194382017-04-04 14:32:48 -0700334 // TODO: Remove mActivitiesWaitingForVisibleActivity list and just remove activity from
335 // mStoppingActivities when something else comes up.
336 final ArrayList<ActivityRecord> mActivitiesWaitingForVisibleActivity = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700337
Bryce Lee4a194382017-04-04 14:32:48 -0700338 /** List of processes waiting to find out when a specific activity becomes visible. */
339 private final ArrayList<WaitInfo> mWaitingForActivityVisible = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700340
341 /** List of processes waiting to find out about the next launched activity. */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700342 final ArrayList<WaitResult> mWaitingActivityLaunched = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700343
Craig Mautnerde4ef022013-04-07 19:01:33 -0700344 /** List of activities that are ready to be stopped, but waiting for the next activity to
345 * settle down before doing so. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800346 final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700347
Craig Mautnerf3333272013-04-22 10:55:53 -0700348 /** List of activities that are ready to be finished, but waiting for the previous activity to
349 * settle down before doing so. It contains ActivityRecord objects. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800350 final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700351
Craig Mautner0eea92c2013-05-16 13:35:39 -0700352 /** List of activities that are in the process of going to sleep. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800353 final ArrayList<ActivityRecord> mGoingToSleepActivities = new ArrayList<>();
Craig Mautner0eea92c2013-05-16 13:35:39 -0700354
Wale Ogunwale22e25262016-02-01 10:32:02 -0800355 /** List of activities whose multi-window mode changed that we need to report to the
356 * application */
357 final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
358
359 /** List of activities whose picture-in-picture mode changed that we need to report to the
360 * application */
361 final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
362
Winson Chung5af42fc2017-03-24 17:11:33 -0700363 /** The target stack bounds for the picture-in-picture mode changed that we need to report to
364 * the application */
365 Rect mPipModeChangedTargetStackBounds;
366
Craig Mautnerf3333272013-04-22 10:55:53 -0700367 /** Used on user changes */
Amith Yamasani37a40c22015-06-17 13:25:42 -0700368 final ArrayList<UserState> mStartingUsers = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700369
Craig Mautnerde4ef022013-04-07 19:01:33 -0700370 /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity
371 * is being brought in front of us. */
372 boolean mUserLeaving = false;
373
Craig Mautner0eea92c2013-05-16 13:35:39 -0700374 /**
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700375 * We don't want to allow the device to go to sleep while in the process
376 * of launching an activity. This is primarily to allow alarm intent
377 * receivers to launch an activity and get that to run before the device
378 * goes back to sleep.
379 */
Jeff Brown2c43c332014-06-12 22:38:59 -0700380 PowerManager.WakeLock mLaunchingActivity;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700381
382 /**
Craig Mautner0eea92c2013-05-16 13:35:39 -0700383 * Set when the system is going to sleep, until we have
384 * successfully paused the current activity and released our wake lock.
385 * At that point the system is allowed to actually sleep.
386 */
Jeff Brown2c43c332014-06-12 22:38:59 -0700387 PowerManager.WakeLock mGoingToSleep;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700388
David Stevens9440dc82017-03-16 19:00:20 -0700389 /**
390 * A list of tokens that cause the top activity to be put to sleep.
391 * They are used by components that may hide and block interaction with underlying
392 * activities.
393 */
Wale Ogunwale9dcf9462017-09-19 15:13:01 -0700394 final ArrayList<SleepToken> mSleepTokens = new ArrayList<>();
David Stevens9440dc82017-03-16 19:00:20 -0700395
Craig Mautner4f1df4f2013-10-15 15:44:14 -0700396 /** Stack id of the front stack when user switched, indexed by userId. */
397 SparseIntArray mUserStackInFront = new SparseIntArray(2);
Craig Mautner93529a42013-10-04 15:03:13 -0700398
Bryce Leeaf3a4002017-03-20 10:37:12 -0700399 // TODO: There should be an ActivityDisplayController coordinating am/wm interaction.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800400 /** Mapping from displayId to display current state */
Craig Mautner15df08a2015-04-01 12:17:18 -0700401 private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800402
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800403 private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>();
404
405 private DisplayManagerInternal mDisplayManagerInternal;
406 private InputManagerInternal mInputManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800407
Wale Ogunwaled046a012015-12-24 13:05:59 -0800408 /** Used to keep resumeTopActivityUncheckedLocked() from being entered recursively */
Craig Mautner42d04db2014-11-06 12:13:23 -0800409 boolean inResumeTopActivity;
410
Andrii Kulian1e32e022016-09-16 15:29:34 -0700411 /**
412 * Temporary rect used during docked stack resize calculation so we don't need to create a new
413 * object each time.
414 */
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700415 private final Rect tempRect = new Rect();
Filip Gruszczynskiebcc8752015-08-25 16:51:05 -0700416
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700417 // The default minimal size that will be used if the activity doesn't specify its minimal size.
418 // It will be calculated when the default display gets added.
Andrii Kulianf66a83d2016-05-17 12:17:44 -0700419 int mDefaultMinSizeOfResizeableTask = -1;
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700420
Chong Zhangfdcc4d42015-10-14 16:50:12 -0700421 // Whether tasks have moved and we need to rank the tasks before next OOM scoring
422 private boolean mTaskLayersChanged = true;
423
Jorim Jaggi275561a2016-02-23 10:11:02 -0500424 final ActivityMetricsLogger mActivityMetricsLogger;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800425
Jorim Jaggiea039a82017-08-02 14:37:49 +0200426 private final ArrayList<ActivityRecord> mTmpActivityList = new ArrayList<>();
427
Andrii Kulian1779e612016-10-12 21:58:25 -0700428 @Override
429 protected int getChildCount() {
430 return mActivityDisplays.size();
431 }
432
433 @Override
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700434 protected ActivityDisplay getChildAt(int index) {
Andrii Kulian1779e612016-10-12 21:58:25 -0700435 return mActivityDisplays.valueAt(index);
436 }
437
438 @Override
439 protected ConfigurationContainer getParent() {
440 return null;
441 }
442
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700443 Configuration getDisplayOverrideConfiguration(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700444 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700445 if (activityDisplay == null) {
446 throw new IllegalArgumentException("No display found with id: " + displayId);
447 }
448
449 return activityDisplay.getOverrideConfiguration();
450 }
451
452 void setDisplayOverrideConfiguration(Configuration overrideConfiguration, int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700453 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700454 if (activityDisplay == null) {
455 throw new IllegalArgumentException("No display found with id: " + displayId);
456 }
457
458 activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
459 }
460
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700461 /** Check if placing task or activity on specified display is allowed. */
Andrii Kulian02689a72017-07-06 14:28:59 -0700462 boolean canPlaceEntityOnDisplay(int displayId, boolean resizeable, int callingPid,
463 int callingUid, ActivityInfo activityInfo) {
464 if (displayId == DEFAULT_DISPLAY) {
465 // No restrictions for the default display.
466 return true;
467 }
468 if (!mService.mSupportsMultiDisplay) {
469 // Can't launch on secondary displays if feature is not supported.
470 return false;
471 }
472 if (!resizeable && !displayConfigMatchesGlobal(displayId)) {
473 // Can't apply wrong configuration to non-resizeable activities.
474 return false;
475 }
476 if (!isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, displayId, activityInfo)) {
477 // Can't place activities to a display that has restricted launch rules.
478 // In this case the request should be made by explicitly adding target display id and
479 // by caller with corresponding permissions. See #isCallerAllowedToLaunchOnDisplay().
480 return false;
481 }
482 return true;
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700483 }
484
485 /**
486 * Check if configuration of specified display matches current global config.
487 * Used to check if we can put a non-resizeable activity on a secondary display and it will get
488 * the same config as on the default display.
489 * @param displayId Id of the display to check.
490 * @return {@code true} if configuration matches.
491 */
492 private boolean displayConfigMatchesGlobal(int displayId) {
493 if (displayId == DEFAULT_DISPLAY) {
494 return true;
495 }
496 if (displayId == INVALID_DISPLAY) {
497 return false;
498 }
Andrii Kulian62e6f252017-05-30 22:46:53 -0700499 final ActivityDisplay targetDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700500 if (targetDisplay == null) {
501 throw new IllegalArgumentException("No display found with id: " + displayId);
502 }
503 return getConfiguration().equals(targetDisplay.getConfiguration());
504 }
505
Wale Ogunwale39381972015-12-17 17:15:29 -0800506 static class FindTaskResult {
507 ActivityRecord r;
508 boolean matchedByRootAffinity;
509 }
510 private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
511
Craig Mautneree36c772014-07-16 14:56:05 -0700512 /**
Andrii Kulian7fc22812016-12-28 13:04:11 -0800513 * Temp storage for display ids sorted in focus order.
514 * Maps position to id. Using {@link SparseIntArray} instead of {@link ArrayList} because
515 * it's more efficient, as the number of displays is usually small.
516 */
517 private SparseIntArray mTmpOrderedDisplayIds = new SparseIntArray();
518
519 /**
Jorim Jaggia0fdeec2016-01-07 14:42:28 +0100520 * Used to keep track whether app visibilities got changed since the last pause. Useful to
521 * determine whether to invoke the task stack change listener after pausing.
522 */
523 boolean mAppVisibilitiesChangedSinceLastPause;
524
525 /**
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100526 * Set of tasks that are in resizing mode during an app transition to fill the "void".
527 */
528 private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
529
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700530
531 /**
532 * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked}
533 * will be ignored. Useful for the case where the caller is handling resizing of other stack and
534 * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger
535 * like the docked stack going empty.
536 */
537 private boolean mAllowDockedStackResize = true;
538
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100539 /**
Tony Mak853304c2016-04-18 15:17:41 +0100540 * Is dock currently minimized.
541 */
542 boolean mIsDockMinimized;
543
Jorim Jaggife762342016-10-13 14:33:27 +0200544 final KeyguardController mKeyguardController;
545
chaviw59b98852017-06-13 12:05:44 -0700546 private PowerManager mPowerManager;
547 private int mDeferResumeCount;
548
Tony Mak853304c2016-04-18 15:17:41 +0100549 /**
Craig Mautneree36c772014-07-16 14:56:05 -0700550 * Description of a request to start a new activity, which has been held
551 * due to app switches being disabled.
552 */
553 static class PendingActivityLaunch {
554 final ActivityRecord r;
555 final ActivityRecord sourceRecord;
556 final int startFlags;
557 final ActivityStack stack;
Robert Carr13997f52015-10-23 13:13:39 -0700558 final ProcessRecord callerApp;
Craig Mautneree36c772014-07-16 14:56:05 -0700559
560 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
Robert Carr13997f52015-10-23 13:13:39 -0700561 int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
Craig Mautneree36c772014-07-16 14:56:05 -0700562 r = _r;
563 sourceRecord = _sourceRecord;
564 startFlags = _startFlags;
565 stack = _stack;
Robert Carr13997f52015-10-23 13:13:39 -0700566 callerApp = _callerApp;
567 }
568
569 void sendErrorResult(String message) {
570 try {
571 if (callerApp.thread != null) {
572 callerApp.thread.scheduleCrash(message);
573 }
574 } catch (RemoteException e) {
575 Slog.e(TAG, "Exception scheduling crash of failed "
576 + "activity launcher sourceRecord=" + sourceRecord, e);
577 }
Craig Mautneree36c772014-07-16 14:56:05 -0700578 }
579 }
580
Bryce Leeaf691c02017-03-20 14:20:22 -0700581 public ActivityStackSupervisor(ActivityManagerService service, Looper looper) {
Craig Mautner27084302013-03-25 08:05:25 -0700582 mService = service;
Bryce Leeaf691c02017-03-20 14:20:22 -0700583 mHandler = new ActivityStackSupervisorHandler(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800584 mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
Jorim Jaggife762342016-10-13 14:33:27 +0200585 mKeyguardController = new KeyguardController(service, this);
Jeff Brown2c43c332014-06-12 22:38:59 -0700586 }
587
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800588 void setRecentTasks(RecentTasks recentTasks) {
589 mRecentTasks = recentTasks;
590 }
591
Jeff Brown2c43c332014-06-12 22:38:59 -0700592 /**
593 * At the time when the constructor runs, the power manager has not yet been
594 * initialized. So we initialize our wakelocks afterwards.
595 */
596 void initPowerManagement() {
chaviw59b98852017-06-13 12:05:44 -0700597 mPowerManager = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
598 mGoingToSleep = mPowerManager
599 .newWakeLock(PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
600 mLaunchingActivity = mPowerManager.newWakeLock(PARTIAL_WAKE_LOCK, "*launch*");
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700601 mLaunchingActivity.setReferenceCounted(false);
Craig Mautner2219a1b2013-03-25 09:44:30 -0700602 }
603
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700604 void setWindowManager(WindowManagerService wm) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800605 synchronized (mService) {
606 mWindowManager = wm;
Jorim Jaggife762342016-10-13 14:33:27 +0200607 mKeyguardController.setWindowManager(wm);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800608
609 mDisplayManager =
610 (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
611 mDisplayManager.registerDisplayListener(this, null);
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800612 mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800613
614 Display[] displays = mDisplayManager.getDisplays();
615 for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
616 final int displayId = displays[displayNdx].getDisplayId();
Wale Ogunwale9dcf9462017-09-19 15:13:01 -0700617 ActivityDisplay activityDisplay = new ActivityDisplay(this, displayId);
Craig Mautnere0a38842013-12-16 16:14:02 -0800618 mActivityDisplays.put(displayId, activityDisplay);
Filip Gruszczynski7be9a8c2015-10-15 18:20:30 -0700619 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800620 }
621
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800622 mHomeStack = mFocusedStack = mLastFocusedStack =
623 getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Jeff Brownca9bc702014-02-11 14:32:56 -0800624
625 mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800626 }
Craig Mautner27084302013-03-25 08:05:25 -0700627 }
628
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700629 ActivityStack getFocusedStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800630 return mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700631 }
632
Craig Mautnerde4ef022013-04-07 19:01:33 -0700633 ActivityStack getLastStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800634 return mLastFocusedStack;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700635 }
636
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700637 boolean isFocusedStack(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700638 return stack != null && stack == mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700639 }
640
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800641 /** The top most stack on its display. */
642 boolean isFrontStackOnDisplay(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700643 return isFrontOfStackList(stack, stack.getDisplay().mStacks);
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800644 }
645
646 private boolean isFrontOfStackList(ActivityStack stack, List<ActivityStack> stackList) {
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800647 return stack == stackList.get((stackList.size() - 1));
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700648 }
649
Wale Ogunwaled046a012015-12-24 13:05:59 -0800650 /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800651 void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
652 if (!focusCandidate.isFocusable()) {
653 // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
Andrii Kulian7fc22812016-12-28 13:04:11 -0800654 focusCandidate = getNextFocusableStackLocked(focusCandidate);
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800655 }
656
657 if (focusCandidate != mFocusedStack) {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800658 mLastFocusedStack = mFocusedStack;
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800659 mFocusedStack = focusCandidate;
Wale Ogunwalecb82f302015-02-25 07:53:40 -0800660
Wale Ogunwaled046a012015-12-24 13:05:59 -0800661 EventLogTags.writeAmFocusedStack(
662 mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
663 mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
664 }
665
666 final ActivityRecord r = topRunningActivityLocked();
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800667 if (mService.mBooting || !mService.mBooted) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800668 if (r != null && r.idle) {
669 checkFinishBootingLocked();
670 }
671 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700672 }
673
Wale Ogunwale925d0d12015-09-23 15:40:07 -0700674 void moveHomeStackToFront(String reason) {
675 mHomeStack.moveToFront(reason);
676 }
677
Matthew Ng330757d2017-02-28 14:19:17 -0800678 void moveRecentsStackToFront(String reason) {
679 final ActivityStack recentsStack = getStack(RECENTS_STACK_ID);
680 if (recentsStack != null) {
681 recentsStack.moveToFront(reason);
682 }
683 }
684
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700685 /** Returns true if the focus activity was adjusted to the home stack top activity. */
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800686 boolean moveHomeStackTaskToTop(String reason) {
687 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700688
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700689 final ActivityRecord top = getHomeActivity();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700690 if (top == null) {
691 return false;
692 }
Chong Zhang6cda19c2016-06-14 19:07:56 -0700693 moveFocusableActivityStackToFrontLocked(top, reason);
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700694 return true;
Craig Mautner8e569572013-10-11 17:36:59 -0700695 }
696
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800697 boolean resumeHomeStackTask(ActivityRecord prev, String reason) {
Dianne Hackborn7622a0f2014-09-30 14:31:42 -0700698 if (!mService.mBooting && !mService.mBooted) {
699 // Not ready yet!
700 return false;
701 }
702
Craig Mautner84984fa2014-06-19 11:19:20 -0700703 if (prev != null) {
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -0700704 prev.getTask().setTaskToReturnTo(ACTIVITY_TYPE_STANDARD);
Craig Mautner84984fa2014-06-19 11:19:20 -0700705 }
706
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800707 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700708 ActivityRecord r = getHomeActivity();
Wale Ogunwaled046a012015-12-24 13:05:59 -0800709 final String myReason = reason + " resumeHomeStackTask";
710
Mark Lua56ea122015-10-08 13:31:01 +0800711 // Only resume home activity if isn't finishing.
712 if (r != null && !r.finishing) {
Chong Zhang6cda19c2016-06-14 19:07:56 -0700713 moveFocusableActivityStackToFrontLocked(r, myReason);
Wale Ogunwaled046a012015-12-24 13:05:59 -0800714 return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
Craig Mautner69ada552013-04-18 13:51:51 -0700715 }
Wale Ogunwaled046a012015-12-24 13:05:59 -0800716 return mService.startHomeActivityLocked(mCurrentUser, myReason);
Craig Mautner69ada552013-04-18 13:51:51 -0700717 }
718
Craig Mautner8d341ef2013-03-26 09:03:27 -0700719 TaskRecord anyTaskForIdLocked(int id) {
Wale Ogunwale0568aed2017-09-08 13:29:37 -0700720 return anyTaskForIdLocked(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE);
721 }
722
723 TaskRecord anyTaskForIdLocked(int id, @AnyTaskForIdMatchTaskMode int matchMode) {
724 return anyTaskForIdLocked(id, matchMode, null);
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700725 }
726
727 /**
Bryce Lee92b7b652017-04-03 08:33:11 -0700728 * Returns a {@link TaskRecord} for the input id if available. {@code null} otherwise.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700729 * @param id Id of the task we would like returned.
Winson Chung7900bee2017-03-10 08:59:25 -0800730 * @param matchMode The mode to match the given task id in.
Wale Ogunwale0568aed2017-09-08 13:29:37 -0700731 * @param aOptions The activity options to use for restoration. Can be null.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700732 */
Wale Ogunwale0568aed2017-09-08 13:29:37 -0700733 TaskRecord anyTaskForIdLocked(int id, @AnyTaskForIdMatchTaskMode int matchMode,
734 @Nullable ActivityOptions aOptions) {
Winson Chung7900bee2017-03-10 08:59:25 -0800735 // If there is a stack id set, ensure that we are attempting to actually restore a task
Wale Ogunwale0568aed2017-09-08 13:29:37 -0700736 // TODO: Don't really know if this is needed...
737 if (matchMode != MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE && aOptions != null) {
738 throw new IllegalArgumentException("Should not specify activity options for non-restore"
739 + " lookup");
Winson Chung7900bee2017-03-10 08:59:25 -0800740 }
741
Craig Mautnere0a38842013-12-16 16:14:02 -0800742 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800743 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800744 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800745 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
746 ActivityStack stack = stacks.get(stackNdx);
Bryce Lee92b7b652017-04-03 08:33:11 -0700747 final TaskRecord task = stack.taskForIdLocked(id);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800748 if (task != null) {
749 return task;
750 }
Craig Mautner8d341ef2013-03-26 09:03:27 -0700751 }
752 }
Wale Ogunwale7de05352014-12-12 15:21:33 -0800753
Winson Chung7900bee2017-03-10 08:59:25 -0800754 // If we are matching stack tasks only, return now
755 if (matchMode == MATCH_TASK_IN_STACKS_ONLY) {
Wale Ogunwale7de05352014-12-12 15:21:33 -0800756 return null;
757 }
758
Winson Chung7900bee2017-03-10 08:59:25 -0800759 // Otherwise, check the recent tasks and return if we find it there and we are not restoring
760 // the task from recents
761 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
Bryce Lee92b7b652017-04-03 08:33:11 -0700762 final TaskRecord task = mRecentTasks.taskForIdLocked(id);
763
764 if (task == null) {
765 if (DEBUG_RECENTS) {
Winson Chung7900bee2017-03-10 08:59:25 -0800766 Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
767 }
Bryce Lee92b7b652017-04-03 08:33:11 -0700768
769 return null;
770 }
771
772 if (matchMode == MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) {
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700773 return task;
774 }
775
Winson Chung7900bee2017-03-10 08:59:25 -0800776 // Implicitly, this case is MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
Wale Ogunwale0568aed2017-09-08 13:29:37 -0700777 if (!restoreRecentTaskLocked(task, aOptions)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700778 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
779 "Couldn't restore task id=" + id + " found in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800780 return null;
781 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700782 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800783 return task;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700784 }
785
Craig Mautner6170f732013-04-02 13:05:23 -0700786 ActivityRecord isInAnyStackLocked(IBinder token) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800787 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800788 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800789 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800790 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
791 final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
792 if (r != null) {
793 return r;
794 }
Craig Mautner6170f732013-04-02 13:05:23 -0700795 }
796 }
797 return null;
798 }
799
Tony Mak853304c2016-04-18 15:17:41 +0100800 /**
Robin Lee3fef1f22016-12-20 14:50:13 +0000801 * Detects whether we should show a lock screen in front of this task for a locked user.
802 * <p>
803 * We'll do this if either of the following holds:
804 * <ul>
805 * <li>The top activity explicitly belongs to {@param userId}.</li>
806 * <li>The top activity returns a result to an activity belonging to {@param userId}.</li>
807 * </ul>
808 *
809 * @return {@code true} if the top activity looks like it belongs to {@param userId}.
Tony Mak853304c2016-04-18 15:17:41 +0100810 */
Robin Lee3fef1f22016-12-20 14:50:13 +0000811 private boolean taskTopActivityIsUser(TaskRecord task, @UserIdInt int userId) {
812 // To handle the case that work app is in the task but just is not the top one.
813 final ActivityRecord activityRecord = task.getTopActivity();
814 final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null);
815
816 return (activityRecord != null && activityRecord.userId == userId)
817 || (resultTo != null && resultTo.userId == userId);
818 }
819
820 /**
821 * Find all visible task stacks containing {@param userId} and intercept them with an activity
822 * to block out the contents and possibly start a credential-confirming intent.
823 *
824 * @param userId user handle for the locked managed profile.
825 */
826 void lockAllProfileTasks(@UserIdInt int userId) {
827 mWindowManager.deferSurfaceLayout();
828 try {
829 final List<ActivityStack> stacks = getStacks();
830 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; stackNdx--) {
831 final List<TaskRecord> tasks = stacks.get(stackNdx).getAllTasks();
832 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) {
833 final TaskRecord task = tasks.get(taskNdx);
834
835 // Check the task for a top activity belonging to userId, or returning a result
836 // to an activity belonging to userId. Example case: a document picker for
837 // personal files, opened by a work app, should still get locked.
838 if (taskTopActivityIsUser(task, userId)) {
Robin Leec41f6ec2017-01-10 17:02:34 +0000839 mService.mTaskChangeNotificationController.notifyTaskProfileLocked(
840 task.taskId, userId);
Robin Lee3fef1f22016-12-20 14:50:13 +0000841 }
Tony Mak853304c2016-04-18 15:17:41 +0100842 }
843 }
Robin Lee3fef1f22016-12-20 14:50:13 +0000844 } finally {
845 mWindowManager.continueSurfaceLayout();
Tony Mak853304c2016-04-18 15:17:41 +0100846 }
Clara Bayarrif0649ce2016-01-14 12:30:42 +0000847 }
848
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800849 void setNextTaskIdForUserLocked(int taskId, int userId) {
850 final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
851 if (taskId > currentTaskId) {
852 mCurTaskIdForUser.put(userId, taskId);
Craig Mautneref73ee12014-04-23 11:45:37 -0700853 }
854 }
855
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700856 static int nextTaskIdForUser(int taskId, int userId) {
857 int nextTaskId = taskId + 1;
858 if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
859 // Wrap around as there will be smaller task ids that are available now.
860 nextTaskId -= MAX_TASK_IDS_PER_USER;
861 }
862 return nextTaskId;
863 }
864
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800865 int getNextTaskIdForUserLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800866 final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
867 // for a userId u, a taskId can only be in the range
868 // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
869 // 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 -0700870 int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800871 while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
Wale Ogunwale0568aed2017-09-08 13:29:37 -0700872 || anyTaskForIdLocked(
873 candidateTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) != null) {
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700874 candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800875 if (candidateTaskId == currentTaskId) {
876 // Something wrong!
877 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
878 throw new IllegalStateException("Cannot get an available task id."
879 + " Reached limit of " + MAX_TASK_IDS_PER_USER
880 + " running tasks per user.");
881 }
882 }
883 mCurTaskIdForUser.put(userId, candidateTaskId);
884 return candidateTaskId;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700885 }
886
Chong Zhang6cda19c2016-06-14 19:07:56 -0700887 ActivityRecord getResumedActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -0800888 ActivityStack stack = mFocusedStack;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700889 if (stack == null) {
890 return null;
891 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700892 ActivityRecord resumedActivity = stack.mResumedActivity;
893 if (resumedActivity == null || resumedActivity.app == null) {
894 resumedActivity = stack.mPausingActivity;
895 if (resumedActivity == null || resumedActivity.app == null) {
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -0700896 resumedActivity = stack.topRunningActivityLocked();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700897 }
898 }
899 return resumedActivity;
900 }
901
Dianne Hackbornff072722014-09-24 10:56:28 -0700902 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
Craig Mautner20e72272013-04-01 13:45:53 -0700903 final String processName = app.processName;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800904 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800905 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
906 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800907 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
908 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700909 if (!isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800910 continue;
911 }
Jorim Jaggiea039a82017-08-02 14:37:49 +0200912 stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
913 final ActivityRecord top = stack.topRunningActivityLocked();
914 final int size = mTmpActivityList.size();
915 for (int i = 0; i < size; i++) {
916 final ActivityRecord activity = mTmpActivityList.get(i);
917 if (activity.app == null && app.uid == activity.info.applicationInfo.uid
918 && processName.equals(activity.processName)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800919 try {
Jorim Jaggiea039a82017-08-02 14:37:49 +0200920 if (realStartActivityLocked(activity, app,
921 top == activity /* andResume */, true /* checkConfig */)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800922 didSomething = true;
923 }
Dianne Hackbornff072722014-09-24 10:56:28 -0700924 } catch (RemoteException e) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800925 Slog.w(TAG, "Exception in new application when starting activity "
Jorim Jaggiea039a82017-08-02 14:37:49 +0200926 + top.intent.getComponent().flattenToShortString(), e);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800927 throw e;
Craig Mautner20e72272013-04-01 13:45:53 -0700928 }
Craig Mautner20e72272013-04-01 13:45:53 -0700929 }
Craig Mautner20e72272013-04-01 13:45:53 -0700930 }
931 }
932 }
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700933 if (!didSomething) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700934 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700935 }
Craig Mautner20e72272013-04-01 13:45:53 -0700936 return didSomething;
937 }
938
939 boolean allResumedActivitiesIdle() {
Craig Mautnere0a38842013-12-16 16:14:02 -0800940 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
941 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800942 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
943 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700944 if (!isFocusedStack(stack) || stack.numActivities() == 0) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800945 continue;
946 }
947 final ActivityRecord resumedActivity = stack.mResumedActivity;
948 if (resumedActivity == null || !resumedActivity.idle) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700949 if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
Craig Mautner34b73df2014-01-12 21:11:08 -0800950 + stack.mStackId + " " + resumedActivity + " not idle");
Craig Mautner4a1cb222013-12-04 16:14:06 -0800951 return false;
952 }
Craig Mautner20e72272013-04-01 13:45:53 -0700953 }
954 }
Wei Wang65c7a152016-06-02 18:51:22 -0700955 // Send launch end powerhint when idle
956 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
Craig Mautner20e72272013-04-01 13:45:53 -0700957 return true;
958 }
959
Craig Mautnerde4ef022013-04-07 19:01:33 -0700960 boolean allResumedActivitiesComplete() {
Craig Mautnere0a38842013-12-16 16:14:02 -0800961 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
962 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800963 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
964 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700965 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800966 final ActivityRecord r = stack.mResumedActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700967 if (r != null && r.state != RESUMED) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800968 return false;
969 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700970 }
971 }
972 }
973 // TODO: Not sure if this should check if all Paused are complete too.
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700974 if (DEBUG_STACK) Slog.d(TAG_STACK,
Craig Mautner4a1cb222013-12-04 16:14:06 -0800975 "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
976 mLastFocusedStack + " to=" + mFocusedStack);
977 mLastFocusedStack = mFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -0700978 return true;
979 }
980
981 boolean allResumedActivitiesVisible() {
riddle_hsudb46d6b2015-04-01 18:58:07 +0800982 boolean foundResumed = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800983 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
984 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800985 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
986 final ActivityStack stack = stacks.get(stackNdx);
987 final ActivityRecord r = stack.mResumedActivity;
riddle_hsudb46d6b2015-04-01 18:58:07 +0800988 if (r != null) {
Bryce Lee4a194382017-04-04 14:32:48 -0700989 if (!r.nowVisible || mActivitiesWaitingForVisibleActivity.contains(r)) {
riddle_hsudb46d6b2015-04-01 18:58:07 +0800990 return false;
991 }
992 foundResumed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800993 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700994 }
995 }
riddle_hsudb46d6b2015-04-01 18:58:07 +0800996 return foundResumed;
Craig Mautnerde4ef022013-04-07 19:01:33 -0700997 }
998
Craig Mautner2acc3892013-09-23 10:28:14 -0700999 /**
1000 * Pause all activities in either all of the stacks or just the back stacks.
1001 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
Wale Ogunwale950faff2016-08-08 09:51:04 -07001002 * @param resuming The resuming activity.
1003 * @param dontWait The resuming activity isn't going to wait for all activities to be paused
1004 * before resuming.
Craig Mautner2acc3892013-09-23 10:28:14 -07001005 * @return true if any activity was paused as a result of this call.
1006 */
Wale Ogunwale950faff2016-08-08 09:51:04 -07001007 boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
Craig Mautnercf910b02013-04-23 11:23:27 -07001008 boolean someActivityPaused = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001009 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1010 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001011 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1012 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001013 if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001014 if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
Craig Mautner4a1cb222013-12-04 16:14:06 -08001015 " mResumedActivity=" + stack.mResumedActivity);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001016 someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
1017 dontWait);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001018 }
Craig Mautnercf910b02013-04-23 11:23:27 -07001019 }
1020 }
1021 return someActivityPaused;
1022 }
1023
Craig Mautnerde4ef022013-04-07 19:01:33 -07001024 boolean allPausedActivitiesComplete() {
Craig Mautnerac6f8432013-07-17 13:24:59 -07001025 boolean pausing = true;
Craig Mautnere0a38842013-12-16 16:14:02 -08001026 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1027 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001028 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1029 final ActivityStack stack = stacks.get(stackNdx);
1030 final ActivityRecord r = stack.mPausingActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001031 if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001032 if (DEBUG_STATES) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001033 Slog.d(TAG_STATES,
1034 "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001035 pausing = false;
1036 } else {
1037 return false;
1038 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001039 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001040 }
1041 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001042 return pausing;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001043 }
1044
Wale Ogunwale2be760d2016-02-17 11:16:10 -08001045 void cancelInitializingActivities() {
1046 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1047 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1048 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1049 stacks.get(stackNdx).cancelInitializingActivities();
1050 }
1051 }
1052 }
1053
Bryce Lee4a194382017-04-04 14:32:48 -07001054 void waitActivityVisible(ComponentName name, WaitResult result) {
1055 final WaitInfo waitInfo = new WaitInfo(name, result);
1056 mWaitingForActivityVisible.add(waitInfo);
1057 }
1058
1059 void cleanupActivity(ActivityRecord r) {
1060 // Make sure this record is no longer in the pending finishes list.
1061 // This could happen, for example, if we are trimming activities
1062 // down to the max limit while they are still waiting to finish.
1063 mFinishingActivities.remove(r);
1064 mActivitiesWaitingForVisibleActivity.remove(r);
1065
1066 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
Wale Ogunwale3270f172017-04-26 07:29:42 -07001067 if (mWaitingForActivityVisible.get(i).matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001068 mWaitingForActivityVisible.remove(i);
1069 }
1070 }
1071 }
1072
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001073 void reportActivityVisibleLocked(ActivityRecord r) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001074 sendWaitingVisibleReportLocked(r);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001075 }
1076
1077 void sendWaitingVisibleReportLocked(ActivityRecord r) {
1078 boolean changed = false;
Bryce Lee4a194382017-04-04 14:32:48 -07001079 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
1080 final WaitInfo w = mWaitingForActivityVisible.get(i);
Wale Ogunwale3270f172017-04-26 07:29:42 -07001081 if (w.matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001082 final WaitResult result = w.getResult();
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001083 changed = true;
Bryce Lee4a194382017-04-04 14:32:48 -07001084 result.timeout = false;
1085 result.who = w.getComponent();
1086 result.totalTime = SystemClock.uptimeMillis() - result.thisTime;
1087 result.thisTime = result.totalTime;
1088 mWaitingForActivityVisible.remove(w);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001089 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001090 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001091 if (changed) {
1092 mService.notifyAll();
1093 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001094 }
1095
Chong Zhang5022da32016-06-21 16:31:37 -07001096 void reportTaskToFrontNoLaunch(ActivityRecord r) {
1097 boolean changed = false;
1098 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1099 WaitResult w = mWaitingActivityLaunched.remove(i);
1100 if (w.who == null) {
1101 changed = true;
1102 // Set result to START_TASK_TO_FRONT so that startActivityMayWait() knows that
1103 // the starting activity ends up moving another activity to front, and it should
1104 // wait for this new activity to become visible instead.
1105 // Do not modify other fields.
1106 w.result = START_TASK_TO_FRONT;
1107 }
1108 }
1109 if (changed) {
1110 mService.notifyAll();
1111 }
1112 }
1113
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001114 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
1115 long thisTime, long totalTime) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001116 boolean changed = false;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001117 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
Craig Mautnerc64f73e2013-04-24 16:44:56 -07001118 WaitResult w = mWaitingActivityLaunched.remove(i);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001119 if (w.who == null) {
1120 changed = true;
1121 w.timeout = timeout;
1122 if (r != null) {
1123 w.who = new ComponentName(r.info.packageName, r.info.name);
1124 }
1125 w.thisTime = thisTime;
1126 w.totalTime = totalTime;
Chong Zhang5022da32016-06-21 16:31:37 -07001127 // Do not modify w.result.
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001128 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001129 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001130 if (changed) {
1131 mService.notifyAll();
1132 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001133 }
1134
Craig Mautner29219d92013-04-16 20:19:12 -07001135 ActivityRecord topRunningActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -08001136 final ActivityStack focusedStack = mFocusedStack;
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07001137 ActivityRecord r = focusedStack.topRunningActivityLocked();
Craig Mautner1602ec22013-05-12 10:24:27 -07001138 if (r != null) {
1139 return r;
Craig Mautner29219d92013-04-16 20:19:12 -07001140 }
Craig Mautner1602ec22013-05-12 10:24:27 -07001141
Andrii Kulian7318d632016-07-20 18:59:28 -07001142 // Look in other non-focused and non-home stacks.
Andrii Kulian7d95df42017-02-15 10:11:48 -08001143 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
1144
1145 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
1146 final int displayId = mTmpOrderedDisplayIds.get(i);
1147 final List<ActivityStack> stacks = mActivityDisplays.get(displayId).mStacks;
1148 if (stacks == null) {
1149 continue;
1150 }
1151 for (int j = stacks.size() - 1; j >= 0; --j) {
1152 final ActivityStack stack = stacks.get(j);
1153 if (stack != focusedStack && isFrontStackOnDisplay(stack) && stack.isFocusable()) {
1154 r = stack.topRunningActivityLocked();
1155 if (r != null) {
1156 return r;
1157 }
Craig Mautner29219d92013-04-16 20:19:12 -07001158 }
1159 }
1160 }
1161 return null;
1162 }
1163
Dianne Hackborn09233282014-04-30 11:33:59 -07001164 void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001165 // Gather all of the running tasks for each stack into runningTaskLists.
Craig Mautner4a1cb222013-12-04 16:14:06 -08001166 ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1167 new ArrayList<ArrayList<RunningTaskInfo>>();
Craig Mautnere0a38842013-12-16 16:14:02 -08001168 final int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001169 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08001170 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001171 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1172 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautner15df08a2015-04-01 12:17:18 -07001173 ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001174 runningTaskLists.add(stackTaskList);
Dianne Hackborn09233282014-04-30 11:33:59 -07001175 stack.getTasksLocked(stackTaskList, callingUid, allowed);
Craig Mautner20e72272013-04-01 13:45:53 -07001176 }
1177 }
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001178
1179 // The lists are already sorted from most recent to oldest. Just pull the most recent off
1180 // each list and add it to list. Stop when all lists are empty or maxNum reached.
1181 while (maxNum > 0) {
1182 long mostRecentActiveTime = Long.MIN_VALUE;
1183 ArrayList<RunningTaskInfo> selectedStackList = null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001184 final int numTaskLists = runningTaskLists.size();
1185 for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1186 ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001187 if (!stackTaskList.isEmpty()) {
1188 final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1189 if (lastActiveTime > mostRecentActiveTime) {
1190 mostRecentActiveTime = lastActiveTime;
1191 selectedStackList = stackTaskList;
1192 }
1193 }
1194 }
1195 if (selectedStackList != null) {
1196 list.add(selectedStackList.remove(0));
1197 --maxNum;
1198 } else {
1199 break;
1200 }
1201 }
Craig Mautner20e72272013-04-01 13:45:53 -07001202 }
1203
Todd Kennedy7440f172015-12-09 14:31:22 -08001204 ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1205 ProfilerInfo profilerInfo) {
1206 final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
Craig Mautner23ac33b2013-04-01 16:26:35 -07001207 if (aInfo != null) {
1208 // Store the found target back into the intent, because now that
1209 // we have it we never want to do this again. For example, if the
1210 // user navigates back to this point in the history, we should
1211 // always restart the exact same activity.
1212 intent.setComponent(new ComponentName(
1213 aInfo.applicationInfo.packageName, aInfo.name));
1214
1215 // Don't debug things in the system process
Man Caocfa78b22015-06-11 20:14:34 -07001216 if (!aInfo.processName.equals("system")) {
1217 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
Chong Zhangd25944e2016-06-09 16:15:27 -07001218 mService.setDebugApp(aInfo.processName, true, false);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001219 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001220
Tamas Berghammerdf6cb282016-01-29 12:07:00 +00001221 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1222 mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1223 }
1224
Man Caocfa78b22015-06-11 20:14:34 -07001225 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1226 mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1227 }
1228
1229 if (profilerInfo != null) {
Jeff Hao1b012d32014-08-20 10:35:34 -07001230 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001231 }
1232 }
Todd Kennedyb3b431302017-03-20 16:05:48 -07001233 final String intentLaunchToken = intent.getLaunchToken();
1234 if (aInfo.launchToken == null && intentLaunchToken != null) {
1235 aInfo.launchToken = intentLaunchToken;
1236 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001237 }
1238 return aInfo;
1239 }
1240
Todd Kennedy7440f172015-12-09 14:31:22 -08001241 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
Kenny Guyb1b30262016-02-09 16:02:35 +00001242 return resolveIntent(intent, resolvedType, userId, 0);
1243 }
1244
1245 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
Todd Kennedy4d1de7d2017-02-23 10:32:18 -08001246 synchronized (mService) {
1247 return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001248 PackageManager.MATCH_INSTANT | PackageManager.MATCH_DEFAULT_ONLY | flags
Kenny Guyb1b30262016-02-09 16:02:35 +00001249 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Todd Kennedy7440f172015-12-09 14:31:22 -08001250 }
Todd Kennedy7440f172015-12-09 14:31:22 -08001251 }
1252
1253 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1254 ProfilerInfo profilerInfo, int userId) {
1255 final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1256 return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1257 }
1258
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001259 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1260 boolean andResume, boolean checkConfig) throws RemoteException {
1261
1262 if (!allPausedActivitiesComplete()) {
1263 // While there are activities pausing we skipping starting any new activities until
1264 // pauses are complete. NOTE: that we also do this for activities that are starting in
1265 // the paused state because they will first be resumed then paused on the client side.
1266 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1267 "realStartActivityLocked: Skipping start of r=" + r
1268 + " some activities pausing...");
1269 return false;
1270 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001271
Bryce Leeaf691c02017-03-20 14:20:22 -07001272 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07001273 final ActivityStack stack = task.getStack();
chaviw59b98852017-06-13 12:05:44 -07001274
1275 beginDeferResume();
1276
Craig Mautner2420ead2013-04-01 17:13:20 -07001277 try {
chaviw59b98852017-06-13 12:05:44 -07001278 r.startFreezingScreenLocked(app, 0);
1279
1280 // schedule launch ticks to collect information about slow apps.
1281 r.startLaunchTickingLocked();
1282
1283 r.app = app;
1284
Jorim Jaggi838c2452017-08-28 15:44:43 +02001285 if (mKeyguardController.isKeyguardLocked()) {
1286 r.notifyUnknownVisibilityLaunched();
1287 }
1288
chaviw59b98852017-06-13 12:05:44 -07001289 // Have the window manager re-evaluate the orientation of the screen based on the new
1290 // activity order. Note that as a result of this, it can call back into the activity
1291 // manager with a new orientation. We don't care about that, because the activity is
1292 // not currently running so we are just restarting it anyway.
1293 if (checkConfig) {
1294 final int displayId = r.getDisplayId();
1295 final Configuration config = mWindowManager.updateOrientationFromAppTokens(
1296 getDisplayOverrideConfiguration(displayId),
1297 r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
1298 // Deferring resume here because we're going to launch new activity shortly.
1299 // We don't want to perform a redundant launch of the same record while ensuring
1300 // configurations and trying to resume top activity of focused stack.
1301 mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
1302 displayId);
Craig Mautner2420ead2013-04-01 17:13:20 -07001303 }
chaviw59b98852017-06-13 12:05:44 -07001304
1305 if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */,
1306 true /* isTop */)) {
1307 // We only set the visibility to true if the activity is allowed to be visible
1308 // based on
1309 // keyguard state. This avoids setting this into motion in window manager that is
1310 // later cancelled due to later calls to ensure visible activities that set
1311 // visibility back to false.
1312 r.setVisibility(true);
Craig Mautner2420ead2013-04-01 17:13:20 -07001313 }
chaviw59b98852017-06-13 12:05:44 -07001314
chaviw59b98852017-06-13 12:05:44 -07001315 final int applicationInfoUid =
1316 (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
1317 if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
1318 Slog.wtf(TAG,
1319 "User ID for activity changing for " + r
1320 + " appInfo.uid=" + r.appInfo.uid
1321 + " info.ai.uid=" + applicationInfoUid
1322 + " old=" + r.app + " new=" + app);
1323 }
1324
1325 app.waitingToKill = null;
1326 r.launchCount++;
1327 r.lastLaunchTime = SystemClock.uptimeMillis();
1328
1329 if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1330
1331 int idx = app.activities.indexOf(r);
1332 if (idx < 0) {
1333 app.activities.add(r);
1334 }
1335 mService.updateLruProcessLocked(app, true, null);
1336 mService.updateOomAdjLocked();
1337
1338 if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1339 task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
Benjamin Franza83859f2017-07-03 16:34:14 +01001340 mService.mLockTaskController.startLockTaskMode(task, false, 0 /* blank UID */);
chaviw59b98852017-06-13 12:05:44 -07001341 }
1342
1343 try {
1344 if (app.thread == null) {
1345 throw new RemoteException();
1346 }
1347 List<ResultInfo> results = null;
1348 List<ReferrerIntent> newIntents = null;
1349 if (andResume) {
1350 // We don't need to deliver new intents and/or set results if activity is going
1351 // to pause immediately after launch.
1352 results = r.results;
1353 newIntents = r.newIntents;
1354 }
1355 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1356 "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1357 + " newIntents=" + newIntents + " andResume=" + andResume);
1358 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
1359 System.identityHashCode(r), task.taskId, r.shortComponentName);
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07001360 if (r.isActivityTypeHome()) {
chaviw59b98852017-06-13 12:05:44 -07001361 // Home process is the root process of the task.
1362 mService.mHomeProcess = task.mActivities.get(0).app;
1363 }
1364 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
1365 PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
1366 r.sleeping = false;
1367 r.forceNewConfig = false;
1368 mService.showUnsupportedZoomDialogIfNeededLocked(r);
1369 mService.showAskCompatModeDialogLocked(r);
1370 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1371 ProfilerInfo profilerInfo = null;
1372 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1373 if (mService.mProfileProc == null || mService.mProfileProc == app) {
1374 mService.mProfileProc = app;
Andreas Gampe2b073a02017-06-22 17:28:57 -07001375 ProfilerInfo profilerInfoSvc = mService.mProfilerInfo;
1376 if (profilerInfoSvc != null && profilerInfoSvc.profileFile != null) {
1377 if (profilerInfoSvc.profileFd != null) {
chaviw59b98852017-06-13 12:05:44 -07001378 try {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001379 profilerInfoSvc.profileFd = profilerInfoSvc.profileFd.dup();
chaviw59b98852017-06-13 12:05:44 -07001380 } catch (IOException e) {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001381 profilerInfoSvc.closeFd();
Craig Mautner2568c3a2015-03-26 14:22:34 -07001382 }
1383 }
chaviw59b98852017-06-13 12:05:44 -07001384
Andreas Gampe2b073a02017-06-22 17:28:57 -07001385 profilerInfo = new ProfilerInfo(profilerInfoSvc);
Craig Mautner2420ead2013-04-01 17:13:20 -07001386 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001387 }
1388 }
Adam Powellcfbe9be2013-11-06 14:58:58 -08001389
chaviw59b98852017-06-13 12:05:44 -07001390 app.hasShownUi = true;
1391 app.pendingUiClean = true;
1392 app.forceProcessStateUpTo(mService.mTopProcessState);
1393 // Because we could be starting an Activity in the system process this may not go
1394 // across a Binder interface which would create a new Configuration. Consequently
1395 // we have to always create a new Configuration here.
Bryce Leea163b762017-01-24 11:05:01 -08001396
chaviw59b98852017-06-13 12:05:44 -07001397 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
1398 mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
1399 r.setLastReportedConfiguration(mergedConfiguration);
Bryce Leea163b762017-01-24 11:05:01 -08001400
chaviw59b98852017-06-13 12:05:44 -07001401 logIfTransactionTooLarge(r.intent, r.icicle);
1402 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1403 System.identityHashCode(r), r.info,
1404 // TODO: Have this take the merged configuration instead of separate global
1405 // and override configs.
1406 mergedConfiguration.getGlobalConfiguration(),
1407 mergedConfiguration.getOverrideConfiguration(), r.compat,
1408 r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1409 r.persistentState, results, newIntents, !andResume,
1410 mService.isNextTransitionForward(), profilerInfo);
Craig Mautner2420ead2013-04-01 17:13:20 -07001411
chaviw59b98852017-06-13 12:05:44 -07001412 if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1413 // This may be a heavy-weight process! Note that the package
1414 // manager will ensure that only activity can run in the main
1415 // process of the .apk, which is the only thing that will be
1416 // considered heavy-weight.
1417 if (app.processName.equals(app.info.packageName)) {
1418 if (mService.mHeavyWeightProcess != null
1419 && mService.mHeavyWeightProcess != app) {
1420 Slog.w(TAG, "Starting new heavy weight process " + app
1421 + " when already running "
1422 + mService.mHeavyWeightProcess);
1423 }
1424 mService.mHeavyWeightProcess = app;
1425 Message msg = mService.mHandler.obtainMessage(
1426 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1427 msg.obj = r;
1428 mService.mHandler.sendMessage(msg);
Craig Mautner2420ead2013-04-01 17:13:20 -07001429 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001430 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001431
chaviw59b98852017-06-13 12:05:44 -07001432 } catch (RemoteException e) {
1433 if (r.launchFailed) {
1434 // This is the second time we failed -- finish activity
1435 // and give up.
1436 Slog.e(TAG, "Second failure launching "
1437 + r.intent.getComponent().flattenToShortString()
1438 + ", giving up", e);
1439 mService.appDiedLocked(app);
1440 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1441 "2nd-crash", false);
1442 return false;
1443 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001444
chaviw59b98852017-06-13 12:05:44 -07001445 // This is the first time we failed -- restart process and
1446 // retry.
1447 r.launchFailed = true;
1448 app.activities.remove(r);
1449 throw e;
1450 }
1451 } finally {
1452 endDeferResume();
Craig Mautner2420ead2013-04-01 17:13:20 -07001453 }
1454
1455 r.launchFailed = false;
1456 if (stack.updateLRUListLocked(r)) {
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07001457 Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
Craig Mautner2420ead2013-04-01 17:13:20 -07001458 }
1459
chaviw59b98852017-06-13 12:05:44 -07001460 if (andResume && readyToResume()) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001461 // As part of the process of launching, ActivityThread also performs
1462 // a resume.
1463 stack.minimalResumeActivityLocked(r);
1464 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001465 // This activity is not starting in the resumed state... which should look like we asked
Wale Ogunwale919a05d2017-04-13 00:36:34 +00001466 // it to pause+stop (but remain visible), and it has done so and reported back the
Wale Ogunwaled046a012015-12-24 13:05:59 -08001467 // current icicle and other state.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001468 if (DEBUG_STATES) Slog.v(TAG_STATES,
Wale Ogunwaled046a012015-12-24 13:05:59 -08001469 "Moving to PAUSED: " + r + " (starting in paused state)");
1470 r.state = PAUSED;
Craig Mautner2420ead2013-04-01 17:13:20 -07001471 }
1472
1473 // Launch the new version setup screen if needed. We do this -after-
1474 // launching the initial activity (that is, home), so that it can have
1475 // a chance to initialize itself while in the background, making the
1476 // switch back to it faster and look better.
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001477 if (isFocusedStack(stack)) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001478 mService.startSetupActivityLocked();
1479 }
1480
Dianne Hackborn465fa392014-09-14 14:21:18 -07001481 // Update any services we are bound to that might care about whether
1482 // their client may have activities.
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001483 if (r.app != null) {
1484 mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1485 }
Dianne Hackborn465fa392014-09-14 14:21:18 -07001486
Craig Mautner2420ead2013-04-01 17:13:20 -07001487 return true;
1488 }
1489
Sudheer Shankafab200f2017-05-17 20:41:53 -07001490 private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
1491 int extrasSize = 0;
1492 if (intent != null) {
1493 final Bundle extras = intent.getExtras();
1494 if (extras != null) {
1495 extrasSize = extras.getSize();
1496 }
1497 }
1498 int icicleSize = (icicle == null ? 0 : icicle.getSize());
1499 if (extrasSize + icicleSize > 200000) {
1500 Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
1501 + ", icicle size: " + icicleSize);
1502 }
1503 }
1504
Craig Mautnere79d42682013-04-01 19:01:53 -07001505 void startSpecificActivityLocked(ActivityRecord r,
George Mount2c92c972014-03-20 09:38:23 -07001506 boolean andResume, boolean checkConfig) {
Craig Mautnere79d42682013-04-01 19:01:53 -07001507 // Is this activity's application already running?
1508 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001509 r.info.applicationInfo.uid, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001510
Andrii Kulian02b7a832016-10-06 23:11:56 -07001511 r.getStack().setLaunchTime(r);
Craig Mautnere79d42682013-04-01 19:01:53 -07001512
1513 if (app != null && app.thread != null) {
1514 try {
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001515 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1516 || !"android".equals(r.info.packageName)) {
1517 // Don't add this if it is a platform component that is marked
1518 // to run in multiple processes, because this is actually
1519 // part of the framework so doesn't make sense to track as a
1520 // separate apk in the process.
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001521 app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1522 mService.mProcessStats);
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001523 }
George Mount2c92c972014-03-20 09:38:23 -07001524 realStartActivityLocked(r, app, andResume, checkConfig);
Craig Mautnere79d42682013-04-01 19:01:53 -07001525 return;
1526 } catch (RemoteException e) {
1527 Slog.w(TAG, "Exception when starting activity "
1528 + r.intent.getComponent().flattenToShortString(), e);
1529 }
1530
1531 // If a dead object exception was thrown -- fall through to
1532 // restart the application.
1533 }
1534
1535 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001536 "activity", r.intent.getComponent(), false, false, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001537 }
1538
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001539 boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001540 String resultWho, int requestCode, int callingPid, int callingUid,
1541 String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
Jorim Jaggi2adba072016-03-03 13:43:39 +01001542 ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001543 final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1544 callingUid);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001545 if (startAnyPerm == PERMISSION_GRANTED) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001546 return true;
1547 }
1548 final int componentRestriction = getComponentRestrictionForCallingPackage(
1549 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1550 final int actionRestriction = getActionRestrictionForCallingPackage(
1551 intent.getAction(), callingPackage, callingPid, callingUid);
1552 if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1553 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1554 if (resultRecord != null) {
1555 resultStack.sendActivityResultLocked(-1,
1556 resultRecord, resultWho, requestCode,
1557 Activity.RESULT_CANCELED, null);
1558 }
1559 final String msg;
1560 if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1561 msg = "Permission Denial: starting " + intent.toString()
1562 + " from " + callerApp + " (pid=" + callingPid
1563 + ", uid=" + callingUid + ")" + " with revoked permission "
1564 + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1565 } else if (!aInfo.exported) {
1566 msg = "Permission Denial: starting " + intent.toString()
1567 + " from " + callerApp + " (pid=" + callingPid
1568 + ", uid=" + callingUid + ")"
1569 + " not exported from uid " + aInfo.applicationInfo.uid;
1570 } else {
1571 msg = "Permission Denial: starting " + intent.toString()
1572 + " from " + callerApp + " (pid=" + callingPid
1573 + ", uid=" + callingUid + ")"
1574 + " requires " + aInfo.permission;
1575 }
1576 Slog.w(TAG, msg);
1577 throw new SecurityException(msg);
1578 }
1579
1580 if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1581 final String message = "Appop Denial: starting " + intent.toString()
1582 + " from " + callerApp + " (pid=" + callingPid
1583 + ", uid=" + callingUid + ")"
1584 + " requires " + AppOpsManager.permissionToOp(
1585 ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1586 Slog.w(TAG, message);
1587 return false;
1588 } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1589 final String message = "Appop Denial: starting " + intent.toString()
1590 + " from " + callerApp + " (pid=" + callingPid
1591 + ", uid=" + callingUid + ")"
1592 + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1593 Slog.w(TAG, message);
1594 return false;
1595 }
Andrii Kulian16802aa2016-11-02 12:21:33 -07001596 if (options != null) {
1597 if (options.getLaunchTaskId() != INVALID_STACK_ID) {
1598 final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1599 callingPid, callingUid);
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001600 if (startInTaskPerm == PERMISSION_DENIED) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07001601 final String msg = "Permission Denial: starting " + intent.toString()
1602 + " from " + callerApp + " (pid=" + callingPid
1603 + ", uid=" + callingUid + ") with launchTaskId="
1604 + options.getLaunchTaskId();
1605 Slog.w(TAG, msg);
1606 throw new SecurityException(msg);
1607 }
1608 }
1609 // Check if someone tries to launch an activity on a private display with a different
1610 // owner.
1611 final int launchDisplayId = options.getLaunchDisplayId();
Andrii Kulian02689a72017-07-06 14:28:59 -07001612 if (launchDisplayId != INVALID_DISPLAY && !isCallerAllowedToLaunchOnDisplay(callingPid,
1613 callingUid, launchDisplayId, aInfo)) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001614 final String msg = "Permission Denial: starting " + intent.toString()
1615 + " from " + callerApp + " (pid=" + callingPid
1616 + ", uid=" + callingUid + ") with launchDisplayId="
1617 + launchDisplayId;
1618 Slog.w(TAG, msg);
1619 throw new SecurityException(msg);
Jorim Jaggi2adba072016-03-03 13:43:39 +01001620 }
1621 }
1622
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001623 return true;
1624 }
1625
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001626 /** Check if caller is allowed to launch activities on specified display. */
Andrii Kulian02689a72017-07-06 14:28:59 -07001627 boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId,
1628 ActivityInfo aInfo) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001629 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId
1630 + " callingPid=" + callingPid + " callingUid=" + callingUid);
1631
Andrii Kulian02689a72017-07-06 14:28:59 -07001632 if (callingPid == -1 && callingUid == -1) {
1633 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: no caller info, skip check");
1634 return true;
1635 }
1636
Andrii Kulian62e6f252017-05-30 22:46:53 -07001637 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(launchDisplayId);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001638 if (activityDisplay == null) {
1639 Slog.w(TAG, "Launch on display check: display not found");
1640 return false;
1641 }
1642
Andrii Kulian02689a72017-07-06 14:28:59 -07001643 // Check if the caller has enough privileges to embed activities and launch to private
1644 // displays.
Andrii Kulian3a95edc2017-06-28 16:21:07 -07001645 final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001646 callingUid);
1647 if (startAnyPerm == PERMISSION_GRANTED) {
1648 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1649 + " allow launch any on display");
1650 return true;
1651 }
1652
Andrii Kulian8f070292017-09-12 22:56:49 -07001653 // Check if caller is already present on display
1654 final boolean uidPresentOnDisplay = activityDisplay.isUidPresent(callingUid);
1655
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001656 final int displayOwnerUid = activityDisplay.mDisplay.getOwnerUid();
1657 if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL && displayOwnerUid != SYSTEM_UID
1658 && displayOwnerUid != aInfo.applicationInfo.uid) {
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001659 // Limit launching on virtual displays, because their contents can be read from Surface
1660 // by apps that created them.
Andrii Kulian02689a72017-07-06 14:28:59 -07001661 if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
1662 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1663 + " disallow launch on virtual display for not-embedded activity.");
1664 return false;
1665 }
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001666 // Check if the caller is allowed to embed activities from other apps.
1667 if (mService.checkPermission(ACTIVITY_EMBEDDING, callingPid, callingUid)
Andrii Kulian8f070292017-09-12 22:56:49 -07001668 == PERMISSION_DENIED && !uidPresentOnDisplay) {
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001669 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1670 + " disallow activity embedding without permission.");
1671 return false;
1672 }
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001673 }
1674
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001675 if (!activityDisplay.isPrivate()) {
1676 // Anyone can launch on a public display.
1677 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1678 + " allow launch on public display");
1679 return true;
1680 }
1681
1682 // Check if the caller is the owner of the display.
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001683 if (displayOwnerUid == callingUid) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001684 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1685 + " allow launch for owner of the display");
1686 return true;
1687 }
1688
Andrii Kulian8f070292017-09-12 22:56:49 -07001689 if (uidPresentOnDisplay) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001690 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1691 + " allow launch for caller present on the display");
1692 return true;
1693 }
1694
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001695 Slog.w(TAG, "Launch on display check: denied");
1696 return false;
1697 }
1698
1699 /** Update lists of UIDs that are present on displays and have access to them. */
1700 void updateUIDsPresentOnDisplay() {
1701 mDisplayAccessUIDs.clear();
1702 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1703 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
David Stevens82ea6cb2017-03-03 16:18:50 -08001704 // Only bother calculating the whitelist for private displays
1705 if (activityDisplay.isPrivate()) {
1706 mDisplayAccessUIDs.append(
1707 activityDisplay.mDisplayId, activityDisplay.getPresentUIDs());
1708 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001709 }
1710 // Store updated lists in DisplayManager. Callers from outside of AM should get them there.
1711 mDisplayManagerInternal.setDisplayAccessUIDs(mDisplayAccessUIDs);
1712 }
1713
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001714 UserInfo getUserInfo(int userId) {
Clara Bayarrif7fea162015-10-22 16:09:52 +01001715 final long identity = Binder.clearCallingIdentity();
1716 try {
1717 return UserManager.get(mService.mContext).getUserInfo(userId);
1718 } finally {
1719 Binder.restoreCallingIdentity(identity);
1720 }
1721 }
1722
Svet Ganov99b60432015-06-27 13:15:22 -07001723 private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001724 String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001725 if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1726 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001727 == PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001728 return ACTIVITY_RESTRICTION_PERMISSION;
1729 }
1730
Christopher Tateff7add02015-08-17 10:23:22 -07001731 if (activityInfo.permission == null) {
1732 return ACTIVITY_RESTRICTION_NONE;
1733 }
1734
Svet Ganov99b60432015-06-27 13:15:22 -07001735 final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1736 if (opCode == AppOpsManager.OP_NONE) {
1737 return ACTIVITY_RESTRICTION_NONE;
1738 }
1739
1740 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1741 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001742 if (!ignoreTargetSecurity) {
1743 return ACTIVITY_RESTRICTION_APPOP;
1744 }
Svet Ganov99b60432015-06-27 13:15:22 -07001745 }
1746
1747 return ACTIVITY_RESTRICTION_NONE;
1748 }
1749
Svetoslav7008b512015-06-24 18:47:07 -07001750 private int getActionRestrictionForCallingPackage(String action,
1751 String callingPackage, int callingPid, int callingUid) {
1752 if (action == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001753 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001754 }
1755
1756 String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1757 if (permission == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001758 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001759 }
1760
1761 final PackageInfo packageInfo;
1762 try {
1763 packageInfo = mService.mContext.getPackageManager()
1764 .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1765 } catch (PackageManager.NameNotFoundException e) {
1766 Slog.i(TAG, "Cannot find package info for " + callingPackage);
Svet Ganov99b60432015-06-27 13:15:22 -07001767 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001768 }
1769
1770 if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
Svet Ganov99b60432015-06-27 13:15:22 -07001771 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001772 }
1773
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001774 if (mService.checkPermission(permission, callingPid, callingUid) == PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001775 return ACTIVITY_RESTRICTION_PERMISSION;
Svetoslav7008b512015-06-24 18:47:07 -07001776 }
1777
1778 final int opCode = AppOpsManager.permissionToOpCode(permission);
1779 if (opCode == AppOpsManager.OP_NONE) {
Svet Ganov99b60432015-06-27 13:15:22 -07001780 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001781 }
1782
1783 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1784 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001785 return ACTIVITY_RESTRICTION_APPOP;
Svetoslav7008b512015-06-24 18:47:07 -07001786 }
1787
Svet Ganov99b60432015-06-27 13:15:22 -07001788 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001789 }
1790
Dianne Hackborn3d07c942015-03-13 18:02:54 -07001791 void setLaunchSource(int uid) {
1792 mLaunchingActivity.setWorkSource(new WorkSource(uid));
1793 }
1794
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001795 void acquireLaunchWakelock() {
1796 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1797 throw new IllegalStateException("Calling must be system uid");
1798 }
1799 mLaunchingActivity.acquire();
1800 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1801 // To be safe, don't allow the wake lock to be held for too long.
1802 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1803 }
1804 }
1805
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001806 /**
1807 * Called when the frontmost task is idle.
1808 * @return the state of mService.mBooting before this was called.
1809 */
1810 private boolean checkFinishBootingLocked() {
1811 final boolean booting = mService.mBooting;
1812 boolean enableScreen = false;
1813 mService.mBooting = false;
1814 if (!mService.mBooted) {
1815 mService.mBooted = true;
1816 enableScreen = true;
1817 }
1818 if (booting || enableScreen) {
1819 mService.postFinishBooting(booting, enableScreen);
1820 }
1821 return booting;
1822 }
1823
Craig Mautnerf3333272013-04-22 10:55:53 -07001824 // Checked.
1825 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
Winson Chung4dabf232017-01-25 13:25:22 -08001826 boolean processPausingActivities, Configuration config) {
Wale Ogunwalee23149f2015-03-06 15:39:44 -08001827 if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001828
Craig Mautnerf3333272013-04-22 10:55:53 -07001829 ArrayList<ActivityRecord> finishes = null;
Amith Yamasani37a40c22015-06-17 13:25:42 -07001830 ArrayList<UserState> startingUsers = null;
Craig Mautnerf3333272013-04-22 10:55:53 -07001831 int NS = 0;
1832 int NF = 0;
Craig Mautnerf3333272013-04-22 10:55:53 -07001833 boolean booting = false;
Craig Mautnerf3333272013-04-22 10:55:53 -07001834 boolean activityRemoved = false;
1835
Wale Ogunwale7d701172015-03-11 15:36:30 -07001836 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001837 if (r != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001838 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1839 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07001840 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1841 r.finishLaunchTickingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001842 if (fromTimeout) {
1843 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
Craig Mautnerf3333272013-04-22 10:55:53 -07001844 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001845
1846 // This is a hack to semi-deal with a race condition
1847 // in the client where it can be constructed with a
1848 // newer configuration from when we asked it to launch.
1849 // We'll update with whatever configuration it now says
1850 // it used to launch.
1851 if (config != null) {
Bryce Leea163b762017-01-24 11:05:01 -08001852 r.setLastReportedGlobalConfiguration(config);
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001853 }
1854
1855 // We are now idle. If someone is waiting for a thumbnail from
1856 // us, we can now deliver.
1857 r.idle = true;
1858
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001859 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001860 if (isFocusedStack(r.getStack()) || fromTimeout) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001861 booting = checkFinishBootingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001862 }
1863 }
1864
1865 if (allResumedActivitiesIdle()) {
1866 if (r != null) {
1867 mService.scheduleAppGcsLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001868 }
1869
1870 if (mLaunchingActivity.isHeld()) {
1871 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1872 if (VALIDATE_WAKE_LOCK_CALLER &&
1873 Binder.getCallingUid() != Process.myUid()) {
1874 throw new IllegalStateException("Calling must be system uid");
1875 }
1876 mLaunchingActivity.release();
1877 }
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07001878 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerf3333272013-04-22 10:55:53 -07001879 }
1880
1881 // Atomically retrieve all of the other things to do.
Winson Chung4dabf232017-01-25 13:25:22 -08001882 final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
1883 true /* remove */, processPausingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001884 NS = stops != null ? stops.size() : 0;
Wale Ogunwale7d701172015-03-11 15:36:30 -07001885 if ((NF = mFinishingActivities.size()) > 0) {
1886 finishes = new ArrayList<>(mFinishingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001887 mFinishingActivities.clear();
1888 }
1889
Craig Mautnerf3333272013-04-22 10:55:53 -07001890 if (mStartingUsers.size() > 0) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07001891 startingUsers = new ArrayList<>(mStartingUsers);
Craig Mautnerf3333272013-04-22 10:55:53 -07001892 mStartingUsers.clear();
1893 }
1894
Craig Mautnerf3333272013-04-22 10:55:53 -07001895 // Stop any activities that are scheduled to do so but have been
1896 // waiting for the next one to start.
1897 for (int i = 0; i < NS; i++) {
1898 r = stops.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001899 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001900 if (stack != null) {
1901 if (r.finishing) {
1902 stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1903 } else {
1904 stack.stopActivityLocked(r);
1905 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001906 }
1907 }
1908
1909 // Finish any activities that are scheduled to do so but have been
1910 // waiting for the next one to start.
1911 for (int i = 0; i < NF; i++) {
1912 r = finishes.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001913 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001914 if (stack != null) {
1915 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1916 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001917 }
1918
Dianne Hackborn7622a0f2014-09-30 14:31:42 -07001919 if (!booting) {
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001920 // Complete user switch
1921 if (startingUsers != null) {
1922 for (int i = 0; i < startingUsers.size(); i++) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001923 mService.mUserController.finishUserSwitch(startingUsers.get(i));
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001924 }
1925 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001926 }
1927
1928 mService.trimApplications();
1929 //dump();
1930 //mWindowManager.dump();
1931
Craig Mautnerf3333272013-04-22 10:55:53 -07001932 if (activityRemoved) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001933 resumeFocusedStackTopActivityLocked();
Craig Mautnerf3333272013-04-22 10:55:53 -07001934 }
1935
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001936 return r;
Craig Mautnerf3333272013-04-22 10:55:53 -07001937 }
1938
Craig Mautner8e569572013-10-11 17:36:59 -07001939 boolean handleAppDiedLocked(ProcessRecord app) {
Craig Mautner19091252013-10-05 00:03:53 -07001940 boolean hasVisibleActivities = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001941 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1942 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001943 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1944 hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
1945 }
Craig Mautner6b74cb52013-09-27 17:02:21 -07001946 }
Craig Mautner19091252013-10-05 00:03:53 -07001947 return hasVisibleActivities;
Craig Mautner8d341ef2013-03-26 09:03:27 -07001948 }
1949
1950 void closeSystemDialogsLocked() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001951 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1952 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001953 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1954 stacks.get(stackNdx).closeSystemDialogsLocked();
1955 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07001956 }
1957 }
1958
Craig Mautner93529a42013-10-04 15:03:13 -07001959 void removeUserLocked(int userId) {
Craig Mautner4f1df4f2013-10-15 15:44:14 -07001960 mUserStackInFront.delete(userId);
Craig Mautner93529a42013-10-04 15:03:13 -07001961 }
1962
Craig Mautner8d341ef2013-03-26 09:03:27 -07001963 /**
Chong Zhang45c25ce2015-08-10 22:18:26 -07001964 * Update the last used stack id for non-current user (current user's last
1965 * used stack is the focused stack)
1966 */
1967 void updateUserStackLocked(int userId, ActivityStack stack) {
1968 if (userId != mCurrentUser) {
1969 mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
1970 }
1971 }
1972
1973 /**
Craig Mautner8d341ef2013-03-26 09:03:27 -07001974 * @return true if some activity was finished (or would have finished if doit were true).
1975 */
Wale Ogunwale540e1232015-05-01 15:35:39 -07001976 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
1977 boolean doit, boolean evenPersistent, int userId) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07001978 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001979 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1980 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
louis_chang8f0555a2015-10-27 10:45:53 +08001981 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001982 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale540e1232015-05-01 15:35:39 -07001983 if (stack.finishDisabledPackageActivitiesLocked(
1984 packageName, filterByClasses, doit, evenPersistent, userId)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001985 didSomething = true;
1986 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07001987 }
1988 }
1989 return didSomething;
1990 }
1991
Dianne Hackborna413dc02013-07-12 12:02:55 -07001992 void updatePreviousProcessLocked(ActivityRecord r) {
1993 // Now that this process has stopped, we may want to consider
1994 // it to be the previous app to try to keep around in case
1995 // the user wants to return to it.
1996
1997 // First, found out what is currently the foreground app, so that
1998 // we don't blow away the previous app if this activity is being
1999 // hosted by the process that is actually still the foreground.
2000 ProcessRecord fgApp = null;
Craig Mautnere0a38842013-12-16 16:14:02 -08002001 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2002 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002003 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2004 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07002005 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002006 if (stack.mResumedActivity != null) {
2007 fgApp = stack.mResumedActivity.app;
2008 } else if (stack.mPausingActivity != null) {
2009 fgApp = stack.mPausingActivity.app;
2010 }
2011 break;
Dianne Hackborna413dc02013-07-12 12:02:55 -07002012 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07002013 }
2014 }
2015
2016 // Now set this one as the previous process, only if that really
2017 // makes sense to.
2018 if (r.app != null && fgApp != null && r.app != fgApp
2019 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
Craig Mautner4ef26932013-09-18 15:15:52 -07002020 && r.app != mService.mHomeProcess) {
Dianne Hackborna413dc02013-07-12 12:02:55 -07002021 mService.mPreviousProcess = r.app;
2022 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
2023 }
2024 }
2025
Wale Ogunwaled046a012015-12-24 13:05:59 -08002026 boolean resumeFocusedStackTopActivityLocked() {
2027 return resumeFocusedStackTopActivityLocked(null, null, null);
Craig Mautner05d29032013-05-03 13:40:13 -07002028 }
2029
Wale Ogunwaled046a012015-12-24 13:05:59 -08002030 boolean resumeFocusedStackTopActivityLocked(
Chong Zhang280d3322015-11-03 17:27:26 -08002031 ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
chaviw59b98852017-06-13 12:05:44 -07002032
2033 if (!readyToResume()) {
2034 return false;
2035 }
2036
Wale Ogunwaled046a012015-12-24 13:05:59 -08002037 if (targetStack != null && isFocusedStack(targetStack)) {
2038 return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
Craig Mautner05d29032013-05-03 13:40:13 -07002039 }
chaviw59b98852017-06-13 12:05:44 -07002040
Wale Ogunwale06579d62016-04-30 15:29:06 -07002041 final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2042 if (r == null || r.state != RESUMED) {
2043 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
skuhne@google.com1b974dc2016-12-09 13:41:29 -08002044 } else if (r.state == RESUMED) {
2045 // Kick off any lingering app transitions form the MoveTaskToFront operation.
2046 mFocusedStack.executeAppTransition(targetOptions);
Wale Ogunwale06579d62016-04-30 15:29:06 -07002047 }
chaviw59b98852017-06-13 12:05:44 -07002048
Wale Ogunwaled046a012015-12-24 13:05:59 -08002049 return false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002050 }
2051
Todd Kennedy39bfee52016-02-24 10:28:21 -08002052 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
2053 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2054 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2055 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2056 stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
2057 }
2058 }
2059 }
2060
Adrian Roos20d7df32016-01-12 18:59:43 +01002061 TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
2062 TaskRecord finishedTask = null;
2063 ActivityStack focusedStack = getFocusedStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08002064 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2065 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002066 final int numStacks = stacks.size();
2067 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2068 final ActivityStack stack = stacks.get(stackNdx);
Adrian Roos20d7df32016-01-12 18:59:43 +01002069 TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
2070 if (stack == focusedStack || finishedTask == null) {
2071 finishedTask = t;
2072 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08002073 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002074 }
Adrian Roos20d7df32016-01-12 18:59:43 +01002075 return finishedTask;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002076 }
2077
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07002078 void finishVoiceTask(IVoiceInteractionSession session) {
2079 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2080 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2081 final int numStacks = stacks.size();
2082 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2083 final ActivityStack stack = stacks.get(stackNdx);
2084 stack.finishVoiceTask(session);
2085 }
2086 }
2087 }
2088
Andrii Kulianc27916642016-04-12 17:59:27 -07002089 void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
2090 String reason, boolean forceNonResizeable) {
Craig Mautneraea74a52014-03-08 14:23:10 -08002091 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
2092 mUserLeaving = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002093 }
Craig Mautneraea74a52014-03-08 14:23:10 -08002094 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
2095 // Caller wants the home activity moved with it. To accomplish this,
2096 // we'll just indicate that this task returns to the home task.
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07002097 task.setTaskToReturnTo(ACTIVITY_TYPE_HOME);
Craig Mautneraea74a52014-03-08 14:23:10 -08002098 }
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002099 final ActivityStack currentStack = task.getStack();
Andrii Kulian02b7a832016-10-06 23:11:56 -07002100 if (currentStack == null) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07002101 Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
2102 + task + " to front. Stack is null");
2103 return;
2104 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002105
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002106 if (task.isResizeable() && canUseActivityOptionsLaunchBounds(options)) {
2107 final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
2108 task.updateOverrideConfiguration(bounds);
2109
2110 int stackId = getLaunchStackId(null, options, task);
2111
2112 if (stackId != currentStack.mStackId) {
2113 task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE,
2114 DEFER_RESUME, "findTaskToMoveToFrontLocked");
2115 stackId = currentStack.mStackId;
2116 // moveTaskToStackUncheckedLocked() should already placed the task on top,
2117 // still need moveTaskToFrontLocked() below for any transition settings.
2118 }
2119 if (StackId.resizeStackWithLaunchBounds(stackId)) {
2120 resizeStackLocked(stackId, bounds,
2121 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2122 !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */, !DEFER_RESUME);
2123 } else {
2124 // WM resizeTask must be done after the task is moved to the correct stack,
2125 // because Task's setBounds() also updates dim layer's bounds, but that has
2126 // dependency on the stack.
2127 task.resizeWindowContainer();
Chong Zhang0fa656b2015-08-31 15:17:21 -07002128 }
2129 }
2130
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002131 final ActivityRecord r = task.getTopActivity();
Andrii Kulian02b7a832016-10-06 23:11:56 -07002132 currentStack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002133 r == null ? null : r.appTimeTracker, reason);
2134
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002135 if (DEBUG_STACK) Slog.d(TAG_STACK,
Andrii Kulian02b7a832016-10-06 23:11:56 -07002136 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
Jorim Jaggi2adba072016-03-03 13:43:39 +01002137
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002138 handleNonResizableTaskIfNeeded(task, WINDOWING_MODE_UNDEFINED, DEFAULT_DISPLAY,
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002139 currentStack.mStackId, forceNonResizeable);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002140 }
2141
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002142 boolean canUseActivityOptionsLaunchBounds(ActivityOptions options) {
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002143 // We use the launch bounds in the activity options is the device supports freeform
Wale Ogunwale854809c2015-12-27 16:18:19 -08002144 // window management or is launching into the pinned stack.
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002145 if (options == null || options.getLaunchBounds() == null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002146 return false;
2147 }
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002148 return (mService.mSupportsPictureInPicture
2149 && options.getLaunchWindowingMode() == WINDOWING_MODE_PINNED)
Wale Ogunwale854809c2015-12-27 16:18:19 -08002150 || mService.mSupportsFreeformWindowManagement;
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002151 }
2152
Winson Chung55893332017-02-17 17:13:10 -08002153 protected <T extends ActivityStack> T getStack(int stackId) {
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002154 for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
2155 final T stack = mActivityDisplays.valueAt(i).getStack(stackId);
2156 if (stack != null) {
2157 return stack;
2158 }
2159 }
2160 return null;
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002161 }
2162
Winson Chung55893332017-02-17 17:13:10 -08002163 protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
2164 boolean createOnTop) {
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002165 final ActivityStack stack = getStack(stackId);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002166 if (stack != null) {
2167 return (T) stack;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002168 }
Wale Ogunwale3797c222015-10-27 14:21:58 -07002169 if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002170 return null;
2171 }
Matthew Ng330757d2017-02-28 14:19:17 -08002172 if (stackId == DOCKED_STACK_ID) {
2173 // Make sure recents stack exist when creating a dock stack as it normally need to be on
2174 // the other side of the docked stack and we make visibility decisions based on that.
2175 getStack(RECENTS_STACK_ID, CREATE_IF_NEEDED, createOnTop);
2176 }
Winson Chung55893332017-02-17 17:13:10 -08002177 return (T) createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002178 }
2179
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002180 private int resolveWindowingMode(@Nullable ActivityRecord r, @Nullable ActivityOptions options,
2181 @Nullable TaskRecord task) {
2182
2183 // First preference if the windowing mode in the activity options if set.
2184 int windowingMode = (options != null)
2185 ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
2186
2187 // If windowing mode is unset, then next preference is the candidate task, then the
2188 // activity record.
2189 if (windowingMode == WINDOWING_MODE_UNDEFINED) {
2190 if (task != null) {
2191 windowingMode = task.getWindowingMode();
2192 }
2193 if (windowingMode == WINDOWING_MODE_UNDEFINED && r != null) {
2194 windowingMode = r.getWindowingMode();
2195 }
2196 }
2197
2198 // Make sure the windowing mode we are trying to use makes sense for what is supported.
2199 if (!mService.mSupportsMultiWindow && windowingMode != WINDOWING_MODE_FULLSCREEN) {
2200 windowingMode = WINDOWING_MODE_FULLSCREEN;
2201 }
2202
2203 if (!mService.mSupportsSplitScreenMultiWindow
2204 && (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
2205 || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY)) {
2206 windowingMode = WINDOWING_MODE_FULLSCREEN;
2207 }
2208
2209 if (windowingMode == WINDOWING_MODE_FREEFORM
2210 && !mService.mSupportsFreeformWindowManagement) {
2211 windowingMode = WINDOWING_MODE_FULLSCREEN;
2212 }
2213
2214 return windowingMode;
2215 }
2216
2217 private int resolveActivityType(@Nullable ActivityRecord r, @Nullable ActivityOptions options,
2218 @Nullable TaskRecord task) {
2219 // First preference if the activity type in the activity options if set.
2220 int activityType = (options != null)
2221 ? options.getLaunchActivityType() : ACTIVITY_TYPE_UNDEFINED;
2222
2223 if (activityType != ACTIVITY_TYPE_UNDEFINED) {
2224 return activityType;
2225 }
2226
2227 // If activity type is unset, then next preference is the task, then the activity record.
2228 if (task != null) {
2229 activityType = task.getActivityType();
2230 }
2231 if (activityType == ACTIVITY_TYPE_UNDEFINED && r != null) {
2232 activityType = r.getActivityType();
2233 }
2234 return activityType;
2235 }
2236
2237 int getLaunchStackId(@Nullable ActivityRecord r, @Nullable ActivityOptions options,
2238 @Nullable TaskRecord candidateTask) {
2239 return getLaunchStackId(r, options, candidateTask, INVALID_DISPLAY);
2240 }
2241
2242 /**
2243 * Returns the right stack to use for launching factoring in all the input parameters.
2244 *
2245 * @param r The activity we are trying to launch. Can be null.
2246 * @param options The activity options used to the launch. Can be null.
2247 * @param candidateTask The possible task the activity might be launched in. Can be null.
2248 *
2249 * @return The stack to use for the launch or INVALID_STACK_ID.
2250 */
2251 int getLaunchStackId(@Nullable ActivityRecord r, @Nullable ActivityOptions options,
2252 @Nullable TaskRecord candidateTask, int candidateDisplayId) {
2253 int taskId = INVALID_TASK_ID;
2254 int displayId = INVALID_DISPLAY;
2255 //Rect bounds = null;
2256
2257 // We give preference to the launch preference in activity options.
2258 if (options != null) {
2259 taskId = options.getLaunchTaskId();
2260 displayId = options.getLaunchDisplayId();
2261 // TODO: Need to work this into the equation...
2262 //bounds = options.getLaunchBounds();
2263 }
2264
2265 // First preference for stack goes to the task Id set in the activity options. Use the stack
2266 // associated with that if possible.
2267 if (taskId != INVALID_TASK_ID) {
2268 // Temporarily set the task id to invalid in case in re-entry.
2269 options.setLaunchTaskId(INVALID_TASK_ID);
2270 final TaskRecord task = anyTaskForIdLocked(taskId,
2271 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE, options);
2272 options.setLaunchTaskId(taskId);
2273 if (task != null) {
2274 return task.getStack().mStackId;
2275 }
2276 }
2277
2278 final int windowingMode = resolveWindowingMode(r, options, candidateTask);
2279 final int activityType = resolveActivityType(r, options, candidateTask);
2280 ActivityStack stack = null;
2281
2282 // Next preference for stack goes to the display Id set in the activity options or the
2283 // candidate display.
2284 if (displayId == INVALID_DISPLAY) {
2285 displayId = candidateDisplayId;
2286 }
2287 if (displayId != INVALID_DISPLAY) {
2288 if (r != null) {
2289 // TODO: This should also take in the windowing mode and activity type into account.
2290 stack = getValidLaunchStackOnDisplay(displayId, r);
2291 if (stack != null) {
2292 return stack.mStackId;
2293 }
2294 }
2295 final ActivityDisplay display = getActivityDisplayOrCreateLocked(displayId);
2296 if (display != null) {
2297 for (int i = display.mStacks.size() - 1; i >= 0; --i) {
2298 stack = display.mStacks.get(i);
2299 if (stack.getWindowingMode() == windowingMode
2300 && stack.getActivityType() == activityType) {
2301 return stack.mStackId;
2302 }
2303 }
2304 // TODO: We should create the stack we want on the display at this point.
2305 }
2306 }
2307
2308 // Give preference to the stack and display of the input task and activity if they match the
2309 // mode we want to launch into.
2310 if (candidateTask != null) {
2311 stack = candidateTask.getStack();
2312 }
2313 if (stack == null && r != null) {
2314 stack = r.getStack();
2315 }
2316 if (stack != null) {
2317 if (stack.getWindowingMode() == windowingMode
2318 && stack.getActivityType() == activityType) {
2319 return stack.mStackId;
2320 }
2321 ActivityDisplay display = stack.getDisplay();
2322
2323 if (display != null) {
2324 for (int i = display.mStacks.size() - 1; i >= 0; --i) {
2325 stack = display.mStacks.get(i);
2326 if (stack.getWindowingMode() == windowingMode
2327 && stack.getActivityType() == activityType) {
2328 return stack.mStackId;
2329 }
2330 }
2331 }
2332 }
2333
2334 // Give preference to the type of activity we are trying to launch followed by the windowing
2335 // mode.
2336 int stackId = getStackIdForActivityType(activityType);
2337 if (stackId != INVALID_STACK_ID) {
2338 return stackId;
2339 }
2340 stackId = getStackIdForWindowingMode(windowingMode);
2341 if (stackId != INVALID_STACK_ID) {
2342 return stackId;
2343 }
2344
2345 // Whatever...return some default for now.
2346 if (candidateTask != null && candidateTask.mBounds != null
2347 && mService.mSupportsFreeformWindowManagement) {
2348 return FREEFORM_WORKSPACE_STACK_ID;
2349 }
2350 return FULLSCREEN_WORKSPACE_STACK_ID;
2351 }
2352
Andrii Kulian16802aa2016-11-02 12:21:33 -07002353 /**
2354 * Get a topmost stack on the display, that is a valid launch stack for specified activity.
2355 * If there is no such stack, new dynamic stack can be created.
2356 * @param displayId Target display.
2357 * @param r Activity that should be launched there.
2358 * @return Existing stack if there is a valid one, new dynamic stack if it is valid or null.
2359 */
2360 ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002361 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian16802aa2016-11-02 12:21:33 -07002362 if (activityDisplay == null) {
2363 throw new IllegalArgumentException(
2364 "Display with displayId=" + displayId + " not found.");
2365 }
2366
2367 // Return the topmost valid stack on the display.
2368 for (int i = activityDisplay.mStacks.size() - 1; i >= 0; --i) {
2369 final ActivityStack stack = activityDisplay.mStacks.get(i);
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002370 if (isValidLaunchStackId(stack.mStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002371 return stack;
2372 }
2373 }
2374
2375 // If there is no valid stack on the external display - check if new dynamic stack will do.
2376 if (displayId != Display.DEFAULT_DISPLAY) {
2377 final int newDynamicStackId = getNextStackId();
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002378 if (isValidLaunchStackId(newDynamicStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002379 return createStackOnDisplay(newDynamicStackId, displayId, true /*onTop*/);
2380 }
2381 }
2382
2383 Slog.w(TAG, "getValidLaunchStackOnDisplay: can't launch on displayId " + displayId);
2384 return null;
2385 }
2386
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002387 boolean isValidLaunchStackId(int stackId, int displayId, ActivityRecord r) {
2388 switch (stackId) {
2389 case INVALID_STACK_ID:
2390 case HOME_STACK_ID:
2391 return false;
2392 case FULLSCREEN_WORKSPACE_STACK_ID:
2393 return true;
2394 case FREEFORM_WORKSPACE_STACK_ID:
2395 return r.supportsFreeform();
2396 case DOCKED_STACK_ID:
2397 return r.supportsSplitScreen();
2398 case PINNED_STACK_ID:
2399 return r.supportsPictureInPicture();
2400 case RECENTS_STACK_ID:
2401 return r.isActivityTypeRecents();
2402 case ASSISTANT_STACK_ID:
2403 return r.isActivityTypeAssistant();
2404 default:
2405 if (StackId.isDynamicStack(stackId)) {
2406 return r.canBeLaunchedOnDisplay(displayId);
2407 }
2408 Slog.e(TAG, "isValidLaunchStackId: Unexpected stackId=" + stackId);
2409 return false;
2410 }
2411 }
2412
Craig Mautner967212c2013-04-13 21:10:58 -07002413 ArrayList<ActivityStack> getStacks() {
Wale Ogunwale3797c222015-10-27 14:21:58 -07002414 ArrayList<ActivityStack> allStacks = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08002415 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2416 allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002417 }
2418 return allStacks;
Craig Mautner967212c2013-04-13 21:10:58 -07002419 }
2420
Jorim Jaggife762342016-10-13 14:33:27 +02002421 ArrayList<ActivityStack> getStacksOnDefaultDisplay() {
2422 return mActivityDisplays.valueAt(DEFAULT_DISPLAY).mStacks;
2423 }
2424
Andrii Kulian7fc22812016-12-28 13:04:11 -08002425 /**
2426 * Get next focusable stack in the system. This will search across displays and stacks
2427 * in last-focused order for a focusable and visible stack, different from the target stack.
2428 *
2429 * @param currentFocus The stack that previously had focus and thus needs to be ignored when
2430 * searching for next candidate.
2431 * @return Next focusable {@link ActivityStack}, null if not found.
2432 */
2433 ActivityStack getNextFocusableStackLocked(ActivityStack currentFocus) {
2434 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2435
2436 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2437 final int displayId = mTmpOrderedDisplayIds.get(i);
Andrii Kulian62e6f252017-05-30 22:46:53 -07002438 // If a display is registered in WM, it must also be available in AM.
2439 @SuppressWarnings("ConstantConditions")
2440 final List<ActivityStack> stacks = getActivityDisplayOrCreateLocked(displayId).mStacks;
Andrii Kulian7fc22812016-12-28 13:04:11 -08002441 for (int j = stacks.size() - 1; j >= 0; --j) {
2442 final ActivityStack stack = stacks.get(j);
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002443 if (stack != currentFocus && stack.isFocusable() && stack.shouldBeVisible(null)) {
Andrii Kulian7fc22812016-12-28 13:04:11 -08002444 return stack;
2445 }
2446 }
2447 }
2448
2449 return null;
2450 }
2451
Andrii Kuliana8fe3df2017-06-16 15:29:26 -07002452 /**
2453 * Get next valid stack for launching provided activity in the system. This will search across
2454 * displays and stacks in last-focused order for a focusable and visible stack, except those
2455 * that are on a currently focused display.
2456 *
2457 * @param r The activity that is being launched.
2458 * @param currentFocus The display that previously had focus and thus needs to be ignored when
2459 * searching for the next candidate.
2460 * @return Next valid {@link ActivityStack}, null if not found.
2461 */
2462 ActivityStack getNextValidLaunchStackLocked(@NonNull ActivityRecord r, int currentFocus) {
2463 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2464 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2465 final int displayId = mTmpOrderedDisplayIds.get(i);
2466 if (displayId == currentFocus) {
2467 continue;
2468 }
2469 final ActivityStack stack = getValidLaunchStackOnDisplay(displayId, r);
2470 if (stack != null) {
2471 return stack;
2472 }
2473 }
2474 return null;
2475 }
2476
Craig Mautneree2e45a2014-06-27 12:10:03 -07002477 ActivityRecord getHomeActivity() {
Craig Mautnerdb49fec2015-05-21 15:33:30 -07002478 return getHomeActivityForUser(mCurrentUser);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002479 }
2480
2481 ActivityRecord getHomeActivityForUser(int userId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002482 final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
2483 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
2484 final TaskRecord task = tasks.get(taskNdx);
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07002485 if (task.isActivityTypeHome()) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002486 final ArrayList<ActivityRecord> activities = task.mActivities;
2487 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2488 final ActivityRecord r = activities.get(activityNdx);
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07002489 if (r.isActivityTypeHome()
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002490 && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
Craig Mautneree2e45a2014-06-27 12:10:03 -07002491 return r;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002492 }
2493 }
2494 }
2495 }
2496 return null;
2497 }
2498
Jorim Jaggidc249c42015-12-15 14:57:31 -08002499 void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002500 boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
Jorim Jaggidc249c42015-12-15 14:57:31 -08002501 if (stackId == DOCKED_STACK_ID) {
2502 resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002503 preserveWindows, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002504 return;
2505 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08002506 final ActivityStack stack = getStack(stackId);
2507 if (stack == null) {
2508 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2509 return;
2510 }
Wale Ogunwale9d3de4c2015-02-01 16:49:44 -08002511
Wale Ogunwale926aade2017-08-29 11:24:37 -07002512 final boolean splitScreenActive = getStack(DOCKED_STACK_ID) != null;
Wale Ogunwale3382ab12017-07-27 08:55:03 -07002513 if (!allowResizeInDockedMode
Wale Ogunwale926aade2017-08-29 11:24:37 -07002514 && !stack.getWindowConfiguration().tasksAreFloating() && splitScreenActive) {
Winson Chunga2249ac2017-03-30 18:15:30 -07002515 // If the docked stack exists, don't resize non-floating stacks independently of the
2516 // size computed from the docked stack size (otherwise they will be out of sync)
Wale Ogunwaleffc11bb2015-10-10 13:05:45 -07002517 return;
2518 }
2519
Wale Ogunwalecad05a02015-09-25 10:41:44 -07002520 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
Jorim Jaggic4025202015-10-22 16:43:34 +02002521 mWindowManager.deferSurfaceLayout();
2522 try {
Wale Ogunwale926aade2017-08-29 11:24:37 -07002523 if (stack.supportSplitScreenWindowingMode()) {
2524 if (bounds == null && stack.inSplitScreenWindowingMode()) {
2525 // null bounds = fullscreen windowing mode...at least for now.
2526 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
2527 } else if (splitScreenActive) {
2528 // If we are in split-screen mode and this stack support split-screen, then
2529 // it should be split-screen secondary mode. i.e. adjacent to the docked stack.
2530 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
2531 }
2532 }
Wale Ogunwale1666e312016-12-16 11:27:18 -08002533 stack.resize(bounds, tempTaskBounds, tempTaskInsetBounds);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002534 if (!deferResume) {
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002535 stack.ensureVisibleActivitiesConfigurationLocked(
2536 stack.topRunningActivityLocked(), preserveWindows);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002537 }
Jorim Jaggic4025202015-10-22 16:43:34 +02002538 } finally {
2539 mWindowManager.continueSurfaceLayout();
2540 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07002541 }
2542 }
2543
Wale Ogunwale926aade2017-08-29 11:24:37 -07002544 private void deferUpdateBounds(int stackId) {
Jorim Jaggi192086e2016-03-11 17:17:03 +01002545 final ActivityStack stack = getStack(stackId);
2546 if (stack != null) {
2547 stack.deferUpdateBounds();
2548 }
2549 }
2550
Wale Ogunwale926aade2017-08-29 11:24:37 -07002551 private void continueUpdateBounds(int stackId) {
Jorim Jaggi192086e2016-03-11 17:17:03 +01002552 final ActivityStack stack = getStack(stackId);
2553 if (stack != null) {
2554 stack.continueUpdateBounds();
2555 }
2556 }
2557
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002558 void notifyAppTransitionDone() {
Matthew Ng606dd802017-06-05 14:06:32 -07002559 continueUpdateBounds(RECENTS_STACK_ID);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002560 for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2561 final int taskId = mResizingTasksDuringAnimation.valueAt(i);
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002562 final TaskRecord task = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002563 if (task != null) {
2564 task.setTaskDockedResizing(false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002565 }
2566 }
2567 mResizingTasksDuringAnimation.clear();
2568 }
2569
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002570 private void moveTasksToFullscreenStackInSurfaceTransaction(ActivityStack fromStack,
Robert Carre7cc44d2017-03-20 19:04:30 -07002571 boolean onTop) {
Robert Carr6914f082017-03-20 19:04:30 -07002572
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002573 mWindowManager.deferSurfaceLayout();
2574 try {
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002575 final int fromStackId = fromStack.mStackId;
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002576 if (fromStackId == DOCKED_STACK_ID) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002577 // We are moving all tasks from the docked stack to the fullscreen stack,
2578 // which is dismissing the docked stack, so resize all other stacks to
2579 // fullscreen here already so we don't end up with resize trashing.
2580 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
Wale Ogunwale926aade2017-08-29 11:24:37 -07002581 final ActivityStack otherStack = getStack(i);
2582 if (otherStack == null) {
2583 continue;
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002584 }
Wale Ogunwale926aade2017-08-29 11:24:37 -07002585 if (!otherStack.inSplitScreenSecondaryWindowingMode()) {
2586 continue;
2587 }
2588 resizeStackLocked(i, null, null, null, PRESERVE_WINDOWS,
2589 true /* allowResizeInDockedMode */, DEFER_RESUME);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002590 }
2591
2592 // Also disable docked stack resizing since we have manually adjusted the
2593 // size of other stacks above and we don't want to trigger a docked stack
2594 // resize when we remove task from it below and it is detached from the
2595 // display because it no longer contains any tasks.
2596 mAllowDockedStackResize = false;
Winson Chung47900652017-04-06 18:44:25 -07002597 } else if (fromStackId == PINNED_STACK_ID) {
2598 if (onTop) {
2599 // Log if we are expanding the PiP to fullscreen
2600 MetricsLogger.action(mService.mContext,
2601 ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN);
2602 }
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002603 }
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002604 ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002605 final boolean isFullscreenStackVisible = fullscreenStack != null
2606 && fullscreenStack.shouldBeVisible(null);
Winson Chung5af42fc2017-03-24 17:11:33 -07002607 // If we are moving from the pinned stack, then the animation takes care of updating
2608 // the picture-in-picture mode.
Winson Chung47900652017-04-06 18:44:25 -07002609 final boolean schedulePictureInPictureModeChange = (fromStackId == PINNED_STACK_ID);
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002610 final ArrayList<TaskRecord> tasks = fromStack.getAllTasks();
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002611 final int size = tasks.size();
2612 if (onTop) {
2613 for (int i = 0; i < size; i++) {
Winson Chung0c1ca092016-11-10 17:40:34 -08002614 final TaskRecord task = tasks.get(i);
Winson Chung74666102017-02-22 17:49:24 -08002615 final boolean isTopTask = i == (size - 1);
Winson Chung0c1ca092016-11-10 17:40:34 -08002616 if (fromStackId == PINNED_STACK_ID) {
2617 // Update the return-to to reflect where the pinned stack task was moved
2618 // from so that we retain the stack that was previously visible if the
2619 // pinned stack is recreated. See moveActivityToPinnedStackLocked().
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07002620 task.setTaskToReturnTo(isFullscreenStackVisible ?
2621 ACTIVITY_TYPE_STANDARD : ACTIVITY_TYPE_HOME);
Winson Chung0c1ca092016-11-10 17:40:34 -08002622 }
Winson Chung74666102017-02-22 17:49:24 -08002623 // Defer resume until all the tasks have been moved to the fullscreen stack
2624 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
2625 REPARENT_MOVE_STACK_TO_FRONT, isTopTask /* animate */, DEFER_RESUME,
Winson Chung5af42fc2017-03-24 17:11:33 -07002626 schedulePictureInPictureModeChange,
Winson Chung74666102017-02-22 17:49:24 -08002627 "moveTasksToFullscreenStack - onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002628 }
2629 } else {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002630 for (int i = 0; i < size; i++) {
Wale Ogunwalec5cc3012017-01-13 13:26:16 -08002631 final TaskRecord task = tasks.get(i);
Winson Chung3a649982017-04-19 10:16:17 -07002632 // Position the tasks in the fullscreen stack in order at the bottom of the
2633 // stack. Also defer resume until all the tasks have been moved to the
2634 // fullscreen stack.
2635 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, i /* position */,
Winson Chung5af42fc2017-03-24 17:11:33 -07002636 REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME,
2637 schedulePictureInPictureModeChange,
2638 "moveTasksToFullscreenStack - NOT_onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002639 }
2640 }
Winson Chung74666102017-02-22 17:49:24 -08002641
2642 ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2643 resumeFocusedStackTopActivityLocked();
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002644 } finally {
2645 mAllowDockedStackResize = true;
2646 mWindowManager.continueSurfaceLayout();
2647 }
2648 }
2649
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002650 void moveTasksToFullscreenStackLocked(ActivityStack fromStack, boolean onTop) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002651 mWindowManager.inSurfaceTransaction(
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002652 () -> moveTasksToFullscreenStackInSurfaceTransaction(fromStack, onTop));
Robert Carr6914f082017-03-20 19:04:30 -07002653 }
2654
Jorim Jaggidc249c42015-12-15 14:57:31 -08002655 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002656 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2657 boolean preserveWindows) {
2658 resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
2659 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows,
2660 false /* deferResume */);
2661 }
2662
2663 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2664 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2665 boolean preserveWindows, boolean deferResume) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002666
2667 if (!mAllowDockedStackResize) {
2668 // Docked stack resize currently disabled.
2669 return;
2670 }
2671
Jorim Jaggidc249c42015-12-15 14:57:31 -08002672 final ActivityStack stack = getStack(DOCKED_STACK_ID);
2673 if (stack == null) {
2674 Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2675 return;
2676 }
2677
2678 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2679 mWindowManager.deferSurfaceLayout();
2680 try {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002681 // Don't allow re-entry while resizing. E.g. due to docked stack detaching.
2682 mAllowDockedStackResize = false;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002683 ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwale1666e312016-12-16 11:27:18 -08002684 stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002685
Andrii Kulian69fb5e42016-04-05 16:47:29 -07002686 // TODO: Checking for isAttached might not be needed as if the user passes in null
2687 // dockedBounds then they want the docked stack to be dismissed.
2688 if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2689 // The dock stack either was dismissed or went fullscreen, which is kinda the same.
Jorim Jaggidc249c42015-12-15 14:57:31 -08002690 // In this case we make all other static stacks fullscreen and move all
2691 // docked stack tasks to the fullscreen stack.
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002692 moveTasksToFullscreenStackLocked(stack, ON_TOP);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002693
2694 // stack shouldn't contain anymore activities, so nothing to resume.
2695 r = null;
2696 } else {
2697 // Docked stacks occupy a dedicated region on screen so the size of all other
2698 // static stacks need to be adjusted so they don't overlap with the docked stack.
2699 // We get the bounds to use from window manager which has been adjusted for any
2700 // screen controls and is also the same for all stacks.
Matthew Ngaa2b6202017-02-10 14:48:21 -08002701 final Rect otherTaskRect = new Rect();
Jorim Jaggidc249c42015-12-15 14:57:31 -08002702 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
Wale Ogunwale926aade2017-08-29 11:24:37 -07002703 if (i == DOCKED_STACK_ID) {
2704 continue;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002705 }
Wale Ogunwale926aade2017-08-29 11:24:37 -07002706 final ActivityStack current = getStack(i);
2707 if (current == null || !current.supportSplitScreenWindowingMode()) {
2708 continue;
2709 }
2710 // Need to set windowing mode here before we try to get the dock bounds.
2711 current.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
2712 current.getStackDockedModeBounds(
2713 tempOtherTaskBounds /* currentTempTaskBounds */,
2714 tempRect /* outStackBounds */,
2715 otherTaskRect /* outTempTaskBounds */, true /* ignoreVisibility */);
2716
2717 resizeStackLocked(i, !tempRect.isEmpty() ? tempRect : null,
2718 !otherTaskRect.isEmpty() ? otherTaskRect : tempOtherTaskBounds,
2719 tempOtherTaskInsetBounds, preserveWindows,
2720 true /* allowResizeInDockedMode */, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002721 }
2722 }
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002723 if (!deferResume) {
2724 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows);
2725 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002726 } finally {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002727 mAllowDockedStackResize = true;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002728 mWindowManager.continueSurfaceLayout();
2729 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2730 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002731 }
2732
Robert Carr0d00c2e2016-02-29 17:45:02 -08002733 void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Winson Chung19953ca2017-04-11 11:19:23 -07002734 final PinnedActivityStack stack = getStack(PINNED_STACK_ID);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002735 if (stack == null) {
2736 Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2737 return;
2738 }
Winson Chung19953ca2017-04-11 11:19:23 -07002739
2740 // It is possible for the bounds animation from the WM to call this but be delayed by
2741 // another AM call that is holding the AMS lock. In such a case, the pinnedBounds may be
2742 // incorrect if AMS.resizeStackWithBoundsFromWindowManager() is already called while waiting
2743 // for the AMS lock to be freed. So check and make sure these bounds are still good.
2744 final PinnedStackWindowController stackController = stack.getWindowContainerController();
Winson Chung8bca9e42017-04-16 15:59:43 -07002745 if (stackController.pinnedStackResizeDisallowed()) {
Winson Chung19953ca2017-04-11 11:19:23 -07002746 return;
2747 }
2748
Robert Carr0d00c2e2016-02-29 17:45:02 -08002749 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2750 mWindowManager.deferSurfaceLayout();
2751 try {
2752 ActivityRecord r = stack.topRunningActivityLocked();
Robert Carr7e4c90e2017-02-15 19:52:38 -08002753 Rect insetBounds = null;
2754 if (tempPinnedTaskBounds != null) {
2755 // We always use 0,0 as the position for the inset rect because
2756 // if we are getting insets at all in the pinned stack it must mean
2757 // we are headed for fullscreen.
2758 insetBounds = tempRect;
2759 insetBounds.top = 0;
2760 insetBounds.left = 0;
2761 insetBounds.right = tempPinnedTaskBounds.width();
2762 insetBounds.bottom = tempPinnedTaskBounds.height();
2763 }
2764 stack.resize(pinnedBounds, tempPinnedTaskBounds, insetBounds);
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002765 stack.ensureVisibleActivitiesConfigurationLocked(r, false);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002766 } finally {
2767 mWindowManager.continueSurfaceLayout();
2768 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2769 }
2770 }
2771
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002772 ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002773 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Craig Mautnere0a38842013-12-16 16:14:02 -08002774 if (activityDisplay == null) {
Todd Kennedy4900bf92015-01-16 16:05:14 -08002775 return null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002776 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002777 return createStack(stackId, activityDisplay, onTop);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002778
Craig Mautner4a1cb222013-12-04 16:14:06 -08002779 }
2780
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002781 ActivityStack createStack(int stackId, ActivityDisplay display, boolean onTop) {
2782 switch (stackId) {
2783 case PINNED_STACK_ID:
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002784 return new PinnedActivityStack(display, stackId, this, onTop);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002785 default:
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002786 return new ActivityStack(display, stackId, this, onTop);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002787 }
2788 }
Robert Carr6914f082017-03-20 19:04:30 -07002789
Robert Carre7cc44d2017-03-20 19:04:30 -07002790 void removeStackInSurfaceTransaction(int stackId) {
Winson Chung010927a2016-12-15 16:12:35 -08002791 final ActivityStack stack = getStack(stackId);
2792 if (stack == null) {
2793 return;
2794 }
2795
2796 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2797 if (stack.getStackId() == PINNED_STACK_ID) {
Winson Chung47900652017-04-06 18:44:25 -07002798 /**
2799 * Workaround: Force-stop all the activities in the pinned stack before we reparent them
2800 * to the fullscreen stack. This is to guarantee that when we are removing a stack,
2801 * that the client receives onStop() before it is reparented. We do this by detaching
2802 * the stack from the display so that it will be considered invisible when
2803 * ensureActivitiesVisibleLocked() is called, and all of its activitys will be marked
2804 * invisible as well and added to the stopping list. After which we process the
2805 * stopping list by handling the idle.
2806 */
2807 final PinnedActivityStack pinnedStack = (PinnedActivityStack) stack;
2808 pinnedStack.mForceHidden = true;
2809 pinnedStack.ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2810 pinnedStack.mForceHidden = false;
2811 activityIdleInternalLocked(null, false /* fromTimeout */,
2812 true /* processPausingActivites */, null /* configuration */);
2813
2814 // Move all the tasks to the bottom of the fullscreen stack
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002815 moveTasksToFullscreenStackLocked(pinnedStack, !ON_TOP);
Winson Chung010927a2016-12-15 16:12:35 -08002816 } else {
2817 for (int i = tasks.size() - 1; i >= 0; i--) {
2818 removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */,
2819 REMOVE_FROM_RECENTS);
2820 }
2821 }
2822 }
2823
2824 /**
Robert Carr6914f082017-03-20 19:04:30 -07002825 * Removes the stack associated with the given {@param stackId}. If the {@param stackId} is the
2826 * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
2827 * instead moved back onto the fullscreen stack.
2828 */
2829 void removeStackLocked(int stackId) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002830 mWindowManager.inSurfaceTransaction(
2831 () -> removeStackInSurfaceTransaction(stackId));
Robert Carr6914f082017-03-20 19:04:30 -07002832 }
2833
2834 /**
Winson Chung6954fc92017-03-24 16:22:12 -07002835 * See {@link #removeTaskByIdLocked(int, boolean, boolean, boolean)}
2836 */
2837 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents) {
2838 return removeTaskByIdLocked(taskId, killProcess, removeFromRecents, !PAUSE_IMMEDIATELY);
2839 }
2840
2841 /**
Winson Chung010927a2016-12-15 16:12:35 -08002842 * Removes the task with the specified task id.
2843 *
2844 * @param taskId Identifier of the task to be removed.
2845 * @param killProcess Kill any process associated with the task if possible.
2846 * @param removeFromRecents Whether to also remove the task from recents.
Winson Chung6954fc92017-03-24 16:22:12 -07002847 * @param pauseImmediately Pauses all task activities immediately without waiting for the
2848 * pause-complete callback from the activity.
Winson Chung010927a2016-12-15 16:12:35 -08002849 * @return Returns true if the given task was found and removed.
2850 */
Winson Chung6954fc92017-03-24 16:22:12 -07002851 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents,
2852 boolean pauseImmediately) {
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002853 final TaskRecord tr = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
Winson Chung010927a2016-12-15 16:12:35 -08002854 if (tr != null) {
Winson Chung6954fc92017-03-24 16:22:12 -07002855 tr.removeTaskActivitiesLocked(pauseImmediately);
Winson Chung010927a2016-12-15 16:12:35 -08002856 cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents);
2857 if (tr.isPersistable) {
2858 mService.notifyTaskPersisterLocked(null, true);
2859 }
2860 return true;
2861 }
2862 Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
2863 return false;
2864 }
2865
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002866 void addRecentActivity(ActivityRecord r) {
2867 if (r == null) {
2868 return;
2869 }
2870 final TaskRecord task = r.getTask();
2871 mRecentTasks.addLocked(task);
2872 task.touchActiveTime();
2873 }
2874
2875 void removeTaskFromRecents(TaskRecord task) {
2876 mRecentTasks.remove(task);
2877 task.removedFromRecents();
2878 }
2879
Winson Chung010927a2016-12-15 16:12:35 -08002880 void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) {
2881 if (removeFromRecents) {
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002882 removeTaskFromRecents(tr);
Winson Chung010927a2016-12-15 16:12:35 -08002883 }
2884 ComponentName component = tr.getBaseIntent().getComponent();
2885 if (component == null) {
2886 Slog.w(TAG, "No component for base intent of task: " + tr);
2887 return;
2888 }
2889
2890 // Find any running services associated with this app and stop if needed.
2891 mService.mServices.cleanUpRemovedTaskLocked(tr, component, new Intent(tr.getBaseIntent()));
2892
2893 if (!killProcess) {
2894 return;
2895 }
2896
2897 // Determine if the process(es) for this task should be killed.
2898 final String pkg = component.getPackageName();
2899 ArrayList<ProcessRecord> procsToKill = new ArrayList<>();
2900 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mService.mProcessNames.getMap();
2901 for (int i = 0; i < pmap.size(); i++) {
2902
2903 SparseArray<ProcessRecord> uids = pmap.valueAt(i);
2904 for (int j = 0; j < uids.size(); j++) {
2905 ProcessRecord proc = uids.valueAt(j);
2906 if (proc.userId != tr.userId) {
2907 // Don't kill process for a different user.
2908 continue;
2909 }
2910 if (proc == mService.mHomeProcess) {
2911 // Don't kill the home process along with tasks from the same package.
2912 continue;
2913 }
2914 if (!proc.pkgList.containsKey(pkg)) {
2915 // Don't kill process that is not associated with this task.
2916 continue;
2917 }
2918
2919 for (int k = 0; k < proc.activities.size(); k++) {
Bryce Leeaf691c02017-03-20 14:20:22 -07002920 TaskRecord otherTask = proc.activities.get(k).getTask();
Winson Chung010927a2016-12-15 16:12:35 -08002921 if (tr.taskId != otherTask.taskId && otherTask.inRecents) {
2922 // Don't kill process(es) that has an activity in a different task that is
2923 // also in recents.
2924 return;
2925 }
2926 }
2927
2928 if (proc.foregroundServices) {
2929 // Don't kill process(es) with foreground service.
2930 return;
2931 }
2932
2933 // Add process to kill list.
2934 procsToKill.add(proc);
2935 }
2936 }
2937
2938 // Kill the running processes.
2939 for (int i = 0; i < procsToKill.size(); i++) {
2940 ProcessRecord pr = procsToKill.get(i);
2941 if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
2942 && pr.curReceivers.isEmpty()) {
2943 pr.kill("remove task", true);
2944 } else {
2945 // We delay killing processes that are not in the background or running a receiver.
2946 pr.waitingToKill = "remove task";
2947 }
2948 }
2949 }
2950
Craig Mautner4a1cb222013-12-04 16:14:06 -08002951 int getNextStackId() {
Craig Mautner858d8a62013-04-23 17:08:34 -07002952 while (true) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002953 if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2954 && getStack(mNextFreeStackId) == null) {
Craig Mautner858d8a62013-04-23 17:08:34 -07002955 break;
2956 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002957 mNextFreeStackId++;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002958 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002959 return mNextFreeStackId;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002960 }
2961
Chong Zhang5dcb2752015-08-18 13:50:26 -07002962 /**
2963 * Restores a recent task to a stack
2964 * @param task The recent task to be restored.
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002965 * @param aOptions The activity options to use for restoration.
Chong Zhang5dcb2752015-08-18 13:50:26 -07002966 * @return true if the task has been restored successfully.
2967 */
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002968 boolean restoreRecentTaskLocked(TaskRecord task, ActivityOptions aOptions) {
2969 final int stackId = getLaunchStackId(null, aOptions, task);
Andrii Kulian02b7a832016-10-06 23:11:56 -07002970 final ActivityStack currentStack = task.getStack();
2971 if (currentStack != null) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002972 // Task has already been restored once. See if we need to do anything more
Andrii Kulian02b7a832016-10-06 23:11:56 -07002973 if (currentStack.mStackId == stackId) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002974 // Nothing else to do since it is already restored in the right stack.
2975 return true;
2976 }
2977 // Remove current stack association, so we can re-associate the task with the
2978 // right stack below.
Andrii Kulian02b7a832016-10-06 23:11:56 -07002979 currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING);
Wale Ogunwale706ed792015-08-02 10:29:44 -07002980 }
2981
Wale Ogunwale0568aed2017-09-08 13:29:37 -07002982 final ActivityStack stack = getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002983
Wale Ogunwale72919d22016-12-08 18:58:50 -08002984 stack.addTask(task, false /* toTop */, "restoreRecentTask");
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002985 // TODO: move call for creation here and other place into Stack.addTask()
2986 task.createWindowContainer(false /* toTop */, true /* showForAllUsers */);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002987 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2988 "Added restored task=" + task + " to stack=" + stack);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002989 final ArrayList<ActivityRecord> activities = task.mActivities;
2990 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002991 activities.get(activityNdx).createWindowContainer();
Wale Ogunwale7de05352014-12-12 15:21:33 -08002992 }
2993 return true;
Craig Mautneref73ee12014-04-23 11:45:37 -07002994 }
2995
Wale Ogunwale040b4702015-08-06 18:10:50 -07002996 /**
Andrii Kulian839def92016-11-02 10:58:58 -07002997 * Move stack with all its existing content to specified display.
2998 * @param stackId Id of stack to move.
2999 * @param displayId Id of display to move stack to.
Andrii Kulian250d6532017-02-08 23:30:45 -08003000 * @param onTop Indicates whether container should be place on top or on bottom.
Andrii Kulian839def92016-11-02 10:58:58 -07003001 */
Andrii Kulian250d6532017-02-08 23:30:45 -08003002 void moveStackToDisplayLocked(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003003 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian839def92016-11-02 10:58:58 -07003004 if (activityDisplay == null) {
3005 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown displayId="
3006 + displayId);
3007 }
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07003008 final ActivityStack stack = getStack(stackId);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003009 if (stack == null) {
Andrii Kulian839def92016-11-02 10:58:58 -07003010 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
3011 + stackId);
3012 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003013
3014 final ActivityDisplay currentDisplay = stack.getDisplay();
3015 if (currentDisplay == null) {
3016 throw new IllegalStateException("moveStackToDisplayLocked: Stack with stack=" + stack
3017 + " is not attached to any display.");
3018 }
3019
3020 if (currentDisplay.mDisplayId == displayId) {
3021 throw new IllegalArgumentException("Trying to move stack=" + stack
3022 + " to its current displayId=" + displayId);
3023 }
3024
3025 stack.reparent(activityDisplay, onTop);
Andrii Kulian839def92016-11-02 10:58:58 -07003026 // TODO(multi-display): resize stacks properly if moved from split-screen.
3027 }
3028
3029 /**
Winson Chung74666102017-02-22 17:49:24 -08003030 * Returns the reparent target stack, creating the stack if necessary. This call also enforces
3031 * the various checks on tasks that are going to be reparented from one stack to another.
Wale Ogunwale040b4702015-08-06 18:10:50 -07003032 */
Winson Chung74666102017-02-22 17:49:24 -08003033 ActivityStack getReparentTargetStack(TaskRecord task, int stackId, boolean toTop) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07003034 final ActivityStack prevStack = task.getStack();
Chong Zhang02898352015-08-21 17:27:14 -07003035
Winson Chung74666102017-02-22 17:49:24 -08003036 // Check that we aren't reparenting to the same stack that the task is already in
3037 if (prevStack != null && prevStack.mStackId == stackId) {
3038 Slog.w(TAG, "Can not reparent to same stack, task=" + task
3039 + " already in stackId=" + stackId);
3040 return prevStack;
Wale Ogunwale513346d2016-01-27 10:55:01 -08003041 }
3042
Winson Chung74666102017-02-22 17:49:24 -08003043 // Ensure that we aren't trying to move into a multi-window stack without multi-window
3044 // support
3045 if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
3046 throw new IllegalArgumentException("Device doesn't support multi-window, can not"
3047 + " reparent task=" + task + " to stackId=" + stackId);
Winson Chungc2baac02017-01-11 13:34:47 -08003048 }
3049
Andrii Kulianeafd9db2017-04-05 22:01:35 -07003050 // Ensure that we're not moving a task to a dynamic stack if device doesn't support
3051 // multi-display.
3052 // TODO(multi-display): Support non-dynamic stacks on secondary displays.
Andrii Kulianeafd9db2017-04-05 22:01:35 -07003053 if (StackId.isDynamicStack(stackId) && !mService.mSupportsMultiDisplay) {
3054 throw new IllegalArgumentException("Device doesn't support multi-display, can not"
3055 + " reparent task=" + task + " to stackId=" + stackId);
3056 }
3057
Winson Chung74666102017-02-22 17:49:24 -08003058 // Ensure that we aren't trying to move into a freeform stack without freeform
3059 // support
Wale Ogunwale08559dc2016-02-23 12:20:08 -08003060 if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
Winson Chung74666102017-02-22 17:49:24 -08003061 throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
3062 + " task=" + task);
Wale Ogunwale08559dc2016-02-23 12:20:08 -08003063 }
3064
Winson Chung74666102017-02-22 17:49:24 -08003065 // We don't allow moving a unresizeable task to the docked stack since the docked stack is
3066 // used for split-screen mode and will cause things like the docked divider to show up. We
3067 // instead leave the task in its current stack or move it to the fullscreen stack if it
3068 // isn't currently in a stack.
3069 if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
3070 stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
3071 Slog.w(TAG, "Can not move unresizeable task=" + task + " to docked stack."
3072 + " Moving to stackId=" + stackId + " instead.");
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07003073 }
Wale Ogunwale961f4852016-02-01 20:25:54 -08003074
Winson Chung74666102017-02-22 17:49:24 -08003075 // Temporarily disable resizeablility of the task as we don't want it to be resized if, for
3076 // example, a docked stack is created which will lead to the stack we are moving from being
3077 // resized and and its resizeable tasks being resized.
Wale Ogunwale961f4852016-02-01 20:25:54 -08003078 try {
Winson Chung74666102017-02-22 17:49:24 -08003079 task.mTemporarilyUnresizable = true;
3080 return getStack(stackId, CREATE_IF_NEEDED, toTop);
Wale Ogunwale961f4852016-02-01 20:25:54 -08003081 } finally {
Winson Chung74666102017-02-22 17:49:24 -08003082 task.mTemporarilyUnresizable = false;
Chong Zhangf596cd52016-01-05 13:42:44 -08003083 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003084 }
3085
Winson Chung08f81892017-03-02 15:40:51 -08003086 boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect destBounds) {
Wale Ogunwale079a0042015-10-24 11:44:07 -07003087 final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
3088 if (stack == null) {
3089 throw new IllegalArgumentException(
3090 "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
3091 }
3092
3093 final ActivityRecord r = stack.topRunningActivityLocked();
3094 if (r == null) {
3095 Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
3096 + " in stack=" + stack);
3097 return false;
3098 }
3099
Wale Ogunwale6cae7652015-12-26 07:36:26 -08003100 if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
Wale Ogunwaleb60692e2015-10-24 12:35:56 -07003101 Slog.w(TAG,
3102 "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
Filip Gruszczynski77d94482015-12-11 13:59:52 -08003103 + " r=" + r);
Wale Ogunwale079a0042015-10-24 11:44:07 -07003104 return false;
3105 }
3106
Winson Chung3a682872017-04-10 14:38:05 -07003107 moveActivityToPinnedStackLocked(r, null /* sourceBounds */, 0f /* aspectRatio */,
Winson Chung08f81892017-03-02 15:40:51 -08003108 true /* moveHomeStackToFront */, "moveTopActivityToPinnedStack");
Wale Ogunwale9c604c72015-12-06 18:42:57 -08003109 return true;
3110 }
3111
Winson Chung8bca9e42017-04-16 15:59:43 -07003112 void moveActivityToPinnedStackLocked(ActivityRecord r, Rect sourceHintBounds, float aspectRatio,
Winson Chung08f81892017-03-02 15:40:51 -08003113 boolean moveHomeStackToFront, String reason) {
3114
Wale Ogunwale480dca02016-02-06 13:58:29 -08003115 mWindowManager.deferSurfaceLayout();
Winson Chung74666102017-02-22 17:49:24 -08003116
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07003117 PinnedActivityStack stack = getStack(PINNED_STACK_ID);
3118
Bryce Lee04ab3462017-04-10 15:06:33 -07003119 // This will clear the pinned stack by moving an existing task to the full screen stack,
3120 // ensuring only one task is present.
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07003121 if (stack != null) {
3122 moveTasksToFullscreenStackLocked(stack, !ON_TOP);
3123 }
Bryce Lee04ab3462017-04-10 15:06:33 -07003124
Wale Ogunwale1666e312016-12-16 11:27:18 -08003125 // Need to make sure the pinned stack exist so we can resize it below...
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07003126 stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Wale Ogunwale1666e312016-12-16 11:27:18 -08003127
Wale Ogunwale480dca02016-02-06 13:58:29 -08003128 try {
Bryce Leeaf691c02017-03-20 14:20:22 -07003129 final TaskRecord task = r.getTask();
Wale Ogunwale480dca02016-02-06 13:58:29 -08003130 // Resize the pinned stack to match the current size of the task the activity we are
3131 // going to be moving is currently contained in. We do this to have the right starting
3132 // animation bounds for the pinned stack to the desired bounds the caller wants.
3133 resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
3134 null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07003135 true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwale480dca02016-02-06 13:58:29 -08003136
3137 if (task.mActivities.size() == 1) {
3138 // There is only one activity in the task. So, we can just move the task over to
Winson Chungc2baac02017-01-11 13:34:47 -08003139 // the stack without re-parenting the activity in a different task. We don't
3140 // move the home stack forward if we are currently entering picture-in-picture
3141 // while pausing because that changes the focused stack and may prevent the new
3142 // starting activity from resuming.
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07003143 if (moveHomeStackToFront && task.returnsToHomeTask()
Winson Chungf7e03e12017-08-22 11:32:16 -07003144 && (r.state == RESUMED || !r.supportsEnterPipOnTaskSwitch)) {
Wale Ogunwaleda4ba962016-03-11 09:33:17 -08003145 // Move the home stack forward if the task we just moved to the pinned stack
3146 // was launched from home so home should be visible behind it.
3147 moveHomeStackToFront(reason);
3148 }
Winson Chung5af42fc2017-03-24 17:11:33 -07003149 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08003150 task.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07003151 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08003152 } else {
Winson Chungb5c41b72016-12-07 15:00:47 -08003153 // There are multiple activities in the task and moving the top activity should
Winson Chung74666102017-02-22 17:49:24 -08003154 // reveal/leave the other activities in their original task.
3155
3156 // Currently, we don't support reparenting activities across tasks in two different
3157 // stacks, so instead, just create a new task in the same stack, reparent the
3158 // activity into that task, and then reparent the whole task to the new stack. This
3159 // ensures that all the necessary work to migrate states in the old and new stacks
3160 // is also done.
3161 final TaskRecord newTask = task.getStack().createTaskRecord(
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07003162 getNextTaskIdForUserLocked(r.userId), r.info, r.intent, null, null, true);
Winson Chung74666102017-02-22 17:49:24 -08003163 r.reparent(newTask, MAX_VALUE, "moveActivityToStack");
3164
Winson Chung5af42fc2017-03-24 17:11:33 -07003165 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08003166 newTask.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07003167 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08003168 }
Winson Chungc2baac02017-01-11 13:34:47 -08003169
3170 // Reset the state that indicates it can enter PiP while pausing after we've moved it
3171 // to the pinned stack
Winson Chungf7e03e12017-08-22 11:32:16 -07003172 r.supportsEnterPipOnTaskSwitch = false;
Wale Ogunwale480dca02016-02-06 13:58:29 -08003173 } finally {
3174 mWindowManager.continueSurfaceLayout();
Wale Ogunwale079a0042015-10-24 11:44:07 -07003175 }
3176
Winson Chunge7ba6862017-05-24 12:13:33 -07003177 // Calculate the default bounds (don't use existing stack bounds as we may have just created
3178 // the stack, and schedule the start of the animation into PiP (the bounds animator that
3179 // is triggered by this is posted on another thread)
Winson Chunga71febe2017-05-22 11:14:22 -07003180 final Rect destBounds = stack.getDefaultPictureInPictureBounds(aspectRatio);
3181
Winson Chunge7ba6862017-05-24 12:13:33 -07003182 stack.animateResizePinnedStack(sourceHintBounds, destBounds, -1 /* animationDuration */,
3183 true /* fromFullscreen */);
3184
3185 // Update the visibility of all activities after the they have been reparented to the new
3186 // stack. This MUST run after the animation above is scheduled to ensure that the windows
3187 // drawn signal is scheduled after the bounds animation start call on the bounds animator
3188 // thread.
Wale Ogunwale079a0042015-10-24 11:44:07 -07003189 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwaled046a012015-12-24 13:05:59 -08003190 resumeFocusedStackTopActivityLocked();
Wale Ogunwale03ce8632015-12-29 16:15:22 -08003191
Winson Chung85d3c8a2017-09-15 15:41:00 -07003192 mService.mTaskChangeNotificationController.notifyActivityPinned(r.packageName, r.userId,
Winson Chungb5026902017-05-03 12:45:13 -07003193 r.getTask().taskId);
Wale Ogunwale079a0042015-10-24 11:44:07 -07003194 }
3195
Andrii Kulian0864bbb2017-02-16 15:45:58 -08003196 /** Move activity with its stack to front and make the stack focused. */
Chong Zhang6cda19c2016-06-14 19:07:56 -07003197 boolean moveFocusableActivityStackToFrontLocked(ActivityRecord r, String reason) {
3198 if (r == null || !r.isFocusable()) {
3199 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3200 "moveActivityStackToFront: unfocusable r=" + r);
3201 return false;
3202 }
3203
Bryce Leeaf691c02017-03-20 14:20:22 -07003204 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003205 final ActivityStack stack = r.getStack();
3206 if (stack == null) {
Chong Zhang6cda19c2016-06-14 19:07:56 -07003207 Slog.w(TAG, "moveActivityStackToFront: invalid task or stack: r="
3208 + r + " task=" + task);
3209 return false;
3210 }
3211
Chong Zhang6cda19c2016-06-14 19:07:56 -07003212 if (stack == mFocusedStack && stack.topRunningActivityLocked() == r) {
3213 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3214 "moveActivityStackToFront: already on top, r=" + r);
3215 return false;
3216 }
3217
3218 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3219 "moveActivityStackToFront: r=" + r);
3220
3221 stack.moveToFront(reason, task);
3222 return true;
3223 }
3224
David Stevensc6b91c62017-02-08 14:23:58 -08003225 ActivityRecord findTaskLocked(ActivityRecord r, int displayId) {
Wale Ogunwale39381972015-12-17 17:15:29 -08003226 mTmpFindTaskResult.r = null;
3227 mTmpFindTaskResult.matchedByRootAffinity = false;
David Stevensc6b91c62017-02-08 14:23:58 -08003228 ActivityRecord affinityMatch = null;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003229 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
Craig Mautnere0a38842013-12-16 16:14:02 -08003230 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3231 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003232 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3233 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07003234 if (!r.hasCompatibleActivityType(stack)) {
Winson Chung91e5c882017-04-21 14:44:38 -07003235 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) "
3236 + stack);
Craig Mautner1b4bf852014-05-26 15:06:32 -07003237 continue;
3238 }
Wale Ogunwale39381972015-12-17 17:15:29 -08003239 stack.findTaskLocked(r, mTmpFindTaskResult);
David Stevensc6b91c62017-02-08 14:23:58 -08003240 // It is possible to have tasks in multiple stacks with the same root affinity, so
3241 // we should keep looking after finding an affinity match to see if there is a
3242 // better match in another stack. Also, task affinity isn't a good enough reason
3243 // to target a display which isn't the source of the intent, so skip any affinity
3244 // matches not on the specified display.
3245 if (mTmpFindTaskResult.r != null) {
3246 if (!mTmpFindTaskResult.matchedByRootAffinity) {
3247 return mTmpFindTaskResult.r;
3248 } else if (mTmpFindTaskResult.r.getDisplayId() == displayId) {
Winson Chung5b895b72017-05-01 13:46:25 -07003249 // Note: since the traversing through the stacks is top down, the floating
3250 // tasks should always have lower priority than any affinity-matching tasks
3251 // in the fullscreen stacks
David Stevensc6b91c62017-02-08 14:23:58 -08003252 affinityMatch = mTmpFindTaskResult.r;
David Stevense5a7b642017-05-22 13:18:23 -07003253 } else if (DEBUG_TASKS && mTmpFindTaskResult.matchedByRootAffinity) {
3254 Slog.d(TAG_TASKS, "Skipping match on different display "
3255 + mTmpFindTaskResult.r.getDisplayId() + " " + displayId);
David Stevensc6b91c62017-02-08 14:23:58 -08003256 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003257 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003258 }
3259 }
Winson Chung5b895b72017-05-01 13:46:25 -07003260
David Stevensc6b91c62017-02-08 14:23:58 -08003261 if (DEBUG_TASKS && affinityMatch == null) Slog.d(TAG_TASKS, "No task found");
3262 return affinityMatch;
Craig Mautner8849a5e2013-04-02 16:41:03 -07003263 }
3264
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003265 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
3266 boolean compareIntentFilters) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003267 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3268 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003269 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003270 final ActivityRecord ar = stacks.get(stackNdx)
3271 .findActivityLocked(intent, info, compareIntentFilters);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003272 if (ar != null) {
3273 return ar;
3274 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003275 }
3276 }
3277 return null;
3278 }
3279
David Stevens9440dc82017-03-16 19:00:20 -07003280 boolean hasAwakeDisplay() {
3281 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3282 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3283 if (!display.shouldSleep()) {
3284 return true;
3285 }
3286 }
3287 return false;
3288 }
3289
Craig Mautner8d341ef2013-03-26 09:03:27 -07003290 void goingToSleepLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003291 scheduleSleepTimeout();
3292 if (!mGoingToSleep.isHeld()) {
3293 mGoingToSleep.acquire();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003294 if (mLaunchingActivity.isHeld()) {
3295 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
3296 throw new IllegalStateException("Calling must be system uid");
Craig Mautner0eea92c2013-05-16 13:35:39 -07003297 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003298 mLaunchingActivity.release();
3299 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003300 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003301 }
David Stevens9440dc82017-03-16 19:00:20 -07003302
3303 applySleepTokensLocked(false /* applyToStacks */);
3304
3305 checkReadyForSleepLocked(true /* allowDelay */);
3306 }
3307
3308 void prepareForShutdownLocked() {
3309 for (int i = 0; i < mActivityDisplays.size(); i++) {
3310 createSleepTokenLocked("shutdown", mActivityDisplays.keyAt(i));
3311 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003312 }
3313
3314 boolean shutdownLocked(int timeout) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003315 goingToSleepLocked();
Craig Mautner0eea92c2013-05-16 13:35:39 -07003316
Craig Mautnerf4c909b2014-04-17 18:39:38 -07003317 boolean timedout = false;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003318 final long endTime = System.currentTimeMillis() + timeout;
3319 while (true) {
David Stevens18abd0e2017-08-17 14:55:47 -07003320 if (!putStacksToSleepLocked(true /* allowDelay */, true /* shuttingDown */)) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003321 long timeRemaining = endTime - System.currentTimeMillis();
3322 if (timeRemaining > 0) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003323 try {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003324 mService.wait(timeRemaining);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003325 } catch (InterruptedException e) {
3326 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003327 } else {
3328 Slog.w(TAG, "Activity manager shutdown timed out");
3329 timedout = true;
3330 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003331 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003332 } else {
3333 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003334 }
3335 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003336
3337 // Force checkReadyForSleep to complete.
David Stevens9440dc82017-03-16 19:00:20 -07003338 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003339
Craig Mautner8d341ef2013-03-26 09:03:27 -07003340 return timedout;
3341 }
3342
3343 void comeOutOfSleepIfNeededLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003344 removeSleepTimeouts();
3345 if (mGoingToSleep.isHeld()) {
3346 mGoingToSleep.release();
3347 }
David Stevens9440dc82017-03-16 19:00:20 -07003348 }
3349
3350 void applySleepTokensLocked(boolean applyToStacks) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003351 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
David Stevens9440dc82017-03-16 19:00:20 -07003352 // Set the sleeping state of the display.
3353 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3354 final boolean displayShouldSleep = display.shouldSleep();
3355 if (displayShouldSleep == display.isSleeping()) {
3356 continue;
3357 }
3358 display.setIsSleeping(displayShouldSleep);
3359
3360 if (!applyToStacks) {
3361 continue;
3362 }
3363
3364 // Set the sleeping state of the stacks on the display.
3365 final ArrayList<ActivityStack> stacks = display.mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003366 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3367 final ActivityStack stack = stacks.get(stackNdx);
David Stevens9440dc82017-03-16 19:00:20 -07003368 if (displayShouldSleep) {
3369 stack.goToSleepIfPossible(false /* shuttingDown */);
3370 } else {
3371 stack.awakeFromSleepingLocked();
3372 if (isFocusedStack(stack)) {
3373 resumeFocusedStackTopActivityLocked();
3374 }
3375 }
3376 }
3377
3378 if (displayShouldSleep || mGoingToSleepActivities.isEmpty()) {
3379 continue;
3380 }
3381 // The display is awake now, so clean up the going to sleep list.
3382 for (Iterator<ActivityRecord> it = mGoingToSleepActivities.iterator(); it.hasNext(); ) {
3383 final ActivityRecord r = it.next();
3384 if (r.getDisplayId() == display.mDisplayId) {
3385 it.remove();
Craig Mautner4a1cb222013-12-04 16:14:06 -08003386 }
Craig Mautner5314a402013-09-26 12:40:16 -07003387 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003388 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003389 }
3390
3391 void activitySleptLocked(ActivityRecord r) {
3392 mGoingToSleepActivities.remove(r);
David Stevens9440dc82017-03-16 19:00:20 -07003393 final ActivityStack s = r.getStack();
3394 if (s != null) {
3395 s.checkReadyForSleep();
3396 } else {
3397 checkReadyForSleepLocked(true);
3398 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003399 }
3400
David Stevens9440dc82017-03-16 19:00:20 -07003401 void checkReadyForSleepLocked(boolean allowDelay) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07003402 if (!mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003403 // Do not care.
3404 return;
3405 }
3406
David Stevens18abd0e2017-08-17 14:55:47 -07003407 if (!putStacksToSleepLocked(allowDelay, false /* shuttingDown */)) {
3408 return;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003409 }
3410
Wei Wang65c7a152016-06-02 18:51:22 -07003411 // Send launch end powerhint before going sleep
3412 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
3413
Craig Mautner0eea92c2013-05-16 13:35:39 -07003414 removeSleepTimeouts();
3415
3416 if (mGoingToSleep.isHeld()) {
3417 mGoingToSleep.release();
3418 }
3419 if (mService.mShuttingDown) {
3420 mService.notifyAll();
3421 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003422 }
3423
David Stevens18abd0e2017-08-17 14:55:47 -07003424 // Tries to put all activity stacks to sleep. Returns true if all stacks were
3425 // successfully put to sleep.
3426 private boolean putStacksToSleepLocked(boolean allowDelay, boolean shuttingDown) {
3427 boolean allSleep = true;
3428 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3429 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3430 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3431 if (allowDelay) {
3432 allSleep &= stacks.get(stackNdx).goToSleepIfPossible(shuttingDown);
3433 } else {
3434 stacks.get(stackNdx).goToSleep();
3435 }
3436 }
3437 }
3438 return allSleep;
3439 }
3440
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003441 boolean reportResumedActivityLocked(ActivityRecord r) {
Bryce Lee29a649d2017-08-18 13:52:31 -07003442 // A resumed activity cannot be stopping. remove from list
3443 mStoppingActivities.remove(r);
3444
Andrii Kulian02b7a832016-10-06 23:11:56 -07003445 final ActivityStack stack = r.getStack();
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003446 if (isFocusedStack(stack)) {
Jeff Sharkey5782da72013-04-25 14:32:30 -07003447 mService.updateUsageStats(r, true);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003448 }
3449 if (allResumedActivitiesComplete()) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003450 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003451 mWindowManager.executeAppTransition();
3452 return true;
3453 }
3454 return false;
3455 }
3456
Craig Mautner8d341ef2013-03-26 09:03:27 -07003457 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003458 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3459 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Wale Ogunwale28b23972015-07-29 16:01:50 -07003460 int stackNdx = stacks.size() - 1;
3461 while (stackNdx >= 0) {
3462 stacks.get(stackNdx).handleAppCrashLocked(app);
3463 stackNdx--;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003464 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003465 }
3466 }
3467
Craig Mautnerbb742462014-07-07 15:28:55 -07003468 // Called when WindowManager has finished animating the launchingBehind activity to the back.
Andrii Kulian21713ac2016-10-12 22:05:05 -07003469 private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003470 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003471 final ActivityStack stack = task.getStack();
Winson730bf062016-03-31 18:04:56 -07003472
3473 r.mLaunchTaskBehind = false;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08003474 mRecentTasks.addLocked(task);
Yorke Leebd54c2a2016-10-25 13:49:23 -07003475 mService.mTaskChangeNotificationController.notifyTaskStackChanged();
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003476 r.setVisibility(false);
Winson730bf062016-03-31 18:04:56 -07003477
3478 // When launching tasks behind, update the last active time of the top task after the new
3479 // task has been shown briefly
3480 final ActivityRecord top = stack.topActivity();
3481 if (top != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003482 top.getTask().touchActiveTime();
Winson730bf062016-03-31 18:04:56 -07003483 }
Craig Mautnerbb742462014-07-07 15:28:55 -07003484 }
3485
3486 void scheduleLaunchTaskBehindComplete(IBinder token) {
3487 mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
3488 }
3489
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003490 void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
3491 boolean preserveWindows) {
Jorim Jaggife762342016-10-13 14:33:27 +02003492 mKeyguardController.beginActivityVisibilityUpdate();
3493 try {
3494 // First the front stacks. In case any are not fullscreen and are in front of home.
3495 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3496 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3497 final int topStackNdx = stacks.size() - 1;
3498 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3499 final ActivityStack stack = stacks.get(stackNdx);
3500 stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
3501 }
Craig Mautner580ea812013-04-25 12:58:38 -07003502 }
Jorim Jaggife762342016-10-13 14:33:27 +02003503 } finally {
3504 mKeyguardController.endActivityVisibilityUpdate();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003505 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003506 }
3507
Jorim Jaggi8b702ed2017-01-20 16:59:03 +01003508 void addStartingWindowsForVisibleActivities(boolean taskSwitch) {
3509 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3510 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3511 final int topStackNdx = stacks.size() - 1;
3512 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3513 final ActivityStack stack = stacks.get(stackNdx);
3514 stack.addStartingWindowsForVisibleActivities(taskSwitch);
3515 }
3516 }
3517 }
3518
Chong Zhangfdcc4d42015-10-14 16:50:12 -07003519 void invalidateTaskLayers() {
3520 mTaskLayersChanged = true;
3521 }
3522
3523 void rankTaskLayersIfNeeded() {
3524 if (!mTaskLayersChanged) {
3525 return;
3526 }
3527 mTaskLayersChanged = false;
3528 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
3529 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3530 int baseLayer = 0;
3531 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3532 baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
3533 }
3534 }
3535 }
3536
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07003537 void clearOtherAppTimeTrackers(AppTimeTracker except) {
3538 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3539 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3540 final int topStackNdx = stacks.size() - 1;
3541 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3542 final ActivityStack stack = stacks.get(stackNdx);
3543 stack.clearOtherAppTimeTrackers(except);
3544 }
3545 }
3546 }
3547
Craig Mautner8d341ef2013-03-26 09:03:27 -07003548 void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003549 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3550 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003551 final int numStacks = stacks.size();
3552 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
3553 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003554 stack.scheduleDestroyActivities(app, reason);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003555 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003556 }
3557 }
3558
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003559 void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
3560 // Examine all activities currently running in the process.
3561 TaskRecord firstTask = null;
3562 // Tasks is non-null only if two or more tasks are found.
3563 ArraySet<TaskRecord> tasks = null;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003564 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
3565 for (int i = 0; i < app.activities.size(); i++) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003566 ActivityRecord r = app.activities.get(i);
3567 // First, if we find an activity that is in the process of being destroyed,
3568 // then we just aren't going to do anything for now; we want things to settle
3569 // down before we try to prune more activities.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003570 if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003571 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003572 return;
3573 }
3574 // Don't consider any activies that are currently not in a state where they
3575 // can be destroyed.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003576 if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
3577 || r.state == PAUSED || r.state == STOPPING) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003578 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003579 continue;
3580 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003581
3582 final TaskRecord task = r.getTask();
3583 if (task != null) {
3584 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + task
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003585 + " from " + r);
3586 if (firstTask == null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003587 firstTask = task;
3588 } else if (firstTask != task) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003589 if (tasks == null) {
3590 tasks = new ArraySet<>();
3591 tasks.add(firstTask);
3592 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003593 tasks.add(task);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003594 }
3595 }
3596 }
3597 if (tasks == null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003598 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003599 return;
3600 }
3601 // If we have activities in multiple tasks that are in a position to be destroyed,
3602 // let's iterate through the tasks and release the oldest one.
3603 final int numDisplays = mActivityDisplays.size();
3604 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3605 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3606 // Step through all stacks starting from behind, to hit the oldest things first.
3607 for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
3608 final ActivityStack stack = stacks.get(stackNdx);
3609 // Try to release activities in this stack; if we manage to, we are done.
3610 if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
3611 return;
3612 }
3613 }
3614 }
3615 }
3616
Amith Yamasani37a40c22015-06-17 13:25:42 -07003617 boolean switchUserLocked(int userId, UserState uss) {
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003618 final int focusStackId = mFocusedStack.getStackId();
3619 // We dismiss the docked stack whenever we switch users.
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07003620 final ActivityStack dockedStack = getStack(DOCKED_STACK_ID);
3621 if (dockedStack != null) {
3622 moveTasksToFullscreenStackLocked(dockedStack, mFocusedStack == dockedStack);
3623 }
Winson Chungc2b23a52017-01-09 15:44:55 -08003624 // Also dismiss the pinned stack whenever we switch users. Removing the pinned stack will
3625 // also cause all tasks to be moved to the fullscreen stack at a position that is
3626 // appropriate.
3627 removeStackLocked(PINNED_STACK_ID);
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003628
3629 mUserStackInFront.put(mCurrentUser, focusStackId);
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003630 final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
Craig Mautner2420ead2013-04-01 17:13:20 -07003631 mCurrentUser = userId;
Craig Mautnerac6f8432013-07-17 13:24:59 -07003632
Craig Mautner858d8a62013-04-23 17:08:34 -07003633 mStartingUsers.add(uss);
Craig Mautnere0a38842013-12-16 16:14:02 -08003634 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3635 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003636 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003637 final ActivityStack stack = stacks.get(stackNdx);
3638 stack.switchUserLocked(userId);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003639 TaskRecord task = stack.topTask();
3640 if (task != null) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08003641 stack.positionChildWindowContainerAtTop(task);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003642 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003643 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07003644 }
Craig Mautner858d8a62013-04-23 17:08:34 -07003645
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003646 ActivityStack stack = getStack(restoreStackId);
3647 if (stack == null) {
3648 stack = mHomeStack;
3649 }
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07003650 final boolean homeInFront = stack.isActivityTypeHome();
Craig Mautnere0a38842013-12-16 16:14:02 -08003651 if (stack.isOnHomeDisplay()) {
Wale Ogunwale925d0d12015-09-23 15:40:07 -07003652 stack.moveToFront("switchUserOnHomeDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003653 } else {
3654 // Stack was moved to another display while user was swapped out.
Matthew Ngae1ff4f2016-11-10 15:49:14 -08003655 resumeHomeStackTask(null, "switchUserOnOtherDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003656 }
Craig Mautner93529a42013-10-04 15:03:13 -07003657 return homeInFront;
Craig Mautner2219a1b2013-03-25 09:44:30 -07003658 }
3659
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003660 /** Checks whether the userid is a profile of the current user. */
3661 boolean isCurrentProfileLocked(int userId) {
3662 if (userId == mCurrentUser) return true;
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003663 return mService.mUserController.isCurrentProfile(userId);
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003664 }
3665
Bryce Leeb7c9b802017-05-02 14:20:24 -07003666 /**
3667 * Returns whether a stopping activity is present that should be stopped after visible, rather
3668 * than idle.
3669 * @return {@code true} if such activity is present. {@code false} otherwise.
3670 */
3671 boolean isStoppingNoHistoryActivity() {
3672 // Activities that are marked as nohistory should be stopped immediately after the resumed
3673 // activity has become visible.
3674 for (ActivityRecord record : mStoppingActivities) {
3675 if (record.isNoHistory()) {
3676 return true;
3677 }
3678 }
3679
3680 return false;
3681 }
3682
Winson Chung4dabf232017-01-25 13:25:22 -08003683 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
3684 boolean remove, boolean processPausingActivities) {
Craig Mautnerde4ef022013-04-07 19:01:33 -07003685 ArrayList<ActivityRecord> stops = null;
3686
3687 final boolean nowVisible = allResumedActivitiesVisible();
Craig Mautner8c14c152015-01-15 17:32:07 -08003688 for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3689 ActivityRecord s = mStoppingActivities.get(activityNdx);
Bryce Lee4a194382017-04-04 14:32:48 -07003690 boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003691 if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
Craig Mautner8c14c152015-01-15 17:32:07 -08003692 + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
3693 if (waitingVisible && nowVisible) {
Bryce Lee4a194382017-04-04 14:32:48 -07003694 mActivitiesWaitingForVisibleActivity.remove(s);
Andrii Kulianee056812016-09-21 15:34:45 -07003695 waitingVisible = false;
Craig Mautnerde4ef022013-04-07 19:01:33 -07003696 if (s.finishing) {
3697 // If this activity is finishing, it is sitting on top of
3698 // everyone else but we now know it is no longer needed...
3699 // so get rid of it. Otherwise, we need to go through the
3700 // normal flow and hide it once we determine that it is
3701 // hidden by the activities in front of it.
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003702 if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003703 s.setVisibility(false);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003704 }
3705 }
David Stevens9440dc82017-03-16 19:00:20 -07003706 if (remove) {
3707 final ActivityStack stack = s.getStack();
3708 final boolean shouldSleepOrShutDown = stack != null
3709 ? stack.shouldSleepOrShutDownActivities()
3710 : mService.isSleepingOrShuttingDownLocked();
3711 if (!waitingVisible || shouldSleepOrShutDown) {
3712 if (!processPausingActivities && s.state == PAUSING) {
3713 // Defer processing pausing activities in this iteration and reschedule
3714 // a delayed idle to reprocess it again
3715 removeTimeoutsForActivityLocked(idleActivity);
3716 scheduleIdleTimeoutLocked(idleActivity);
3717 continue;
3718 }
Winson Chung4dabf232017-01-25 13:25:22 -08003719
David Stevens9440dc82017-03-16 19:00:20 -07003720 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
3721 if (stops == null) {
3722 stops = new ArrayList<>();
3723 }
3724 stops.add(s);
3725 mStoppingActivities.remove(activityNdx);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003726 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07003727 }
3728 }
3729
3730 return stops;
3731 }
3732
Craig Mautnercf910b02013-04-23 11:23:27 -07003733 void validateTopActivitiesLocked() {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003734 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3735 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3736 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3737 final ActivityStack stack = stacks.get(stackNdx);
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07003738 final ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003739 final ActivityState state = r == null ? DESTROYED : r.state;
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003740 if (isFocusedStack(stack)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003741 if (r == null) Slog.e(TAG,
3742 "validateTop...: null top activity, stack=" + stack);
3743 else {
3744 final ActivityRecord pausing = stack.mPausingActivity;
3745 if (pausing != null && pausing == r) Slog.e(TAG,
3746 "validateTop...: top stack has pausing activity r=" + r
3747 + " state=" + state);
3748 if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3749 "validateTop...: activity in front not resumed r=" + r
3750 + " state=" + state);
3751 }
Craig Mautnercf910b02013-04-23 11:23:27 -07003752 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003753 final ActivityRecord resumed = stack.mResumedActivity;
3754 if (resumed != null && resumed == r) Slog.e(TAG,
3755 "validateTop...: back stack has resumed activity r=" + r
3756 + " state=" + state);
3757 if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3758 "validateTop...: activity in back resumed r=" + r + " state=" + state);
Craig Mautnercf910b02013-04-23 11:23:27 -07003759 }
3760 }
3761 }
Craig Mautner76ea2242013-05-15 11:40:05 -07003762 }
3763
Craig Mautner27084302013-03-25 08:05:25 -07003764 public void dump(PrintWriter pw, String prefix) {
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003765 pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003766 pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
Suprabh Shukla09a88f52015-12-02 14:36:31 -08003767 pw.print(prefix);
3768 pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003769 pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07003770 for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
3771 final ActivityDisplay display = mActivityDisplays.valueAt(i);
3772 pw.println(prefix + "displayId=" + display.mDisplayId + " mStacks=" + display.mStacks);
3773 }
Bryce Lee4a194382017-04-04 14:32:48 -07003774 if (!mWaitingForActivityVisible.isEmpty()) {
3775 pw.print(prefix); pw.println("mWaitingForActivityVisible=");
3776 for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
3777 pw.print(prefix); pw.print(prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
3778 }
3779 }
3780
Jorim Jaggi8d786932016-10-26 19:08:36 -07003781 mKeyguardController.dump(pw, prefix);
Benjamin Franza83859f2017-07-03 16:34:14 +01003782 mService.mLockTaskController.dump(pw, prefix);
Craig Mautner27084302013-03-25 08:05:25 -07003783 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003784
Steven Timotius4346f0a2017-09-12 11:07:21 -07003785 public void writeToProto(ProtoOutputStream proto, long fieldId) {
3786 final long token = proto.start(fieldId);
3787 super.writeToProto(proto, CONFIGURATION_CONTAINER);
3788 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3789 ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
3790 activityDisplay.writeToProto(proto, DISPLAYS);
3791 }
3792 mKeyguardController.writeToProto(proto, KEYGUARD_CONTROLLER);
3793 if (mFocusedStack != null) {
3794 proto.write(FOCUSED_STACK_ID, mFocusedStack.mStackId);
3795 ActivityRecord focusedActivity = getResumedActivityLocked();
3796 if (focusedActivity != null) {
3797 focusedActivity.writeIdentifierToProto(proto, RESUMED_ACTIVITY);
3798 }
3799 } else {
3800 proto.write(FOCUSED_STACK_ID, INVALID_STACK_ID);
3801 }
3802 proto.end(token);
3803 }
3804
Winson43d1f262016-06-14 16:05:55 -07003805 /**
Andrii Kulian5406e7a2016-10-21 11:55:23 -07003806 * Dump all connected displays' configurations.
3807 * @param prefix Prefix to apply to each line of the dump.
3808 */
3809 void dumpDisplayConfigs(PrintWriter pw, String prefix) {
3810 pw.print(prefix); pw.println("Display override configurations:");
3811 final int displayCount = mActivityDisplays.size();
3812 for (int i = 0; i < displayCount; i++) {
3813 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(i);
3814 pw.print(prefix); pw.print(" "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
3815 pw.println(activityDisplay.getOverrideConfiguration());
3816 }
3817 }
3818
3819 /**
Winson43d1f262016-06-14 16:05:55 -07003820 * Dumps the activities matching the given {@param name} in the either the focused stack
3821 * or all visible stacks if {@param dumpVisibleStacks} is true.
3822 */
Winson Chung6998bc42017-02-28 17:07:05 -08003823 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name, boolean dumpVisibleStacksOnly,
3824 boolean dumpFocusedStackOnly) {
3825 if (dumpFocusedStackOnly) {
3826 return mFocusedStack.getDumpActivitiesLocked(name);
3827 } else {
Winson43d1f262016-06-14 16:05:55 -07003828 ArrayList<ActivityRecord> activities = new ArrayList<>();
3829 int numDisplays = mActivityDisplays.size();
3830 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3831 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3832 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3833 ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07003834 if (!dumpVisibleStacksOnly || stack.shouldBeVisible(null)) {
Winson43d1f262016-06-14 16:05:55 -07003835 activities.addAll(stack.getDumpActivitiesLocked(name));
3836 }
3837 }
3838 }
3839 return activities;
Winson43d1f262016-06-14 16:05:55 -07003840 }
Craig Mautner20e72272013-04-01 13:45:53 -07003841 }
3842
Dianne Hackborn390517b2013-05-30 15:03:32 -07003843 static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3844 boolean needSep, String prefix) {
3845 if (activity != null) {
3846 if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3847 if (needSep) {
3848 pw.println();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003849 }
3850 pw.print(prefix);
3851 pw.println(activity);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003852 return true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003853 }
3854 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003855 return false;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003856 }
3857
Craig Mautner8d341ef2013-03-26 09:03:27 -07003858 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3859 boolean dumpClient, String dumpPackage) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003860 boolean printed = false;
3861 boolean needSep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003862 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3863 ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003864 pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
Craig Mautner737fae22014-10-15 12:52:10 -07003865 pw.println(" (activities from top to bottom):");
Craig Mautnere0a38842013-12-16 16:14:02 -08003866 ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
Craig Mautner737fae22014-10-15 12:52:10 -07003867 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003868 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale34a5b572017-08-31 08:29:41 -07003869 pw.println();
3870 pw.println(" Stack #" + stack.mStackId + ":");
3871 pw.println(" mFullscreen=" + stack.mFullscreen);
3872 pw.println(" isSleeping=" + stack.shouldSleepActivities());
3873 pw.println(" mBounds=" + stack.mBounds);
Winson Chungabb433b2017-03-24 09:35:42 -07003874
Wale Ogunwale34a5b572017-08-31 08:29:41 -07003875 printed |= stack.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, dumpPackage,
3876 needSep);
Winson Chungabb433b2017-03-24 09:35:42 -07003877
Craig Mautner4a1cb222013-12-04 16:14:06 -08003878 printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, " ", "Run", false,
3879 !dumpAll, false, dumpPackage, true,
3880 " Running activities (most recent first):", null);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003881
Craig Mautner4a1cb222013-12-04 16:14:06 -08003882 needSep = printed;
3883 boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3884 " mPausingActivity: ");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003885 if (pr) {
3886 printed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003887 needSep = false;
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003888 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003889 pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3890 " mResumedActivity: ");
3891 if (pr) {
3892 printed = true;
3893 needSep = false;
3894 }
3895 if (dumpAll) {
3896 pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3897 " mLastPausedActivity: ");
3898 if (pr) {
3899 printed = true;
3900 needSep = true;
3901 }
3902 printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3903 needSep, " mLastNoHistoryActivity: ");
3904 }
3905 needSep = printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003906 }
3907 }
3908
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003909 printed |= dumpHistoryList(fd, pw, mFinishingActivities, " ", "Fin", false, !dumpAll,
3910 false, dumpPackage, true, " Activities waiting to finish:", null);
3911 printed |= dumpHistoryList(fd, pw, mStoppingActivities, " ", "Stop", false, !dumpAll,
3912 false, dumpPackage, true, " Activities waiting to stop:", null);
Bryce Lee4a194382017-04-04 14:32:48 -07003913 printed |= dumpHistoryList(fd, pw, mActivitiesWaitingForVisibleActivity, " ", "Wait",
3914 false, !dumpAll, false, dumpPackage, true,
3915 " Activities waiting for another to become visible:", null);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003916 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3917 false, dumpPackage, true, " Activities waiting to sleep:", null);
Craig Mautnerf3333272013-04-22 10:55:53 -07003918
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003919 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003920 }
3921
Dianne Hackborn390517b2013-05-30 15:03:32 -07003922 static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
Craig Mautner8d341ef2013-03-26 09:03:27 -07003923 String prefix, String label, boolean complete, boolean brief, boolean client,
Wale Ogunwale34a5b572017-08-31 08:29:41 -07003924 String dumpPackage, boolean needNL, String header, TaskRecord lastTask) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003925 String innerPrefix = null;
3926 String[] args = null;
3927 boolean printed = false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003928 for (int i=list.size()-1; i>=0; i--) {
3929 final ActivityRecord r = list.get(i);
3930 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3931 continue;
3932 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003933 if (innerPrefix == null) {
3934 innerPrefix = prefix + " ";
3935 args = new String[0];
3936 }
3937 printed = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003938 final boolean full = !brief && (complete || !r.isInHistory());
3939 if (needNL) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003940 pw.println("");
Craig Mautner8d341ef2013-03-26 09:03:27 -07003941 needNL = false;
3942 }
Wale Ogunwale34a5b572017-08-31 08:29:41 -07003943 if (header != null) {
3944 pw.println(header);
3945 header = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003946 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003947 if (lastTask != r.getTask()) {
3948 lastTask = r.getTask();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003949 pw.print(prefix);
3950 pw.print(full ? "* " : " ");
3951 pw.println(lastTask);
3952 if (full) {
3953 lastTask.dump(pw, prefix + " ");
3954 } else if (complete) {
3955 // Complete + brief == give a summary. Isn't that obvious?!?
3956 if (lastTask.intent != null) {
3957 pw.print(prefix); pw.print(" ");
3958 pw.println(lastTask.intent.toInsecureStringWithClip());
3959 }
3960 }
3961 }
3962 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
3963 pw.print(" #"); pw.print(i); pw.print(": ");
3964 pw.println(r);
3965 if (full) {
3966 r.dump(pw, innerPrefix);
3967 } else if (complete) {
3968 // Complete + brief == give a summary. Isn't that obvious?!?
3969 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3970 if (r.app != null) {
3971 pw.print(innerPrefix); pw.println(r.app);
3972 }
3973 }
3974 if (client && r.app != null && r.app.thread != null) {
3975 // flush anything that is already in the PrintWriter since the thread is going
3976 // to write to the file descriptor directly
3977 pw.flush();
3978 try {
3979 TransferPipe tp = new TransferPipe();
3980 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003981 r.app.thread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003982 // Short timeout, since blocking here can
3983 // deadlock with the application.
3984 tp.go(fd, 2000);
3985 } finally {
3986 tp.kill();
3987 }
3988 } catch (IOException e) {
3989 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3990 } catch (RemoteException e) {
3991 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3992 }
3993 needNL = true;
3994 }
3995 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003996 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003997 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003998
Craig Mautnerf3333272013-04-22 10:55:53 -07003999 void scheduleIdleTimeoutLocked(ActivityRecord next) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004000 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
4001 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
Craig Mautnerc64f73e2013-04-24 16:44:56 -07004002 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
4003 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
Craig Mautnerf3333272013-04-22 10:55:53 -07004004 }
4005
4006 final void scheduleIdleLocked() {
Craig Mautner05d29032013-05-03 13:40:13 -07004007 mHandler.sendEmptyMessage(IDLE_NOW_MSG);
Craig Mautnerf3333272013-04-22 10:55:53 -07004008 }
4009
4010 void removeTimeoutsForActivityLocked(ActivityRecord r) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004011 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
4012 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07004013 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
4014 }
4015
Craig Mautner05d29032013-05-03 13:40:13 -07004016 final void scheduleResumeTopActivities() {
Craig Mautner34b73df2014-01-12 21:11:08 -08004017 if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
4018 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
4019 }
Craig Mautner05d29032013-05-03 13:40:13 -07004020 }
4021
Craig Mautner0eea92c2013-05-16 13:35:39 -07004022 void removeSleepTimeouts() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07004023 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
4024 }
4025
4026 final void scheduleSleepTimeout() {
4027 removeSleepTimeouts();
4028 mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
4029 }
4030
Craig Mautner4a1cb222013-12-04 16:14:06 -08004031 @Override
4032 public void onDisplayAdded(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07004033 if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004034 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
4035 }
4036
4037 @Override
4038 public void onDisplayRemoved(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07004039 if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004040 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
4041 }
4042
4043 @Override
4044 public void onDisplayChanged(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07004045 if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004046 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
4047 }
4048
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004049 private void handleDisplayAdded(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004050 synchronized (mService) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07004051 getActivityDisplayOrCreateLocked(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004052 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004053 }
4054
Andrii Kulianca007a62016-11-22 16:33:28 -08004055 /** Check if display with specified id is added to the list. */
4056 boolean isDisplayAdded(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07004057 return getActivityDisplayOrCreateLocked(displayId) != null;
4058 }
4059
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004060 ActivityDisplay getActivityDisplay(int displayId) {
4061 return mActivityDisplays.get(displayId);
4062 }
4063
Andrii Kulian62e6f252017-05-30 22:46:53 -07004064 /**
4065 * Get an existing instance of {@link ActivityDisplay} or create new if there is a
4066 * corresponding record in display manager.
4067 */
4068 private ActivityDisplay getActivityDisplayOrCreateLocked(int displayId) {
4069 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
4070 if (activityDisplay != null) {
4071 return activityDisplay;
4072 }
4073 if (mDisplayManager == null) {
4074 // The system isn't fully initialized yet.
4075 return null;
4076 }
4077 final Display display = mDisplayManager.getDisplay(displayId);
4078 if (display == null) {
4079 // The display is not registered in DisplayManager.
4080 return null;
4081 }
4082 // The display hasn't been added to ActivityManager yet, create a new record now.
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07004083 activityDisplay = new ActivityDisplay(this, displayId);
4084 attachDisplay(activityDisplay);
Andrii Kulian62e6f252017-05-30 22:46:53 -07004085 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
4086 mWindowManager.onDisplayAdded(displayId);
4087 return activityDisplay;
Andrii Kulianca007a62016-11-22 16:33:28 -08004088 }
4089
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07004090 @VisibleForTesting
4091 void attachDisplay(ActivityDisplay display) {
4092 mActivityDisplays.put(display.mDisplayId, display);
4093 }
4094
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07004095 private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
Andrii Kulianf66a83d2016-05-17 12:17:44 -07004096 mDefaultMinSizeOfResizeableTask =
Jorim Jaggi19cf2972016-04-07 23:26:10 -07004097 mService.mContext.getResources().getDimensionPixelSize(
4098 com.android.internal.R.dimen.default_minimal_size_resizable_task);
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07004099 }
4100
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004101 private void handleDisplayRemoved(int displayId) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08004102 if (displayId == DEFAULT_DISPLAY) {
4103 throw new IllegalArgumentException("Can't remove the primary display.");
4104 }
4105
Craig Mautner4a1cb222013-12-04 16:14:06 -08004106 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08004107 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
4108 if (activityDisplay != null) {
Andrii Kulian250d6532017-02-08 23:30:45 -08004109 final boolean destroyContentOnRemoval
4110 = activityDisplay.shouldDestroyContentOnRemove();
Andrii Kuliana33818c2017-02-16 16:11:30 -08004111 final ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
4112 while (!stacks.isEmpty()) {
4113 final ActivityStack stack = stacks.get(0);
Andrii Kulian250d6532017-02-08 23:30:45 -08004114 if (destroyContentOnRemoval) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08004115 moveStackToDisplayLocked(stack.mStackId, DEFAULT_DISPLAY,
4116 false /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08004117 stack.finishAllActivitiesLocked(true /* immediately */);
Andrii Kuliana33818c2017-02-16 16:11:30 -08004118 } else {
4119 // Moving all tasks to fullscreen stack, because it's guaranteed to be
4120 // a valid launch stack for all activities. This way the task history from
4121 // external display will be preserved on primary after move.
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07004122 moveTasksToFullscreenStackLocked(stack, true /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08004123 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004124 }
David Stevens9440dc82017-03-16 19:00:20 -07004125
4126 releaseSleepTokens(activityDisplay);
4127
Craig Mautnere0a38842013-12-16 16:14:02 -08004128 mActivityDisplays.remove(displayId);
Bryce Leeaf3a4002017-03-20 10:37:12 -07004129 mWindowManager.onDisplayRemoved(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004130 }
4131 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004132 }
4133
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004134 private void handleDisplayChanged(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004135 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08004136 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
4137 if (activityDisplay != null) {
David Stevens9440dc82017-03-16 19:00:20 -07004138 // The window policy is responsible for stopping activities on the default display
4139 if (displayId != Display.DEFAULT_DISPLAY) {
4140 int displayState = activityDisplay.mDisplay.getState();
4141 if (displayState == Display.STATE_OFF && activityDisplay.mOffToken == null) {
4142 activityDisplay.mOffToken =
4143 mService.acquireSleepToken("Display-off", displayId);
4144 } else if (displayState == Display.STATE_ON
4145 && activityDisplay.mOffToken != null) {
4146 activityDisplay.mOffToken.release();
4147 activityDisplay.mOffToken = null;
4148 }
4149 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004150 // TODO: Update the bounds.
4151 }
Bryce Leeaf3a4002017-03-20 10:37:12 -07004152 mWindowManager.onDisplayChanged(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004153 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004154 }
4155
David Stevens9440dc82017-03-16 19:00:20 -07004156 SleepToken createSleepTokenLocked(String tag, int displayId) {
4157 ActivityDisplay display = mActivityDisplays.get(displayId);
4158 if (display == null) {
4159 throw new IllegalArgumentException("Invalid display: " + displayId);
4160 }
4161
4162 final SleepTokenImpl token = new SleepTokenImpl(tag, displayId);
4163 mSleepTokens.add(token);
4164 display.mAllSleepTokens.add(token);
4165 return token;
4166 }
4167
4168 private void removeSleepTokenLocked(SleepTokenImpl token) {
4169 mSleepTokens.remove(token);
4170
4171 ActivityDisplay display = mActivityDisplays.get(token.mDisplayId);
4172 if (display != null) {
4173 display.mAllSleepTokens.remove(token);
4174 if (display.mAllSleepTokens.isEmpty()) {
4175 mService.updateSleepIfNeededLocked();
4176 }
4177 }
4178 }
4179
4180 private void releaseSleepTokens(ActivityDisplay display) {
4181 if (display.mAllSleepTokens.isEmpty()) {
4182 return;
4183 }
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07004184 for (SleepToken token : display.mAllSleepTokens) {
David Stevens9440dc82017-03-16 19:00:20 -07004185 mSleepTokens.remove(token);
4186 }
4187 display.mAllSleepTokens.clear();
4188
4189 mService.updateSleepIfNeededLocked();
4190 }
4191
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004192 private StackInfo getStackInfoLocked(ActivityStack stack) {
Andrii Kulian7e215d72017-04-26 18:33:28 -07004193 final int displayId = stack.mDisplayId;
4194 final ActivityDisplay display = mActivityDisplays.get(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004195 StackInfo info = new StackInfo();
Wale Ogunwale1666e312016-12-16 11:27:18 -08004196 stack.getWindowContainerBounds(info.bounds);
Andrii Kulian7e215d72017-04-26 18:33:28 -07004197 info.displayId = displayId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004198 info.stackId = stack.mStackId;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004199 info.userId = stack.mCurrentUser;
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07004200 info.visible = stack.shouldBeVisible(null);
Andrii Kulian62e6f252017-05-30 22:46:53 -07004201 // A stack might be not attached to a display.
Winson529c8e42016-05-17 11:08:40 -07004202 info.position = display != null
4203 ? display.mStacks.indexOf(stack)
4204 : 0;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004205
4206 ArrayList<TaskRecord> tasks = stack.getAllTasks();
4207 final int numTasks = tasks.size();
4208 int[] taskIds = new int[numTasks];
4209 String[] taskNames = new String[numTasks];
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004210 Rect[] taskBounds = new Rect[numTasks];
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004211 int[] taskUserIds = new int[numTasks];
Craig Mautner4a1cb222013-12-04 16:14:06 -08004212 for (int i = 0; i < numTasks; ++i) {
4213 final TaskRecord task = tasks.get(i);
4214 taskIds[i] = task.taskId;
4215 taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
4216 : task.realActivity != null ? task.realActivity.flattenToString()
4217 : task.getTopActivity() != null ? task.getTopActivity().packageName
4218 : "unknown";
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004219 taskBounds[i] = new Rect();
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004220 task.getWindowContainerBounds(taskBounds[i]);
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004221 taskUserIds[i] = task.userId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004222 }
4223 info.taskIds = taskIds;
4224 info.taskNames = taskNames;
Wale Ogunwale868a5e12015-08-02 16:19:20 -07004225 info.taskBounds = taskBounds;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004226 info.taskUserIds = taskUserIds;
Winsond46b7272016-04-20 11:54:27 -07004227
4228 final ActivityRecord top = stack.topRunningActivityLocked();
4229 info.topActivity = top != null ? top.intent.getComponent() : null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004230 return info;
4231 }
4232
4233 StackInfo getStackInfoLocked(int stackId) {
4234 ActivityStack stack = getStack(stackId);
4235 if (stack != null) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004236 return getStackInfoLocked(stack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004237 }
4238 return null;
4239 }
4240
4241 ArrayList<StackInfo> getAllStackInfosLocked() {
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004242 ArrayList<StackInfo> list = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08004243 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
4244 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004245 for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004246 list.add(getStackInfoLocked(stacks.get(ndx)));
Craig Mautner4a1cb222013-12-04 16:14:06 -08004247 }
4248 }
4249 return list;
4250 }
4251
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004252 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredWindowingMode,
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004253 int preferredDisplayId, int actualStackId) {
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004254 handleNonResizableTaskIfNeeded(task, preferredWindowingMode, preferredDisplayId,
4255 actualStackId, false /* forceNonResizable */);
Andrii Kulianc27916642016-04-12 17:59:27 -07004256 }
4257
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004258 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredWindowingMode,
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004259 int preferredDisplayId, int actualStackId, boolean forceNonResizable) {
4260 final boolean isSecondaryDisplayPreferred =
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004261 (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY);
Wale Ogunwale926aade2017-08-29 11:24:37 -07004262 final ActivityStack actualStack = getStack(actualStackId);
4263 final boolean inSplitScreenMode = actualStack != null
4264 && actualStack.inSplitScreenWindowingMode();
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004265 if (((!inSplitScreenMode && preferredWindowingMode != WINDOWING_MODE_SPLIT_SCREEN_PRIMARY)
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07004266 && !isSecondaryDisplayPreferred) || task.isActivityTypeHome()) {
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004267 return;
4268 }
4269
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004270 // Handle incorrect launch/move to secondary display if needed.
4271 final boolean launchOnSecondaryDisplayFailed;
4272 if (isSecondaryDisplayPreferred) {
4273 final int actualDisplayId = task.getStack().mDisplayId;
4274 if (!task.canBeLaunchedOnDisplay(actualDisplayId)) {
4275 // The task landed on an inappropriate display somehow, move it to the default
4276 // display.
4277 // TODO(multi-display): Find proper stack for the task on the default display.
4278 mService.moveTaskToStack(task.taskId, FULLSCREEN_WORKSPACE_STACK_ID,
4279 true /* toTop */);
4280 launchOnSecondaryDisplayFailed = true;
4281 } else {
4282 // The task might have landed on a display different from requested.
4283 launchOnSecondaryDisplayFailed = actualDisplayId == DEFAULT_DISPLAY
4284 || (preferredDisplayId != INVALID_DISPLAY
4285 && preferredDisplayId != actualDisplayId);
4286 }
4287 } else {
4288 // The task wasn't requested to be on a secondary display.
4289 launchOnSecondaryDisplayFailed = false;
4290 }
4291
Jorim Jaggicd13d332016-04-27 15:40:20 -07004292 final ActivityRecord topActivity = task.getTopActivity();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004293 if (launchOnSecondaryDisplayFailed || !task.supportsSplitScreen() || forceNonResizable) {
4294 if (launchOnSecondaryDisplayFailed) {
4295 // Display a warning toast that we tried to put a non-resizeable task on a secondary
4296 // display with config different from global config.
4297 mService.mTaskChangeNotificationController
4298 .notifyActivityLaunchOnSecondaryDisplayFailed();
4299 } else {
4300 // Display a warning toast that we tried to put a non-dockable task in the docked
4301 // stack.
4302 mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
4303 }
Jorim Jaggid53f0922016-04-06 22:16:23 -07004304
Andrii Kulianc27916642016-04-12 17:59:27 -07004305 // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
4306 // we need to move it to top of fullscreen stack, otherwise it will be covered.
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07004307 final ActivityStack dockedStack = getStack(DOCKED_STACK_ID);
4308 if (dockedStack != null) {
4309 moveTasksToFullscreenStackLocked(dockedStack,
4310 actualStackId == dockedStack.getStackId());
4311 }
Winson Chungd3395382016-12-13 11:49:09 -08004312 } else if (topActivity != null && topActivity.isNonResizableOrForcedResizable()
Jorim Jaggicd13d332016-04-27 15:40:20 -07004313 && !topActivity.noDisplay) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004314 final String packageName = topActivity.appInfo.packageName;
4315 final int reason = isSecondaryDisplayPreferred
4316 ? FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY
4317 : FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Yorke Leebd54c2a2016-10-25 13:49:23 -07004318 mService.mTaskChangeNotificationController.notifyActivityForcedResizable(
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004319 task.taskId, reason, packageName);
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004320 }
Chong Zhangb15758a2015-11-17 12:12:03 -08004321 }
4322
Jorim Jaggife89d122015-12-22 16:28:44 +01004323 void activityRelaunchedLocked(IBinder token) {
4324 mWindowManager.notifyAppRelaunchingFinished(token);
David Stevens9440dc82017-03-16 19:00:20 -07004325 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4326 if (r != null) {
4327 if (r.getStack().shouldSleepOrShutDownActivities()) {
Wale Ogunwale3e997362016-09-06 10:37:56 -07004328 r.setSleeping(true, true);
4329 }
4330 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004331 }
4332
4333 void activityRelaunchingLocked(ActivityRecord r) {
4334 mWindowManager.notifyAppRelaunching(r.appToken);
4335 }
4336
Filip Gruszczynski77d94482015-12-11 13:59:52 -08004337 void logStackState() {
4338 mActivityMetricsLogger.logWindowState();
4339 }
4340
Winson Chung5af42fc2017-03-24 17:11:33 -07004341 void scheduleUpdateMultiWindowMode(TaskRecord task) {
Winson Chung8bca9e42017-04-16 15:59:43 -07004342 // If the stack is animating in a way where we will be forcing a multi-mode change at the
4343 // end, then ensure that we defer all in between multi-window mode changes
4344 if (task.getStack().deferScheduleMultiWindowModeChanged()) {
4345 return;
4346 }
4347
Wale Ogunwale22e25262016-02-01 10:32:02 -08004348 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4349 final ActivityRecord r = task.mActivities.get(i);
4350 if (r.app != null && r.app.thread != null) {
4351 mMultiWindowModeChangedActivities.add(r);
4352 }
4353 }
4354
4355 if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
4356 mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
4357 }
4358 }
4359
Winson Chung5af42fc2017-03-24 17:11:33 -07004360 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07004361 final ActivityStack stack = task.getStack();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004362 if (prevStack == null || prevStack == stack
4363 || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
4364 return;
4365 }
4366
Winson Chungab76bbc2017-08-14 13:33:51 -07004367 scheduleUpdatePictureInPictureModeIfNeeded(task, stack.mBounds);
Winson Chung5af42fc2017-03-24 17:11:33 -07004368 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004369
Winson Chungab76bbc2017-08-14 13:33:51 -07004370 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds) {
4371 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4372 final ActivityRecord r = task.mActivities.get(i);
4373 if (r.app != null && r.app.thread != null) {
4374 mPipModeChangedActivities.add(r);
Winson Chung5af42fc2017-03-24 17:11:33 -07004375 }
Winson Chungab76bbc2017-08-14 13:33:51 -07004376 }
4377 mPipModeChangedTargetStackBounds = targetStackBounds;
Winson Chung5af42fc2017-03-24 17:11:33 -07004378
Winson Chungab76bbc2017-08-14 13:33:51 -07004379 if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
4380 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
4381 }
4382 }
4383
4384 void updatePictureInPictureMode(TaskRecord task, Rect targetStackBounds, boolean forceUpdate) {
4385 mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG);
4386 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4387 final ActivityRecord r = task.mActivities.get(i);
4388 if (r.app != null && r.app.thread != null) {
4389 r.updatePictureInPictureMode(targetStackBounds, forceUpdate);
Winson Chung5af42fc2017-03-24 17:11:33 -07004390 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004391 }
4392 }
4393
Tony Mak853304c2016-04-18 15:17:41 +01004394 void setDockedStackMinimized(boolean minimized) {
4395 mIsDockMinimized = minimized;
Tony Mak853304c2016-04-18 15:17:41 +01004396 }
4397
chaviw59b98852017-06-13 12:05:44 -07004398 void wakeUp(String reason) {
4399 mPowerManager.wakeUp(SystemClock.uptimeMillis(), "android.server.am:TURN_ON:" + reason);
4400 }
4401
4402 /**
4403 * Begin deferring resume to avoid duplicate resumes in one pass.
4404 */
4405 private void beginDeferResume() {
4406 mDeferResumeCount++;
4407 }
4408
4409 /**
4410 * End deferring resume and determine if resume can be called.
4411 */
4412 private void endDeferResume() {
4413 mDeferResumeCount--;
4414 }
4415
4416 /**
4417 * @return True if resume can be called.
4418 */
4419 private boolean readyToResume() {
4420 return mDeferResumeCount == 0;
4421 }
4422
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004423 private final class ActivityStackSupervisorHandler extends Handler {
Craig Mautnerf3333272013-04-22 10:55:53 -07004424
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004425 public ActivityStackSupervisorHandler(Looper looper) {
4426 super(looper);
4427 }
4428
Winson Chung4dabf232017-01-25 13:25:22 -08004429 void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) {
Craig Mautnerf3333272013-04-22 10:55:53 -07004430 synchronized (mService) {
Winson Chung4dabf232017-01-25 13:25:22 -08004431 activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */,
4432 processPausingActivities, null);
Craig Mautnerf3333272013-04-22 10:55:53 -07004433 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004434 }
4435
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004436 @Override
4437 public void handleMessage(Message msg) {
4438 switch (msg.what) {
Wale Ogunwale22e25262016-02-01 10:32:02 -08004439 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
4440 synchronized (mService) {
4441 for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
4442 final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004443 r.updateMultiWindowMode();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004444 }
4445 }
4446 } break;
4447 case REPORT_PIP_MODE_CHANGED_MSG: {
4448 synchronized (mService) {
4449 for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
4450 final ActivityRecord r = mPipModeChangedActivities.remove(i);
Winson Chungab76bbc2017-08-14 13:33:51 -07004451 r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds,
4452 false /* forceUpdate */);
Wale Ogunwale22e25262016-02-01 10:32:02 -08004453 }
4454 }
4455 } break;
Craig Mautnerf3333272013-04-22 10:55:53 -07004456 case IDLE_TIMEOUT_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004457 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
4458 "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
Craig Mautnerf3333272013-04-22 10:55:53 -07004459 // We don't at this point know if the activity is fullscreen,
4460 // so we need to be conservative and assume it isn't.
Winson Chung4dabf232017-01-25 13:25:22 -08004461 activityIdleInternal((ActivityRecord) msg.obj,
4462 true /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004463 } break;
4464 case IDLE_NOW_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004465 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
Winson Chung4dabf232017-01-25 13:25:22 -08004466 activityIdleInternal((ActivityRecord) msg.obj,
4467 false /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004468 } break;
Craig Mautner05d29032013-05-03 13:40:13 -07004469 case RESUME_TOP_ACTIVITY_MSG: {
4470 synchronized (mService) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004471 resumeFocusedStackTopActivityLocked();
Craig Mautner05d29032013-05-03 13:40:13 -07004472 }
4473 } break;
Craig Mautner0eea92c2013-05-16 13:35:39 -07004474 case SLEEP_TIMEOUT_MSG: {
4475 synchronized (mService) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07004476 if (mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07004477 Slog.w(TAG, "Sleep timeout! Sleeping now.");
David Stevens9440dc82017-03-16 19:00:20 -07004478 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07004479 }
4480 }
4481 } break;
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004482 case LAUNCH_TIMEOUT_MSG: {
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004483 synchronized (mService) {
4484 if (mLaunchingActivity.isHeld()) {
4485 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
4486 if (VALIDATE_WAKE_LOCK_CALLER
4487 && Binder.getCallingUid() != Process.myUid()) {
4488 throw new IllegalStateException("Calling must be system uid");
4489 }
4490 mLaunchingActivity.release();
4491 }
4492 }
4493 } break;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004494 case HANDLE_DISPLAY_ADDED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004495 handleDisplayAdded(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004496 } break;
4497 case HANDLE_DISPLAY_CHANGED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004498 handleDisplayChanged(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004499 } break;
4500 case HANDLE_DISPLAY_REMOVED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004501 handleDisplayRemoved(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004502 } break;
Craig Mautnerbb742462014-07-07 15:28:55 -07004503 case LAUNCH_TASK_BEHIND_COMPLETE: {
4504 synchronized (mService) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07004505 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
Craig Mautnerbb742462014-07-07 15:28:55 -07004506 if (r != null) {
4507 handleLaunchTaskBehindCompleteLocked(r);
4508 }
4509 }
4510 } break;
Chong Zhangc806d902015-11-30 09:44:27 -08004511
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004512 }
4513 }
4514 }
Craig Mautnered6649f2013-12-02 14:08:25 -08004515
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004516 ActivityStack findStackBehind(ActivityStack stack) {
4517 // TODO(multi-display): We are only looking for stacks on the default display.
Jorim Jaggife762342016-10-13 14:33:27 +02004518 final ActivityDisplay display = mActivityDisplays.get(DEFAULT_DISPLAY);
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004519 if (display == null) {
4520 return null;
4521 }
4522 final ArrayList<ActivityStack> stacks = display.mStacks;
4523 for (int i = stacks.size() - 1; i >= 0; i--) {
4524 if (stacks.get(i) == stack && i > 0) {
4525 return stacks.get(i - 1);
4526 }
4527 }
4528 throw new IllegalStateException("Failed to find a stack behind stack=" + stack
4529 + " in=" + stacks);
4530 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004531
Jorim Jaggic69bd222016-03-15 14:38:37 +01004532 /**
4533 * Puts a task into resizing mode during the next app transition.
4534 *
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004535 * @param task The task to put into resizing mode
Jorim Jaggic69bd222016-03-15 14:38:37 +01004536 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004537 private void setResizingDuringAnimation(TaskRecord task) {
4538 mResizingTasksDuringAnimation.add(task.taskId);
4539 task.setTaskDockedResizing(true);
Jorim Jaggic69bd222016-03-15 14:38:37 +01004540 }
4541
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004542 final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
4543 final TaskRecord task;
4544 final int callingUid;
4545 final String callingPackage;
4546 final Intent intent;
4547 final int userId;
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004548 int activityType = ACTIVITY_TYPE_UNDEFINED;
4549 int windowingMode = WINDOWING_MODE_UNDEFINED;
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004550 final ActivityOptions activityOptions = (bOptions != null)
4551 ? new ActivityOptions(bOptions) : null;
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004552 if (activityOptions != null) {
4553 activityType = activityOptions.getLaunchActivityType();
4554 windowingMode = activityOptions.getLaunchWindowingMode();
4555 }
4556 if (activityType == ACTIVITY_TYPE_HOME || activityType == ACTIVITY_TYPE_RECENTS) {
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004557 throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004558 + taskId + " can't be launch in the home/recents stack.");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004559 }
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004560
Matthew Ng606dd802017-06-05 14:06:32 -07004561 mWindowManager.deferSurfaceLayout();
4562 try {
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004563 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Matthew Ng606dd802017-06-05 14:06:32 -07004564 mWindowManager.setDockedStackCreateState(
4565 activityOptions.getDockCreateMode(), null /* initialBounds */);
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004566
Matthew Ng606dd802017-06-05 14:06:32 -07004567 // Defer updating the stack in which recents is until the app transition is done, to
4568 // not run into issues where we still need to draw the task in recents but the
4569 // docked stack is already created.
4570 deferUpdateBounds(RECENTS_STACK_ID);
4571 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004572 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004573
Matthew Ng606dd802017-06-05 14:06:32 -07004574 task = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004575 activityOptions);
Matthew Ng606dd802017-06-05 14:06:32 -07004576 if (task == null) {
4577 continueUpdateBounds(RECENTS_STACK_ID);
4578 mWindowManager.executeAppTransition();
4579 throw new IllegalArgumentException(
4580 "startActivityFromRecentsInner: Task " + taskId + " not found.");
4581 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004582
Matthew Ng606dd802017-06-05 14:06:32 -07004583 // Since we don't have an actual source record here, we assume that the currently
4584 // focused activity was the source.
4585 final ActivityStack focusedStack = getFocusedStack();
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004586 final ActivityRecord sourceRecord = focusedStack != null
4587 ? focusedStack.topActivity() : null;
4588 final int stackId = getLaunchStackId(null, activityOptions, task);
Matthew Ng606dd802017-06-05 14:06:32 -07004589
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004590 if (stackId != INVALID_STACK_ID && task.getStackId() != stackId) {
4591 task.reparent(stackId, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE, DEFER_RESUME,
4592 "startActivityFromRecents");
Matthew Ng606dd802017-06-05 14:06:32 -07004593 }
4594
4595 // If the user must confirm credentials (e.g. when first launching a work app and the
4596 // Work Challenge is present) let startActivityInPackage handle the intercepting.
4597 if (!mService.mUserController.shouldConfirmCredentials(task.userId)
4598 && task.getRootActivity() != null) {
Bryce Lee28d80422017-07-21 13:25:13 -07004599 final ActivityRecord targetActivity = task.getTopActivity();
4600
4601 mService.mActivityStarter.sendPowerHintForLaunchStartIfNeeded(true /* forceSend */,
4602 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004603 mActivityMetricsLogger.notifyActivityLaunching();
Jorim Jaggi42befc62017-06-13 11:54:04 -07004604 mService.moveTaskToFrontLocked(task.taskId, 0, bOptions, true /* fromRecents */);
Matthew Ng606dd802017-06-05 14:06:32 -07004605 mActivityMetricsLogger.notifyActivityLaunched(ActivityManager.START_TASK_TO_FRONT,
Bryce Lee28d80422017-07-21 13:25:13 -07004606 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004607
4608 // If we are launching the task in the docked stack, put it into resizing mode so
4609 // the window renders full-screen with the background filling the void. Also only
4610 // call this at the end to make sure that tasks exists on the window manager side.
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004611 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Matthew Ng606dd802017-06-05 14:06:32 -07004612 setResizingDuringAnimation(task);
4613 }
4614
4615 mService.mActivityStarter.postStartActivityProcessing(task.getTopActivity(),
4616 ActivityManager.START_TASK_TO_FRONT,
4617 sourceRecord != null
4618 ? sourceRecord.getTask().getStackId() : INVALID_STACK_ID,
4619 sourceRecord, task.getStack());
4620 return ActivityManager.START_TASK_TO_FRONT;
4621 }
4622 callingUid = task.mCallingUid;
4623 callingPackage = task.mCallingPackage;
4624 intent = task.intent;
4625 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4626 userId = task.userId;
4627 int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004628 null, null, 0, 0, bOptions, userId, task, "startActivityFromRecents");
Wale Ogunwale0568aed2017-09-08 13:29:37 -07004629 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004630 setResizingDuringAnimation(task);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004631 }
Matthew Ng606dd802017-06-05 14:06:32 -07004632 return result;
4633 } finally {
4634 mWindowManager.continueSurfaceLayout();
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004635 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004636 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004637
4638 /**
4639 * @return a list of activities which are the top ones in each visible stack. The first
4640 * entry will be the focused activity.
4641 */
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004642 List<IBinder> getTopVisibleActivities() {
4643 final ArrayList<IBinder> topActivityTokens = new ArrayList<>();
4644 // Traverse all displays.
Robert Carr22374c02017-02-21 13:01:47 -08004645 for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004646 final ActivityDisplay display = mActivityDisplays.valueAt(i);
4647 // Traverse all stacks on a display.
4648 for (int j = display.mStacks.size() - 1; j >= 0; j--) {
4649 final ActivityStack stack = display.mStacks.get(j);
4650 // Get top activity from a visible stack and add it to the list.
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07004651 if (stack.shouldBeVisible(null /* starting */)) {
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004652 final ActivityRecord top = stack.topActivity();
4653 if (top != null) {
4654 if (stack == mFocusedStack) {
4655 topActivityTokens.add(0, top.appToken);
4656 } else {
4657 topActivityTokens.add(top.appToken);
4658 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004659 }
4660 }
4661 }
4662 }
4663 return topActivityTokens;
4664 }
Bryce Lee4a194382017-04-04 14:32:48 -07004665
4666 /**
4667 * Internal container to store a match qualifier alongside a WaitResult.
4668 */
4669 static class WaitInfo {
4670 private final ComponentName mTargetComponent;
4671 private final WaitResult mResult;
4672
4673 public WaitInfo(ComponentName targetComponent, WaitResult result) {
4674 this.mTargetComponent = targetComponent;
4675 this.mResult = result;
4676 }
4677
Wale Ogunwale3270f172017-04-26 07:29:42 -07004678 public boolean matches(ComponentName targetComponent) {
4679 return mTargetComponent == null || mTargetComponent.equals(targetComponent);
Bryce Lee4a194382017-04-04 14:32:48 -07004680 }
4681
4682 public WaitResult getResult() {
4683 return mResult;
4684 }
4685
4686 public ComponentName getComponent() {
4687 return mTargetComponent;
4688 }
4689
4690 public void dump(PrintWriter pw, String prefix) {
4691 pw.println(prefix + "WaitInfo:");
4692 pw.println(prefix + " mTargetComponent=" + mTargetComponent);
4693 pw.println(prefix + " mResult=");
4694 mResult.dump(pw, prefix);
4695 }
4696 }
David Stevens9440dc82017-03-16 19:00:20 -07004697
4698 private final class SleepTokenImpl extends SleepToken {
4699 private final String mTag;
4700 private final long mAcquireTime;
4701 private final int mDisplayId;
4702
4703 public SleepTokenImpl(String tag, int displayId) {
4704 mTag = tag;
4705 mDisplayId = displayId;
4706 mAcquireTime = SystemClock.uptimeMillis();
4707 }
4708
4709 @Override
4710 public void release() {
4711 synchronized (mService) {
4712 removeSleepTokenLocked(this);
4713 }
4714 }
4715
4716 @Override
4717 public String toString() {
4718 return "{\"" + mTag + "\", display " + mDisplayId
4719 + ", acquire at " + TimeUtils.formatUptime(mAcquireTime) + "}";
4720 }
4721 }
4722
Craig Mautner27084302013-03-25 08:05:25 -07004723}