blob: 441df0b099bd6da55d75a719d2a4e36e89a88a2b [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 Kulian3a95edc2017-06-28 16:21:07 -070019import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Jorim Jaggife762342016-10-13 14:33:27 +020020import static android.Manifest.permission.START_ANY_ACTIVITY;
21import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
22import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
23import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
24import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
Jorim Jaggife762342016-10-13 14:33:27 +020025import static android.app.ActivityManager.START_TASK_TO_FRONT;
26import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
27import static android.app.ActivityManager.StackId.FIRST_DYNAMIC_STACK_ID;
28import static android.app.ActivityManager.StackId.FIRST_STATIC_STACK_ID;
29import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
30import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
31import static android.app.ActivityManager.StackId.HOME_STACK_ID;
32import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
33import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
34import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
Matthew Ng330757d2017-02-28 14:19:17 -080035import static android.app.ActivityManager.StackId.RECENTS_STACK_ID;
Andrii Kulian036e3ad2017-04-19 10:55:10 -070036import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
37import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Jorim Jaggife762342016-10-13 14:33:27 +020038import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070039import static android.os.Process.SYSTEM_UID;
chaviw59b98852017-06-13 12:05:44 -070040import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
Jorim Jaggife762342016-10-13 14:33:27 +020041import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
42import static android.view.Display.DEFAULT_DISPLAY;
Andrii Kulian16802aa2016-11-02 12:21:33 -070043import static android.view.Display.FLAG_PRIVATE;
44import static android.view.Display.INVALID_DISPLAY;
Andrii Kulian250d6532017-02-08 23:30:45 -080045import static android.view.Display.REMOVE_MODE_DESTROY_CONTENT;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070046import static android.view.Display.TYPE_VIRTUAL;
Jorim Jaggife762342016-10-13 14:33:27 +020047
Winson Chung47900652017-04-06 18:44:25 -070048import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN;
Jorim Jaggife762342016-10-13 14:33:27 +020049import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
Jorim Jaggife762342016-10-13 14:33:27 +020050import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
51import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
52import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
53import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
54import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
55import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
56import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
57import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
58import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
59import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020060import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONTAINERS;
61import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
62import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IDLE;
63import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
64import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
65import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
66import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
67import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
68import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
69import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
70import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020071import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
72import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
73import static com.android.server.am.ActivityManagerService.ANIMATE;
74import static com.android.server.am.ActivityManagerService.FIRST_SUPERVISOR_STACK_MSG;
75import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
76import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
Jorim Jaggife762342016-10-13 14:33:27 +020077import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
78import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
79import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
80import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
81import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
82import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
83import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
84import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
85import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
86import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
87import static com.android.server.am.ActivityStack.STACK_VISIBLE;
88import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
89import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
90import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
91import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
92import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
Winson Chung74666102017-02-22 17:49:24 -080093import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
94import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
95import static com.android.server.am.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
Jorim Jaggife762342016-10-13 14:33:27 +020096import static com.android.server.wm.AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS;
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -080097import static java.lang.Integer.MAX_VALUE;
Jorim Jaggife762342016-10-13 14:33:27 +020098
Svetoslav7008b512015-06-24 18:47:07 -070099import android.Manifest;
Winson Chung7900bee2017-03-10 08:59:25 -0800100import android.annotation.IntDef;
Andrii Kulian16802aa2016-11-02 12:21:33 -0700101import android.annotation.NonNull;
Tony Mak853304c2016-04-18 15:17:41 +0100102import android.annotation.UserIdInt;
Craig Mautner2420ead2013-04-01 17:13:20 -0700103import android.app.Activity;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700104import android.app.ActivityManager;
Filip Gruszczynski80e29f12015-12-14 14:58:30 -0800105import android.app.ActivityManager.RunningTaskInfo;
Wale Ogunwale3797c222015-10-27 14:21:58 -0700106import android.app.ActivityManager.StackId;
Craig Mautnered6649f2013-12-02 14:08:25 -0800107import android.app.ActivityManager.StackInfo;
David Stevens9440dc82017-03-16 19:00:20 -0700108import android.app.ActivityManagerInternal.SleepToken;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700109import android.app.ActivityOptions;
Svetoslav7008b512015-06-24 18:47:07 -0700110import android.app.AppOpsManager;
Jeff Hao1b012d32014-08-20 10:35:34 -0700111import android.app.ProfilerInfo;
Craig Mautner2420ead2013-04-01 17:13:20 -0700112import android.app.ResultInfo;
justinzhang5286d3f2014-05-12 17:06:01 -0400113import android.app.StatusBarManager;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700114import android.app.WaitResult;
Jason Monk35c62a42014-06-17 10:24:47 -0400115import android.app.admin.IDevicePolicyManager;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700116import android.content.ComponentName;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700117import android.content.Context;
118import android.content.Intent;
119import android.content.pm.ActivityInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700120import android.content.pm.ApplicationInfo;
Svetoslav7008b512015-06-24 18:47:07 -0700121import android.content.pm.PackageInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700122import android.content.pm.PackageManager;
123import android.content.pm.ResolveInfo;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100124import android.content.pm.UserInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700125import android.content.res.Configuration;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800126import android.graphics.Rect;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800127import android.hardware.display.DisplayManager;
128import android.hardware.display.DisplayManager.DisplayListener;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800129import android.hardware.display.DisplayManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800130import android.hardware.input.InputManagerInternal;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700131import android.os.Binder;
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100132import android.os.Bundle;
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700133import android.os.Debug;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700134import android.os.Handler;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700135import android.os.IBinder;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700136import android.os.Looper;
Craig Mautner2420ead2013-04-01 17:13:20 -0700137import android.os.Message;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700138import android.os.PowerManager;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700139import android.os.Process;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700140import android.os.RemoteException;
justinzhang5286d3f2014-05-12 17:06:01 -0400141import android.os.ServiceManager;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700142import android.os.SystemClock;
Wale Ogunwalecad05a02015-09-25 10:41:44 -0700143import android.os.Trace;
Craig Mautner6170f732013-04-02 13:05:23 -0700144import android.os.UserHandle;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100145import android.os.UserManager;
Dianne Hackborn3d07c942015-03-13 18:02:54 -0700146import android.os.WorkSource;
Svetoslav7008b512015-06-24 18:47:07 -0700147import android.provider.MediaStore;
Jason Monk62515be2014-05-21 16:06:19 -0400148import android.provider.Settings;
149import android.provider.Settings.SettingNotFoundException;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700150import android.service.voice.IVoiceInteractionSession;
Svetoslav7008b512015-06-24 18:47:07 -0700151import android.util.ArrayMap;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700152import android.util.ArraySet;
Craig Mautner2420ead2013-04-01 17:13:20 -0700153import android.util.EventLog;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800154import android.util.IntArray;
Wale Ogunwalee610d3d2017-04-25 10:23:48 -0700155import android.util.MergedConfiguration;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700156import android.util.Slog;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800157import android.util.SparseArray;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800158import android.util.SparseIntArray;
David Stevens9440dc82017-03-16 19:00:20 -0700159import android.util.TimeUtils;
Craig Mautnered6649f2013-12-02 14:08:25 -0800160import android.view.Display;
Chong Zhangb15758a2015-11-17 12:12:03 -0800161
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700162import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800163import com.android.internal.content.ReferrerIntent;
Winson Chung14fbe142016-12-19 16:18:24 -0800164import com.android.internal.logging.MetricsLogger;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -0700165import com.android.internal.os.TransferPipe;
justinzhang5286d3f2014-05-12 17:06:01 -0400166import com.android.internal.statusbar.IStatusBarService;
Svetoslav7008b512015-06-24 18:47:07 -0700167import com.android.internal.util.ArrayUtils;
Jason Monke0697792014-08-04 16:28:09 -0400168import com.android.internal.widget.LockPatternUtils;
Jeff Brownca9bc702014-02-11 14:32:56 -0800169import com.android.server.LocalServices;
Craig Mautner2420ead2013-04-01 17:13:20 -0700170import com.android.server.am.ActivityStack.ActivityState;
Wale Ogunwale98d62312017-07-12 09:24:56 -0700171import com.android.server.wm.ConfigurationContainer;
Winson Chung19953ca2017-04-11 11:19:23 -0700172import com.android.server.wm.PinnedStackWindowController;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700173import com.android.server.wm.WindowManagerService;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700174
Craig Mautner8d341ef2013-03-26 09:03:27 -0700175import java.io.FileDescriptor;
176import java.io.IOException;
Craig Mautner27084302013-03-25 08:05:25 -0700177import java.io.PrintWriter;
Winson Chung7900bee2017-03-10 08:59:25 -0800178import java.lang.annotation.Retention;
179import java.lang.annotation.RetentionPolicy;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700180import java.util.ArrayList;
Craig Mautnere0570202015-05-13 13:06:11 -0700181import java.util.Arrays;
David Stevens9440dc82017-03-16 19:00:20 -0700182import java.util.Iterator;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700183import java.util.List;
Wale Ogunwale540e1232015-05-01 15:35:39 -0700184import java.util.Set;
Craig Mautner27084302013-03-25 08:05:25 -0700185
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -0800186public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener {
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800187 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_AM;
Chong Zhang6cda19c2016-06-14 19:07:56 -0700188 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700189 private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
Craig Mautnere0570202015-05-13 13:06:11 -0700190 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700191 private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700192 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700193 private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700194 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700195 private static final String TAG_STATES = TAG + POSTFIX_STATES;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700196 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800197 static final String TAG_TASKS = TAG + POSTFIX_TASKS;
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800198
Craig Mautnerf3333272013-04-22 10:55:53 -0700199 /** How long we wait until giving up on the last activity telling us it is idle. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700200 static final int IDLE_TIMEOUT = 10 * 1000;
Craig Mautnerf3333272013-04-22 10:55:53 -0700201
Craig Mautner0eea92c2013-05-16 13:35:39 -0700202 /** How long we can hold the sleep wake lock before giving up. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700203 static final int SLEEP_TIMEOUT = 5 * 1000;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700204
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700205 // How long we can hold the launch wake lock before giving up.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700206 static final int LAUNCH_TIMEOUT = 10 * 1000;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700207
Craig Mautner05d29032013-05-03 13:40:13 -0700208 static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
209 static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
210 static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700211 static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700212 static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800213 static final int HANDLE_DISPLAY_ADDED = FIRST_SUPERVISOR_STACK_MSG + 5;
214 static final int HANDLE_DISPLAY_CHANGED = FIRST_SUPERVISOR_STACK_MSG + 6;
215 static final int HANDLE_DISPLAY_REMOVED = FIRST_SUPERVISOR_STACK_MSG + 7;
justinzhang5286d3f2014-05-12 17:06:01 -0400216 static final int LOCK_TASK_START_MSG = FIRST_SUPERVISOR_STACK_MSG + 9;
217 static final int LOCK_TASK_END_MSG = FIRST_SUPERVISOR_STACK_MSG + 10;
Wale Ogunwale73eba742015-04-07 14:23:14 -0700218 static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
Craig Mautnerc21ae9e2015-04-15 09:45:42 -0700219 static final int SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG = FIRST_SUPERVISOR_STACK_MSG + 13;
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
Jason Monk62515be2014-05-21 16:06:19 -0400225 private static final String LOCK_TASK_TAG = "Lock-to-App";
226
Wale Ogunwale040b4702015-08-06 18:10:50 -0700227 // Used to indicate if an object (e.g. stack) that we are trying to get
228 // should be created if it doesn't exist already.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800229 static final boolean CREATE_IF_NEEDED = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700230
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700231 // Used to indicate that windows of activities should be preserved during the resize.
232 static final boolean PRESERVE_WINDOWS = true;
233
Wale Ogunwale040b4702015-08-06 18:10:50 -0700234 // Used to indicate if an object (e.g. task) should be moved/created
235 // at the top of its container (e.g. stack).
Wale Ogunwaleb30daaa2015-08-07 21:50:49 -0700236 static final boolean ON_TOP = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700237
238 // Used to indicate that an objects (e.g. task) removal from its container
239 // (e.g. stack) is due to it moving to another container.
240 static final boolean MOVING = true;
241
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700242 // Force the focus to change to the stack we are moving a task to..
243 static final boolean FORCE_FOCUS = true;
244
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700245 // Don't execute any calls to resume.
246 static final boolean DEFER_RESUME = true;
247
Winson Chung010927a2016-12-15 16:12:35 -0800248 // Used to indicate that a task is removed it should also be removed from recents.
249 static final boolean REMOVE_FROM_RECENTS = true;
250
Winson Chung6954fc92017-03-24 16:22:12 -0700251 // Used to indicate that pausing an activity should occur immediately without waiting for
252 // the activity callback indicating that it has completed pausing
253 static final boolean PAUSE_IMMEDIATELY = true;
254
Winson Chung7900bee2017-03-10 08:59:25 -0800255 /**
256 * The modes which affect which tasks are returned when calling
257 * {@link ActivityStackSupervisor#anyTaskForIdLocked(int)}.
258 */
259 @Retention(RetentionPolicy.SOURCE)
260 @IntDef({
261 MATCH_TASK_IN_STACKS_ONLY,
262 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
263 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
264 })
265 public @interface AnyTaskForIdMatchTaskMode {}
266 // Match only tasks in the current stacks
267 static final int MATCH_TASK_IN_STACKS_ONLY = 0;
268 // Match either tasks in the current stacks, or in the recent tasks if not found in the stacks
269 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS = 1;
270 // Match either tasks in the current stacks, or in the recent tasks, restoring it to the
271 // provided stack id
272 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE = 2;
273
Svetoslav7008b512015-06-24 18:47:07 -0700274 // Activity actions an app cannot start if it uses a permission which is not granted.
275 private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION =
276 new ArrayMap<>();
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700277
Svetoslav7008b512015-06-24 18:47:07 -0700278 static {
279 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE,
280 Manifest.permission.CAMERA);
281 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE,
282 Manifest.permission.CAMERA);
283 ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL,
284 Manifest.permission.CALL_PHONE);
285 }
286
Svet Ganov99b60432015-06-27 13:15:22 -0700287 /** Action restriction: launching the activity is not restricted. */
288 private static final int ACTIVITY_RESTRICTION_NONE = 0;
289 /** Action restriction: launching the activity is restricted by a permission. */
290 private static final int ACTIVITY_RESTRICTION_PERMISSION = 1;
291 /** Action restriction: launching the activity is restricted by an app op. */
292 private static final int ACTIVITY_RESTRICTION_APPOP = 2;
Svetoslav7008b512015-06-24 18:47:07 -0700293
justinzhang5286d3f2014-05-12 17:06:01 -0400294 /** Status Bar Service **/
295 private IBinder mToken = new Binder();
296 private IStatusBarService mStatusBarService;
Jason Monk35c62a42014-06-17 10:24:47 -0400297 private IDevicePolicyManager mDevicePolicyManager;
justinzhang5286d3f2014-05-12 17:06:01 -0400298
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700299 // For debugging to make sure the caller when acquiring/releasing our
300 // wake lock is the system process.
301 static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800302 /** The number of distinct task ids that can be assigned to the tasks of a single user */
303 private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
Craig Mautnerf3333272013-04-22 10:55:53 -0700304
Craig Mautner27084302013-03-25 08:05:25 -0700305 final ActivityManagerService mService;
306
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800307 private RecentTasks mRecentTasks;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800308
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700309 final ActivityStackSupervisorHandler mHandler;
310
311 /** Short cut */
312 WindowManagerService mWindowManager;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800313 DisplayManager mDisplayManager;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700314
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -0700315 /** Counter for next free stack ID to use for dynamic activity stacks. */
316 private int mNextFreeStackId = FIRST_DYNAMIC_STACK_ID;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700317
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800318 /**
319 * Maps the task identifier that activities are currently being started in to the userId of the
320 * task. Each time a new task is created, the entry for the userId of the task is incremented
321 */
322 private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20);
Craig Mautner8d341ef2013-03-26 09:03:27 -0700323
Craig Mautner2420ead2013-04-01 17:13:20 -0700324 /** The current user */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800325 int mCurrentUser;
Craig Mautner2420ead2013-04-01 17:13:20 -0700326
Craig Mautnere0a38842013-12-16 16:14:02 -0800327 /** The stack containing the launcher app. Assumed to always be attached to
328 * Display.DEFAULT_DISPLAY. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800329 ActivityStack mHomeStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700330
Craig Mautnere0a38842013-12-16 16:14:02 -0800331 /** The stack currently receiving input or launching the next activity. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800332 ActivityStack mFocusedStack;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700333
Craig Mautner4a1cb222013-12-04 16:14:06 -0800334 /** If this is the same as mFocusedStack then the activity on the top of the focused stack has
335 * been resumed. If stacks are changing position this will hold the old stack until the new
Craig Mautnere0a38842013-12-16 16:14:02 -0800336 * stack becomes resumed after which it will be set to mFocusedStack. */
Craig Mautner4a1cb222013-12-04 16:14:06 -0800337 private ActivityStack mLastFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -0700338
339 /** List of activities that are waiting for a new activity to become visible before completing
340 * whatever operation they are supposed to do. */
Bryce Lee4a194382017-04-04 14:32:48 -0700341 // TODO: Remove mActivitiesWaitingForVisibleActivity list and just remove activity from
342 // mStoppingActivities when something else comes up.
343 final ArrayList<ActivityRecord> mActivitiesWaitingForVisibleActivity = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700344
Bryce Lee4a194382017-04-04 14:32:48 -0700345 /** List of processes waiting to find out when a specific activity becomes visible. */
346 private final ArrayList<WaitInfo> mWaitingForActivityVisible = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700347
348 /** List of processes waiting to find out about the next launched activity. */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700349 final ArrayList<WaitResult> mWaitingActivityLaunched = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700350
Craig Mautnerde4ef022013-04-07 19:01:33 -0700351 /** List of activities that are ready to be stopped, but waiting for the next activity to
352 * settle down before doing so. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800353 final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700354
Craig Mautnerf3333272013-04-22 10:55:53 -0700355 /** List of activities that are ready to be finished, but waiting for the previous activity to
356 * settle down before doing so. It contains ActivityRecord objects. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800357 final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700358
Craig Mautner0eea92c2013-05-16 13:35:39 -0700359 /** List of activities that are in the process of going to sleep. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800360 final ArrayList<ActivityRecord> mGoingToSleepActivities = new ArrayList<>();
Craig Mautner0eea92c2013-05-16 13:35:39 -0700361
Wale Ogunwale22e25262016-02-01 10:32:02 -0800362 /** List of activities whose multi-window mode changed that we need to report to the
363 * application */
364 final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
365
366 /** List of activities whose picture-in-picture mode changed that we need to report to the
367 * application */
368 final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
369
Winson Chung5af42fc2017-03-24 17:11:33 -0700370 /** The target stack bounds for the picture-in-picture mode changed that we need to report to
371 * the application */
372 Rect mPipModeChangedTargetStackBounds;
373
Craig Mautnerf3333272013-04-22 10:55:53 -0700374 /** Used on user changes */
Amith Yamasani37a40c22015-06-17 13:25:42 -0700375 final ArrayList<UserState> mStartingUsers = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700376
Craig Mautnerde4ef022013-04-07 19:01:33 -0700377 /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity
378 * is being brought in front of us. */
379 boolean mUserLeaving = false;
380
Craig Mautner0eea92c2013-05-16 13:35:39 -0700381 /**
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700382 * We don't want to allow the device to go to sleep while in the process
383 * of launching an activity. This is primarily to allow alarm intent
384 * receivers to launch an activity and get that to run before the device
385 * goes back to sleep.
386 */
Jeff Brown2c43c332014-06-12 22:38:59 -0700387 PowerManager.WakeLock mLaunchingActivity;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700388
389 /**
Craig Mautner0eea92c2013-05-16 13:35:39 -0700390 * Set when the system is going to sleep, until we have
391 * successfully paused the current activity and released our wake lock.
392 * At that point the system is allowed to actually sleep.
393 */
Jeff Brown2c43c332014-06-12 22:38:59 -0700394 PowerManager.WakeLock mGoingToSleep;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700395
David Stevens9440dc82017-03-16 19:00:20 -0700396 /**
397 * A list of tokens that cause the top activity to be put to sleep.
398 * They are used by components that may hide and block interaction with underlying
399 * activities.
400 */
401 final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>();
402
Craig Mautner4f1df4f2013-10-15 15:44:14 -0700403 /** Stack id of the front stack when user switched, indexed by userId. */
404 SparseIntArray mUserStackInFront = new SparseIntArray(2);
Craig Mautner93529a42013-10-04 15:03:13 -0700405
Craig Mautner4504de52013-12-20 09:06:56 -0800406 // TODO: Add listener for removal of references.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800407 /** Mapping from (ActivityStack/TaskStack).mStackId to their current state */
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700408 SparseArray<ActivityStack> mStacks = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800409
Bryce Leeaf3a4002017-03-20 10:37:12 -0700410 // TODO: There should be an ActivityDisplayController coordinating am/wm interaction.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800411 /** Mapping from displayId to display current state */
Craig Mautner15df08a2015-04-01 12:17:18 -0700412 private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800413
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800414 private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>();
415
416 private DisplayManagerInternal mDisplayManagerInternal;
417 private InputManagerInternal mInputManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800418
Craig Mautner15df08a2015-04-01 12:17:18 -0700419 /** The chain of tasks in lockTask mode. The current frontmost task is at the top, and tasks
420 * may be finished until there is only one entry left. If this is empty the system is not
421 * in lockTask mode. */
422 ArrayList<TaskRecord> mLockTaskModeTasks = new ArrayList<>();
Benjamin Franz43261142015-02-11 15:59:44 +0000423 /** Store the current lock task mode. Possible values:
Craig Mautner2568c3a2015-03-26 14:22:34 -0700424 * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
425 * {@link ActivityManager#LOCK_TASK_MODE_PINNED}
Benjamin Franz43261142015-02-11 15:59:44 +0000426 */
427 private int mLockTaskModeState;
Jason Monk62515be2014-05-21 16:06:19 -0400428 /**
429 * Notifies the user when entering/exiting lock-task.
430 */
431 private LockTaskNotify mLockTaskNotify;
Craig Mautneraea74a52014-03-08 14:23:10 -0800432
Wale Ogunwaled046a012015-12-24 13:05:59 -0800433 /** Used to keep resumeTopActivityUncheckedLocked() from being entered recursively */
Craig Mautner42d04db2014-11-06 12:13:23 -0800434 boolean inResumeTopActivity;
435
Andrii Kulian1e32e022016-09-16 15:29:34 -0700436 /**
437 * Temporary rect used during docked stack resize calculation so we don't need to create a new
438 * object each time.
439 */
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700440 private final Rect tempRect = new Rect();
Filip Gruszczynskiebcc8752015-08-25 16:51:05 -0700441
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700442 // The default minimal size that will be used if the activity doesn't specify its minimal size.
443 // It will be calculated when the default display gets added.
Andrii Kulianf66a83d2016-05-17 12:17:44 -0700444 int mDefaultMinSizeOfResizeableTask = -1;
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700445
Chong Zhangfdcc4d42015-10-14 16:50:12 -0700446 // Whether tasks have moved and we need to rank the tasks before next OOM scoring
447 private boolean mTaskLayersChanged = true;
448
Jorim Jaggi275561a2016-02-23 10:11:02 -0500449 final ActivityMetricsLogger mActivityMetricsLogger;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800450
Jorim Jaggiea039a82017-08-02 14:37:49 +0200451 private final ArrayList<ActivityRecord> mTmpActivityList = new ArrayList<>();
452
Andrii Kulian1779e612016-10-12 21:58:25 -0700453 @Override
454 protected int getChildCount() {
455 return mActivityDisplays.size();
456 }
457
458 @Override
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700459 protected ActivityDisplay getChildAt(int index) {
Andrii Kulian1779e612016-10-12 21:58:25 -0700460 return mActivityDisplays.valueAt(index);
461 }
462
463 @Override
464 protected ConfigurationContainer getParent() {
465 return null;
466 }
467
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700468 Configuration getDisplayOverrideConfiguration(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700469 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700470 if (activityDisplay == null) {
471 throw new IllegalArgumentException("No display found with id: " + displayId);
472 }
473
474 return activityDisplay.getOverrideConfiguration();
475 }
476
477 void setDisplayOverrideConfiguration(Configuration overrideConfiguration, int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700478 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700479 if (activityDisplay == null) {
480 throw new IllegalArgumentException("No display found with id: " + displayId);
481 }
482
483 activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
484 }
485
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700486 /** Check if placing task or activity on specified display is allowed. */
Andrii Kulian02689a72017-07-06 14:28:59 -0700487 boolean canPlaceEntityOnDisplay(int displayId, boolean resizeable, int callingPid,
488 int callingUid, ActivityInfo activityInfo) {
489 if (displayId == DEFAULT_DISPLAY) {
490 // No restrictions for the default display.
491 return true;
492 }
493 if (!mService.mSupportsMultiDisplay) {
494 // Can't launch on secondary displays if feature is not supported.
495 return false;
496 }
497 if (!resizeable && !displayConfigMatchesGlobal(displayId)) {
498 // Can't apply wrong configuration to non-resizeable activities.
499 return false;
500 }
501 if (!isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, displayId, activityInfo)) {
502 // Can't place activities to a display that has restricted launch rules.
503 // In this case the request should be made by explicitly adding target display id and
504 // by caller with corresponding permissions. See #isCallerAllowedToLaunchOnDisplay().
505 return false;
506 }
507 return true;
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700508 }
509
510 /**
511 * Check if configuration of specified display matches current global config.
512 * Used to check if we can put a non-resizeable activity on a secondary display and it will get
513 * the same config as on the default display.
514 * @param displayId Id of the display to check.
515 * @return {@code true} if configuration matches.
516 */
517 private boolean displayConfigMatchesGlobal(int displayId) {
518 if (displayId == DEFAULT_DISPLAY) {
519 return true;
520 }
521 if (displayId == INVALID_DISPLAY) {
522 return false;
523 }
Andrii Kulian62e6f252017-05-30 22:46:53 -0700524 final ActivityDisplay targetDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700525 if (targetDisplay == null) {
526 throw new IllegalArgumentException("No display found with id: " + displayId);
527 }
528 return getConfiguration().equals(targetDisplay.getConfiguration());
529 }
530
Wale Ogunwale39381972015-12-17 17:15:29 -0800531 static class FindTaskResult {
532 ActivityRecord r;
533 boolean matchedByRootAffinity;
534 }
535 private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
536
Craig Mautneree36c772014-07-16 14:56:05 -0700537 /**
Andrii Kulian7fc22812016-12-28 13:04:11 -0800538 * Temp storage for display ids sorted in focus order.
539 * Maps position to id. Using {@link SparseIntArray} instead of {@link ArrayList} because
540 * it's more efficient, as the number of displays is usually small.
541 */
542 private SparseIntArray mTmpOrderedDisplayIds = new SparseIntArray();
543
544 /**
Jorim Jaggia0fdeec2016-01-07 14:42:28 +0100545 * Used to keep track whether app visibilities got changed since the last pause. Useful to
546 * determine whether to invoke the task stack change listener after pausing.
547 */
548 boolean mAppVisibilitiesChangedSinceLastPause;
549
550 /**
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100551 * Set of tasks that are in resizing mode during an app transition to fill the "void".
552 */
553 private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
554
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700555
556 /**
557 * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked}
558 * will be ignored. Useful for the case where the caller is handling resizing of other stack and
559 * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger
560 * like the docked stack going empty.
561 */
562 private boolean mAllowDockedStackResize = true;
563
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100564 /**
Tony Mak853304c2016-04-18 15:17:41 +0100565 * Is dock currently minimized.
566 */
567 boolean mIsDockMinimized;
568
Jorim Jaggife762342016-10-13 14:33:27 +0200569 final KeyguardController mKeyguardController;
570
chaviw59b98852017-06-13 12:05:44 -0700571 private PowerManager mPowerManager;
572 private int mDeferResumeCount;
573
Tony Mak853304c2016-04-18 15:17:41 +0100574 /**
Craig Mautneree36c772014-07-16 14:56:05 -0700575 * Description of a request to start a new activity, which has been held
576 * due to app switches being disabled.
577 */
578 static class PendingActivityLaunch {
579 final ActivityRecord r;
580 final ActivityRecord sourceRecord;
581 final int startFlags;
582 final ActivityStack stack;
Robert Carr13997f52015-10-23 13:13:39 -0700583 final ProcessRecord callerApp;
Craig Mautneree36c772014-07-16 14:56:05 -0700584
585 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
Robert Carr13997f52015-10-23 13:13:39 -0700586 int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
Craig Mautneree36c772014-07-16 14:56:05 -0700587 r = _r;
588 sourceRecord = _sourceRecord;
589 startFlags = _startFlags;
590 stack = _stack;
Robert Carr13997f52015-10-23 13:13:39 -0700591 callerApp = _callerApp;
592 }
593
594 void sendErrorResult(String message) {
595 try {
596 if (callerApp.thread != null) {
597 callerApp.thread.scheduleCrash(message);
598 }
599 } catch (RemoteException e) {
600 Slog.e(TAG, "Exception scheduling crash of failed "
601 + "activity launcher sourceRecord=" + sourceRecord, e);
602 }
Craig Mautneree36c772014-07-16 14:56:05 -0700603 }
604 }
605
Bryce Leeaf691c02017-03-20 14:20:22 -0700606 public ActivityStackSupervisor(ActivityManagerService service, Looper looper) {
Craig Mautner27084302013-03-25 08:05:25 -0700607 mService = service;
Bryce Leeaf691c02017-03-20 14:20:22 -0700608 mHandler = new ActivityStackSupervisorHandler(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800609 mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
Jorim Jaggife762342016-10-13 14:33:27 +0200610 mKeyguardController = new KeyguardController(service, this);
Jeff Brown2c43c332014-06-12 22:38:59 -0700611 }
612
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800613 void setRecentTasks(RecentTasks recentTasks) {
614 mRecentTasks = recentTasks;
615 }
616
Jeff Brown2c43c332014-06-12 22:38:59 -0700617 /**
618 * At the time when the constructor runs, the power manager has not yet been
619 * initialized. So we initialize our wakelocks afterwards.
620 */
621 void initPowerManagement() {
chaviw59b98852017-06-13 12:05:44 -0700622 mPowerManager = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
623 mGoingToSleep = mPowerManager
624 .newWakeLock(PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
625 mLaunchingActivity = mPowerManager.newWakeLock(PARTIAL_WAKE_LOCK, "*launch*");
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700626 mLaunchingActivity.setReferenceCounted(false);
Craig Mautner2219a1b2013-03-25 09:44:30 -0700627 }
628
justinzhang5286d3f2014-05-12 17:06:01 -0400629 // This function returns a IStatusBarService. The value is from ServiceManager.
630 // getService and is cached.
631 private IStatusBarService getStatusBarService() {
632 synchronized (mService) {
633 if (mStatusBarService == null) {
634 mStatusBarService = IStatusBarService.Stub.asInterface(
635 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
636 if (mStatusBarService == null) {
637 Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
638 }
639 }
640 return mStatusBarService;
641 }
642 }
643
Jason Monk35c62a42014-06-17 10:24:47 -0400644 private IDevicePolicyManager getDevicePolicyManager() {
645 synchronized (mService) {
646 if (mDevicePolicyManager == null) {
647 mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
648 ServiceManager.checkService(Context.DEVICE_POLICY_SERVICE));
649 if (mDevicePolicyManager == null) {
650 Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
651 }
652 }
653 return mDevicePolicyManager;
654 }
655 }
656
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700657 void setWindowManager(WindowManagerService wm) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800658 synchronized (mService) {
659 mWindowManager = wm;
Jorim Jaggife762342016-10-13 14:33:27 +0200660 mKeyguardController.setWindowManager(wm);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800661
662 mDisplayManager =
663 (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
664 mDisplayManager.registerDisplayListener(this, null);
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800665 mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800666
667 Display[] displays = mDisplayManager.getDisplays();
668 for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
669 final int displayId = displays[displayNdx].getDisplayId();
Craig Mautnere0a38842013-12-16 16:14:02 -0800670 ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
Craig Mautner1a70a162014-09-13 12:09:31 -0700671 if (activityDisplay.mDisplay == null) {
672 throw new IllegalStateException("Default Display does not exist");
673 }
Craig Mautnere0a38842013-12-16 16:14:02 -0800674 mActivityDisplays.put(displayId, activityDisplay);
Filip Gruszczynski7be9a8c2015-10-15 18:20:30 -0700675 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800676 }
677
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800678 mHomeStack = mFocusedStack = mLastFocusedStack =
679 getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Jeff Brownca9bc702014-02-11 14:32:56 -0800680
681 mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800682 }
Craig Mautner27084302013-03-25 08:05:25 -0700683 }
684
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700685 ActivityStack getFocusedStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800686 return mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700687 }
688
Craig Mautnerde4ef022013-04-07 19:01:33 -0700689 ActivityStack getLastStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800690 return mLastFocusedStack;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700691 }
692
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700693 boolean isFocusedStack(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700694 return stack != null && stack == mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700695 }
696
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800697 /** The top most stack on its display. */
698 boolean isFrontStackOnDisplay(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700699 return isFrontOfStackList(stack, stack.getDisplay().mStacks);
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800700 }
701
702 private boolean isFrontOfStackList(ActivityStack stack, List<ActivityStack> stackList) {
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800703 return stack == stackList.get((stackList.size() - 1));
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700704 }
705
Wale Ogunwaled046a012015-12-24 13:05:59 -0800706 /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800707 void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
708 if (!focusCandidate.isFocusable()) {
709 // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
Andrii Kulian7fc22812016-12-28 13:04:11 -0800710 focusCandidate = getNextFocusableStackLocked(focusCandidate);
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800711 }
712
713 if (focusCandidate != mFocusedStack) {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800714 mLastFocusedStack = mFocusedStack;
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800715 mFocusedStack = focusCandidate;
Wale Ogunwalecb82f302015-02-25 07:53:40 -0800716
Wale Ogunwaled046a012015-12-24 13:05:59 -0800717 EventLogTags.writeAmFocusedStack(
718 mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
719 mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
720 }
721
722 final ActivityRecord r = topRunningActivityLocked();
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800723 if (mService.mBooting || !mService.mBooted) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800724 if (r != null && r.idle) {
725 checkFinishBootingLocked();
726 }
727 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700728 }
729
Wale Ogunwale925d0d12015-09-23 15:40:07 -0700730 void moveHomeStackToFront(String reason) {
731 mHomeStack.moveToFront(reason);
732 }
733
Matthew Ng330757d2017-02-28 14:19:17 -0800734 void moveRecentsStackToFront(String reason) {
735 final ActivityStack recentsStack = getStack(RECENTS_STACK_ID);
736 if (recentsStack != null) {
737 recentsStack.moveToFront(reason);
738 }
739 }
740
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700741 /** Returns true if the focus activity was adjusted to the home stack top activity. */
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800742 boolean moveHomeStackTaskToTop(String reason) {
743 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700744
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700745 final ActivityRecord top = getHomeActivity();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700746 if (top == null) {
747 return false;
748 }
Chong Zhang6cda19c2016-06-14 19:07:56 -0700749 moveFocusableActivityStackToFrontLocked(top, reason);
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700750 return true;
Craig Mautner8e569572013-10-11 17:36:59 -0700751 }
752
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800753 boolean resumeHomeStackTask(ActivityRecord prev, String reason) {
Dianne Hackborn7622a0f2014-09-30 14:31:42 -0700754 if (!mService.mBooting && !mService.mBooted) {
755 // Not ready yet!
756 return false;
757 }
758
Craig Mautner84984fa2014-06-19 11:19:20 -0700759 if (prev != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -0700760 prev.getTask().setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
Craig Mautner84984fa2014-06-19 11:19:20 -0700761 }
762
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800763 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700764 ActivityRecord r = getHomeActivity();
Wale Ogunwaled046a012015-12-24 13:05:59 -0800765 final String myReason = reason + " resumeHomeStackTask";
766
Mark Lua56ea122015-10-08 13:31:01 +0800767 // Only resume home activity if isn't finishing.
768 if (r != null && !r.finishing) {
Chong Zhang6cda19c2016-06-14 19:07:56 -0700769 moveFocusableActivityStackToFrontLocked(r, myReason);
Wale Ogunwaled046a012015-12-24 13:05:59 -0800770 return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
Craig Mautner69ada552013-04-18 13:51:51 -0700771 }
Wale Ogunwaled046a012015-12-24 13:05:59 -0800772 return mService.startHomeActivityLocked(mCurrentUser, myReason);
Craig Mautner69ada552013-04-18 13:51:51 -0700773 }
774
Craig Mautner8d341ef2013-03-26 09:03:27 -0700775 TaskRecord anyTaskForIdLocked(int id) {
Winson Chung7900bee2017-03-10 08:59:25 -0800776 return anyTaskForIdLocked(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
777 INVALID_STACK_ID);
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700778 }
779
780 /**
Bryce Lee92b7b652017-04-03 08:33:11 -0700781 * Returns a {@link TaskRecord} for the input id if available. {@code null} otherwise.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700782 * @param id Id of the task we would like returned.
Winson Chung7900bee2017-03-10 08:59:25 -0800783 * @param matchMode The mode to match the given task id in.
Wale Ogunwale3797c222015-10-27 14:21:58 -0700784 * @param stackId The stack to restore the task to (default launch stack will be used if
Winson Chung7900bee2017-03-10 08:59:25 -0800785 * stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}). Only
786 * valid if the matchMode is
787 * {@link #MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE}.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700788 */
Winson Chung7900bee2017-03-10 08:59:25 -0800789 TaskRecord anyTaskForIdLocked(int id, @AnyTaskForIdMatchTaskMode int matchMode, int stackId) {
790 // If there is a stack id set, ensure that we are attempting to actually restore a task
791 if (matchMode != MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE &&
792 stackId != INVALID_STACK_ID) {
793 throw new IllegalArgumentException("Should not specify stackId for non-restore lookup");
794 }
795
Craig Mautnere0a38842013-12-16 16:14:02 -0800796 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800797 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800798 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800799 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
800 ActivityStack stack = stacks.get(stackNdx);
Bryce Lee92b7b652017-04-03 08:33:11 -0700801 final TaskRecord task = stack.taskForIdLocked(id);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800802 if (task != null) {
803 return task;
804 }
Craig Mautner8d341ef2013-03-26 09:03:27 -0700805 }
806 }
Wale Ogunwale7de05352014-12-12 15:21:33 -0800807
Winson Chung7900bee2017-03-10 08:59:25 -0800808 // If we are matching stack tasks only, return now
809 if (matchMode == MATCH_TASK_IN_STACKS_ONLY) {
Wale Ogunwale7de05352014-12-12 15:21:33 -0800810 return null;
811 }
812
Winson Chung7900bee2017-03-10 08:59:25 -0800813 // Otherwise, check the recent tasks and return if we find it there and we are not restoring
814 // the task from recents
815 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
Bryce Lee92b7b652017-04-03 08:33:11 -0700816 final TaskRecord task = mRecentTasks.taskForIdLocked(id);
817
818 if (task == null) {
819 if (DEBUG_RECENTS) {
Winson Chung7900bee2017-03-10 08:59:25 -0800820 Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
821 }
Bryce Lee92b7b652017-04-03 08:33:11 -0700822
823 return null;
824 }
825
826 if (matchMode == MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) {
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700827 return task;
828 }
829
Winson Chung7900bee2017-03-10 08:59:25 -0800830 // Implicitly, this case is MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
Wale Ogunwale7e8184b2015-10-05 14:37:03 -0700831 if (!restoreRecentTaskLocked(task, stackId)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700832 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
833 "Couldn't restore task id=" + id + " found in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800834 return null;
835 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700836 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800837 return task;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700838 }
839
Craig Mautner6170f732013-04-02 13:05:23 -0700840 ActivityRecord isInAnyStackLocked(IBinder token) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800841 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800842 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800843 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800844 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
845 final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
846 if (r != null) {
847 return r;
848 }
Craig Mautner6170f732013-04-02 13:05:23 -0700849 }
850 }
851 return null;
852 }
853
Tony Mak853304c2016-04-18 15:17:41 +0100854 /**
Robin Lee3fef1f22016-12-20 14:50:13 +0000855 * Detects whether we should show a lock screen in front of this task for a locked user.
856 * <p>
857 * We'll do this if either of the following holds:
858 * <ul>
859 * <li>The top activity explicitly belongs to {@param userId}.</li>
860 * <li>The top activity returns a result to an activity belonging to {@param userId}.</li>
861 * </ul>
862 *
863 * @return {@code true} if the top activity looks like it belongs to {@param userId}.
Tony Mak853304c2016-04-18 15:17:41 +0100864 */
Robin Lee3fef1f22016-12-20 14:50:13 +0000865 private boolean taskTopActivityIsUser(TaskRecord task, @UserIdInt int userId) {
866 // To handle the case that work app is in the task but just is not the top one.
867 final ActivityRecord activityRecord = task.getTopActivity();
868 final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null);
869
870 return (activityRecord != null && activityRecord.userId == userId)
871 || (resultTo != null && resultTo.userId == userId);
872 }
873
874 /**
875 * Find all visible task stacks containing {@param userId} and intercept them with an activity
876 * to block out the contents and possibly start a credential-confirming intent.
877 *
878 * @param userId user handle for the locked managed profile.
879 */
880 void lockAllProfileTasks(@UserIdInt int userId) {
881 mWindowManager.deferSurfaceLayout();
882 try {
883 final List<ActivityStack> stacks = getStacks();
884 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; stackNdx--) {
885 final List<TaskRecord> tasks = stacks.get(stackNdx).getAllTasks();
886 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) {
887 final TaskRecord task = tasks.get(taskNdx);
888
889 // Check the task for a top activity belonging to userId, or returning a result
890 // to an activity belonging to userId. Example case: a document picker for
891 // personal files, opened by a work app, should still get locked.
892 if (taskTopActivityIsUser(task, userId)) {
Robin Leec41f6ec2017-01-10 17:02:34 +0000893 mService.mTaskChangeNotificationController.notifyTaskProfileLocked(
894 task.taskId, userId);
Robin Lee3fef1f22016-12-20 14:50:13 +0000895 }
Tony Mak853304c2016-04-18 15:17:41 +0100896 }
897 }
Robin Lee3fef1f22016-12-20 14:50:13 +0000898 } finally {
899 mWindowManager.continueSurfaceLayout();
Tony Mak853304c2016-04-18 15:17:41 +0100900 }
Clara Bayarrif0649ce2016-01-14 12:30:42 +0000901 }
902
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800903 void setNextTaskIdForUserLocked(int taskId, int userId) {
904 final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
905 if (taskId > currentTaskId) {
906 mCurTaskIdForUser.put(userId, taskId);
Craig Mautneref73ee12014-04-23 11:45:37 -0700907 }
908 }
909
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700910 static int nextTaskIdForUser(int taskId, int userId) {
911 int nextTaskId = taskId + 1;
912 if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
913 // Wrap around as there will be smaller task ids that are available now.
914 nextTaskId -= MAX_TASK_IDS_PER_USER;
915 }
916 return nextTaskId;
917 }
918
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800919 int getNextTaskIdForUserLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800920 final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
921 // for a userId u, a taskId can only be in the range
922 // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
923 // 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 -0700924 int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800925 while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
Winson Chung7900bee2017-03-10 08:59:25 -0800926 || anyTaskForIdLocked(candidateTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800927 INVALID_STACK_ID) != null) {
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700928 candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800929 if (candidateTaskId == currentTaskId) {
930 // Something wrong!
931 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
932 throw new IllegalStateException("Cannot get an available task id."
933 + " Reached limit of " + MAX_TASK_IDS_PER_USER
934 + " running tasks per user.");
935 }
936 }
937 mCurTaskIdForUser.put(userId, candidateTaskId);
938 return candidateTaskId;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700939 }
940
Chong Zhang6cda19c2016-06-14 19:07:56 -0700941 ActivityRecord getResumedActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -0800942 ActivityStack stack = mFocusedStack;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700943 if (stack == null) {
944 return null;
945 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700946 ActivityRecord resumedActivity = stack.mResumedActivity;
947 if (resumedActivity == null || resumedActivity.app == null) {
948 resumedActivity = stack.mPausingActivity;
949 if (resumedActivity == null || resumedActivity.app == null) {
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -0700950 resumedActivity = stack.topRunningActivityLocked();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700951 }
952 }
953 return resumedActivity;
954 }
955
Dianne Hackbornff072722014-09-24 10:56:28 -0700956 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
Craig Mautner20e72272013-04-01 13:45:53 -0700957 final String processName = app.processName;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800958 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800959 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
960 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800961 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
962 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700963 if (!isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800964 continue;
965 }
Jorim Jaggiea039a82017-08-02 14:37:49 +0200966 stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
967 final ActivityRecord top = stack.topRunningActivityLocked();
968 final int size = mTmpActivityList.size();
969 for (int i = 0; i < size; i++) {
970 final ActivityRecord activity = mTmpActivityList.get(i);
971 if (activity.app == null && app.uid == activity.info.applicationInfo.uid
972 && processName.equals(activity.processName)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800973 try {
Jorim Jaggiea039a82017-08-02 14:37:49 +0200974 if (realStartActivityLocked(activity, app,
975 top == activity /* andResume */, true /* checkConfig */)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800976 didSomething = true;
977 }
Dianne Hackbornff072722014-09-24 10:56:28 -0700978 } catch (RemoteException e) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800979 Slog.w(TAG, "Exception in new application when starting activity "
Jorim Jaggiea039a82017-08-02 14:37:49 +0200980 + top.intent.getComponent().flattenToShortString(), e);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800981 throw e;
Craig Mautner20e72272013-04-01 13:45:53 -0700982 }
Craig Mautner20e72272013-04-01 13:45:53 -0700983 }
Craig Mautner20e72272013-04-01 13:45:53 -0700984 }
985 }
986 }
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700987 if (!didSomething) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700988 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700989 }
Craig Mautner20e72272013-04-01 13:45:53 -0700990 return didSomething;
991 }
992
993 boolean allResumedActivitiesIdle() {
Craig Mautnere0a38842013-12-16 16:14:02 -0800994 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
995 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800996 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
997 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700998 if (!isFocusedStack(stack) || stack.numActivities() == 0) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800999 continue;
1000 }
1001 final ActivityRecord resumedActivity = stack.mResumedActivity;
1002 if (resumedActivity == null || !resumedActivity.idle) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001003 if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
Craig Mautner34b73df2014-01-12 21:11:08 -08001004 + stack.mStackId + " " + resumedActivity + " not idle");
Craig Mautner4a1cb222013-12-04 16:14:06 -08001005 return false;
1006 }
Craig Mautner20e72272013-04-01 13:45:53 -07001007 }
1008 }
Wei Wang65c7a152016-06-02 18:51:22 -07001009 // Send launch end powerhint when idle
1010 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
Craig Mautner20e72272013-04-01 13:45:53 -07001011 return true;
1012 }
1013
Craig Mautnerde4ef022013-04-07 19:01:33 -07001014 boolean allResumedActivitiesComplete() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001015 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1016 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001017 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1018 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001019 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001020 final ActivityRecord r = stack.mResumedActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001021 if (r != null && r.state != RESUMED) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001022 return false;
1023 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001024 }
1025 }
1026 }
1027 // TODO: Not sure if this should check if all Paused are complete too.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001028 if (DEBUG_STACK) Slog.d(TAG_STACK,
Craig Mautner4a1cb222013-12-04 16:14:06 -08001029 "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
1030 mLastFocusedStack + " to=" + mFocusedStack);
1031 mLastFocusedStack = mFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001032 return true;
1033 }
1034
1035 boolean allResumedActivitiesVisible() {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001036 boolean foundResumed = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001037 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1038 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001039 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1040 final ActivityStack stack = stacks.get(stackNdx);
1041 final ActivityRecord r = stack.mResumedActivity;
riddle_hsudb46d6b2015-04-01 18:58:07 +08001042 if (r != null) {
Bryce Lee4a194382017-04-04 14:32:48 -07001043 if (!r.nowVisible || mActivitiesWaitingForVisibleActivity.contains(r)) {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001044 return false;
1045 }
1046 foundResumed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001047 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001048 }
1049 }
riddle_hsudb46d6b2015-04-01 18:58:07 +08001050 return foundResumed;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001051 }
1052
Craig Mautner2acc3892013-09-23 10:28:14 -07001053 /**
1054 * Pause all activities in either all of the stacks or just the back stacks.
1055 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
Wale Ogunwale950faff2016-08-08 09:51:04 -07001056 * @param resuming The resuming activity.
1057 * @param dontWait The resuming activity isn't going to wait for all activities to be paused
1058 * before resuming.
Craig Mautner2acc3892013-09-23 10:28:14 -07001059 * @return true if any activity was paused as a result of this call.
1060 */
Wale Ogunwale950faff2016-08-08 09:51:04 -07001061 boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
Craig Mautnercf910b02013-04-23 11:23:27 -07001062 boolean someActivityPaused = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001063 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1064 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001065 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1066 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001067 if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001068 if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
Craig Mautner4a1cb222013-12-04 16:14:06 -08001069 " mResumedActivity=" + stack.mResumedActivity);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001070 someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
1071 dontWait);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001072 }
Craig Mautnercf910b02013-04-23 11:23:27 -07001073 }
1074 }
1075 return someActivityPaused;
1076 }
1077
Craig Mautnerde4ef022013-04-07 19:01:33 -07001078 boolean allPausedActivitiesComplete() {
Craig Mautnerac6f8432013-07-17 13:24:59 -07001079 boolean pausing = true;
Craig Mautnere0a38842013-12-16 16:14:02 -08001080 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1081 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001082 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1083 final ActivityStack stack = stacks.get(stackNdx);
1084 final ActivityRecord r = stack.mPausingActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001085 if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001086 if (DEBUG_STATES) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001087 Slog.d(TAG_STATES,
1088 "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001089 pausing = false;
1090 } else {
1091 return false;
1092 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001093 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001094 }
1095 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001096 return pausing;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001097 }
1098
Wale Ogunwale2be760d2016-02-17 11:16:10 -08001099 void cancelInitializingActivities() {
1100 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1101 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1102 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1103 stacks.get(stackNdx).cancelInitializingActivities();
1104 }
1105 }
1106 }
1107
Bryce Lee4a194382017-04-04 14:32:48 -07001108 void waitActivityVisible(ComponentName name, WaitResult result) {
1109 final WaitInfo waitInfo = new WaitInfo(name, result);
1110 mWaitingForActivityVisible.add(waitInfo);
1111 }
1112
1113 void cleanupActivity(ActivityRecord r) {
1114 // Make sure this record is no longer in the pending finishes list.
1115 // This could happen, for example, if we are trimming activities
1116 // down to the max limit while they are still waiting to finish.
1117 mFinishingActivities.remove(r);
1118 mActivitiesWaitingForVisibleActivity.remove(r);
1119
1120 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
Wale Ogunwale3270f172017-04-26 07:29:42 -07001121 if (mWaitingForActivityVisible.get(i).matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001122 mWaitingForActivityVisible.remove(i);
1123 }
1124 }
1125 }
1126
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001127 void reportActivityVisibleLocked(ActivityRecord r) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001128 sendWaitingVisibleReportLocked(r);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001129 }
1130
1131 void sendWaitingVisibleReportLocked(ActivityRecord r) {
1132 boolean changed = false;
Bryce Lee4a194382017-04-04 14:32:48 -07001133 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
1134 final WaitInfo w = mWaitingForActivityVisible.get(i);
Wale Ogunwale3270f172017-04-26 07:29:42 -07001135 if (w.matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001136 final WaitResult result = w.getResult();
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001137 changed = true;
Bryce Lee4a194382017-04-04 14:32:48 -07001138 result.timeout = false;
1139 result.who = w.getComponent();
1140 result.totalTime = SystemClock.uptimeMillis() - result.thisTime;
1141 result.thisTime = result.totalTime;
1142 mWaitingForActivityVisible.remove(w);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001143 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001144 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001145 if (changed) {
1146 mService.notifyAll();
1147 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001148 }
1149
Chong Zhang5022da32016-06-21 16:31:37 -07001150 void reportTaskToFrontNoLaunch(ActivityRecord r) {
1151 boolean changed = false;
1152 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1153 WaitResult w = mWaitingActivityLaunched.remove(i);
1154 if (w.who == null) {
1155 changed = true;
1156 // Set result to START_TASK_TO_FRONT so that startActivityMayWait() knows that
1157 // the starting activity ends up moving another activity to front, and it should
1158 // wait for this new activity to become visible instead.
1159 // Do not modify other fields.
1160 w.result = START_TASK_TO_FRONT;
1161 }
1162 }
1163 if (changed) {
1164 mService.notifyAll();
1165 }
1166 }
1167
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001168 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
1169 long thisTime, long totalTime) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001170 boolean changed = false;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001171 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
Craig Mautnerc64f73e2013-04-24 16:44:56 -07001172 WaitResult w = mWaitingActivityLaunched.remove(i);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001173 if (w.who == null) {
1174 changed = true;
1175 w.timeout = timeout;
1176 if (r != null) {
1177 w.who = new ComponentName(r.info.packageName, r.info.name);
1178 }
1179 w.thisTime = thisTime;
1180 w.totalTime = totalTime;
Chong Zhang5022da32016-06-21 16:31:37 -07001181 // Do not modify w.result.
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001182 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001183 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001184 if (changed) {
1185 mService.notifyAll();
1186 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001187 }
1188
Craig Mautner29219d92013-04-16 20:19:12 -07001189 ActivityRecord topRunningActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -08001190 final ActivityStack focusedStack = mFocusedStack;
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07001191 ActivityRecord r = focusedStack.topRunningActivityLocked();
Craig Mautner1602ec22013-05-12 10:24:27 -07001192 if (r != null) {
1193 return r;
Craig Mautner29219d92013-04-16 20:19:12 -07001194 }
Craig Mautner1602ec22013-05-12 10:24:27 -07001195
Andrii Kulian7318d632016-07-20 18:59:28 -07001196 // Look in other non-focused and non-home stacks.
Andrii Kulian7d95df42017-02-15 10:11:48 -08001197 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
1198
1199 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
1200 final int displayId = mTmpOrderedDisplayIds.get(i);
1201 final List<ActivityStack> stacks = mActivityDisplays.get(displayId).mStacks;
1202 if (stacks == null) {
1203 continue;
1204 }
1205 for (int j = stacks.size() - 1; j >= 0; --j) {
1206 final ActivityStack stack = stacks.get(j);
1207 if (stack != focusedStack && isFrontStackOnDisplay(stack) && stack.isFocusable()) {
1208 r = stack.topRunningActivityLocked();
1209 if (r != null) {
1210 return r;
1211 }
Craig Mautner29219d92013-04-16 20:19:12 -07001212 }
1213 }
1214 }
1215 return null;
1216 }
1217
Dianne Hackborn09233282014-04-30 11:33:59 -07001218 void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001219 // Gather all of the running tasks for each stack into runningTaskLists.
Craig Mautner4a1cb222013-12-04 16:14:06 -08001220 ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1221 new ArrayList<ArrayList<RunningTaskInfo>>();
Craig Mautnere0a38842013-12-16 16:14:02 -08001222 final int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001223 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08001224 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001225 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1226 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautner15df08a2015-04-01 12:17:18 -07001227 ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001228 runningTaskLists.add(stackTaskList);
Dianne Hackborn09233282014-04-30 11:33:59 -07001229 stack.getTasksLocked(stackTaskList, callingUid, allowed);
Craig Mautner20e72272013-04-01 13:45:53 -07001230 }
1231 }
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001232
1233 // The lists are already sorted from most recent to oldest. Just pull the most recent off
1234 // each list and add it to list. Stop when all lists are empty or maxNum reached.
1235 while (maxNum > 0) {
1236 long mostRecentActiveTime = Long.MIN_VALUE;
1237 ArrayList<RunningTaskInfo> selectedStackList = null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001238 final int numTaskLists = runningTaskLists.size();
1239 for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1240 ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001241 if (!stackTaskList.isEmpty()) {
1242 final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1243 if (lastActiveTime > mostRecentActiveTime) {
1244 mostRecentActiveTime = lastActiveTime;
1245 selectedStackList = stackTaskList;
1246 }
1247 }
1248 }
1249 if (selectedStackList != null) {
1250 list.add(selectedStackList.remove(0));
1251 --maxNum;
1252 } else {
1253 break;
1254 }
1255 }
Craig Mautner20e72272013-04-01 13:45:53 -07001256 }
1257
Todd Kennedy7440f172015-12-09 14:31:22 -08001258 ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1259 ProfilerInfo profilerInfo) {
1260 final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
Craig Mautner23ac33b2013-04-01 16:26:35 -07001261 if (aInfo != null) {
1262 // Store the found target back into the intent, because now that
1263 // we have it we never want to do this again. For example, if the
1264 // user navigates back to this point in the history, we should
1265 // always restart the exact same activity.
1266 intent.setComponent(new ComponentName(
1267 aInfo.applicationInfo.packageName, aInfo.name));
1268
1269 // Don't debug things in the system process
Man Caocfa78b22015-06-11 20:14:34 -07001270 if (!aInfo.processName.equals("system")) {
1271 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
Chong Zhangd25944e2016-06-09 16:15:27 -07001272 mService.setDebugApp(aInfo.processName, true, false);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001273 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001274
Tamas Berghammerdf6cb282016-01-29 12:07:00 +00001275 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1276 mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1277 }
1278
Man Caocfa78b22015-06-11 20:14:34 -07001279 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1280 mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1281 }
1282
1283 if (profilerInfo != null) {
Jeff Hao1b012d32014-08-20 10:35:34 -07001284 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001285 }
1286 }
Todd Kennedyb3b431302017-03-20 16:05:48 -07001287 final String intentLaunchToken = intent.getLaunchToken();
1288 if (aInfo.launchToken == null && intentLaunchToken != null) {
1289 aInfo.launchToken = intentLaunchToken;
1290 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001291 }
1292 return aInfo;
1293 }
1294
Todd Kennedy7440f172015-12-09 14:31:22 -08001295 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
Kenny Guyb1b30262016-02-09 16:02:35 +00001296 return resolveIntent(intent, resolvedType, userId, 0);
1297 }
1298
1299 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
Todd Kennedy4d1de7d2017-02-23 10:32:18 -08001300 synchronized (mService) {
1301 return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001302 PackageManager.MATCH_INSTANT | PackageManager.MATCH_DEFAULT_ONLY | flags
Kenny Guyb1b30262016-02-09 16:02:35 +00001303 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Todd Kennedy7440f172015-12-09 14:31:22 -08001304 }
Todd Kennedy7440f172015-12-09 14:31:22 -08001305 }
1306
1307 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1308 ProfilerInfo profilerInfo, int userId) {
1309 final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1310 return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1311 }
1312
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001313 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1314 boolean andResume, boolean checkConfig) throws RemoteException {
1315
1316 if (!allPausedActivitiesComplete()) {
1317 // While there are activities pausing we skipping starting any new activities until
1318 // pauses are complete. NOTE: that we also do this for activities that are starting in
1319 // the paused state because they will first be resumed then paused on the client side.
1320 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1321 "realStartActivityLocked: Skipping start of r=" + r
1322 + " some activities pausing...");
1323 return false;
1324 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001325
Bryce Leeaf691c02017-03-20 14:20:22 -07001326 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07001327 final ActivityStack stack = task.getStack();
chaviw59b98852017-06-13 12:05:44 -07001328
1329 beginDeferResume();
1330
Craig Mautner2420ead2013-04-01 17:13:20 -07001331 try {
chaviw59b98852017-06-13 12:05:44 -07001332 r.startFreezingScreenLocked(app, 0);
1333
1334 // schedule launch ticks to collect information about slow apps.
1335 r.startLaunchTickingLocked();
1336
1337 r.app = app;
1338
1339 // Have the window manager re-evaluate the orientation of the screen based on the new
1340 // activity order. Note that as a result of this, it can call back into the activity
1341 // manager with a new orientation. We don't care about that, because the activity is
1342 // not currently running so we are just restarting it anyway.
1343 if (checkConfig) {
1344 final int displayId = r.getDisplayId();
1345 final Configuration config = mWindowManager.updateOrientationFromAppTokens(
1346 getDisplayOverrideConfiguration(displayId),
1347 r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
1348 // Deferring resume here because we're going to launch new activity shortly.
1349 // We don't want to perform a redundant launch of the same record while ensuring
1350 // configurations and trying to resume top activity of focused stack.
1351 mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
1352 displayId);
Craig Mautner2420ead2013-04-01 17:13:20 -07001353 }
chaviw59b98852017-06-13 12:05:44 -07001354
1355 if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */,
1356 true /* isTop */)) {
1357 // We only set the visibility to true if the activity is allowed to be visible
1358 // based on
1359 // keyguard state. This avoids setting this into motion in window manager that is
1360 // later cancelled due to later calls to ensure visible activities that set
1361 // visibility back to false.
1362 r.setVisibility(true);
Craig Mautner2420ead2013-04-01 17:13:20 -07001363 }
chaviw59b98852017-06-13 12:05:44 -07001364
1365 if (mKeyguardController.isKeyguardLocked()) {
1366 r.notifyUnknownVisibilityLaunched();
Craig Mautner2420ead2013-04-01 17:13:20 -07001367 }
chaviw59b98852017-06-13 12:05:44 -07001368 final int applicationInfoUid =
1369 (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
1370 if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
1371 Slog.wtf(TAG,
1372 "User ID for activity changing for " + r
1373 + " appInfo.uid=" + r.appInfo.uid
1374 + " info.ai.uid=" + applicationInfoUid
1375 + " old=" + r.app + " new=" + app);
1376 }
1377
1378 app.waitingToKill = null;
1379 r.launchCount++;
1380 r.lastLaunchTime = SystemClock.uptimeMillis();
1381
1382 if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1383
1384 int idx = app.activities.indexOf(r);
1385 if (idx < 0) {
1386 app.activities.add(r);
1387 }
1388 mService.updateLruProcessLocked(app, true, null);
1389 mService.updateOomAdjLocked();
1390
1391 if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1392 task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
1393 setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE",
1394 false);
1395 }
1396
1397 try {
1398 if (app.thread == null) {
1399 throw new RemoteException();
1400 }
1401 List<ResultInfo> results = null;
1402 List<ReferrerIntent> newIntents = null;
1403 if (andResume) {
1404 // We don't need to deliver new intents and/or set results if activity is going
1405 // to pause immediately after launch.
1406 results = r.results;
1407 newIntents = r.newIntents;
1408 }
1409 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1410 "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1411 + " newIntents=" + newIntents + " andResume=" + andResume);
1412 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
1413 System.identityHashCode(r), task.taskId, r.shortComponentName);
1414 if (r.isHomeActivity()) {
1415 // Home process is the root process of the task.
1416 mService.mHomeProcess = task.mActivities.get(0).app;
1417 }
1418 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
1419 PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
1420 r.sleeping = false;
1421 r.forceNewConfig = false;
1422 mService.showUnsupportedZoomDialogIfNeededLocked(r);
1423 mService.showAskCompatModeDialogLocked(r);
1424 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1425 ProfilerInfo profilerInfo = null;
1426 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1427 if (mService.mProfileProc == null || mService.mProfileProc == app) {
1428 mService.mProfileProc = app;
Andreas Gampe2b073a02017-06-22 17:28:57 -07001429 ProfilerInfo profilerInfoSvc = mService.mProfilerInfo;
1430 if (profilerInfoSvc != null && profilerInfoSvc.profileFile != null) {
1431 if (profilerInfoSvc.profileFd != null) {
chaviw59b98852017-06-13 12:05:44 -07001432 try {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001433 profilerInfoSvc.profileFd = profilerInfoSvc.profileFd.dup();
chaviw59b98852017-06-13 12:05:44 -07001434 } catch (IOException e) {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001435 profilerInfoSvc.closeFd();
Craig Mautner2568c3a2015-03-26 14:22:34 -07001436 }
1437 }
chaviw59b98852017-06-13 12:05:44 -07001438
Andreas Gampe2b073a02017-06-22 17:28:57 -07001439 profilerInfo = new ProfilerInfo(profilerInfoSvc);
Craig Mautner2420ead2013-04-01 17:13:20 -07001440 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001441 }
1442 }
Adam Powellcfbe9be2013-11-06 14:58:58 -08001443
chaviw59b98852017-06-13 12:05:44 -07001444 app.hasShownUi = true;
1445 app.pendingUiClean = true;
1446 app.forceProcessStateUpTo(mService.mTopProcessState);
1447 // Because we could be starting an Activity in the system process this may not go
1448 // across a Binder interface which would create a new Configuration. Consequently
1449 // we have to always create a new Configuration here.
Bryce Leea163b762017-01-24 11:05:01 -08001450
chaviw59b98852017-06-13 12:05:44 -07001451 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
1452 mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
1453 r.setLastReportedConfiguration(mergedConfiguration);
Bryce Leea163b762017-01-24 11:05:01 -08001454
chaviw59b98852017-06-13 12:05:44 -07001455 logIfTransactionTooLarge(r.intent, r.icicle);
1456 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1457 System.identityHashCode(r), r.info,
1458 // TODO: Have this take the merged configuration instead of separate global
1459 // and override configs.
1460 mergedConfiguration.getGlobalConfiguration(),
1461 mergedConfiguration.getOverrideConfiguration(), r.compat,
1462 r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1463 r.persistentState, results, newIntents, !andResume,
1464 mService.isNextTransitionForward(), profilerInfo);
Craig Mautner2420ead2013-04-01 17:13:20 -07001465
chaviw59b98852017-06-13 12:05:44 -07001466 if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1467 // This may be a heavy-weight process! Note that the package
1468 // manager will ensure that only activity can run in the main
1469 // process of the .apk, which is the only thing that will be
1470 // considered heavy-weight.
1471 if (app.processName.equals(app.info.packageName)) {
1472 if (mService.mHeavyWeightProcess != null
1473 && mService.mHeavyWeightProcess != app) {
1474 Slog.w(TAG, "Starting new heavy weight process " + app
1475 + " when already running "
1476 + mService.mHeavyWeightProcess);
1477 }
1478 mService.mHeavyWeightProcess = app;
1479 Message msg = mService.mHandler.obtainMessage(
1480 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1481 msg.obj = r;
1482 mService.mHandler.sendMessage(msg);
Craig Mautner2420ead2013-04-01 17:13:20 -07001483 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001484 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001485
chaviw59b98852017-06-13 12:05:44 -07001486 } catch (RemoteException e) {
1487 if (r.launchFailed) {
1488 // This is the second time we failed -- finish activity
1489 // and give up.
1490 Slog.e(TAG, "Second failure launching "
1491 + r.intent.getComponent().flattenToShortString()
1492 + ", giving up", e);
1493 mService.appDiedLocked(app);
1494 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1495 "2nd-crash", false);
1496 return false;
1497 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001498
chaviw59b98852017-06-13 12:05:44 -07001499 // This is the first time we failed -- restart process and
1500 // retry.
1501 r.launchFailed = true;
1502 app.activities.remove(r);
1503 throw e;
1504 }
1505 } finally {
1506 endDeferResume();
Craig Mautner2420ead2013-04-01 17:13:20 -07001507 }
1508
1509 r.launchFailed = false;
1510 if (stack.updateLRUListLocked(r)) {
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07001511 Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
Craig Mautner2420ead2013-04-01 17:13:20 -07001512 }
1513
chaviw59b98852017-06-13 12:05:44 -07001514 if (andResume && readyToResume()) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001515 // As part of the process of launching, ActivityThread also performs
1516 // a resume.
1517 stack.minimalResumeActivityLocked(r);
1518 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001519 // This activity is not starting in the resumed state... which should look like we asked
Wale Ogunwale919a05d2017-04-13 00:36:34 +00001520 // it to pause+stop (but remain visible), and it has done so and reported back the
Wale Ogunwaled046a012015-12-24 13:05:59 -08001521 // current icicle and other state.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001522 if (DEBUG_STATES) Slog.v(TAG_STATES,
Wale Ogunwaled046a012015-12-24 13:05:59 -08001523 "Moving to PAUSED: " + r + " (starting in paused state)");
1524 r.state = PAUSED;
Craig Mautner2420ead2013-04-01 17:13:20 -07001525 }
1526
1527 // Launch the new version setup screen if needed. We do this -after-
1528 // launching the initial activity (that is, home), so that it can have
1529 // a chance to initialize itself while in the background, making the
1530 // switch back to it faster and look better.
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001531 if (isFocusedStack(stack)) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001532 mService.startSetupActivityLocked();
1533 }
1534
Dianne Hackborn465fa392014-09-14 14:21:18 -07001535 // Update any services we are bound to that might care about whether
1536 // their client may have activities.
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001537 if (r.app != null) {
1538 mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1539 }
Dianne Hackborn465fa392014-09-14 14:21:18 -07001540
Craig Mautner2420ead2013-04-01 17:13:20 -07001541 return true;
1542 }
1543
Sudheer Shankafab200f2017-05-17 20:41:53 -07001544 private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
1545 int extrasSize = 0;
1546 if (intent != null) {
1547 final Bundle extras = intent.getExtras();
1548 if (extras != null) {
1549 extrasSize = extras.getSize();
1550 }
1551 }
1552 int icicleSize = (icicle == null ? 0 : icicle.getSize());
1553 if (extrasSize + icicleSize > 200000) {
1554 Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
1555 + ", icicle size: " + icicleSize);
1556 }
1557 }
1558
Craig Mautnere79d42682013-04-01 19:01:53 -07001559 void startSpecificActivityLocked(ActivityRecord r,
George Mount2c92c972014-03-20 09:38:23 -07001560 boolean andResume, boolean checkConfig) {
Craig Mautnere79d42682013-04-01 19:01:53 -07001561 // Is this activity's application already running?
1562 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001563 r.info.applicationInfo.uid, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001564
Andrii Kulian02b7a832016-10-06 23:11:56 -07001565 r.getStack().setLaunchTime(r);
Craig Mautnere79d42682013-04-01 19:01:53 -07001566
1567 if (app != null && app.thread != null) {
1568 try {
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001569 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1570 || !"android".equals(r.info.packageName)) {
1571 // Don't add this if it is a platform component that is marked
1572 // to run in multiple processes, because this is actually
1573 // part of the framework so doesn't make sense to track as a
1574 // separate apk in the process.
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001575 app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1576 mService.mProcessStats);
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001577 }
George Mount2c92c972014-03-20 09:38:23 -07001578 realStartActivityLocked(r, app, andResume, checkConfig);
Craig Mautnere79d42682013-04-01 19:01:53 -07001579 return;
1580 } catch (RemoteException e) {
1581 Slog.w(TAG, "Exception when starting activity "
1582 + r.intent.getComponent().flattenToShortString(), e);
1583 }
1584
1585 // If a dead object exception was thrown -- fall through to
1586 // restart the application.
1587 }
1588
1589 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001590 "activity", r.intent.getComponent(), false, false, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001591 }
1592
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001593 boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001594 String resultWho, int requestCode, int callingPid, int callingUid,
1595 String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
Jorim Jaggi2adba072016-03-03 13:43:39 +01001596 ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001597 final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1598 callingUid);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001599 if (startAnyPerm == PERMISSION_GRANTED) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001600 return true;
1601 }
1602 final int componentRestriction = getComponentRestrictionForCallingPackage(
1603 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1604 final int actionRestriction = getActionRestrictionForCallingPackage(
1605 intent.getAction(), callingPackage, callingPid, callingUid);
1606 if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1607 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1608 if (resultRecord != null) {
1609 resultStack.sendActivityResultLocked(-1,
1610 resultRecord, resultWho, requestCode,
1611 Activity.RESULT_CANCELED, null);
1612 }
1613 final String msg;
1614 if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1615 msg = "Permission Denial: starting " + intent.toString()
1616 + " from " + callerApp + " (pid=" + callingPid
1617 + ", uid=" + callingUid + ")" + " with revoked permission "
1618 + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1619 } else if (!aInfo.exported) {
1620 msg = "Permission Denial: starting " + intent.toString()
1621 + " from " + callerApp + " (pid=" + callingPid
1622 + ", uid=" + callingUid + ")"
1623 + " not exported from uid " + aInfo.applicationInfo.uid;
1624 } else {
1625 msg = "Permission Denial: starting " + intent.toString()
1626 + " from " + callerApp + " (pid=" + callingPid
1627 + ", uid=" + callingUid + ")"
1628 + " requires " + aInfo.permission;
1629 }
1630 Slog.w(TAG, msg);
1631 throw new SecurityException(msg);
1632 }
1633
1634 if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1635 final String message = "Appop Denial: starting " + intent.toString()
1636 + " from " + callerApp + " (pid=" + callingPid
1637 + ", uid=" + callingUid + ")"
1638 + " requires " + AppOpsManager.permissionToOp(
1639 ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1640 Slog.w(TAG, message);
1641 return false;
1642 } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1643 final String message = "Appop Denial: starting " + intent.toString()
1644 + " from " + callerApp + " (pid=" + callingPid
1645 + ", uid=" + callingUid + ")"
1646 + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1647 Slog.w(TAG, message);
1648 return false;
1649 }
Andrii Kulian16802aa2016-11-02 12:21:33 -07001650 if (options != null) {
1651 if (options.getLaunchTaskId() != INVALID_STACK_ID) {
1652 final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1653 callingPid, callingUid);
1654 if (startInTaskPerm != PERMISSION_GRANTED) {
1655 final String msg = "Permission Denial: starting " + intent.toString()
1656 + " from " + callerApp + " (pid=" + callingPid
1657 + ", uid=" + callingUid + ") with launchTaskId="
1658 + options.getLaunchTaskId();
1659 Slog.w(TAG, msg);
1660 throw new SecurityException(msg);
1661 }
1662 }
1663 // Check if someone tries to launch an activity on a private display with a different
1664 // owner.
1665 final int launchDisplayId = options.getLaunchDisplayId();
Andrii Kulian02689a72017-07-06 14:28:59 -07001666 if (launchDisplayId != INVALID_DISPLAY && !isCallerAllowedToLaunchOnDisplay(callingPid,
1667 callingUid, launchDisplayId, aInfo)) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001668 final String msg = "Permission Denial: starting " + intent.toString()
1669 + " from " + callerApp + " (pid=" + callingPid
1670 + ", uid=" + callingUid + ") with launchDisplayId="
1671 + launchDisplayId;
1672 Slog.w(TAG, msg);
1673 throw new SecurityException(msg);
Jorim Jaggi2adba072016-03-03 13:43:39 +01001674 }
1675 }
1676
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001677 return true;
1678 }
1679
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001680 /** Check if caller is allowed to launch activities on specified display. */
Andrii Kulian02689a72017-07-06 14:28:59 -07001681 boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId,
1682 ActivityInfo aInfo) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001683 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId
1684 + " callingPid=" + callingPid + " callingUid=" + callingUid);
1685
Andrii Kulian02689a72017-07-06 14:28:59 -07001686 if (callingPid == -1 && callingUid == -1) {
1687 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: no caller info, skip check");
1688 return true;
1689 }
1690
Andrii Kulian62e6f252017-05-30 22:46:53 -07001691 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(launchDisplayId);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001692 if (activityDisplay == null) {
1693 Slog.w(TAG, "Launch on display check: display not found");
1694 return false;
1695 }
1696
Andrii Kulian02689a72017-07-06 14:28:59 -07001697 // Check if the caller has enough privileges to embed activities and launch to private
1698 // displays.
Andrii Kulian3a95edc2017-06-28 16:21:07 -07001699 final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001700 callingUid);
1701 if (startAnyPerm == PERMISSION_GRANTED) {
1702 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1703 + " allow launch any on display");
1704 return true;
1705 }
1706
1707 if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL
Andrii Kulian02689a72017-07-06 14:28:59 -07001708 && activityDisplay.mDisplay.getOwnerUid() != SYSTEM_UID
1709 && activityDisplay.mDisplay.getOwnerUid() != aInfo.applicationInfo.uid) {
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001710 // Limit launching on virtual displays, because their contents can be read from Surface
1711 // by apps that created them.
Andrii Kulian02689a72017-07-06 14:28:59 -07001712 if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
1713 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1714 + " disallow launch on virtual display for not-embedded activity.");
1715 return false;
1716 }
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001717 }
1718
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001719 if (!activityDisplay.isPrivate()) {
1720 // Anyone can launch on a public display.
1721 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1722 + " allow launch on public display");
1723 return true;
1724 }
1725
1726 // Check if the caller is the owner of the display.
1727 if (activityDisplay.mDisplay.getOwnerUid() == callingUid) {
1728 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1729 + " allow launch for owner of the display");
1730 return true;
1731 }
1732
1733 // Check if caller is present on display
1734 if (activityDisplay.isUidPresent(callingUid)) {
1735 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1736 + " allow launch for caller present on the display");
1737 return true;
1738 }
1739
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001740 Slog.w(TAG, "Launch on display check: denied");
1741 return false;
1742 }
1743
1744 /** Update lists of UIDs that are present on displays and have access to them. */
1745 void updateUIDsPresentOnDisplay() {
1746 mDisplayAccessUIDs.clear();
1747 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1748 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
David Stevens82ea6cb2017-03-03 16:18:50 -08001749 // Only bother calculating the whitelist for private displays
1750 if (activityDisplay.isPrivate()) {
1751 mDisplayAccessUIDs.append(
1752 activityDisplay.mDisplayId, activityDisplay.getPresentUIDs());
1753 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001754 }
1755 // Store updated lists in DisplayManager. Callers from outside of AM should get them there.
1756 mDisplayManagerInternal.setDisplayAccessUIDs(mDisplayAccessUIDs);
1757 }
1758
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001759 UserInfo getUserInfo(int userId) {
Clara Bayarrif7fea162015-10-22 16:09:52 +01001760 final long identity = Binder.clearCallingIdentity();
1761 try {
1762 return UserManager.get(mService.mContext).getUserInfo(userId);
1763 } finally {
1764 Binder.restoreCallingIdentity(identity);
1765 }
1766 }
1767
Svet Ganov99b60432015-06-27 13:15:22 -07001768 private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001769 String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001770 if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1771 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
Svet Ganov99b60432015-06-27 13:15:22 -07001772 == PackageManager.PERMISSION_DENIED) {
1773 return ACTIVITY_RESTRICTION_PERMISSION;
1774 }
1775
Christopher Tateff7add02015-08-17 10:23:22 -07001776 if (activityInfo.permission == null) {
1777 return ACTIVITY_RESTRICTION_NONE;
1778 }
1779
Svet Ganov99b60432015-06-27 13:15:22 -07001780 final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1781 if (opCode == AppOpsManager.OP_NONE) {
1782 return ACTIVITY_RESTRICTION_NONE;
1783 }
1784
1785 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1786 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001787 if (!ignoreTargetSecurity) {
1788 return ACTIVITY_RESTRICTION_APPOP;
1789 }
Svet Ganov99b60432015-06-27 13:15:22 -07001790 }
1791
1792 return ACTIVITY_RESTRICTION_NONE;
1793 }
1794
Svetoslav7008b512015-06-24 18:47:07 -07001795 private int getActionRestrictionForCallingPackage(String action,
1796 String callingPackage, int callingPid, int callingUid) {
1797 if (action == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001798 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001799 }
1800
1801 String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1802 if (permission == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001803 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001804 }
1805
1806 final PackageInfo packageInfo;
1807 try {
1808 packageInfo = mService.mContext.getPackageManager()
1809 .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1810 } catch (PackageManager.NameNotFoundException e) {
1811 Slog.i(TAG, "Cannot find package info for " + callingPackage);
Svet Ganov99b60432015-06-27 13:15:22 -07001812 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001813 }
1814
1815 if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
Svet Ganov99b60432015-06-27 13:15:22 -07001816 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001817 }
1818
1819 if (mService.checkPermission(permission, callingPid, callingUid) ==
1820 PackageManager.PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001821 return ACTIVITY_RESTRICTION_PERMISSION;
Svetoslav7008b512015-06-24 18:47:07 -07001822 }
1823
1824 final int opCode = AppOpsManager.permissionToOpCode(permission);
1825 if (opCode == AppOpsManager.OP_NONE) {
Svet Ganov99b60432015-06-27 13:15:22 -07001826 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001827 }
1828
1829 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1830 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001831 return ACTIVITY_RESTRICTION_APPOP;
Svetoslav7008b512015-06-24 18:47:07 -07001832 }
1833
Svet Ganov99b60432015-06-27 13:15:22 -07001834 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001835 }
1836
Dianne Hackborn3d07c942015-03-13 18:02:54 -07001837 void setLaunchSource(int uid) {
1838 mLaunchingActivity.setWorkSource(new WorkSource(uid));
1839 }
1840
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001841 void acquireLaunchWakelock() {
1842 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1843 throw new IllegalStateException("Calling must be system uid");
1844 }
1845 mLaunchingActivity.acquire();
1846 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1847 // To be safe, don't allow the wake lock to be held for too long.
1848 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1849 }
1850 }
1851
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001852 /**
1853 * Called when the frontmost task is idle.
1854 * @return the state of mService.mBooting before this was called.
1855 */
1856 private boolean checkFinishBootingLocked() {
1857 final boolean booting = mService.mBooting;
1858 boolean enableScreen = false;
1859 mService.mBooting = false;
1860 if (!mService.mBooted) {
1861 mService.mBooted = true;
1862 enableScreen = true;
1863 }
1864 if (booting || enableScreen) {
1865 mService.postFinishBooting(booting, enableScreen);
1866 }
1867 return booting;
1868 }
1869
Craig Mautnerf3333272013-04-22 10:55:53 -07001870 // Checked.
1871 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
Winson Chung4dabf232017-01-25 13:25:22 -08001872 boolean processPausingActivities, Configuration config) {
Wale Ogunwalee23149f2015-03-06 15:39:44 -08001873 if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001874
Craig Mautnerf3333272013-04-22 10:55:53 -07001875 ArrayList<ActivityRecord> finishes = null;
Amith Yamasani37a40c22015-06-17 13:25:42 -07001876 ArrayList<UserState> startingUsers = null;
Craig Mautnerf3333272013-04-22 10:55:53 -07001877 int NS = 0;
1878 int NF = 0;
Craig Mautnerf3333272013-04-22 10:55:53 -07001879 boolean booting = false;
Craig Mautnerf3333272013-04-22 10:55:53 -07001880 boolean activityRemoved = false;
1881
Wale Ogunwale7d701172015-03-11 15:36:30 -07001882 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001883 if (r != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001884 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1885 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07001886 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1887 r.finishLaunchTickingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001888 if (fromTimeout) {
1889 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
Craig Mautnerf3333272013-04-22 10:55:53 -07001890 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001891
1892 // This is a hack to semi-deal with a race condition
1893 // in the client where it can be constructed with a
1894 // newer configuration from when we asked it to launch.
1895 // We'll update with whatever configuration it now says
1896 // it used to launch.
1897 if (config != null) {
Bryce Leea163b762017-01-24 11:05:01 -08001898 r.setLastReportedGlobalConfiguration(config);
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001899 }
1900
1901 // We are now idle. If someone is waiting for a thumbnail from
1902 // us, we can now deliver.
1903 r.idle = true;
1904
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001905 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001906 if (isFocusedStack(r.getStack()) || fromTimeout) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001907 booting = checkFinishBootingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001908 }
1909 }
1910
1911 if (allResumedActivitiesIdle()) {
1912 if (r != null) {
1913 mService.scheduleAppGcsLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001914 }
1915
1916 if (mLaunchingActivity.isHeld()) {
1917 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1918 if (VALIDATE_WAKE_LOCK_CALLER &&
1919 Binder.getCallingUid() != Process.myUid()) {
1920 throw new IllegalStateException("Calling must be system uid");
1921 }
1922 mLaunchingActivity.release();
1923 }
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07001924 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerf3333272013-04-22 10:55:53 -07001925 }
1926
1927 // Atomically retrieve all of the other things to do.
Winson Chung4dabf232017-01-25 13:25:22 -08001928 final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
1929 true /* remove */, processPausingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001930 NS = stops != null ? stops.size() : 0;
Wale Ogunwale7d701172015-03-11 15:36:30 -07001931 if ((NF = mFinishingActivities.size()) > 0) {
1932 finishes = new ArrayList<>(mFinishingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001933 mFinishingActivities.clear();
1934 }
1935
Craig Mautnerf3333272013-04-22 10:55:53 -07001936 if (mStartingUsers.size() > 0) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07001937 startingUsers = new ArrayList<>(mStartingUsers);
Craig Mautnerf3333272013-04-22 10:55:53 -07001938 mStartingUsers.clear();
1939 }
1940
Craig Mautnerf3333272013-04-22 10:55:53 -07001941 // Stop any activities that are scheduled to do so but have been
1942 // waiting for the next one to start.
1943 for (int i = 0; i < NS; i++) {
1944 r = stops.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001945 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001946 if (stack != null) {
1947 if (r.finishing) {
1948 stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1949 } else {
1950 stack.stopActivityLocked(r);
1951 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001952 }
1953 }
1954
1955 // Finish any activities that are scheduled to do so but have been
1956 // waiting for the next one to start.
1957 for (int i = 0; i < NF; i++) {
1958 r = finishes.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001959 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001960 if (stack != null) {
1961 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1962 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001963 }
1964
Dianne Hackborn7622a0f2014-09-30 14:31:42 -07001965 if (!booting) {
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001966 // Complete user switch
1967 if (startingUsers != null) {
1968 for (int i = 0; i < startingUsers.size(); i++) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001969 mService.mUserController.finishUserSwitch(startingUsers.get(i));
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001970 }
1971 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001972 }
1973
1974 mService.trimApplications();
1975 //dump();
1976 //mWindowManager.dump();
1977
Craig Mautnerf3333272013-04-22 10:55:53 -07001978 if (activityRemoved) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001979 resumeFocusedStackTopActivityLocked();
Craig Mautnerf3333272013-04-22 10:55:53 -07001980 }
1981
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001982 return r;
Craig Mautnerf3333272013-04-22 10:55:53 -07001983 }
1984
Craig Mautner8e569572013-10-11 17:36:59 -07001985 boolean handleAppDiedLocked(ProcessRecord app) {
Craig Mautner19091252013-10-05 00:03:53 -07001986 boolean hasVisibleActivities = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001987 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1988 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001989 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1990 hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
1991 }
Craig Mautner6b74cb52013-09-27 17:02:21 -07001992 }
Craig Mautner19091252013-10-05 00:03:53 -07001993 return hasVisibleActivities;
Craig Mautner8d341ef2013-03-26 09:03:27 -07001994 }
1995
1996 void closeSystemDialogsLocked() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001997 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1998 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001999 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2000 stacks.get(stackNdx).closeSystemDialogsLocked();
2001 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002002 }
2003 }
2004
Craig Mautner93529a42013-10-04 15:03:13 -07002005 void removeUserLocked(int userId) {
Craig Mautner4f1df4f2013-10-15 15:44:14 -07002006 mUserStackInFront.delete(userId);
Craig Mautner93529a42013-10-04 15:03:13 -07002007 }
2008
Craig Mautner8d341ef2013-03-26 09:03:27 -07002009 /**
Chong Zhang45c25ce2015-08-10 22:18:26 -07002010 * Update the last used stack id for non-current user (current user's last
2011 * used stack is the focused stack)
2012 */
2013 void updateUserStackLocked(int userId, ActivityStack stack) {
2014 if (userId != mCurrentUser) {
2015 mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
2016 }
2017 }
2018
2019 /**
Craig Mautner8d341ef2013-03-26 09:03:27 -07002020 * @return true if some activity was finished (or would have finished if doit were true).
2021 */
Wale Ogunwale540e1232015-05-01 15:35:39 -07002022 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
2023 boolean doit, boolean evenPersistent, int userId) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07002024 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08002025 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2026 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
louis_chang8f0555a2015-10-27 10:45:53 +08002027 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002028 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002029 if (stack.finishDisabledPackageActivitiesLocked(
2030 packageName, filterByClasses, doit, evenPersistent, userId)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002031 didSomething = true;
2032 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002033 }
2034 }
2035 return didSomething;
2036 }
2037
Dianne Hackborna413dc02013-07-12 12:02:55 -07002038 void updatePreviousProcessLocked(ActivityRecord r) {
2039 // Now that this process has stopped, we may want to consider
2040 // it to be the previous app to try to keep around in case
2041 // the user wants to return to it.
2042
2043 // First, found out what is currently the foreground app, so that
2044 // we don't blow away the previous app if this activity is being
2045 // hosted by the process that is actually still the foreground.
2046 ProcessRecord fgApp = null;
Craig Mautnere0a38842013-12-16 16:14:02 -08002047 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2048 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002049 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2050 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07002051 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002052 if (stack.mResumedActivity != null) {
2053 fgApp = stack.mResumedActivity.app;
2054 } else if (stack.mPausingActivity != null) {
2055 fgApp = stack.mPausingActivity.app;
2056 }
2057 break;
Dianne Hackborna413dc02013-07-12 12:02:55 -07002058 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07002059 }
2060 }
2061
2062 // Now set this one as the previous process, only if that really
2063 // makes sense to.
2064 if (r.app != null && fgApp != null && r.app != fgApp
2065 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
Craig Mautner4ef26932013-09-18 15:15:52 -07002066 && r.app != mService.mHomeProcess) {
Dianne Hackborna413dc02013-07-12 12:02:55 -07002067 mService.mPreviousProcess = r.app;
2068 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
2069 }
2070 }
2071
Wale Ogunwaled046a012015-12-24 13:05:59 -08002072 boolean resumeFocusedStackTopActivityLocked() {
2073 return resumeFocusedStackTopActivityLocked(null, null, null);
Craig Mautner05d29032013-05-03 13:40:13 -07002074 }
2075
Wale Ogunwaled046a012015-12-24 13:05:59 -08002076 boolean resumeFocusedStackTopActivityLocked(
Chong Zhang280d3322015-11-03 17:27:26 -08002077 ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
chaviw59b98852017-06-13 12:05:44 -07002078
2079 if (!readyToResume()) {
2080 return false;
2081 }
2082
Wale Ogunwaled046a012015-12-24 13:05:59 -08002083 if (targetStack != null && isFocusedStack(targetStack)) {
2084 return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
Craig Mautner05d29032013-05-03 13:40:13 -07002085 }
chaviw59b98852017-06-13 12:05:44 -07002086
Wale Ogunwale06579d62016-04-30 15:29:06 -07002087 final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2088 if (r == null || r.state != RESUMED) {
2089 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
skuhne@google.com1b974dc2016-12-09 13:41:29 -08002090 } else if (r.state == RESUMED) {
2091 // Kick off any lingering app transitions form the MoveTaskToFront operation.
2092 mFocusedStack.executeAppTransition(targetOptions);
Wale Ogunwale06579d62016-04-30 15:29:06 -07002093 }
chaviw59b98852017-06-13 12:05:44 -07002094
Wale Ogunwaled046a012015-12-24 13:05:59 -08002095 return false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002096 }
2097
Todd Kennedy39bfee52016-02-24 10:28:21 -08002098 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
2099 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2100 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2101 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2102 stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
2103 }
2104 }
2105 }
2106
Adrian Roos20d7df32016-01-12 18:59:43 +01002107 TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
2108 TaskRecord finishedTask = null;
2109 ActivityStack focusedStack = getFocusedStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08002110 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2111 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002112 final int numStacks = stacks.size();
2113 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2114 final ActivityStack stack = stacks.get(stackNdx);
Adrian Roos20d7df32016-01-12 18:59:43 +01002115 TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
2116 if (stack == focusedStack || finishedTask == null) {
2117 finishedTask = t;
2118 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08002119 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002120 }
Adrian Roos20d7df32016-01-12 18:59:43 +01002121 return finishedTask;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002122 }
2123
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07002124 void finishVoiceTask(IVoiceInteractionSession session) {
2125 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2126 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2127 final int numStacks = stacks.size();
2128 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2129 final ActivityStack stack = stacks.get(stackNdx);
2130 stack.finishVoiceTask(session);
2131 }
2132 }
2133 }
2134
Andrii Kulianc27916642016-04-12 17:59:27 -07002135 void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
2136 String reason, boolean forceNonResizeable) {
Craig Mautneraea74a52014-03-08 14:23:10 -08002137 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
2138 mUserLeaving = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002139 }
Craig Mautneraea74a52014-03-08 14:23:10 -08002140 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
2141 // Caller wants the home activity moved with it. To accomplish this,
2142 // we'll just indicate that this task returns to the home task.
Craig Mautner84984fa2014-06-19 11:19:20 -07002143 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
Craig Mautneraea74a52014-03-08 14:23:10 -08002144 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002145 ActivityStack currentStack = task.getStack();
2146 if (currentStack == null) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07002147 Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
2148 + task + " to front. Stack is null");
2149 return;
2150 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002151
Wale Ogunwaleb1faf602016-01-27 09:12:31 -08002152 if (task.isResizeable() && options != null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002153 int stackId = options.getLaunchStackId();
2154 if (canUseActivityOptionsLaunchBounds(options, stackId)) {
Filip Gruszczynskidce2d162016-01-12 15:40:13 -08002155 final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
Chong Zhang0fa656b2015-08-31 15:17:21 -07002156 task.updateOverrideConfiguration(bounds);
Wale Ogunwale854809c2015-12-27 16:18:19 -08002157 if (stackId == INVALID_STACK_ID) {
2158 stackId = task.getLaunchStackId();
2159 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002160 if (stackId != currentStack.mStackId) {
Winson Chung74666102017-02-22 17:49:24 -08002161 task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE,
2162 DEFER_RESUME, "findTaskToMoveToFrontLocked");
Andrii Kulian02b7a832016-10-06 23:11:56 -07002163 stackId = currentStack.mStackId;
Chong Zhang112eb8c2015-11-02 11:17:00 -08002164 // moveTaskToStackUncheckedLocked() should already placed the task on top,
2165 // still need moveTaskToFrontLocked() below for any transition settings.
2166 }
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002167 if (StackId.resizeStackWithLaunchBounds(stackId)) {
2168 resizeStackLocked(stackId, bounds,
2169 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002170 !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002171 } else {
2172 // WM resizeTask must be done after the task is moved to the correct stack,
2173 // because Task's setBounds() also updates dim layer's bounds, but that has
2174 // dependency on the stack.
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002175 task.resizeWindowContainer();
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002176 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002177 }
2178 }
2179
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002180 final ActivityRecord r = task.getTopActivity();
Andrii Kulian02b7a832016-10-06 23:11:56 -07002181 currentStack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002182 r == null ? null : r.appTimeTracker, reason);
2183
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002184 if (DEBUG_STACK) Slog.d(TAG_STACK,
Andrii Kulian02b7a832016-10-06 23:11:56 -07002185 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
Jorim Jaggi2adba072016-03-03 13:43:39 +01002186
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002187 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
2188 currentStack.mStackId, forceNonResizeable);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002189 }
2190
Wale Ogunwale854809c2015-12-27 16:18:19 -08002191 boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002192 // We use the launch bounds in the activity options is the device supports freeform
Wale Ogunwale854809c2015-12-27 16:18:19 -08002193 // window management or is launching into the pinned stack.
Wale Ogunwale5122df02016-01-29 22:33:38 -08002194 if (options.getLaunchBounds() == null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002195 return false;
2196 }
2197 return (mService.mSupportsPictureInPicture && launchStackId == PINNED_STACK_ID)
2198 || mService.mSupportsFreeformWindowManagement;
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002199 }
2200
Winson Chung55893332017-02-17 17:13:10 -08002201 protected <T extends ActivityStack> T getStack(int stackId) {
Wale Ogunwale040b4702015-08-06 18:10:50 -07002202 return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002203 }
2204
Winson Chung55893332017-02-17 17:13:10 -08002205 protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
2206 boolean createOnTop) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002207 final ActivityStack stack = mStacks.get(stackId);
2208 if (stack != null) {
2209 return (T) stack;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002210 }
Wale Ogunwale3797c222015-10-27 14:21:58 -07002211 if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002212 return null;
2213 }
Matthew Ng330757d2017-02-28 14:19:17 -08002214 if (stackId == DOCKED_STACK_ID) {
2215 // Make sure recents stack exist when creating a dock stack as it normally need to be on
2216 // the other side of the docked stack and we make visibility decisions based on that.
2217 getStack(RECENTS_STACK_ID, CREATE_IF_NEEDED, createOnTop);
2218 }
Winson Chung55893332017-02-17 17:13:10 -08002219 return (T) createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002220 }
2221
Andrii Kulian16802aa2016-11-02 12:21:33 -07002222 /**
2223 * Get a topmost stack on the display, that is a valid launch stack for specified activity.
2224 * If there is no such stack, new dynamic stack can be created.
2225 * @param displayId Target display.
2226 * @param r Activity that should be launched there.
2227 * @return Existing stack if there is a valid one, new dynamic stack if it is valid or null.
2228 */
2229 ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002230 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian16802aa2016-11-02 12:21:33 -07002231 if (activityDisplay == null) {
2232 throw new IllegalArgumentException(
2233 "Display with displayId=" + displayId + " not found.");
2234 }
2235
2236 // Return the topmost valid stack on the display.
2237 for (int i = activityDisplay.mStacks.size() - 1; i >= 0; --i) {
2238 final ActivityStack stack = activityDisplay.mStacks.get(i);
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002239 if (mService.mActivityStarter.isValidLaunchStackId(stack.mStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002240 return stack;
2241 }
2242 }
2243
2244 // If there is no valid stack on the external display - check if new dynamic stack will do.
2245 if (displayId != Display.DEFAULT_DISPLAY) {
2246 final int newDynamicStackId = getNextStackId();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002247 if (mService.mActivityStarter.isValidLaunchStackId(newDynamicStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002248 return createStackOnDisplay(newDynamicStackId, displayId, true /*onTop*/);
2249 }
2250 }
2251
2252 Slog.w(TAG, "getValidLaunchStackOnDisplay: can't launch on displayId " + displayId);
2253 return null;
2254 }
2255
Craig Mautner967212c2013-04-13 21:10:58 -07002256 ArrayList<ActivityStack> getStacks() {
Wale Ogunwale3797c222015-10-27 14:21:58 -07002257 ArrayList<ActivityStack> allStacks = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08002258 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2259 allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002260 }
2261 return allStacks;
Craig Mautner967212c2013-04-13 21:10:58 -07002262 }
2263
Jorim Jaggife762342016-10-13 14:33:27 +02002264 ArrayList<ActivityStack> getStacksOnDefaultDisplay() {
2265 return mActivityDisplays.valueAt(DEFAULT_DISPLAY).mStacks;
2266 }
2267
Andrii Kulian7fc22812016-12-28 13:04:11 -08002268 /**
2269 * Get next focusable stack in the system. This will search across displays and stacks
2270 * in last-focused order for a focusable and visible stack, different from the target stack.
2271 *
2272 * @param currentFocus The stack that previously had focus and thus needs to be ignored when
2273 * searching for next candidate.
2274 * @return Next focusable {@link ActivityStack}, null if not found.
2275 */
2276 ActivityStack getNextFocusableStackLocked(ActivityStack currentFocus) {
2277 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2278
2279 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2280 final int displayId = mTmpOrderedDisplayIds.get(i);
Andrii Kulian62e6f252017-05-30 22:46:53 -07002281 // If a display is registered in WM, it must also be available in AM.
2282 @SuppressWarnings("ConstantConditions")
2283 final List<ActivityStack> stacks = getActivityDisplayOrCreateLocked(displayId).mStacks;
Andrii Kulian7fc22812016-12-28 13:04:11 -08002284 for (int j = stacks.size() - 1; j >= 0; --j) {
2285 final ActivityStack stack = stacks.get(j);
2286 if (stack != currentFocus && stack.isFocusable()
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002287 && stack.shouldBeVisible(null) != STACK_INVISIBLE) {
Andrii Kulian7fc22812016-12-28 13:04:11 -08002288 return stack;
2289 }
2290 }
2291 }
2292
2293 return null;
2294 }
2295
Andrii Kuliana8fe3df2017-06-16 15:29:26 -07002296 /**
2297 * Get next valid stack for launching provided activity in the system. This will search across
2298 * displays and stacks in last-focused order for a focusable and visible stack, except those
2299 * that are on a currently focused display.
2300 *
2301 * @param r The activity that is being launched.
2302 * @param currentFocus The display that previously had focus and thus needs to be ignored when
2303 * searching for the next candidate.
2304 * @return Next valid {@link ActivityStack}, null if not found.
2305 */
2306 ActivityStack getNextValidLaunchStackLocked(@NonNull ActivityRecord r, int currentFocus) {
2307 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2308 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2309 final int displayId = mTmpOrderedDisplayIds.get(i);
2310 if (displayId == currentFocus) {
2311 continue;
2312 }
2313 final ActivityStack stack = getValidLaunchStackOnDisplay(displayId, r);
2314 if (stack != null) {
2315 return stack;
2316 }
2317 }
2318 return null;
2319 }
2320
Craig Mautneree2e45a2014-06-27 12:10:03 -07002321 ActivityRecord getHomeActivity() {
Craig Mautnerdb49fec2015-05-21 15:33:30 -07002322 return getHomeActivityForUser(mCurrentUser);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002323 }
2324
2325 ActivityRecord getHomeActivityForUser(int userId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002326 final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
2327 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
2328 final TaskRecord task = tasks.get(taskNdx);
2329 if (task.isHomeTask()) {
2330 final ArrayList<ActivityRecord> activities = task.mActivities;
2331 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2332 final ActivityRecord r = activities.get(activityNdx);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002333 if (r.isHomeActivity()
2334 && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
Craig Mautneree2e45a2014-06-27 12:10:03 -07002335 return r;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002336 }
2337 }
2338 }
2339 }
2340 return null;
2341 }
2342
Chong Zhangb15758a2015-11-17 12:12:03 -08002343 /**
2344 * Returns if a stack should be treated as if it's docked. Returns true if the stack is
2345 * the docked stack itself, or if it's side-by-side to the docked stack.
2346 */
2347 boolean isStackDockedInEffect(int stackId) {
2348 return stackId == DOCKED_STACK_ID ||
2349 (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
2350 }
2351
Jorim Jaggidc249c42015-12-15 14:57:31 -08002352 void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002353 boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
Jorim Jaggidc249c42015-12-15 14:57:31 -08002354 if (stackId == DOCKED_STACK_ID) {
2355 resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002356 preserveWindows, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002357 return;
2358 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08002359 final ActivityStack stack = getStack(stackId);
2360 if (stack == null) {
2361 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2362 return;
2363 }
Wale Ogunwale9d3de4c2015-02-01 16:49:44 -08002364
Winson Chunga2249ac2017-03-30 18:15:30 -07002365 if (!allowResizeInDockedMode && !StackId.tasksAreFloating(stackId) &&
2366 getStack(DOCKED_STACK_ID) != null) {
2367 // If the docked stack exists, don't resize non-floating stacks independently of the
2368 // size computed from the docked stack size (otherwise they will be out of sync)
Wale Ogunwaleffc11bb2015-10-10 13:05:45 -07002369 return;
2370 }
2371
Wale Ogunwalecad05a02015-09-25 10:41:44 -07002372 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
Jorim Jaggic4025202015-10-22 16:43:34 +02002373 mWindowManager.deferSurfaceLayout();
2374 try {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002375 stack.resize(bounds, tempTaskBounds, tempTaskInsetBounds);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002376 if (!deferResume) {
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002377 stack.ensureVisibleActivitiesConfigurationLocked(
2378 stack.topRunningActivityLocked(), preserveWindows);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002379 }
Jorim Jaggic4025202015-10-22 16:43:34 +02002380 } finally {
2381 mWindowManager.continueSurfaceLayout();
2382 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07002383 }
2384 }
2385
Jorim Jaggi192086e2016-03-11 17:17:03 +01002386 void deferUpdateBounds(int stackId) {
2387 final ActivityStack stack = getStack(stackId);
2388 if (stack != null) {
2389 stack.deferUpdateBounds();
2390 }
2391 }
2392
2393 void continueUpdateBounds(int stackId) {
2394 final ActivityStack stack = getStack(stackId);
2395 if (stack != null) {
2396 stack.continueUpdateBounds();
2397 }
2398 }
2399
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002400 void notifyAppTransitionDone() {
Matthew Ng606dd802017-06-05 14:06:32 -07002401 continueUpdateBounds(RECENTS_STACK_ID);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002402 for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2403 final int taskId = mResizingTasksDuringAnimation.valueAt(i);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002404 final TaskRecord task =
Winson Chung7900bee2017-03-10 08:59:25 -08002405 anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002406 if (task != null) {
2407 task.setTaskDockedResizing(false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002408 }
2409 }
2410 mResizingTasksDuringAnimation.clear();
2411 }
2412
Robert Carre7cc44d2017-03-20 19:04:30 -07002413 private void moveTasksToFullscreenStackInSurfaceTransaction(int fromStackId,
2414 boolean onTop) {
Robert Carr6914f082017-03-20 19:04:30 -07002415
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002416 final ActivityStack stack = getStack(fromStackId);
2417 if (stack == null) {
2418 return;
2419 }
2420
2421 mWindowManager.deferSurfaceLayout();
2422 try {
2423 if (fromStackId == DOCKED_STACK_ID) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002424 // We are moving all tasks from the docked stack to the fullscreen stack,
2425 // which is dismissing the docked stack, so resize all other stacks to
2426 // fullscreen here already so we don't end up with resize trashing.
2427 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2428 if (StackId.isResizeableByDockedStack(i)) {
2429 ActivityStack otherStack = getStack(i);
2430 if (otherStack != null) {
2431 resizeStackLocked(i, null, null, null, PRESERVE_WINDOWS,
2432 true /* allowResizeInDockedMode */, DEFER_RESUME);
2433 }
2434 }
2435 }
2436
2437 // Also disable docked stack resizing since we have manually adjusted the
2438 // size of other stacks above and we don't want to trigger a docked stack
2439 // resize when we remove task from it below and it is detached from the
2440 // display because it no longer contains any tasks.
2441 mAllowDockedStackResize = false;
Winson Chung47900652017-04-06 18:44:25 -07002442 } else if (fromStackId == PINNED_STACK_ID) {
2443 if (onTop) {
2444 // Log if we are expanding the PiP to fullscreen
2445 MetricsLogger.action(mService.mContext,
2446 ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN);
2447 }
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002448 }
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002449 ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
Winson Chungc85d9ce2017-01-03 11:59:52 -08002450 final boolean isFullscreenStackVisible = fullscreenStack != null &&
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002451 fullscreenStack.shouldBeVisible(null) == STACK_VISIBLE;
Winson Chung5af42fc2017-03-24 17:11:33 -07002452 // If we are moving from the pinned stack, then the animation takes care of updating
2453 // the picture-in-picture mode.
Winson Chung47900652017-04-06 18:44:25 -07002454 final boolean schedulePictureInPictureModeChange = (fromStackId == PINNED_STACK_ID);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002455 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2456 final int size = tasks.size();
2457 if (onTop) {
2458 for (int i = 0; i < size; i++) {
Winson Chung0c1ca092016-11-10 17:40:34 -08002459 final TaskRecord task = tasks.get(i);
Winson Chung74666102017-02-22 17:49:24 -08002460 final boolean isTopTask = i == (size - 1);
Winson Chung0c1ca092016-11-10 17:40:34 -08002461 if (fromStackId == PINNED_STACK_ID) {
2462 // Update the return-to to reflect where the pinned stack task was moved
2463 // from so that we retain the stack that was previously visible if the
2464 // pinned stack is recreated. See moveActivityToPinnedStackLocked().
Winson Chungc85d9ce2017-01-03 11:59:52 -08002465 task.setTaskToReturnTo(isFullscreenStackVisible && onTop ?
2466 APPLICATION_ACTIVITY_TYPE : HOME_ACTIVITY_TYPE);
Winson Chung0c1ca092016-11-10 17:40:34 -08002467 }
Winson Chung74666102017-02-22 17:49:24 -08002468 // Defer resume until all the tasks have been moved to the fullscreen stack
2469 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
2470 REPARENT_MOVE_STACK_TO_FRONT, isTopTask /* animate */, DEFER_RESUME,
Winson Chung5af42fc2017-03-24 17:11:33 -07002471 schedulePictureInPictureModeChange,
Winson Chung74666102017-02-22 17:49:24 -08002472 "moveTasksToFullscreenStack - onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002473 }
2474 } else {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002475 for (int i = 0; i < size; i++) {
Wale Ogunwalec5cc3012017-01-13 13:26:16 -08002476 final TaskRecord task = tasks.get(i);
Winson Chung3a649982017-04-19 10:16:17 -07002477 // Position the tasks in the fullscreen stack in order at the bottom of the
2478 // stack. Also defer resume until all the tasks have been moved to the
2479 // fullscreen stack.
2480 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, i /* position */,
Winson Chung5af42fc2017-03-24 17:11:33 -07002481 REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME,
2482 schedulePictureInPictureModeChange,
2483 "moveTasksToFullscreenStack - NOT_onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002484 }
2485 }
Winson Chung74666102017-02-22 17:49:24 -08002486
2487 ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2488 resumeFocusedStackTopActivityLocked();
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002489 } finally {
2490 mAllowDockedStackResize = true;
2491 mWindowManager.continueSurfaceLayout();
2492 }
2493 }
2494
Robert Carr6914f082017-03-20 19:04:30 -07002495 void moveTasksToFullscreenStackLocked(int fromStackId, boolean onTop) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002496 mWindowManager.inSurfaceTransaction(
2497 () -> moveTasksToFullscreenStackInSurfaceTransaction(fromStackId, onTop));
Robert Carr6914f082017-03-20 19:04:30 -07002498 }
2499
Jorim Jaggidc249c42015-12-15 14:57:31 -08002500 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002501 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2502 boolean preserveWindows) {
2503 resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
2504 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows,
2505 false /* deferResume */);
2506 }
2507
2508 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2509 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2510 boolean preserveWindows, boolean deferResume) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002511
2512 if (!mAllowDockedStackResize) {
2513 // Docked stack resize currently disabled.
2514 return;
2515 }
2516
Jorim Jaggidc249c42015-12-15 14:57:31 -08002517 final ActivityStack stack = getStack(DOCKED_STACK_ID);
2518 if (stack == null) {
2519 Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2520 return;
2521 }
2522
2523 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2524 mWindowManager.deferSurfaceLayout();
2525 try {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002526 // Don't allow re-entry while resizing. E.g. due to docked stack detaching.
2527 mAllowDockedStackResize = false;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002528 ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwale1666e312016-12-16 11:27:18 -08002529 stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002530
Andrii Kulian69fb5e42016-04-05 16:47:29 -07002531 // TODO: Checking for isAttached might not be needed as if the user passes in null
2532 // dockedBounds then they want the docked stack to be dismissed.
2533 if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2534 // The dock stack either was dismissed or went fullscreen, which is kinda the same.
Jorim Jaggidc249c42015-12-15 14:57:31 -08002535 // In this case we make all other static stacks fullscreen and move all
2536 // docked stack tasks to the fullscreen stack.
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002537 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, ON_TOP);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002538
2539 // stack shouldn't contain anymore activities, so nothing to resume.
2540 r = null;
2541 } else {
2542 // Docked stacks occupy a dedicated region on screen so the size of all other
2543 // static stacks need to be adjusted so they don't overlap with the docked stack.
2544 // We get the bounds to use from window manager which has been adjusted for any
2545 // screen controls and is also the same for all stacks.
Matthew Ngaa2b6202017-02-10 14:48:21 -08002546 final Rect otherTaskRect = new Rect();
Jorim Jaggidc249c42015-12-15 14:57:31 -08002547 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002548 final ActivityStack current = getStack(i);
2549 if (current != null && StackId.isResizeableByDockedStack(i)) {
Matthew Ngaa2b6202017-02-10 14:48:21 -08002550 current.getStackDockedModeBounds(
2551 tempOtherTaskBounds /* currentTempTaskBounds */,
2552 tempRect /* outStackBounds */,
2553 otherTaskRect /* outTempTaskBounds */, true /* ignoreVisibility */);
2554
Andrii Kuliane48b7d82017-04-28 14:51:05 -07002555 resizeStackLocked(i, !tempRect.isEmpty() ? tempRect : null,
Matthew Ngaa2b6202017-02-10 14:48:21 -08002556 !otherTaskRect.isEmpty() ? otherTaskRect : tempOtherTaskBounds,
2557 tempOtherTaskInsetBounds, preserveWindows,
2558 true /* allowResizeInDockedMode */, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002559 }
2560 }
2561 }
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002562 if (!deferResume) {
2563 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows);
2564 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002565 } finally {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002566 mAllowDockedStackResize = true;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002567 mWindowManager.continueSurfaceLayout();
2568 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2569 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002570 }
2571
Robert Carr0d00c2e2016-02-29 17:45:02 -08002572 void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Winson Chung19953ca2017-04-11 11:19:23 -07002573 final PinnedActivityStack stack = getStack(PINNED_STACK_ID);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002574 if (stack == null) {
2575 Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2576 return;
2577 }
Winson Chung19953ca2017-04-11 11:19:23 -07002578
2579 // It is possible for the bounds animation from the WM to call this but be delayed by
2580 // another AM call that is holding the AMS lock. In such a case, the pinnedBounds may be
2581 // incorrect if AMS.resizeStackWithBoundsFromWindowManager() is already called while waiting
2582 // for the AMS lock to be freed. So check and make sure these bounds are still good.
2583 final PinnedStackWindowController stackController = stack.getWindowContainerController();
Winson Chung8bca9e42017-04-16 15:59:43 -07002584 if (stackController.pinnedStackResizeDisallowed()) {
Winson Chung19953ca2017-04-11 11:19:23 -07002585 return;
2586 }
2587
Robert Carr0d00c2e2016-02-29 17:45:02 -08002588 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2589 mWindowManager.deferSurfaceLayout();
2590 try {
2591 ActivityRecord r = stack.topRunningActivityLocked();
Robert Carr7e4c90e2017-02-15 19:52:38 -08002592 Rect insetBounds = null;
2593 if (tempPinnedTaskBounds != null) {
2594 // We always use 0,0 as the position for the inset rect because
2595 // if we are getting insets at all in the pinned stack it must mean
2596 // we are headed for fullscreen.
2597 insetBounds = tempRect;
2598 insetBounds.top = 0;
2599 insetBounds.left = 0;
2600 insetBounds.right = tempPinnedTaskBounds.width();
2601 insetBounds.bottom = tempPinnedTaskBounds.height();
2602 }
2603 stack.resize(pinnedBounds, tempPinnedTaskBounds, insetBounds);
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002604 stack.ensureVisibleActivitiesConfigurationLocked(r, false);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002605 } finally {
2606 mWindowManager.continueSurfaceLayout();
2607 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2608 }
2609 }
2610
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002611 ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002612 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Craig Mautnere0a38842013-12-16 16:14:02 -08002613 if (activityDisplay == null) {
Todd Kennedy4900bf92015-01-16 16:05:14 -08002614 return null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002615 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002616 return createStack(stackId, activityDisplay, onTop);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002617
Craig Mautner4a1cb222013-12-04 16:14:06 -08002618 }
2619
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002620 ActivityStack createStack(int stackId, ActivityDisplay display, boolean onTop) {
2621 switch (stackId) {
2622 case PINNED_STACK_ID:
2623 return new PinnedActivityStack(display, stackId, this, mRecentTasks, onTop);
2624 default:
2625 return new ActivityStack(display, stackId, this, mRecentTasks, onTop);
2626 }
2627 }
Robert Carr6914f082017-03-20 19:04:30 -07002628
Robert Carre7cc44d2017-03-20 19:04:30 -07002629 void removeStackInSurfaceTransaction(int stackId) {
Winson Chung010927a2016-12-15 16:12:35 -08002630 final ActivityStack stack = getStack(stackId);
2631 if (stack == null) {
2632 return;
2633 }
2634
2635 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2636 if (stack.getStackId() == PINNED_STACK_ID) {
Winson Chung47900652017-04-06 18:44:25 -07002637 /**
2638 * Workaround: Force-stop all the activities in the pinned stack before we reparent them
2639 * to the fullscreen stack. This is to guarantee that when we are removing a stack,
2640 * that the client receives onStop() before it is reparented. We do this by detaching
2641 * the stack from the display so that it will be considered invisible when
2642 * ensureActivitiesVisibleLocked() is called, and all of its activitys will be marked
2643 * invisible as well and added to the stopping list. After which we process the
2644 * stopping list by handling the idle.
2645 */
2646 final PinnedActivityStack pinnedStack = (PinnedActivityStack) stack;
2647 pinnedStack.mForceHidden = true;
2648 pinnedStack.ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2649 pinnedStack.mForceHidden = false;
2650 activityIdleInternalLocked(null, false /* fromTimeout */,
2651 true /* processPausingActivites */, null /* configuration */);
2652
2653 // Move all the tasks to the bottom of the fullscreen stack
2654 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
Winson Chung010927a2016-12-15 16:12:35 -08002655 } else {
2656 for (int i = tasks.size() - 1; i >= 0; i--) {
2657 removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */,
2658 REMOVE_FROM_RECENTS);
2659 }
2660 }
2661 }
2662
2663 /**
Robert Carr6914f082017-03-20 19:04:30 -07002664 * Removes the stack associated with the given {@param stackId}. If the {@param stackId} is the
2665 * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
2666 * instead moved back onto the fullscreen stack.
2667 */
2668 void removeStackLocked(int stackId) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002669 mWindowManager.inSurfaceTransaction(
2670 () -> removeStackInSurfaceTransaction(stackId));
Robert Carr6914f082017-03-20 19:04:30 -07002671 }
2672
2673 /**
Winson Chung6954fc92017-03-24 16:22:12 -07002674 * See {@link #removeTaskByIdLocked(int, boolean, boolean, boolean)}
2675 */
2676 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents) {
2677 return removeTaskByIdLocked(taskId, killProcess, removeFromRecents, !PAUSE_IMMEDIATELY);
2678 }
2679
2680 /**
Winson Chung010927a2016-12-15 16:12:35 -08002681 * Removes the task with the specified task id.
2682 *
2683 * @param taskId Identifier of the task to be removed.
2684 * @param killProcess Kill any process associated with the task if possible.
2685 * @param removeFromRecents Whether to also remove the task from recents.
Winson Chung6954fc92017-03-24 16:22:12 -07002686 * @param pauseImmediately Pauses all task activities immediately without waiting for the
2687 * pause-complete callback from the activity.
Winson Chung010927a2016-12-15 16:12:35 -08002688 * @return Returns true if the given task was found and removed.
2689 */
Winson Chung6954fc92017-03-24 16:22:12 -07002690 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents,
2691 boolean pauseImmediately) {
Winson Chung7900bee2017-03-10 08:59:25 -08002692 final TaskRecord tr = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
2693 INVALID_STACK_ID);
Winson Chung010927a2016-12-15 16:12:35 -08002694 if (tr != null) {
Winson Chung6954fc92017-03-24 16:22:12 -07002695 tr.removeTaskActivitiesLocked(pauseImmediately);
Winson Chung010927a2016-12-15 16:12:35 -08002696 cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents);
2697 if (tr.isPersistable) {
2698 mService.notifyTaskPersisterLocked(null, true);
2699 }
2700 return true;
2701 }
2702 Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
2703 return false;
2704 }
2705
2706 void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) {
2707 if (removeFromRecents) {
2708 mRecentTasks.remove(tr);
2709 tr.removedFromRecents();
2710 }
2711 ComponentName component = tr.getBaseIntent().getComponent();
2712 if (component == null) {
2713 Slog.w(TAG, "No component for base intent of task: " + tr);
2714 return;
2715 }
2716
2717 // Find any running services associated with this app and stop if needed.
2718 mService.mServices.cleanUpRemovedTaskLocked(tr, component, new Intent(tr.getBaseIntent()));
2719
2720 if (!killProcess) {
2721 return;
2722 }
2723
2724 // Determine if the process(es) for this task should be killed.
2725 final String pkg = component.getPackageName();
2726 ArrayList<ProcessRecord> procsToKill = new ArrayList<>();
2727 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mService.mProcessNames.getMap();
2728 for (int i = 0; i < pmap.size(); i++) {
2729
2730 SparseArray<ProcessRecord> uids = pmap.valueAt(i);
2731 for (int j = 0; j < uids.size(); j++) {
2732 ProcessRecord proc = uids.valueAt(j);
2733 if (proc.userId != tr.userId) {
2734 // Don't kill process for a different user.
2735 continue;
2736 }
2737 if (proc == mService.mHomeProcess) {
2738 // Don't kill the home process along with tasks from the same package.
2739 continue;
2740 }
2741 if (!proc.pkgList.containsKey(pkg)) {
2742 // Don't kill process that is not associated with this task.
2743 continue;
2744 }
2745
2746 for (int k = 0; k < proc.activities.size(); k++) {
Bryce Leeaf691c02017-03-20 14:20:22 -07002747 TaskRecord otherTask = proc.activities.get(k).getTask();
Winson Chung010927a2016-12-15 16:12:35 -08002748 if (tr.taskId != otherTask.taskId && otherTask.inRecents) {
2749 // Don't kill process(es) that has an activity in a different task that is
2750 // also in recents.
2751 return;
2752 }
2753 }
2754
2755 if (proc.foregroundServices) {
2756 // Don't kill process(es) with foreground service.
2757 return;
2758 }
2759
2760 // Add process to kill list.
2761 procsToKill.add(proc);
2762 }
2763 }
2764
2765 // Kill the running processes.
2766 for (int i = 0; i < procsToKill.size(); i++) {
2767 ProcessRecord pr = procsToKill.get(i);
2768 if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
2769 && pr.curReceivers.isEmpty()) {
2770 pr.kill("remove task", true);
2771 } else {
2772 // We delay killing processes that are not in the background or running a receiver.
2773 pr.waitingToKill = "remove task";
2774 }
2775 }
2776 }
2777
Craig Mautner4a1cb222013-12-04 16:14:06 -08002778 int getNextStackId() {
Craig Mautner858d8a62013-04-23 17:08:34 -07002779 while (true) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002780 if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2781 && getStack(mNextFreeStackId) == null) {
Craig Mautner858d8a62013-04-23 17:08:34 -07002782 break;
2783 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002784 mNextFreeStackId++;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002785 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002786 return mNextFreeStackId;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002787 }
2788
Chong Zhang5dcb2752015-08-18 13:50:26 -07002789 /**
2790 * Restores a recent task to a stack
2791 * @param task The recent task to be restored.
2792 * @param stackId The stack to restore the task to (default launch stack will be used
Andrii Kulian16802aa2016-11-02 12:21:33 -07002793 * if stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}
2794 * or is not a static stack).
Chong Zhang5dcb2752015-08-18 13:50:26 -07002795 * @return true if the task has been restored successfully.
2796 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002797 boolean restoreRecentTaskLocked(TaskRecord task, int stackId) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002798 if (!StackId.isStaticStack(stackId)) {
2799 // If stack is not static (or stack id is invalid) - use the default one.
2800 // This means that tasks that were on external displays will be restored on the
2801 // primary display.
Wale Ogunwale8b06a582015-10-22 14:38:21 -07002802 stackId = task.getLaunchStackId();
Winson Chungd3395382016-12-13 11:49:09 -08002803 } else if (stackId == DOCKED_STACK_ID && !task.supportsSplitScreen()) {
Wale Ogunwale513346d2016-01-27 10:55:01 -08002804 // Preferred stack is the docked stack, but the task can't go in the docked stack.
2805 // Put it in the fullscreen stack.
2806 stackId = FULLSCREEN_WORKSPACE_STACK_ID;
Chong Zhang5dcb2752015-08-18 13:50:26 -07002807 }
Wale Ogunwale513346d2016-01-27 10:55:01 -08002808
Andrii Kulian02b7a832016-10-06 23:11:56 -07002809 final ActivityStack currentStack = task.getStack();
2810 if (currentStack != null) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002811 // Task has already been restored once. See if we need to do anything more
Andrii Kulian02b7a832016-10-06 23:11:56 -07002812 if (currentStack.mStackId == stackId) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002813 // Nothing else to do since it is already restored in the right stack.
2814 return true;
2815 }
2816 // Remove current stack association, so we can re-associate the task with the
2817 // right stack below.
Andrii Kulian02b7a832016-10-06 23:11:56 -07002818 currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING);
Wale Ogunwale706ed792015-08-02 10:29:44 -07002819 }
2820
Wale Ogunwale6c5eb1c2015-11-10 07:52:22 -08002821 final ActivityStack stack =
Wale Ogunwale040b4702015-08-06 18:10:50 -07002822 getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002823
2824 if (stack == null) {
2825 // What does this mean??? Not sure how we would get here...
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002826 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2827 "Unable to find/create stack to restore recent task=" + task);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002828 return false;
2829 }
2830
Wale Ogunwale72919d22016-12-08 18:58:50 -08002831 stack.addTask(task, false /* toTop */, "restoreRecentTask");
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002832 // TODO: move call for creation here and other place into Stack.addTask()
2833 task.createWindowContainer(false /* toTop */, true /* showForAllUsers */);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002834 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2835 "Added restored task=" + task + " to stack=" + stack);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002836 final ArrayList<ActivityRecord> activities = task.mActivities;
2837 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002838 activities.get(activityNdx).createWindowContainer();
Wale Ogunwale7de05352014-12-12 15:21:33 -08002839 }
2840 return true;
Craig Mautneref73ee12014-04-23 11:45:37 -07002841 }
2842
Wale Ogunwale040b4702015-08-06 18:10:50 -07002843 /**
Andrii Kulian839def92016-11-02 10:58:58 -07002844 * Move stack with all its existing content to specified display.
2845 * @param stackId Id of stack to move.
2846 * @param displayId Id of display to move stack to.
Andrii Kulian250d6532017-02-08 23:30:45 -08002847 * @param onTop Indicates whether container should be place on top or on bottom.
Andrii Kulian839def92016-11-02 10:58:58 -07002848 */
Andrii Kulian250d6532017-02-08 23:30:45 -08002849 void moveStackToDisplayLocked(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002850 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian839def92016-11-02 10:58:58 -07002851 if (activityDisplay == null) {
2852 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown displayId="
2853 + displayId);
2854 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002855 final ActivityStack stack = mStacks.get(stackId);
2856 if (stack == null) {
Andrii Kulian839def92016-11-02 10:58:58 -07002857 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
2858 + stackId);
2859 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002860
2861 final ActivityDisplay currentDisplay = stack.getDisplay();
2862 if (currentDisplay == null) {
2863 throw new IllegalStateException("moveStackToDisplayLocked: Stack with stack=" + stack
2864 + " is not attached to any display.");
2865 }
2866
2867 if (currentDisplay.mDisplayId == displayId) {
2868 throw new IllegalArgumentException("Trying to move stack=" + stack
2869 + " to its current displayId=" + displayId);
2870 }
2871
2872 stack.reparent(activityDisplay, onTop);
Andrii Kulian839def92016-11-02 10:58:58 -07002873 // TODO(multi-display): resize stacks properly if moved from split-screen.
2874 }
2875
2876 /**
Winson Chung74666102017-02-22 17:49:24 -08002877 * Returns the reparent target stack, creating the stack if necessary. This call also enforces
2878 * the various checks on tasks that are going to be reparented from one stack to another.
Wale Ogunwale040b4702015-08-06 18:10:50 -07002879 */
Winson Chung74666102017-02-22 17:49:24 -08002880 ActivityStack getReparentTargetStack(TaskRecord task, int stackId, boolean toTop) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07002881 final ActivityStack prevStack = task.getStack();
Chong Zhang02898352015-08-21 17:27:14 -07002882
Winson Chung74666102017-02-22 17:49:24 -08002883 // Check that we aren't reparenting to the same stack that the task is already in
2884 if (prevStack != null && prevStack.mStackId == stackId) {
2885 Slog.w(TAG, "Can not reparent to same stack, task=" + task
2886 + " already in stackId=" + stackId);
2887 return prevStack;
Wale Ogunwale513346d2016-01-27 10:55:01 -08002888 }
2889
Winson Chung74666102017-02-22 17:49:24 -08002890 // Ensure that we aren't trying to move into a multi-window stack without multi-window
2891 // support
2892 if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
2893 throw new IllegalArgumentException("Device doesn't support multi-window, can not"
2894 + " reparent task=" + task + " to stackId=" + stackId);
Winson Chungc2baac02017-01-11 13:34:47 -08002895 }
2896
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002897 // Ensure that we're not moving a task to a dynamic stack if device doesn't support
2898 // multi-display.
2899 // TODO(multi-display): Support non-dynamic stacks on secondary displays.
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002900 if (StackId.isDynamicStack(stackId) && !mService.mSupportsMultiDisplay) {
2901 throw new IllegalArgumentException("Device doesn't support multi-display, can not"
2902 + " reparent task=" + task + " to stackId=" + stackId);
2903 }
2904
Winson Chung74666102017-02-22 17:49:24 -08002905 // Ensure that we aren't trying to move into a freeform stack without freeform
2906 // support
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002907 if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
Winson Chung74666102017-02-22 17:49:24 -08002908 throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
2909 + " task=" + task);
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002910 }
2911
Winson Chung74666102017-02-22 17:49:24 -08002912 // We don't allow moving a unresizeable task to the docked stack since the docked stack is
2913 // used for split-screen mode and will cause things like the docked divider to show up. We
2914 // instead leave the task in its current stack or move it to the fullscreen stack if it
2915 // isn't currently in a stack.
2916 if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
2917 stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
2918 Slog.w(TAG, "Can not move unresizeable task=" + task + " to docked stack."
2919 + " Moving to stackId=" + stackId + " instead.");
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07002920 }
Wale Ogunwale961f4852016-02-01 20:25:54 -08002921
Winson Chung74666102017-02-22 17:49:24 -08002922 // Temporarily disable resizeablility of the task as we don't want it to be resized if, for
2923 // example, a docked stack is created which will lead to the stack we are moving from being
2924 // resized and and its resizeable tasks being resized.
Wale Ogunwale961f4852016-02-01 20:25:54 -08002925 try {
Winson Chung74666102017-02-22 17:49:24 -08002926 task.mTemporarilyUnresizable = true;
2927 return getStack(stackId, CREATE_IF_NEEDED, toTop);
Wale Ogunwale961f4852016-02-01 20:25:54 -08002928 } finally {
Winson Chung74666102017-02-22 17:49:24 -08002929 task.mTemporarilyUnresizable = false;
Chong Zhangf596cd52016-01-05 13:42:44 -08002930 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002931 }
2932
Winson Chung08f81892017-03-02 15:40:51 -08002933 boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect destBounds) {
Wale Ogunwale079a0042015-10-24 11:44:07 -07002934 final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2935 if (stack == null) {
2936 throw new IllegalArgumentException(
2937 "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
2938 }
2939
2940 final ActivityRecord r = stack.topRunningActivityLocked();
2941 if (r == null) {
2942 Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
2943 + " in stack=" + stack);
2944 return false;
2945 }
2946
Wale Ogunwale6cae7652015-12-26 07:36:26 -08002947 if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
Wale Ogunwaleb60692e2015-10-24 12:35:56 -07002948 Slog.w(TAG,
2949 "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
Filip Gruszczynski77d94482015-12-11 13:59:52 -08002950 + " r=" + r);
Wale Ogunwale079a0042015-10-24 11:44:07 -07002951 return false;
2952 }
2953
Winson Chung3a682872017-04-10 14:38:05 -07002954 moveActivityToPinnedStackLocked(r, null /* sourceBounds */, 0f /* aspectRatio */,
Winson Chung08f81892017-03-02 15:40:51 -08002955 true /* moveHomeStackToFront */, "moveTopActivityToPinnedStack");
Wale Ogunwale9c604c72015-12-06 18:42:57 -08002956 return true;
2957 }
2958
Winson Chung8bca9e42017-04-16 15:59:43 -07002959 void moveActivityToPinnedStackLocked(ActivityRecord r, Rect sourceHintBounds, float aspectRatio,
Winson Chung08f81892017-03-02 15:40:51 -08002960 boolean moveHomeStackToFront, String reason) {
2961
Wale Ogunwale480dca02016-02-06 13:58:29 -08002962 mWindowManager.deferSurfaceLayout();
Winson Chung74666102017-02-22 17:49:24 -08002963
Bryce Lee04ab3462017-04-10 15:06:33 -07002964 // This will clear the pinned stack by moving an existing task to the full screen stack,
2965 // ensuring only one task is present.
2966 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
2967
Wale Ogunwale1666e312016-12-16 11:27:18 -08002968 // Need to make sure the pinned stack exist so we can resize it below...
Winson Chung55893332017-02-17 17:13:10 -08002969 final PinnedActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Wale Ogunwale1666e312016-12-16 11:27:18 -08002970
Wale Ogunwale480dca02016-02-06 13:58:29 -08002971 try {
Bryce Leeaf691c02017-03-20 14:20:22 -07002972 final TaskRecord task = r.getTask();
Wale Ogunwale480dca02016-02-06 13:58:29 -08002973 // Resize the pinned stack to match the current size of the task the activity we are
2974 // going to be moving is currently contained in. We do this to have the right starting
2975 // animation bounds for the pinned stack to the desired bounds the caller wants.
2976 resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
2977 null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002978 true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002979
2980 if (task.mActivities.size() == 1) {
2981 // There is only one activity in the task. So, we can just move the task over to
Winson Chungc2baac02017-01-11 13:34:47 -08002982 // the stack without re-parenting the activity in a different task. We don't
2983 // move the home stack forward if we are currently entering picture-in-picture
2984 // while pausing because that changes the focused stack and may prevent the new
2985 // starting activity from resuming.
2986 if (moveHomeStackToFront && task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE
Winson Chung105ae5f2017-03-06 15:06:28 -08002987 && (r.state == RESUMED || !r.supportsPictureInPictureWhilePausing)) {
Wale Ogunwaleda4ba962016-03-11 09:33:17 -08002988 // Move the home stack forward if the task we just moved to the pinned stack
2989 // was launched from home so home should be visible behind it.
2990 moveHomeStackToFront(reason);
2991 }
Winson Chung5af42fc2017-03-24 17:11:33 -07002992 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08002993 task.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07002994 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002995 } else {
Winson Chungb5c41b72016-12-07 15:00:47 -08002996 // There are multiple activities in the task and moving the top activity should
Winson Chung74666102017-02-22 17:49:24 -08002997 // reveal/leave the other activities in their original task.
2998
2999 // Currently, we don't support reparenting activities across tasks in two different
3000 // stacks, so instead, just create a new task in the same stack, reparent the
3001 // activity into that task, and then reparent the whole task to the new stack. This
3002 // ensures that all the necessary work to migrate states in the old and new stacks
3003 // is also done.
3004 final TaskRecord newTask = task.getStack().createTaskRecord(
3005 getNextTaskIdForUserLocked(r.userId), r.info, r.intent, null, null, true,
3006 r.mActivityType);
3007 r.reparent(newTask, MAX_VALUE, "moveActivityToStack");
3008
Winson Chung5af42fc2017-03-24 17:11:33 -07003009 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08003010 newTask.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07003011 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08003012 }
Winson Chungc2baac02017-01-11 13:34:47 -08003013
3014 // Reset the state that indicates it can enter PiP while pausing after we've moved it
3015 // to the pinned stack
3016 r.supportsPictureInPictureWhilePausing = false;
Wale Ogunwale480dca02016-02-06 13:58:29 -08003017 } finally {
3018 mWindowManager.continueSurfaceLayout();
Wale Ogunwale079a0042015-10-24 11:44:07 -07003019 }
3020
Winson Chunge7ba6862017-05-24 12:13:33 -07003021 // Calculate the default bounds (don't use existing stack bounds as we may have just created
3022 // the stack, and schedule the start of the animation into PiP (the bounds animator that
3023 // is triggered by this is posted on another thread)
Winson Chunga71febe2017-05-22 11:14:22 -07003024 final Rect destBounds = stack.getDefaultPictureInPictureBounds(aspectRatio);
3025
Winson Chunge7ba6862017-05-24 12:13:33 -07003026 stack.animateResizePinnedStack(sourceHintBounds, destBounds, -1 /* animationDuration */,
3027 true /* fromFullscreen */);
3028
3029 // Update the visibility of all activities after the they have been reparented to the new
3030 // stack. This MUST run after the animation above is scheduled to ensure that the windows
3031 // drawn signal is scheduled after the bounds animation start call on the bounds animator
3032 // thread.
Wale Ogunwale079a0042015-10-24 11:44:07 -07003033 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwaled046a012015-12-24 13:05:59 -08003034 resumeFocusedStackTopActivityLocked();
Wale Ogunwale03ce8632015-12-29 16:15:22 -08003035
Winson Chungb5026902017-05-03 12:45:13 -07003036 mService.mTaskChangeNotificationController.notifyActivityPinned(r.packageName,
3037 r.getTask().taskId);
Wale Ogunwale079a0042015-10-24 11:44:07 -07003038 }
3039
Andrii Kulian0864bbb2017-02-16 15:45:58 -08003040 /** Move activity with its stack to front and make the stack focused. */
Chong Zhang6cda19c2016-06-14 19:07:56 -07003041 boolean moveFocusableActivityStackToFrontLocked(ActivityRecord r, String reason) {
3042 if (r == null || !r.isFocusable()) {
3043 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3044 "moveActivityStackToFront: unfocusable r=" + r);
3045 return false;
3046 }
3047
Bryce Leeaf691c02017-03-20 14:20:22 -07003048 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003049 final ActivityStack stack = r.getStack();
3050 if (stack == null) {
Chong Zhang6cda19c2016-06-14 19:07:56 -07003051 Slog.w(TAG, "moveActivityStackToFront: invalid task or stack: r="
3052 + r + " task=" + task);
3053 return false;
3054 }
3055
Chong Zhang6cda19c2016-06-14 19:07:56 -07003056 if (stack == mFocusedStack && stack.topRunningActivityLocked() == r) {
3057 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3058 "moveActivityStackToFront: already on top, r=" + r);
3059 return false;
3060 }
3061
3062 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3063 "moveActivityStackToFront: r=" + r);
3064
3065 stack.moveToFront(reason, task);
3066 return true;
3067 }
3068
David Stevensc6b91c62017-02-08 14:23:58 -08003069 ActivityRecord findTaskLocked(ActivityRecord r, int displayId) {
Wale Ogunwale39381972015-12-17 17:15:29 -08003070 mTmpFindTaskResult.r = null;
3071 mTmpFindTaskResult.matchedByRootAffinity = false;
David Stevensc6b91c62017-02-08 14:23:58 -08003072 ActivityRecord affinityMatch = null;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003073 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
Craig Mautnere0a38842013-12-16 16:14:02 -08003074 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3075 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003076 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3077 final ActivityStack stack = stacks.get(stackNdx);
Winson Chung91e5c882017-04-21 14:44:38 -07003078 if (!checkActivityBelongsInStack(r, stack)) {
3079 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) "
3080 + stack);
Craig Mautner1b4bf852014-05-26 15:06:32 -07003081 continue;
3082 }
Wale Ogunwale39381972015-12-17 17:15:29 -08003083 stack.findTaskLocked(r, mTmpFindTaskResult);
David Stevensc6b91c62017-02-08 14:23:58 -08003084 // It is possible to have tasks in multiple stacks with the same root affinity, so
3085 // we should keep looking after finding an affinity match to see if there is a
3086 // better match in another stack. Also, task affinity isn't a good enough reason
3087 // to target a display which isn't the source of the intent, so skip any affinity
3088 // matches not on the specified display.
3089 if (mTmpFindTaskResult.r != null) {
3090 if (!mTmpFindTaskResult.matchedByRootAffinity) {
3091 return mTmpFindTaskResult.r;
3092 } else if (mTmpFindTaskResult.r.getDisplayId() == displayId) {
Winson Chung5b895b72017-05-01 13:46:25 -07003093 // Note: since the traversing through the stacks is top down, the floating
3094 // tasks should always have lower priority than any affinity-matching tasks
3095 // in the fullscreen stacks
David Stevensc6b91c62017-02-08 14:23:58 -08003096 affinityMatch = mTmpFindTaskResult.r;
3097 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003098 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003099 }
3100 }
Winson Chung5b895b72017-05-01 13:46:25 -07003101
David Stevensc6b91c62017-02-08 14:23:58 -08003102 if (DEBUG_TASKS && affinityMatch == null) Slog.d(TAG_TASKS, "No task found");
3103 return affinityMatch;
Craig Mautner8849a5e2013-04-02 16:41:03 -07003104 }
3105
Winson Chung91e5c882017-04-21 14:44:38 -07003106 /**
3107 * Checks that for the given activity {@param r}, its activity type matches the {@param stack}
3108 * type.
3109 */
3110 private boolean checkActivityBelongsInStack(ActivityRecord r, ActivityStack stack) {
3111 if (r.isHomeActivity()) {
3112 return stack.isHomeStack();
3113 } else if (r.isRecentsActivity()) {
3114 return stack.isRecentsStack();
3115 } else if (r.isAssistantActivity()) {
3116 return stack.isAssistantStack();
3117 }
3118 return true;
3119 }
3120
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003121 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
3122 boolean compareIntentFilters) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003123 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3124 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003125 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003126 final ActivityRecord ar = stacks.get(stackNdx)
3127 .findActivityLocked(intent, info, compareIntentFilters);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003128 if (ar != null) {
3129 return ar;
3130 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003131 }
3132 }
3133 return null;
3134 }
3135
David Stevens9440dc82017-03-16 19:00:20 -07003136 boolean hasAwakeDisplay() {
3137 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3138 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3139 if (!display.shouldSleep()) {
3140 return true;
3141 }
3142 }
3143 return false;
3144 }
3145
Craig Mautner8d341ef2013-03-26 09:03:27 -07003146 void goingToSleepLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003147 scheduleSleepTimeout();
3148 if (!mGoingToSleep.isHeld()) {
3149 mGoingToSleep.acquire();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003150 if (mLaunchingActivity.isHeld()) {
3151 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
3152 throw new IllegalStateException("Calling must be system uid");
Craig Mautner0eea92c2013-05-16 13:35:39 -07003153 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003154 mLaunchingActivity.release();
3155 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003156 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003157 }
David Stevens9440dc82017-03-16 19:00:20 -07003158
3159 applySleepTokensLocked(false /* applyToStacks */);
3160
3161 checkReadyForSleepLocked(true /* allowDelay */);
3162 }
3163
3164 void prepareForShutdownLocked() {
3165 for (int i = 0; i < mActivityDisplays.size(); i++) {
3166 createSleepTokenLocked("shutdown", mActivityDisplays.keyAt(i));
3167 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003168 }
3169
3170 boolean shutdownLocked(int timeout) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003171 goingToSleepLocked();
Craig Mautner0eea92c2013-05-16 13:35:39 -07003172
Craig Mautnerf4c909b2014-04-17 18:39:38 -07003173 boolean timedout = false;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003174 final long endTime = System.currentTimeMillis() + timeout;
3175 while (true) {
David Stevens18abd0e2017-08-17 14:55:47 -07003176 if (!putStacksToSleepLocked(true /* allowDelay */, true /* shuttingDown */)) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003177 long timeRemaining = endTime - System.currentTimeMillis();
3178 if (timeRemaining > 0) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003179 try {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003180 mService.wait(timeRemaining);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003181 } catch (InterruptedException e) {
3182 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003183 } else {
3184 Slog.w(TAG, "Activity manager shutdown timed out");
3185 timedout = true;
3186 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003187 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003188 } else {
3189 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003190 }
3191 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003192
3193 // Force checkReadyForSleep to complete.
David Stevens9440dc82017-03-16 19:00:20 -07003194 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003195
Craig Mautner8d341ef2013-03-26 09:03:27 -07003196 return timedout;
3197 }
3198
3199 void comeOutOfSleepIfNeededLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003200 removeSleepTimeouts();
3201 if (mGoingToSleep.isHeld()) {
3202 mGoingToSleep.release();
3203 }
David Stevens9440dc82017-03-16 19:00:20 -07003204 }
3205
3206 void applySleepTokensLocked(boolean applyToStacks) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003207 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
David Stevens9440dc82017-03-16 19:00:20 -07003208 // Set the sleeping state of the display.
3209 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3210 final boolean displayShouldSleep = display.shouldSleep();
3211 if (displayShouldSleep == display.isSleeping()) {
3212 continue;
3213 }
3214 display.setIsSleeping(displayShouldSleep);
3215
3216 if (!applyToStacks) {
3217 continue;
3218 }
3219
3220 // Set the sleeping state of the stacks on the display.
3221 final ArrayList<ActivityStack> stacks = display.mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003222 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3223 final ActivityStack stack = stacks.get(stackNdx);
David Stevens9440dc82017-03-16 19:00:20 -07003224 if (displayShouldSleep) {
3225 stack.goToSleepIfPossible(false /* shuttingDown */);
3226 } else {
3227 stack.awakeFromSleepingLocked();
3228 if (isFocusedStack(stack)) {
3229 resumeFocusedStackTopActivityLocked();
3230 }
3231 }
3232 }
3233
3234 if (displayShouldSleep || mGoingToSleepActivities.isEmpty()) {
3235 continue;
3236 }
3237 // The display is awake now, so clean up the going to sleep list.
3238 for (Iterator<ActivityRecord> it = mGoingToSleepActivities.iterator(); it.hasNext(); ) {
3239 final ActivityRecord r = it.next();
3240 if (r.getDisplayId() == display.mDisplayId) {
3241 it.remove();
Craig Mautner4a1cb222013-12-04 16:14:06 -08003242 }
Craig Mautner5314a402013-09-26 12:40:16 -07003243 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003244 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003245 }
3246
3247 void activitySleptLocked(ActivityRecord r) {
3248 mGoingToSleepActivities.remove(r);
David Stevens9440dc82017-03-16 19:00:20 -07003249 final ActivityStack s = r.getStack();
3250 if (s != null) {
3251 s.checkReadyForSleep();
3252 } else {
3253 checkReadyForSleepLocked(true);
3254 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003255 }
3256
David Stevens9440dc82017-03-16 19:00:20 -07003257 void checkReadyForSleepLocked(boolean allowDelay) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07003258 if (!mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003259 // Do not care.
3260 return;
3261 }
3262
David Stevens18abd0e2017-08-17 14:55:47 -07003263 if (!putStacksToSleepLocked(allowDelay, false /* shuttingDown */)) {
3264 return;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003265 }
3266
Wei Wang65c7a152016-06-02 18:51:22 -07003267 // Send launch end powerhint before going sleep
3268 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
3269
Craig Mautner0eea92c2013-05-16 13:35:39 -07003270 removeSleepTimeouts();
3271
3272 if (mGoingToSleep.isHeld()) {
3273 mGoingToSleep.release();
3274 }
3275 if (mService.mShuttingDown) {
3276 mService.notifyAll();
3277 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003278 }
3279
David Stevens18abd0e2017-08-17 14:55:47 -07003280 // Tries to put all activity stacks to sleep. Returns true if all stacks were
3281 // successfully put to sleep.
3282 private boolean putStacksToSleepLocked(boolean allowDelay, boolean shuttingDown) {
3283 boolean allSleep = true;
3284 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3285 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3286 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3287 if (allowDelay) {
3288 allSleep &= stacks.get(stackNdx).goToSleepIfPossible(shuttingDown);
3289 } else {
3290 stacks.get(stackNdx).goToSleep();
3291 }
3292 }
3293 }
3294 return allSleep;
3295 }
3296
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003297 boolean reportResumedActivityLocked(ActivityRecord r) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07003298 final ActivityStack stack = r.getStack();
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003299 if (isFocusedStack(stack)) {
Jeff Sharkey5782da72013-04-25 14:32:30 -07003300 mService.updateUsageStats(r, true);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003301 }
3302 if (allResumedActivitiesComplete()) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003303 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003304 mWindowManager.executeAppTransition();
3305 return true;
3306 }
3307 return false;
3308 }
3309
Craig Mautner8d341ef2013-03-26 09:03:27 -07003310 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003311 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3312 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Wale Ogunwale28b23972015-07-29 16:01:50 -07003313 int stackNdx = stacks.size() - 1;
3314 while (stackNdx >= 0) {
3315 stacks.get(stackNdx).handleAppCrashLocked(app);
3316 stackNdx--;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003317 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003318 }
3319 }
3320
Craig Mautnerbb742462014-07-07 15:28:55 -07003321 // Called when WindowManager has finished animating the launchingBehind activity to the back.
Andrii Kulian21713ac2016-10-12 22:05:05 -07003322 private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003323 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003324 final ActivityStack stack = task.getStack();
Winson730bf062016-03-31 18:04:56 -07003325
3326 r.mLaunchTaskBehind = false;
Andrii Kulian21713ac2016-10-12 22:05:05 -07003327 task.setLastThumbnailLocked(r.screenshotActivityLocked());
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08003328 mRecentTasks.addLocked(task);
Yorke Leebd54c2a2016-10-25 13:49:23 -07003329 mService.mTaskChangeNotificationController.notifyTaskStackChanged();
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003330 r.setVisibility(false);
Winson730bf062016-03-31 18:04:56 -07003331
3332 // When launching tasks behind, update the last active time of the top task after the new
3333 // task has been shown briefly
3334 final ActivityRecord top = stack.topActivity();
3335 if (top != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003336 top.getTask().touchActiveTime();
Winson730bf062016-03-31 18:04:56 -07003337 }
Craig Mautnerbb742462014-07-07 15:28:55 -07003338 }
3339
3340 void scheduleLaunchTaskBehindComplete(IBinder token) {
3341 mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
3342 }
3343
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003344 void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
3345 boolean preserveWindows) {
Jorim Jaggife762342016-10-13 14:33:27 +02003346 mKeyguardController.beginActivityVisibilityUpdate();
3347 try {
3348 // First the front stacks. In case any are not fullscreen and are in front of home.
3349 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3350 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3351 final int topStackNdx = stacks.size() - 1;
3352 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3353 final ActivityStack stack = stacks.get(stackNdx);
3354 stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
3355 }
Craig Mautner580ea812013-04-25 12:58:38 -07003356 }
Jorim Jaggife762342016-10-13 14:33:27 +02003357 } finally {
3358 mKeyguardController.endActivityVisibilityUpdate();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003359 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003360 }
3361
Jorim Jaggi8b702ed2017-01-20 16:59:03 +01003362 void addStartingWindowsForVisibleActivities(boolean taskSwitch) {
3363 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3364 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3365 final int topStackNdx = stacks.size() - 1;
3366 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3367 final ActivityStack stack = stacks.get(stackNdx);
3368 stack.addStartingWindowsForVisibleActivities(taskSwitch);
3369 }
3370 }
3371 }
3372
Chong Zhangfdcc4d42015-10-14 16:50:12 -07003373 void invalidateTaskLayers() {
3374 mTaskLayersChanged = true;
3375 }
3376
3377 void rankTaskLayersIfNeeded() {
3378 if (!mTaskLayersChanged) {
3379 return;
3380 }
3381 mTaskLayersChanged = false;
3382 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
3383 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3384 int baseLayer = 0;
3385 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3386 baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
3387 }
3388 }
3389 }
3390
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07003391 void clearOtherAppTimeTrackers(AppTimeTracker except) {
3392 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3393 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3394 final int topStackNdx = stacks.size() - 1;
3395 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3396 final ActivityStack stack = stacks.get(stackNdx);
3397 stack.clearOtherAppTimeTrackers(except);
3398 }
3399 }
3400 }
3401
Craig Mautner8d341ef2013-03-26 09:03:27 -07003402 void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003403 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3404 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003405 final int numStacks = stacks.size();
3406 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
3407 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003408 stack.scheduleDestroyActivities(app, reason);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003409 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003410 }
3411 }
3412
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003413 void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
3414 // Examine all activities currently running in the process.
3415 TaskRecord firstTask = null;
3416 // Tasks is non-null only if two or more tasks are found.
3417 ArraySet<TaskRecord> tasks = null;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003418 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
3419 for (int i = 0; i < app.activities.size(); i++) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003420 ActivityRecord r = app.activities.get(i);
3421 // First, if we find an activity that is in the process of being destroyed,
3422 // then we just aren't going to do anything for now; we want things to settle
3423 // down before we try to prune more activities.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003424 if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003425 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003426 return;
3427 }
3428 // Don't consider any activies that are currently not in a state where they
3429 // can be destroyed.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003430 if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
3431 || r.state == PAUSED || r.state == STOPPING) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003432 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003433 continue;
3434 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003435
3436 final TaskRecord task = r.getTask();
3437 if (task != null) {
3438 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + task
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003439 + " from " + r);
3440 if (firstTask == null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003441 firstTask = task;
3442 } else if (firstTask != task) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003443 if (tasks == null) {
3444 tasks = new ArraySet<>();
3445 tasks.add(firstTask);
3446 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003447 tasks.add(task);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003448 }
3449 }
3450 }
3451 if (tasks == null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003452 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003453 return;
3454 }
3455 // If we have activities in multiple tasks that are in a position to be destroyed,
3456 // let's iterate through the tasks and release the oldest one.
3457 final int numDisplays = mActivityDisplays.size();
3458 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3459 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3460 // Step through all stacks starting from behind, to hit the oldest things first.
3461 for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
3462 final ActivityStack stack = stacks.get(stackNdx);
3463 // Try to release activities in this stack; if we manage to, we are done.
3464 if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
3465 return;
3466 }
3467 }
3468 }
3469 }
3470
Amith Yamasani37a40c22015-06-17 13:25:42 -07003471 boolean switchUserLocked(int userId, UserState uss) {
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003472 final int focusStackId = mFocusedStack.getStackId();
3473 // We dismiss the docked stack whenever we switch users.
3474 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, focusStackId == DOCKED_STACK_ID);
Winson Chungc2b23a52017-01-09 15:44:55 -08003475 // Also dismiss the pinned stack whenever we switch users. Removing the pinned stack will
3476 // also cause all tasks to be moved to the fullscreen stack at a position that is
3477 // appropriate.
3478 removeStackLocked(PINNED_STACK_ID);
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003479
3480 mUserStackInFront.put(mCurrentUser, focusStackId);
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003481 final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
Craig Mautner2420ead2013-04-01 17:13:20 -07003482 mCurrentUser = userId;
Craig Mautnerac6f8432013-07-17 13:24:59 -07003483
Craig Mautner858d8a62013-04-23 17:08:34 -07003484 mStartingUsers.add(uss);
Craig Mautnere0a38842013-12-16 16:14:02 -08003485 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3486 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003487 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003488 final ActivityStack stack = stacks.get(stackNdx);
3489 stack.switchUserLocked(userId);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003490 TaskRecord task = stack.topTask();
3491 if (task != null) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08003492 stack.positionChildWindowContainerAtTop(task);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003493 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003494 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07003495 }
Craig Mautner858d8a62013-04-23 17:08:34 -07003496
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003497 ActivityStack stack = getStack(restoreStackId);
3498 if (stack == null) {
3499 stack = mHomeStack;
3500 }
3501 final boolean homeInFront = stack.isHomeStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08003502 if (stack.isOnHomeDisplay()) {
Wale Ogunwale925d0d12015-09-23 15:40:07 -07003503 stack.moveToFront("switchUserOnHomeDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003504 } else {
3505 // Stack was moved to another display while user was swapped out.
Matthew Ngae1ff4f2016-11-10 15:49:14 -08003506 resumeHomeStackTask(null, "switchUserOnOtherDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003507 }
Craig Mautner93529a42013-10-04 15:03:13 -07003508 return homeInFront;
Craig Mautner2219a1b2013-03-25 09:44:30 -07003509 }
3510
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003511 /** Checks whether the userid is a profile of the current user. */
3512 boolean isCurrentProfileLocked(int userId) {
3513 if (userId == mCurrentUser) return true;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07003514 return mService.mUserController.isCurrentProfileLocked(userId);
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003515 }
3516
Bryce Leeb7c9b802017-05-02 14:20:24 -07003517 /**
3518 * Returns whether a stopping activity is present that should be stopped after visible, rather
3519 * than idle.
3520 * @return {@code true} if such activity is present. {@code false} otherwise.
3521 */
3522 boolean isStoppingNoHistoryActivity() {
3523 // Activities that are marked as nohistory should be stopped immediately after the resumed
3524 // activity has become visible.
3525 for (ActivityRecord record : mStoppingActivities) {
3526 if (record.isNoHistory()) {
3527 return true;
3528 }
3529 }
3530
3531 return false;
3532 }
3533
Winson Chung4dabf232017-01-25 13:25:22 -08003534 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
3535 boolean remove, boolean processPausingActivities) {
Craig Mautnerde4ef022013-04-07 19:01:33 -07003536 ArrayList<ActivityRecord> stops = null;
3537
3538 final boolean nowVisible = allResumedActivitiesVisible();
Craig Mautner8c14c152015-01-15 17:32:07 -08003539 for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3540 ActivityRecord s = mStoppingActivities.get(activityNdx);
Bryce Lee4a194382017-04-04 14:32:48 -07003541 boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003542 if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
Craig Mautner8c14c152015-01-15 17:32:07 -08003543 + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
3544 if (waitingVisible && nowVisible) {
Bryce Lee4a194382017-04-04 14:32:48 -07003545 mActivitiesWaitingForVisibleActivity.remove(s);
Andrii Kulianee056812016-09-21 15:34:45 -07003546 waitingVisible = false;
Craig Mautnerde4ef022013-04-07 19:01:33 -07003547 if (s.finishing) {
3548 // If this activity is finishing, it is sitting on top of
3549 // everyone else but we now know it is no longer needed...
3550 // so get rid of it. Otherwise, we need to go through the
3551 // normal flow and hide it once we determine that it is
3552 // hidden by the activities in front of it.
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003553 if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003554 s.setVisibility(false);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003555 }
3556 }
David Stevens9440dc82017-03-16 19:00:20 -07003557 if (remove) {
3558 final ActivityStack stack = s.getStack();
3559 final boolean shouldSleepOrShutDown = stack != null
3560 ? stack.shouldSleepOrShutDownActivities()
3561 : mService.isSleepingOrShuttingDownLocked();
3562 if (!waitingVisible || shouldSleepOrShutDown) {
3563 if (!processPausingActivities && s.state == PAUSING) {
3564 // Defer processing pausing activities in this iteration and reschedule
3565 // a delayed idle to reprocess it again
3566 removeTimeoutsForActivityLocked(idleActivity);
3567 scheduleIdleTimeoutLocked(idleActivity);
3568 continue;
3569 }
Winson Chung4dabf232017-01-25 13:25:22 -08003570
David Stevens9440dc82017-03-16 19:00:20 -07003571 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
3572 if (stops == null) {
3573 stops = new ArrayList<>();
3574 }
3575 stops.add(s);
3576 mStoppingActivities.remove(activityNdx);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003577 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07003578 }
3579 }
3580
3581 return stops;
3582 }
3583
Craig Mautnercf910b02013-04-23 11:23:27 -07003584 void validateTopActivitiesLocked() {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003585 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3586 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3587 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3588 final ActivityStack stack = stacks.get(stackNdx);
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07003589 final ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003590 final ActivityState state = r == null ? DESTROYED : r.state;
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003591 if (isFocusedStack(stack)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003592 if (r == null) Slog.e(TAG,
3593 "validateTop...: null top activity, stack=" + stack);
3594 else {
3595 final ActivityRecord pausing = stack.mPausingActivity;
3596 if (pausing != null && pausing == r) Slog.e(TAG,
3597 "validateTop...: top stack has pausing activity r=" + r
3598 + " state=" + state);
3599 if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3600 "validateTop...: activity in front not resumed r=" + r
3601 + " state=" + state);
3602 }
Craig Mautnercf910b02013-04-23 11:23:27 -07003603 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003604 final ActivityRecord resumed = stack.mResumedActivity;
3605 if (resumed != null && resumed == r) Slog.e(TAG,
3606 "validateTop...: back stack has resumed activity r=" + r
3607 + " state=" + state);
3608 if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3609 "validateTop...: activity in back resumed r=" + r + " state=" + state);
Craig Mautnercf910b02013-04-23 11:23:27 -07003610 }
3611 }
3612 }
Craig Mautner76ea2242013-05-15 11:40:05 -07003613 }
3614
Craig Mautnere0570202015-05-13 13:06:11 -07003615 private String lockTaskModeToString() {
3616 switch (mLockTaskModeState) {
3617 case LOCK_TASK_MODE_LOCKED:
3618 return "LOCKED";
3619 case LOCK_TASK_MODE_PINNED:
3620 return "PINNED";
3621 case LOCK_TASK_MODE_NONE:
3622 return "NONE";
3623 default: return "unknown=" + mLockTaskModeState;
3624 }
3625 }
3626
Craig Mautner27084302013-03-25 08:05:25 -07003627 public void dump(PrintWriter pw, String prefix) {
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003628 pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003629 pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
Suprabh Shukla09a88f52015-12-02 14:36:31 -08003630 pw.print(prefix);
3631 pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003632 pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003633 pw.print(prefix); pw.println("mStacks=" + mStacks);
Craig Mautnere0570202015-05-13 13:06:11 -07003634 pw.print(prefix); pw.print("mLockTaskModeState=" + lockTaskModeToString());
Jorim Jaggi8d786932016-10-26 19:08:36 -07003635 final SparseArray<String[]> packages = mService.mLockTaskPackages;
3636 if (packages.size() > 0) {
3637 pw.print(prefix); pw.println("mLockTaskPackages (userId:packages)=");
3638 for (int i = 0; i < packages.size(); ++i) {
3639 pw.print(prefix); pw.print(prefix); pw.print(packages.keyAt(i));
3640 pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
3641 }
3642 }
Bryce Lee4a194382017-04-04 14:32:48 -07003643 if (!mWaitingForActivityVisible.isEmpty()) {
3644 pw.print(prefix); pw.println("mWaitingForActivityVisible=");
3645 for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
3646 pw.print(prefix); pw.print(prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
3647 }
3648 }
3649
Jorim Jaggi8d786932016-10-26 19:08:36 -07003650 pw.println(" mLockTaskModeTasks" + mLockTaskModeTasks);
3651 mKeyguardController.dump(pw, prefix);
Craig Mautner27084302013-03-25 08:05:25 -07003652 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003653
Winson43d1f262016-06-14 16:05:55 -07003654 /**
Andrii Kulian5406e7a2016-10-21 11:55:23 -07003655 * Dump all connected displays' configurations.
3656 * @param prefix Prefix to apply to each line of the dump.
3657 */
3658 void dumpDisplayConfigs(PrintWriter pw, String prefix) {
3659 pw.print(prefix); pw.println("Display override configurations:");
3660 final int displayCount = mActivityDisplays.size();
3661 for (int i = 0; i < displayCount; i++) {
3662 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(i);
3663 pw.print(prefix); pw.print(" "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
3664 pw.println(activityDisplay.getOverrideConfiguration());
3665 }
3666 }
3667
3668 /**
Winson43d1f262016-06-14 16:05:55 -07003669 * Dumps the activities matching the given {@param name} in the either the focused stack
3670 * or all visible stacks if {@param dumpVisibleStacks} is true.
3671 */
Winson Chung6998bc42017-02-28 17:07:05 -08003672 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name, boolean dumpVisibleStacksOnly,
3673 boolean dumpFocusedStackOnly) {
3674 if (dumpFocusedStackOnly) {
3675 return mFocusedStack.getDumpActivitiesLocked(name);
3676 } else {
Winson43d1f262016-06-14 16:05:55 -07003677 ArrayList<ActivityRecord> activities = new ArrayList<>();
3678 int numDisplays = mActivityDisplays.size();
3679 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3680 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3681 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3682 ActivityStack stack = stacks.get(stackNdx);
Winson Chung6998bc42017-02-28 17:07:05 -08003683 if (!dumpVisibleStacksOnly ||
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07003684 stack.shouldBeVisible(null) == STACK_VISIBLE) {
Winson43d1f262016-06-14 16:05:55 -07003685 activities.addAll(stack.getDumpActivitiesLocked(name));
3686 }
3687 }
3688 }
3689 return activities;
Winson43d1f262016-06-14 16:05:55 -07003690 }
Craig Mautner20e72272013-04-01 13:45:53 -07003691 }
3692
Dianne Hackborn390517b2013-05-30 15:03:32 -07003693 static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3694 boolean needSep, String prefix) {
3695 if (activity != null) {
3696 if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3697 if (needSep) {
3698 pw.println();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003699 }
3700 pw.print(prefix);
3701 pw.println(activity);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003702 return true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003703 }
3704 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003705 return false;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003706 }
3707
Craig Mautner8d341ef2013-03-26 09:03:27 -07003708 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3709 boolean dumpClient, String dumpPackage) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003710 boolean printed = false;
3711 boolean needSep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003712 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3713 ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003714 pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
Craig Mautner737fae22014-10-15 12:52:10 -07003715 pw.println(" (activities from top to bottom):");
Craig Mautnere0a38842013-12-16 16:14:02 -08003716 ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
Craig Mautner737fae22014-10-15 12:52:10 -07003717 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003718 final ActivityStack stack = stacks.get(stackNdx);
3719 StringBuilder stackHeader = new StringBuilder(128);
3720 stackHeader.append(" Stack #");
3721 stackHeader.append(stack.mStackId);
3722 stackHeader.append(":");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003723 stackHeader.append("\n");
3724 stackHeader.append(" mFullscreen=" + stack.mFullscreen);
3725 stackHeader.append("\n");
David Stevens9440dc82017-03-16 19:00:20 -07003726 stackHeader.append(" isSleeping=" + stack.shouldSleepActivities());
3727 stackHeader.append("\n");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003728 stackHeader.append(" mBounds=" + stack.mBounds);
Winson Chungabb433b2017-03-24 09:35:42 -07003729
3730 final boolean printedStackHeader = stack.dumpActivitiesLocked(fd, pw, dumpAll,
3731 dumpClient, dumpPackage, needSep, stackHeader.toString());
3732 printed |= printedStackHeader;
3733 if (!printedStackHeader) {
3734 // Ensure we always dump the stack header even if there are no activities
3735 pw.println();
3736 pw.println(stackHeader);
3737 }
3738
Craig Mautner4a1cb222013-12-04 16:14:06 -08003739 printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, " ", "Run", false,
3740 !dumpAll, false, dumpPackage, true,
3741 " Running activities (most recent first):", null);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003742
Craig Mautner4a1cb222013-12-04 16:14:06 -08003743 needSep = printed;
3744 boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3745 " mPausingActivity: ");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003746 if (pr) {
3747 printed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003748 needSep = false;
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003749 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003750 pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3751 " mResumedActivity: ");
3752 if (pr) {
3753 printed = true;
3754 needSep = false;
3755 }
3756 if (dumpAll) {
3757 pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3758 " mLastPausedActivity: ");
3759 if (pr) {
3760 printed = true;
3761 needSep = true;
3762 }
3763 printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3764 needSep, " mLastNoHistoryActivity: ");
3765 }
3766 needSep = printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003767 }
3768 }
3769
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003770 printed |= dumpHistoryList(fd, pw, mFinishingActivities, " ", "Fin", false, !dumpAll,
3771 false, dumpPackage, true, " Activities waiting to finish:", null);
3772 printed |= dumpHistoryList(fd, pw, mStoppingActivities, " ", "Stop", false, !dumpAll,
3773 false, dumpPackage, true, " Activities waiting to stop:", null);
Bryce Lee4a194382017-04-04 14:32:48 -07003774 printed |= dumpHistoryList(fd, pw, mActivitiesWaitingForVisibleActivity, " ", "Wait",
3775 false, !dumpAll, false, dumpPackage, true,
3776 " Activities waiting for another to become visible:", null);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003777 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3778 false, dumpPackage, true, " Activities waiting to sleep:", null);
Craig Mautnerf3333272013-04-22 10:55:53 -07003779
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003780 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003781 }
3782
Dianne Hackborn390517b2013-05-30 15:03:32 -07003783 static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
Craig Mautner8d341ef2013-03-26 09:03:27 -07003784 String prefix, String label, boolean complete, boolean brief, boolean client,
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003785 String dumpPackage, boolean needNL, String header1, String header2) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003786 TaskRecord lastTask = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003787 String innerPrefix = null;
3788 String[] args = null;
3789 boolean printed = false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003790 for (int i=list.size()-1; i>=0; i--) {
3791 final ActivityRecord r = list.get(i);
3792 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3793 continue;
3794 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003795 if (innerPrefix == null) {
3796 innerPrefix = prefix + " ";
3797 args = new String[0];
3798 }
3799 printed = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003800 final boolean full = !brief && (complete || !r.isInHistory());
3801 if (needNL) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003802 pw.println("");
Craig Mautner8d341ef2013-03-26 09:03:27 -07003803 needNL = false;
3804 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003805 if (header1 != null) {
3806 pw.println(header1);
3807 header1 = null;
3808 }
3809 if (header2 != null) {
3810 pw.println(header2);
3811 header2 = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003812 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003813 if (lastTask != r.getTask()) {
3814 lastTask = r.getTask();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003815 pw.print(prefix);
3816 pw.print(full ? "* " : " ");
3817 pw.println(lastTask);
3818 if (full) {
3819 lastTask.dump(pw, prefix + " ");
3820 } else if (complete) {
3821 // Complete + brief == give a summary. Isn't that obvious?!?
3822 if (lastTask.intent != null) {
3823 pw.print(prefix); pw.print(" ");
3824 pw.println(lastTask.intent.toInsecureStringWithClip());
3825 }
3826 }
3827 }
3828 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
3829 pw.print(" #"); pw.print(i); pw.print(": ");
3830 pw.println(r);
3831 if (full) {
3832 r.dump(pw, innerPrefix);
3833 } else if (complete) {
3834 // Complete + brief == give a summary. Isn't that obvious?!?
3835 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3836 if (r.app != null) {
3837 pw.print(innerPrefix); pw.println(r.app);
3838 }
3839 }
3840 if (client && r.app != null && r.app.thread != null) {
3841 // flush anything that is already in the PrintWriter since the thread is going
3842 // to write to the file descriptor directly
3843 pw.flush();
3844 try {
3845 TransferPipe tp = new TransferPipe();
3846 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003847 r.app.thread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003848 // Short timeout, since blocking here can
3849 // deadlock with the application.
3850 tp.go(fd, 2000);
3851 } finally {
3852 tp.kill();
3853 }
3854 } catch (IOException e) {
3855 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3856 } catch (RemoteException e) {
3857 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3858 }
3859 needNL = true;
3860 }
3861 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003862 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003863 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003864
Craig Mautnerf3333272013-04-22 10:55:53 -07003865 void scheduleIdleTimeoutLocked(ActivityRecord next) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003866 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3867 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
Craig Mautnerc64f73e2013-04-24 16:44:56 -07003868 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
3869 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
Craig Mautnerf3333272013-04-22 10:55:53 -07003870 }
3871
3872 final void scheduleIdleLocked() {
Craig Mautner05d29032013-05-03 13:40:13 -07003873 mHandler.sendEmptyMessage(IDLE_NOW_MSG);
Craig Mautnerf3333272013-04-22 10:55:53 -07003874 }
3875
3876 void removeTimeoutsForActivityLocked(ActivityRecord r) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003877 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
3878 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07003879 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3880 }
3881
Craig Mautner05d29032013-05-03 13:40:13 -07003882 final void scheduleResumeTopActivities() {
Craig Mautner34b73df2014-01-12 21:11:08 -08003883 if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
3884 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
3885 }
Craig Mautner05d29032013-05-03 13:40:13 -07003886 }
3887
Craig Mautner0eea92c2013-05-16 13:35:39 -07003888 void removeSleepTimeouts() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003889 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
3890 }
3891
3892 final void scheduleSleepTimeout() {
3893 removeSleepTimeouts();
3894 mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
3895 }
3896
Craig Mautner4a1cb222013-12-04 16:14:06 -08003897 @Override
3898 public void onDisplayAdded(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003899 if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003900 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
3901 }
3902
3903 @Override
3904 public void onDisplayRemoved(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003905 if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003906 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
3907 }
3908
3909 @Override
3910 public void onDisplayChanged(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003911 if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003912 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
3913 }
3914
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003915 private void handleDisplayAdded(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003916 synchronized (mService) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003917 getActivityDisplayOrCreateLocked(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003918 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003919 }
3920
Andrii Kulianca007a62016-11-22 16:33:28 -08003921 /** Check if display with specified id is added to the list. */
3922 boolean isDisplayAdded(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003923 return getActivityDisplayOrCreateLocked(displayId) != null;
3924 }
3925
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003926 ActivityDisplay getActivityDisplay(int displayId) {
3927 return mActivityDisplays.get(displayId);
3928 }
3929
Andrii Kulian62e6f252017-05-30 22:46:53 -07003930 /**
3931 * Get an existing instance of {@link ActivityDisplay} or create new if there is a
3932 * corresponding record in display manager.
3933 */
3934 private ActivityDisplay getActivityDisplayOrCreateLocked(int displayId) {
3935 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3936 if (activityDisplay != null) {
3937 return activityDisplay;
3938 }
3939 if (mDisplayManager == null) {
3940 // The system isn't fully initialized yet.
3941 return null;
3942 }
3943 final Display display = mDisplayManager.getDisplay(displayId);
3944 if (display == null) {
3945 // The display is not registered in DisplayManager.
3946 return null;
3947 }
3948 // The display hasn't been added to ActivityManager yet, create a new record now.
3949 activityDisplay = new ActivityDisplay(displayId);
3950 if (activityDisplay.mDisplay == null) {
3951 Slog.w(TAG, "Display " + displayId + " gone before initialization complete");
3952 return null;
3953 }
3954 mActivityDisplays.put(displayId, activityDisplay);
3955 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
3956 mWindowManager.onDisplayAdded(displayId);
3957 return activityDisplay;
Andrii Kulianca007a62016-11-22 16:33:28 -08003958 }
3959
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003960 private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
Andrii Kulianf66a83d2016-05-17 12:17:44 -07003961 mDefaultMinSizeOfResizeableTask =
Jorim Jaggi19cf2972016-04-07 23:26:10 -07003962 mService.mContext.getResources().getDimensionPixelSize(
3963 com.android.internal.R.dimen.default_minimal_size_resizable_task);
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003964 }
3965
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003966 private void handleDisplayRemoved(int displayId) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003967 if (displayId == DEFAULT_DISPLAY) {
3968 throw new IllegalArgumentException("Can't remove the primary display.");
3969 }
3970
Craig Mautner4a1cb222013-12-04 16:14:06 -08003971 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003972 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3973 if (activityDisplay != null) {
Andrii Kulian250d6532017-02-08 23:30:45 -08003974 final boolean destroyContentOnRemoval
3975 = activityDisplay.shouldDestroyContentOnRemove();
Andrii Kuliana33818c2017-02-16 16:11:30 -08003976 final ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3977 while (!stacks.isEmpty()) {
3978 final ActivityStack stack = stacks.get(0);
Andrii Kulian250d6532017-02-08 23:30:45 -08003979 if (destroyContentOnRemoval) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003980 moveStackToDisplayLocked(stack.mStackId, DEFAULT_DISPLAY,
3981 false /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003982 stack.finishAllActivitiesLocked(true /* immediately */);
Andrii Kuliana33818c2017-02-16 16:11:30 -08003983 } else {
3984 // Moving all tasks to fullscreen stack, because it's guaranteed to be
3985 // a valid launch stack for all activities. This way the task history from
3986 // external display will be preserved on primary after move.
3987 moveTasksToFullscreenStackLocked(stack.getStackId(), true /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003988 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003989 }
David Stevens9440dc82017-03-16 19:00:20 -07003990
3991 releaseSleepTokens(activityDisplay);
3992
Craig Mautnere0a38842013-12-16 16:14:02 -08003993 mActivityDisplays.remove(displayId);
Bryce Leeaf3a4002017-03-20 10:37:12 -07003994 mWindowManager.onDisplayRemoved(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003995 }
3996 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003997 }
3998
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003999 private void handleDisplayChanged(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004000 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08004001 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
4002 if (activityDisplay != null) {
David Stevens9440dc82017-03-16 19:00:20 -07004003 // The window policy is responsible for stopping activities on the default display
4004 if (displayId != Display.DEFAULT_DISPLAY) {
4005 int displayState = activityDisplay.mDisplay.getState();
4006 if (displayState == Display.STATE_OFF && activityDisplay.mOffToken == null) {
4007 activityDisplay.mOffToken =
4008 mService.acquireSleepToken("Display-off", displayId);
4009 } else if (displayState == Display.STATE_ON
4010 && activityDisplay.mOffToken != null) {
4011 activityDisplay.mOffToken.release();
4012 activityDisplay.mOffToken = null;
4013 }
4014 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004015 // TODO: Update the bounds.
4016 }
Bryce Leeaf3a4002017-03-20 10:37:12 -07004017 mWindowManager.onDisplayChanged(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004018 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004019 }
4020
David Stevens9440dc82017-03-16 19:00:20 -07004021 SleepToken createSleepTokenLocked(String tag, int displayId) {
4022 ActivityDisplay display = mActivityDisplays.get(displayId);
4023 if (display == null) {
4024 throw new IllegalArgumentException("Invalid display: " + displayId);
4025 }
4026
4027 final SleepTokenImpl token = new SleepTokenImpl(tag, displayId);
4028 mSleepTokens.add(token);
4029 display.mAllSleepTokens.add(token);
4030 return token;
4031 }
4032
4033 private void removeSleepTokenLocked(SleepTokenImpl token) {
4034 mSleepTokens.remove(token);
4035
4036 ActivityDisplay display = mActivityDisplays.get(token.mDisplayId);
4037 if (display != null) {
4038 display.mAllSleepTokens.remove(token);
4039 if (display.mAllSleepTokens.isEmpty()) {
4040 mService.updateSleepIfNeededLocked();
4041 }
4042 }
4043 }
4044
4045 private void releaseSleepTokens(ActivityDisplay display) {
4046 if (display.mAllSleepTokens.isEmpty()) {
4047 return;
4048 }
4049 for (SleepTokenImpl token : display.mAllSleepTokens) {
4050 mSleepTokens.remove(token);
4051 }
4052 display.mAllSleepTokens.clear();
4053
4054 mService.updateSleepIfNeededLocked();
4055 }
4056
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004057 private StackInfo getStackInfoLocked(ActivityStack stack) {
Andrii Kulian7e215d72017-04-26 18:33:28 -07004058 final int displayId = stack.mDisplayId;
4059 final ActivityDisplay display = mActivityDisplays.get(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004060 StackInfo info = new StackInfo();
Wale Ogunwale1666e312016-12-16 11:27:18 -08004061 stack.getWindowContainerBounds(info.bounds);
Andrii Kulian7e215d72017-04-26 18:33:28 -07004062 info.displayId = displayId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004063 info.stackId = stack.mStackId;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004064 info.userId = stack.mCurrentUser;
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004065 info.visible = stack.shouldBeVisible(null) == STACK_VISIBLE;
Andrii Kulian62e6f252017-05-30 22:46:53 -07004066 // A stack might be not attached to a display.
Winson529c8e42016-05-17 11:08:40 -07004067 info.position = display != null
4068 ? display.mStacks.indexOf(stack)
4069 : 0;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004070
4071 ArrayList<TaskRecord> tasks = stack.getAllTasks();
4072 final int numTasks = tasks.size();
4073 int[] taskIds = new int[numTasks];
4074 String[] taskNames = new String[numTasks];
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004075 Rect[] taskBounds = new Rect[numTasks];
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004076 int[] taskUserIds = new int[numTasks];
Craig Mautner4a1cb222013-12-04 16:14:06 -08004077 for (int i = 0; i < numTasks; ++i) {
4078 final TaskRecord task = tasks.get(i);
4079 taskIds[i] = task.taskId;
4080 taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
4081 : task.realActivity != null ? task.realActivity.flattenToString()
4082 : task.getTopActivity() != null ? task.getTopActivity().packageName
4083 : "unknown";
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004084 taskBounds[i] = new Rect();
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004085 task.getWindowContainerBounds(taskBounds[i]);
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004086 taskUserIds[i] = task.userId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004087 }
4088 info.taskIds = taskIds;
4089 info.taskNames = taskNames;
Wale Ogunwale868a5e12015-08-02 16:19:20 -07004090 info.taskBounds = taskBounds;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004091 info.taskUserIds = taskUserIds;
Winsond46b7272016-04-20 11:54:27 -07004092
4093 final ActivityRecord top = stack.topRunningActivityLocked();
4094 info.topActivity = top != null ? top.intent.getComponent() : null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004095 return info;
4096 }
4097
4098 StackInfo getStackInfoLocked(int stackId) {
4099 ActivityStack stack = getStack(stackId);
4100 if (stack != null) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004101 return getStackInfoLocked(stack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004102 }
4103 return null;
4104 }
4105
4106 ArrayList<StackInfo> getAllStackInfosLocked() {
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004107 ArrayList<StackInfo> list = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08004108 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
4109 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004110 for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004111 list.add(getStackInfoLocked(stacks.get(ndx)));
Craig Mautner4a1cb222013-12-04 16:14:06 -08004112 }
4113 }
4114 return list;
4115 }
4116
Craig Mautner15df08a2015-04-01 12:17:18 -07004117 TaskRecord getLockedTaskLocked() {
4118 final int top = mLockTaskModeTasks.size() - 1;
4119 if (top >= 0) {
4120 return mLockTaskModeTasks.get(top);
4121 }
4122 return null;
4123 }
4124
4125 boolean isLockedTask(TaskRecord task) {
4126 return mLockTaskModeTasks.contains(task);
4127 }
4128
4129 boolean isLastLockedTask(TaskRecord task) {
4130 return mLockTaskModeTasks.size() == 1 && mLockTaskModeTasks.contains(task);
4131 }
4132
4133 void removeLockedTaskLocked(final TaskRecord task) {
Craig Mautner432f64e2015-05-20 14:59:57 -07004134 if (!mLockTaskModeTasks.remove(task)) {
4135 return;
4136 }
4137 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "removeLockedTaskLocked: removed " + task);
4138 if (mLockTaskModeTasks.isEmpty()) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004139 // Last one.
Craig Mautnere0570202015-05-13 13:06:11 -07004140 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
4141 " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
Craig Mautner15df08a2015-04-01 12:17:18 -07004142 final Message lockTaskMsg = Message.obtain();
4143 lockTaskMsg.arg1 = task.userId;
4144 lockTaskMsg.what = LOCK_TASK_END_MSG;
4145 mHandler.sendMessage(lockTaskMsg);
4146 }
4147 }
4148
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004149 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4150 int preferredDisplayId, int actualStackId) {
4151 handleNonResizableTaskIfNeeded(task, preferredStackId, preferredDisplayId, actualStackId,
Andrii Kulianc27916642016-04-12 17:59:27 -07004152 false /* forceNonResizable */);
4153 }
4154
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004155 private void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4156 int preferredDisplayId, int actualStackId, boolean forceNonResizable) {
4157 final boolean isSecondaryDisplayPreferred =
4158 (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY)
4159 || StackId.isDynamicStack(preferredStackId);
4160 if (((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
4161 && !isSecondaryDisplayPreferred) || task.isHomeTask()) {
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004162 return;
4163 }
4164
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004165 // Handle incorrect launch/move to secondary display if needed.
4166 final boolean launchOnSecondaryDisplayFailed;
4167 if (isSecondaryDisplayPreferred) {
4168 final int actualDisplayId = task.getStack().mDisplayId;
4169 if (!task.canBeLaunchedOnDisplay(actualDisplayId)) {
4170 // The task landed on an inappropriate display somehow, move it to the default
4171 // display.
4172 // TODO(multi-display): Find proper stack for the task on the default display.
4173 mService.moveTaskToStack(task.taskId, FULLSCREEN_WORKSPACE_STACK_ID,
4174 true /* toTop */);
4175 launchOnSecondaryDisplayFailed = true;
4176 } else {
4177 // The task might have landed on a display different from requested.
4178 launchOnSecondaryDisplayFailed = actualDisplayId == DEFAULT_DISPLAY
4179 || (preferredDisplayId != INVALID_DISPLAY
4180 && preferredDisplayId != actualDisplayId);
4181 }
4182 } else {
4183 // The task wasn't requested to be on a secondary display.
4184 launchOnSecondaryDisplayFailed = false;
4185 }
4186
Jorim Jaggicd13d332016-04-27 15:40:20 -07004187 final ActivityRecord topActivity = task.getTopActivity();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004188 if (launchOnSecondaryDisplayFailed || !task.supportsSplitScreen() || forceNonResizable) {
4189 if (launchOnSecondaryDisplayFailed) {
4190 // Display a warning toast that we tried to put a non-resizeable task on a secondary
4191 // display with config different from global config.
4192 mService.mTaskChangeNotificationController
4193 .notifyActivityLaunchOnSecondaryDisplayFailed();
4194 } else {
4195 // Display a warning toast that we tried to put a non-dockable task in the docked
4196 // stack.
4197 mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
4198 }
Jorim Jaggid53f0922016-04-06 22:16:23 -07004199
Andrii Kulianc27916642016-04-12 17:59:27 -07004200 // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
4201 // we need to move it to top of fullscreen stack, otherwise it will be covered.
Wale Ogunwale9a98c522016-04-27 09:23:55 -07004202 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
Winson Chungd3395382016-12-13 11:49:09 -08004203 } else if (topActivity != null && topActivity.isNonResizableOrForcedResizable()
Jorim Jaggicd13d332016-04-27 15:40:20 -07004204 && !topActivity.noDisplay) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004205 final String packageName = topActivity.appInfo.packageName;
4206 final int reason = isSecondaryDisplayPreferred
4207 ? FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY
4208 : FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Yorke Leebd54c2a2016-10-25 13:49:23 -07004209 mService.mTaskChangeNotificationController.notifyActivityForcedResizable(
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004210 task.taskId, reason, packageName);
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004211 }
Chong Zhangb15758a2015-11-17 12:12:03 -08004212 }
4213
Craig Mautner6cd6cec2015-04-01 00:02:12 -07004214 void showLockTaskToast() {
Hall Liu45784f12016-05-31 15:50:48 -07004215 if (mLockTaskNotify != null) {
4216 mLockTaskNotify.showToast(mLockTaskModeState);
4217 }
Jason Monka8f569c2014-07-07 12:15:21 -04004218 }
4219
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004220 void showLockTaskEscapeMessageLocked(TaskRecord task) {
4221 if (mLockTaskModeTasks.contains(task)) {
4222 mHandler.sendEmptyMessage(SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG);
4223 }
4224 }
4225
Craig Mautner432f64e2015-05-20 14:59:57 -07004226 void setLockTaskModeLocked(TaskRecord task, int lockTaskModeState, String reason,
4227 boolean andResume) {
Craig Mautneraea74a52014-03-08 14:23:10 -08004228 if (task == null) {
Christopher Tate3bd90612014-06-18 16:37:52 -07004229 // Take out of lock task mode if necessary
Craig Mautner15df08a2015-04-01 12:17:18 -07004230 final TaskRecord lockedTask = getLockedTaskLocked();
4231 if (lockedTask != null) {
4232 removeLockedTaskLocked(lockedTask);
4233 if (!mLockTaskModeTasks.isEmpty()) {
4234 // There are locked tasks remaining, can only finish this task, not unlock it.
Craig Mautnere0570202015-05-13 13:06:11 -07004235 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4236 "setLockTaskModeLocked: Tasks remaining, can't unlock");
Craig Mautner15df08a2015-04-01 12:17:18 -07004237 lockedTask.performClearTaskLocked();
Wale Ogunwaled046a012015-12-24 13:05:59 -08004238 resumeFocusedStackTopActivityLocked();
Craig Mautner15df08a2015-04-01 12:17:18 -07004239 return;
4240 }
Christopher Tate3bd90612014-06-18 16:37:52 -07004241 }
Craig Mautnere0570202015-05-13 13:06:11 -07004242 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4243 "setLockTaskModeLocked: No tasks to unlock. Callers=" + Debug.getCallers(4));
Craig Mautneraea74a52014-03-08 14:23:10 -08004244 return;
4245 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004246
4247 // Should have already been checked, but do it again.
4248 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
Craig Mautnere0570202015-05-13 13:06:11 -07004249 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4250 "setLockTaskModeLocked: Can't lock due to auth");
Craig Mautneraea74a52014-03-08 14:23:10 -08004251 return;
4252 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004253 if (isLockTaskModeViolation(task)) {
Craig Mautnere0570202015-05-13 13:06:11 -07004254 Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
Craig Mautner15df08a2015-04-01 12:17:18 -07004255 return;
4256 }
4257
4258 if (mLockTaskModeTasks.isEmpty()) {
4259 // First locktask.
4260 final Message lockTaskMsg = Message.obtain();
4261 lockTaskMsg.obj = task.intent.getComponent().getPackageName();
4262 lockTaskMsg.arg1 = task.userId;
4263 lockTaskMsg.what = LOCK_TASK_START_MSG;
4264 lockTaskMsg.arg2 = lockTaskModeState;
4265 mHandler.sendMessage(lockTaskMsg);
4266 }
4267 // Add it or move it to the top.
Craig Mautnere0570202015-05-13 13:06:11 -07004268 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskModeLocked: Locking to " + task +
4269 " Callers=" + Debug.getCallers(4));
Craig Mautner15df08a2015-04-01 12:17:18 -07004270 mLockTaskModeTasks.remove(task);
4271 mLockTaskModeTasks.add(task);
4272
4273 if (task.mLockTaskUid == -1) {
Wale Ogunwale5c18d052015-10-12 10:34:14 -07004274 task.mLockTaskUid = task.effectiveUid;
Craig Mautner15df08a2015-04-01 12:17:18 -07004275 }
Craig Mautner432f64e2015-05-20 14:59:57 -07004276
4277 if (andResume) {
Andrii Kulianc27916642016-04-12 17:59:27 -07004278 findTaskToMoveToFrontLocked(task, 0, null, reason,
4279 lockTaskModeState != LOCK_TASK_MODE_NONE);
Wale Ogunwaled046a012015-12-24 13:05:59 -08004280 resumeFocusedStackTopActivityLocked();
Jorim Jaggia42938e2016-11-22 14:31:38 +01004281 mWindowManager.executeAppTransition();
Andrii Kulianc27916642016-04-12 17:59:27 -07004282 } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004283 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
4284 task.getStackId(), true /* forceNonResizable */);
Craig Mautner432f64e2015-05-20 14:59:57 -07004285 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004286 }
4287
4288 boolean isLockTaskModeViolation(TaskRecord task) {
Jason Monk25d237b2015-06-19 10:39:39 -04004289 return isLockTaskModeViolation(task, false);
4290 }
4291
4292 boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) {
4293 if (getLockedTaskLocked() == task && !isNewClearTask) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004294 return false;
4295 }
4296 final int lockTaskAuth = task.mLockTaskAuth;
4297 switch (lockTaskAuth) {
4298 case LOCK_TASK_AUTH_DONT_LOCK:
4299 return !mLockTaskModeTasks.isEmpty();
Benjamin Franz469dd582015-06-09 14:24:36 +01004300 case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
Craig Mautner15df08a2015-04-01 12:17:18 -07004301 case LOCK_TASK_AUTH_LAUNCHABLE:
4302 case LOCK_TASK_AUTH_WHITELISTED:
4303 return false;
4304 case LOCK_TASK_AUTH_PINNABLE:
4305 // Pinnable tasks can't be launched on top of locktask tasks.
4306 return !mLockTaskModeTasks.isEmpty();
4307 default:
4308 Slog.w(TAG, "isLockTaskModeViolation: invalid lockTaskAuth value=" + lockTaskAuth);
4309 return true;
4310 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004311 }
4312
Craig Mautner15df08a2015-04-01 12:17:18 -07004313 void onLockTaskPackagesUpdatedLocked() {
4314 boolean didSomething = false;
4315 for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
4316 final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx);
Benjamin Franz469dd582015-06-09 14:24:36 +01004317 final boolean wasWhitelisted =
4318 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4319 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
Craig Mautner15df08a2015-04-01 12:17:18 -07004320 lockedTask.setLockTaskAuth();
Benjamin Franz469dd582015-06-09 14:24:36 +01004321 final boolean isWhitelisted =
4322 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4323 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
4324 if (wasWhitelisted && !isWhitelisted) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004325 // Lost whitelisting authorization. End it now.
Craig Mautner432f64e2015-05-20 14:59:57 -07004326 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "onLockTaskPackagesUpdated: removing " +
4327 lockedTask + " mLockTaskAuth=" + lockedTask.lockTaskAuthToString());
Craig Mautner15df08a2015-04-01 12:17:18 -07004328 removeLockedTaskLocked(lockedTask);
4329 lockedTask.performClearTaskLocked();
4330 didSomething = true;
4331 }
4332 }
4333 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
4334 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
4335 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
4336 final ActivityStack stack = stacks.get(stackNdx);
4337 stack.onLockTaskPackagesUpdatedLocked();
4338 }
4339 }
Craig Mautnere0570202015-05-13 13:06:11 -07004340 final ActivityRecord r = topRunningActivityLocked();
Bryce Leeaf691c02017-03-20 14:20:22 -07004341 final TaskRecord task = r != null ? r.getTask() : null;
Craig Mautnere0570202015-05-13 13:06:11 -07004342 if (mLockTaskModeTasks.isEmpty() && task != null
4343 && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
4344 // This task must have just been authorized.
Craig Mautner432f64e2015-05-20 14:59:57 -07004345 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK,
4346 "onLockTaskPackagesUpdated: starting new locktask task=" + task);
4347 setLockTaskModeLocked(task, ActivityManager.LOCK_TASK_MODE_LOCKED, "package updated",
4348 false);
4349 didSomething = true;
Craig Mautnere0570202015-05-13 13:06:11 -07004350 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004351 if (didSomething) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004352 resumeFocusedStackTopActivityLocked();
Craig Mautneraea74a52014-03-08 14:23:10 -08004353 }
4354 }
4355
Benjamin Franz43261142015-02-11 15:59:44 +00004356 int getLockTaskModeState() {
4357 return mLockTaskModeState;
Craig Mautneraea74a52014-03-08 14:23:10 -08004358 }
4359
Jorim Jaggife89d122015-12-22 16:28:44 +01004360 void activityRelaunchedLocked(IBinder token) {
4361 mWindowManager.notifyAppRelaunchingFinished(token);
David Stevens9440dc82017-03-16 19:00:20 -07004362 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4363 if (r != null) {
4364 if (r.getStack().shouldSleepOrShutDownActivities()) {
Wale Ogunwale3e997362016-09-06 10:37:56 -07004365 r.setSleeping(true, true);
4366 }
4367 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004368 }
4369
4370 void activityRelaunchingLocked(ActivityRecord r) {
4371 mWindowManager.notifyAppRelaunching(r.appToken);
4372 }
4373
Filip Gruszczynski77d94482015-12-11 13:59:52 -08004374 void logStackState() {
4375 mActivityMetricsLogger.logWindowState();
4376 }
4377
Winson Chung5af42fc2017-03-24 17:11:33 -07004378 void scheduleUpdateMultiWindowMode(TaskRecord task) {
Winson Chung8bca9e42017-04-16 15:59:43 -07004379 // If the stack is animating in a way where we will be forcing a multi-mode change at the
4380 // end, then ensure that we defer all in between multi-window mode changes
4381 if (task.getStack().deferScheduleMultiWindowModeChanged()) {
4382 return;
4383 }
4384
Wale Ogunwale22e25262016-02-01 10:32:02 -08004385 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4386 final ActivityRecord r = task.mActivities.get(i);
4387 if (r.app != null && r.app.thread != null) {
4388 mMultiWindowModeChangedActivities.add(r);
4389 }
4390 }
4391
4392 if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
4393 mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
4394 }
4395 }
4396
Winson Chung5af42fc2017-03-24 17:11:33 -07004397 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07004398 final ActivityStack stack = task.getStack();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004399 if (prevStack == null || prevStack == stack
4400 || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
4401 return;
4402 }
4403
Winson Chung5af42fc2017-03-24 17:11:33 -07004404 scheduleUpdatePictureInPictureModeIfNeeded(task, stack.mBounds, false /* immediate */);
4405 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004406
Winson Chung5af42fc2017-03-24 17:11:33 -07004407 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds,
4408 boolean immediate) {
4409
4410 if (immediate) {
4411 mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG);
4412 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4413 final ActivityRecord r = task.mActivities.get(i);
4414 if (r.app != null && r.app.thread != null) {
4415 r.updatePictureInPictureMode(targetStackBounds);
4416 }
4417 }
4418 } else {
4419 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4420 final ActivityRecord r = task.mActivities.get(i);
4421 if (r.app != null && r.app.thread != null) {
4422 mPipModeChangedActivities.add(r);
4423 }
4424 }
4425 mPipModeChangedTargetStackBounds = targetStackBounds;
4426
4427 if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
4428 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
4429 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004430 }
4431 }
4432
Tony Mak853304c2016-04-18 15:17:41 +01004433 void setDockedStackMinimized(boolean minimized) {
4434 mIsDockMinimized = minimized;
Tony Mak853304c2016-04-18 15:17:41 +01004435 }
4436
chaviw59b98852017-06-13 12:05:44 -07004437 void wakeUp(String reason) {
4438 mPowerManager.wakeUp(SystemClock.uptimeMillis(), "android.server.am:TURN_ON:" + reason);
4439 }
4440
4441 /**
4442 * Begin deferring resume to avoid duplicate resumes in one pass.
4443 */
4444 private void beginDeferResume() {
4445 mDeferResumeCount++;
4446 }
4447
4448 /**
4449 * End deferring resume and determine if resume can be called.
4450 */
4451 private void endDeferResume() {
4452 mDeferResumeCount--;
4453 }
4454
4455 /**
4456 * @return True if resume can be called.
4457 */
4458 private boolean readyToResume() {
4459 return mDeferResumeCount == 0;
4460 }
4461
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004462 private final class ActivityStackSupervisorHandler extends Handler {
Craig Mautnerf3333272013-04-22 10:55:53 -07004463
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004464 public ActivityStackSupervisorHandler(Looper looper) {
4465 super(looper);
4466 }
4467
Winson Chung4dabf232017-01-25 13:25:22 -08004468 void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) {
Craig Mautnerf3333272013-04-22 10:55:53 -07004469 synchronized (mService) {
Winson Chung4dabf232017-01-25 13:25:22 -08004470 activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */,
4471 processPausingActivities, null);
Craig Mautnerf3333272013-04-22 10:55:53 -07004472 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004473 }
4474
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004475 @Override
4476 public void handleMessage(Message msg) {
4477 switch (msg.what) {
Wale Ogunwale22e25262016-02-01 10:32:02 -08004478 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
4479 synchronized (mService) {
4480 for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
4481 final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004482 r.updateMultiWindowMode();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004483 }
4484 }
4485 } break;
4486 case REPORT_PIP_MODE_CHANGED_MSG: {
4487 synchronized (mService) {
4488 for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
4489 final ActivityRecord r = mPipModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004490 r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds);
Wale Ogunwale22e25262016-02-01 10:32:02 -08004491 }
4492 }
4493 } break;
Craig Mautnerf3333272013-04-22 10:55:53 -07004494 case IDLE_TIMEOUT_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004495 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
4496 "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
Craig Mautnerf3333272013-04-22 10:55:53 -07004497 // We don't at this point know if the activity is fullscreen,
4498 // so we need to be conservative and assume it isn't.
Winson Chung4dabf232017-01-25 13:25:22 -08004499 activityIdleInternal((ActivityRecord) msg.obj,
4500 true /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004501 } break;
4502 case IDLE_NOW_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004503 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
Winson Chung4dabf232017-01-25 13:25:22 -08004504 activityIdleInternal((ActivityRecord) msg.obj,
4505 false /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004506 } break;
Craig Mautner05d29032013-05-03 13:40:13 -07004507 case RESUME_TOP_ACTIVITY_MSG: {
4508 synchronized (mService) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004509 resumeFocusedStackTopActivityLocked();
Craig Mautner05d29032013-05-03 13:40:13 -07004510 }
4511 } break;
Craig Mautner0eea92c2013-05-16 13:35:39 -07004512 case SLEEP_TIMEOUT_MSG: {
4513 synchronized (mService) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07004514 if (mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07004515 Slog.w(TAG, "Sleep timeout! Sleeping now.");
David Stevens9440dc82017-03-16 19:00:20 -07004516 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07004517 }
4518 }
4519 } break;
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004520 case LAUNCH_TIMEOUT_MSG: {
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004521 synchronized (mService) {
4522 if (mLaunchingActivity.isHeld()) {
4523 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
4524 if (VALIDATE_WAKE_LOCK_CALLER
4525 && Binder.getCallingUid() != Process.myUid()) {
4526 throw new IllegalStateException("Calling must be system uid");
4527 }
4528 mLaunchingActivity.release();
4529 }
4530 }
4531 } break;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004532 case HANDLE_DISPLAY_ADDED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004533 handleDisplayAdded(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004534 } break;
4535 case HANDLE_DISPLAY_CHANGED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004536 handleDisplayChanged(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004537 } break;
4538 case HANDLE_DISPLAY_REMOVED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004539 handleDisplayRemoved(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004540 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004541 case LOCK_TASK_START_MSG: {
4542 // When lock task starts, we disable the status bars.
4543 try {
Jason Monk62515be2014-05-21 16:06:19 -04004544 if (mLockTaskNotify == null) {
4545 mLockTaskNotify = new LockTaskNotify(mService.mContext);
justinzhang5286d3f2014-05-12 17:06:01 -04004546 }
Jason Monk62515be2014-05-21 16:06:19 -04004547 mLockTaskNotify.show(true);
Benjamin Franz43261142015-02-11 15:59:44 +00004548 mLockTaskModeState = msg.arg2;
Jason Monk62515be2014-05-21 16:06:19 -04004549 if (getStatusBarService() != null) {
Benjamin Franz43261142015-02-11 15:59:44 +00004550 int flags = 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004551 if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004552 flags = StatusBarManager.DISABLE_MASK
4553 & (~StatusBarManager.DISABLE_BACK);
Craig Mautner15df08a2015-04-01 12:17:18 -07004554 } else if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004555 flags = StatusBarManager.DISABLE_MASK
4556 & (~StatusBarManager.DISABLE_BACK)
4557 & (~StatusBarManager.DISABLE_HOME)
4558 & (~StatusBarManager.DISABLE_RECENT);
Jason Monk62515be2014-05-21 16:06:19 -04004559 }
4560 getStatusBarService().disable(flags, mToken,
4561 mService.mContext.getPackageName());
4562 }
4563 mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
Jason Monk35c62a42014-06-17 10:24:47 -04004564 if (getDevicePolicyManager() != null) {
4565 getDevicePolicyManager().notifyLockTaskModeChanged(true,
Jason Monk62515be2014-05-21 16:06:19 -04004566 (String)msg.obj, msg.arg1);
Jason Monk35c62a42014-06-17 10:24:47 -04004567 }
justinzhang5286d3f2014-05-12 17:06:01 -04004568 } catch (RemoteException ex) {
4569 throw new RuntimeException(ex);
4570 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004571 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004572 case LOCK_TASK_END_MSG: {
4573 // When lock task ends, we enable the status bars.
4574 try {
Jason Monk62515be2014-05-21 16:06:19 -04004575 if (getStatusBarService() != null) {
4576 getStatusBarService().disable(StatusBarManager.DISABLE_NONE, mToken,
4577 mService.mContext.getPackageName());
4578 }
4579 mWindowManager.reenableKeyguard(mToken);
Jason Monk35c62a42014-06-17 10:24:47 -04004580 if (getDevicePolicyManager() != null) {
4581 getDevicePolicyManager().notifyLockTaskModeChanged(false, null,
4582 msg.arg1);
4583 }
Jason Monk62515be2014-05-21 16:06:19 -04004584 if (mLockTaskNotify == null) {
4585 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4586 }
4587 mLockTaskNotify.show(false);
4588 try {
Jason Monk94cfd9d2014-10-31 13:18:21 -04004589 boolean shouldLockKeyguard = Settings.Secure.getInt(
Jason Monk62515be2014-05-21 16:06:19 -04004590 mService.mContext.getContentResolver(),
Jason Monk94cfd9d2014-10-31 13:18:21 -04004591 Settings.Secure.LOCK_TO_APP_EXIT_LOCKED) != 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004592 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED && shouldLockKeyguard) {
Jason Monk62515be2014-05-21 16:06:19 -04004593 mWindowManager.lockNow(null);
Jorim Jaggi241ae102016-11-02 21:57:33 -07004594 mWindowManager.dismissKeyguard(null /* callback */);
Jason Monke0697792014-08-04 16:28:09 -04004595 new LockPatternUtils(mService.mContext)
4596 .requireCredentialEntry(UserHandle.USER_ALL);
Jason Monk62515be2014-05-21 16:06:19 -04004597 }
4598 } catch (SettingNotFoundException e) {
4599 // No setting, don't lock.
4600 }
justinzhang5286d3f2014-05-12 17:06:01 -04004601 } catch (RemoteException ex) {
4602 throw new RuntimeException(ex);
Benjamin Franz43261142015-02-11 15:59:44 +00004603 } finally {
Craig Mautner15df08a2015-04-01 12:17:18 -07004604 mLockTaskModeState = LOCK_TASK_MODE_NONE;
justinzhang5286d3f2014-05-12 17:06:01 -04004605 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004606 } break;
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004607 case SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG: {
4608 if (mLockTaskNotify == null) {
4609 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4610 }
4611 mLockTaskNotify.showToast(LOCK_TASK_MODE_PINNED);
4612 } break;
Craig Mautnerbb742462014-07-07 15:28:55 -07004613 case LAUNCH_TASK_BEHIND_COMPLETE: {
4614 synchronized (mService) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07004615 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
Craig Mautnerbb742462014-07-07 15:28:55 -07004616 if (r != null) {
4617 handleLaunchTaskBehindCompleteLocked(r);
4618 }
4619 }
4620 } break;
Chong Zhangc806d902015-11-30 09:44:27 -08004621
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004622 }
4623 }
4624 }
Craig Mautnered6649f2013-12-02 14:08:25 -08004625
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004626 // TODO: Move to its own file.
Craig Mautner4a1cb222013-12-04 16:14:06 -08004627 /** Exactly one of these classes per Display in the system. Capable of holding zero or more
4628 * attached {@link ActivityStack}s */
Andrii Kulian1779e612016-10-12 21:58:25 -07004629 class ActivityDisplay extends ConfigurationContainer {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004630 /** Actual Display this object tracks. */
Craig Mautner34b73df2014-01-12 21:11:08 -08004631 int mDisplayId;
4632 Display mDisplay;
Craig Mautnered6649f2013-12-02 14:08:25 -08004633
Craig Mautner4a1cb222013-12-04 16:14:06 -08004634 /** All of the stacks on this display. Order matters, topmost stack is in front of all other
4635 * stacks, bottommost behind. Accessed directly by ActivityManager package classes */
Wale Ogunwale1f544be2015-12-17 10:27:23 -08004636 final ArrayList<ActivityStack> mStacks = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004637
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004638 /** Array of all UIDs that are present on the display. */
4639 private IntArray mDisplayAccessUIDs = new IntArray();
4640
David Stevens9440dc82017-03-16 19:00:20 -07004641 /** All tokens used to put activities on this stack to sleep (including mOffToken) */
4642 final ArrayList<SleepTokenImpl> mAllSleepTokens = new ArrayList<>();
4643 /** The token acquired by ActivityStackSupervisor to put stacks on the display to sleep */
4644 SleepToken mOffToken;
4645
4646 private boolean mSleeping;
4647
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004648 @VisibleForTesting
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004649 ActivityDisplay() {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004650 mActivityDisplays.put(mDisplayId, this);
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004651 }
Craig Mautner4504de52013-12-20 09:06:56 -08004652
Craig Mautner1a70a162014-09-13 12:09:31 -07004653 // After instantiation, check that mDisplay is not null before using this. The alternative
4654 // is for this to throw an exception if mDisplayManager.getDisplay() returns null.
Craig Mautnere0a38842013-12-16 16:14:02 -08004655 ActivityDisplay(int displayId) {
Craig Mautner1a70a162014-09-13 12:09:31 -07004656 final Display display = mDisplayManager.getDisplay(displayId);
4657 if (display == null) {
4658 return;
4659 }
4660 init(display);
Craig Mautner4504de52013-12-20 09:06:56 -08004661 }
4662
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004663 void init(Display display) {
Craig Mautner4504de52013-12-20 09:06:56 -08004664 mDisplay = display;
4665 mDisplayId = display.getDisplayId();
Craig Mautnered6649f2013-12-02 14:08:25 -08004666 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004667
Winson Chung7c3ede32017-03-14 14:18:34 -07004668 void attachStack(ActivityStack stack, int position) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08004669 if (DEBUG_STACK) Slog.v(TAG_STACK, "attachStack: attaching " + stack
Winson Chung7c3ede32017-03-14 14:18:34 -07004670 + " to displayId=" + mDisplayId + " position=" + position);
4671 mStacks.add(position, stack);
David Stevens9440dc82017-03-16 19:00:20 -07004672 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004673 }
4674
Wale Ogunwale1666e312016-12-16 11:27:18 -08004675 void detachStack(ActivityStack stack) {
4676 if (DEBUG_STACK) Slog.v(TAG_STACK, "detachStack: detaching " + stack
Craig Mautnere0a38842013-12-16 16:14:02 -08004677 + " from displayId=" + mDisplayId);
4678 mStacks.remove(stack);
David Stevens9440dc82017-03-16 19:00:20 -07004679 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004680 }
4681
Craig Mautner34b73df2014-01-12 21:11:08 -08004682 @Override
4683 public String toString() {
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004684 return "ActivityDisplay={" + mDisplayId + " numStacks=" + mStacks.size() + "}";
4685 }
Andrii Kulian1779e612016-10-12 21:58:25 -07004686
4687 @Override
4688 protected int getChildCount() {
4689 return mStacks.size();
4690 }
4691
4692 @Override
4693 protected ConfigurationContainer getChildAt(int index) {
4694 return mStacks.get(index);
4695 }
4696
4697 @Override
4698 protected ConfigurationContainer getParent() {
4699 return ActivityStackSupervisor.this;
4700 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004701
4702 boolean isPrivate() {
4703 return (mDisplay.getFlags() & FLAG_PRIVATE) != 0;
4704 }
4705
4706 boolean isUidPresent(int uid) {
4707 for (ActivityStack stack : mStacks) {
4708 if (stack.isUidPresent(uid)) {
4709 return true;
4710 }
4711 }
4712 return false;
4713 }
4714
4715 /** Update and get all UIDs that are present on the display and have access to it. */
4716 private IntArray getPresentUIDs() {
4717 mDisplayAccessUIDs.clear();
4718 for (ActivityStack stack : mStacks) {
4719 stack.getPresentUIDs(mDisplayAccessUIDs);
4720 }
4721 return mDisplayAccessUIDs;
4722 }
Andrii Kulian250d6532017-02-08 23:30:45 -08004723
4724 boolean shouldDestroyContentOnRemove() {
4725 return mDisplay.getRemoveMode() == REMOVE_MODE_DESTROY_CONTENT;
4726 }
David Stevens9440dc82017-03-16 19:00:20 -07004727
4728 boolean shouldSleep() {
4729 return (mStacks.isEmpty() || !mAllSleepTokens.isEmpty())
4730 && (mService.mRunningVoice == null);
4731 }
4732
4733 boolean isSleeping() {
4734 return mSleeping;
4735 }
4736
4737 void setIsSleeping(boolean asleep) {
4738 mSleeping = asleep;
4739 }
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004740 }
4741
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004742 ActivityStack findStackBehind(ActivityStack stack) {
4743 // TODO(multi-display): We are only looking for stacks on the default display.
Jorim Jaggife762342016-10-13 14:33:27 +02004744 final ActivityDisplay display = mActivityDisplays.get(DEFAULT_DISPLAY);
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004745 if (display == null) {
4746 return null;
4747 }
4748 final ArrayList<ActivityStack> stacks = display.mStacks;
4749 for (int i = stacks.size() - 1; i >= 0; i--) {
4750 if (stacks.get(i) == stack && i > 0) {
4751 return stacks.get(i - 1);
4752 }
4753 }
4754 throw new IllegalStateException("Failed to find a stack behind stack=" + stack
4755 + " in=" + stacks);
4756 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004757
Jorim Jaggic69bd222016-03-15 14:38:37 +01004758 /**
4759 * Puts a task into resizing mode during the next app transition.
4760 *
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004761 * @param task The task to put into resizing mode
Jorim Jaggic69bd222016-03-15 14:38:37 +01004762 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004763 private void setResizingDuringAnimation(TaskRecord task) {
4764 mResizingTasksDuringAnimation.add(task.taskId);
4765 task.setTaskDockedResizing(true);
Jorim Jaggic69bd222016-03-15 14:38:37 +01004766 }
4767
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004768 final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
4769 final TaskRecord task;
4770 final int callingUid;
4771 final String callingPackage;
4772 final Intent intent;
4773 final int userId;
4774 final ActivityOptions activityOptions = (bOptions != null)
4775 ? new ActivityOptions(bOptions) : null;
4776 final int launchStackId = (activityOptions != null)
4777 ? activityOptions.getLaunchStackId() : INVALID_STACK_ID;
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004778 if (StackId.isHomeOrRecentsStack(launchStackId)) {
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004779 throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004780 + taskId + " can't be launch in the home/recents stack.");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004781 }
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004782
Matthew Ng606dd802017-06-05 14:06:32 -07004783 mWindowManager.deferSurfaceLayout();
4784 try {
4785 if (launchStackId == DOCKED_STACK_ID) {
4786 mWindowManager.setDockedStackCreateState(
4787 activityOptions.getDockCreateMode(), null /* initialBounds */);
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004788
Matthew Ng606dd802017-06-05 14:06:32 -07004789 // Defer updating the stack in which recents is until the app transition is done, to
4790 // not run into issues where we still need to draw the task in recents but the
4791 // docked stack is already created.
4792 deferUpdateBounds(RECENTS_STACK_ID);
4793 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004794 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004795
Matthew Ng606dd802017-06-05 14:06:32 -07004796 task = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
4797 launchStackId);
4798 if (task == null) {
4799 continueUpdateBounds(RECENTS_STACK_ID);
4800 mWindowManager.executeAppTransition();
4801 throw new IllegalArgumentException(
4802 "startActivityFromRecentsInner: Task " + taskId + " not found.");
4803 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004804
Matthew Ng606dd802017-06-05 14:06:32 -07004805 // Since we don't have an actual source record here, we assume that the currently
4806 // focused activity was the source.
4807 final ActivityStack focusedStack = getFocusedStack();
4808 final ActivityRecord sourceRecord =
4809 focusedStack != null ? focusedStack.topActivity() : null;
4810
4811 if (launchStackId != INVALID_STACK_ID) {
4812 if (task.getStackId() != launchStackId) {
4813 task.reparent(launchStackId, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE,
4814 DEFER_RESUME, "startActivityFromRecents");
4815 }
4816 }
4817
4818 // If the user must confirm credentials (e.g. when first launching a work app and the
4819 // Work Challenge is present) let startActivityInPackage handle the intercepting.
4820 if (!mService.mUserController.shouldConfirmCredentials(task.userId)
4821 && task.getRootActivity() != null) {
Bryce Lee28d80422017-07-21 13:25:13 -07004822 final ActivityRecord targetActivity = task.getTopActivity();
4823
4824 mService.mActivityStarter.sendPowerHintForLaunchStartIfNeeded(true /* forceSend */,
4825 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004826 mActivityMetricsLogger.notifyActivityLaunching();
Jorim Jaggi42befc62017-06-13 11:54:04 -07004827 mService.moveTaskToFrontLocked(task.taskId, 0, bOptions, true /* fromRecents */);
Matthew Ng606dd802017-06-05 14:06:32 -07004828 mActivityMetricsLogger.notifyActivityLaunched(ActivityManager.START_TASK_TO_FRONT,
Bryce Lee28d80422017-07-21 13:25:13 -07004829 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004830
4831 // If we are launching the task in the docked stack, put it into resizing mode so
4832 // the window renders full-screen with the background filling the void. Also only
4833 // call this at the end to make sure that tasks exists on the window manager side.
4834 if (launchStackId == DOCKED_STACK_ID) {
4835 setResizingDuringAnimation(task);
4836 }
4837
4838 mService.mActivityStarter.postStartActivityProcessing(task.getTopActivity(),
4839 ActivityManager.START_TASK_TO_FRONT,
4840 sourceRecord != null
4841 ? sourceRecord.getTask().getStackId() : INVALID_STACK_ID,
4842 sourceRecord, task.getStack());
4843 return ActivityManager.START_TASK_TO_FRONT;
4844 }
4845 callingUid = task.mCallingUid;
4846 callingPackage = task.mCallingPackage;
4847 intent = task.intent;
4848 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4849 userId = task.userId;
4850 int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004851 null, null, 0, 0, bOptions, userId, task, "startActivityFromRecents");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004852 if (launchStackId == DOCKED_STACK_ID) {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004853 setResizingDuringAnimation(task);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004854 }
Matthew Ng606dd802017-06-05 14:06:32 -07004855 return result;
4856 } finally {
4857 mWindowManager.continueSurfaceLayout();
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004858 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004859 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004860
4861 /**
4862 * @return a list of activities which are the top ones in each visible stack. The first
4863 * entry will be the focused activity.
4864 */
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004865 List<IBinder> getTopVisibleActivities() {
4866 final ArrayList<IBinder> topActivityTokens = new ArrayList<>();
4867 // Traverse all displays.
Robert Carr22374c02017-02-21 13:01:47 -08004868 for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004869 final ActivityDisplay display = mActivityDisplays.valueAt(i);
4870 // Traverse all stacks on a display.
4871 for (int j = display.mStacks.size() - 1; j >= 0; j--) {
4872 final ActivityStack stack = display.mStacks.get(j);
4873 // Get top activity from a visible stack and add it to the list.
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004874 if (stack.shouldBeVisible(null /* starting */)
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004875 == ActivityStack.STACK_VISIBLE) {
4876 final ActivityRecord top = stack.topActivity();
4877 if (top != null) {
4878 if (stack == mFocusedStack) {
4879 topActivityTokens.add(0, top.appToken);
4880 } else {
4881 topActivityTokens.add(top.appToken);
4882 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004883 }
4884 }
4885 }
4886 }
4887 return topActivityTokens;
4888 }
Bryce Lee4a194382017-04-04 14:32:48 -07004889
4890 /**
4891 * Internal container to store a match qualifier alongside a WaitResult.
4892 */
4893 static class WaitInfo {
4894 private final ComponentName mTargetComponent;
4895 private final WaitResult mResult;
4896
4897 public WaitInfo(ComponentName targetComponent, WaitResult result) {
4898 this.mTargetComponent = targetComponent;
4899 this.mResult = result;
4900 }
4901
Wale Ogunwale3270f172017-04-26 07:29:42 -07004902 public boolean matches(ComponentName targetComponent) {
4903 return mTargetComponent == null || mTargetComponent.equals(targetComponent);
Bryce Lee4a194382017-04-04 14:32:48 -07004904 }
4905
4906 public WaitResult getResult() {
4907 return mResult;
4908 }
4909
4910 public ComponentName getComponent() {
4911 return mTargetComponent;
4912 }
4913
4914 public void dump(PrintWriter pw, String prefix) {
4915 pw.println(prefix + "WaitInfo:");
4916 pw.println(prefix + " mTargetComponent=" + mTargetComponent);
4917 pw.println(prefix + " mResult=");
4918 mResult.dump(pw, prefix);
4919 }
4920 }
David Stevens9440dc82017-03-16 19:00:20 -07004921
4922 private final class SleepTokenImpl extends SleepToken {
4923 private final String mTag;
4924 private final long mAcquireTime;
4925 private final int mDisplayId;
4926
4927 public SleepTokenImpl(String tag, int displayId) {
4928 mTag = tag;
4929 mDisplayId = displayId;
4930 mAcquireTime = SystemClock.uptimeMillis();
4931 }
4932
4933 @Override
4934 public void release() {
4935 synchronized (mService) {
4936 removeSleepTokenLocked(this);
4937 }
4938 }
4939
4940 @Override
4941 public String toString() {
4942 return "{\"" + mTag + "\", display " + mDisplayId
4943 + ", acquire at " + TimeUtils.formatUptime(mAcquireTime) + "}";
4944 }
4945 }
4946
Craig Mautner27084302013-03-25 08:05:25 -07004947}