blob: 871277516b1a42bd54601c580f1692d30eca66d8 [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 Mautner23ac33b2013-04-01 16:26:35 -0700138import android.os.ParcelFileDescriptor;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700139import android.os.PowerManager;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700140import android.os.Process;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700141import android.os.RemoteException;
justinzhang5286d3f2014-05-12 17:06:01 -0400142import android.os.ServiceManager;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700143import android.os.SystemClock;
Wale Ogunwalecad05a02015-09-25 10:41:44 -0700144import android.os.Trace;
Craig Mautner6170f732013-04-02 13:05:23 -0700145import android.os.UserHandle;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100146import android.os.UserManager;
Dianne Hackborn3d07c942015-03-13 18:02:54 -0700147import android.os.WorkSource;
Svetoslav7008b512015-06-24 18:47:07 -0700148import android.provider.MediaStore;
Jason Monk62515be2014-05-21 16:06:19 -0400149import android.provider.Settings;
150import android.provider.Settings.SettingNotFoundException;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700151import android.service.voice.IVoiceInteractionSession;
Svetoslav7008b512015-06-24 18:47:07 -0700152import android.util.ArrayMap;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700153import android.util.ArraySet;
Craig Mautner2420ead2013-04-01 17:13:20 -0700154import android.util.EventLog;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800155import android.util.IntArray;
Wale Ogunwalee610d3d2017-04-25 10:23:48 -0700156import android.util.MergedConfiguration;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700157import android.util.Slog;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800158import android.util.SparseArray;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800159import android.util.SparseIntArray;
David Stevens9440dc82017-03-16 19:00:20 -0700160import android.util.TimeUtils;
Craig Mautnered6649f2013-12-02 14:08:25 -0800161import android.view.Display;
Chong Zhangb15758a2015-11-17 12:12:03 -0800162
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700163import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800164import com.android.internal.content.ReferrerIntent;
Winson Chung14fbe142016-12-19 16:18:24 -0800165import com.android.internal.logging.MetricsLogger;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -0700166import com.android.internal.os.TransferPipe;
justinzhang5286d3f2014-05-12 17:06:01 -0400167import com.android.internal.statusbar.IStatusBarService;
Svetoslav7008b512015-06-24 18:47:07 -0700168import com.android.internal.util.ArrayUtils;
Jason Monke0697792014-08-04 16:28:09 -0400169import com.android.internal.widget.LockPatternUtils;
Jeff Brownca9bc702014-02-11 14:32:56 -0800170import com.android.server.LocalServices;
Craig Mautner2420ead2013-04-01 17:13:20 -0700171import com.android.server.am.ActivityStack.ActivityState;
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
Andrii Kulian1779e612016-10-12 21:58:25 -0700451 @Override
452 protected int getChildCount() {
453 return mActivityDisplays.size();
454 }
455
456 @Override
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700457 protected ActivityDisplay getChildAt(int index) {
Andrii Kulian1779e612016-10-12 21:58:25 -0700458 return mActivityDisplays.valueAt(index);
459 }
460
461 @Override
462 protected ConfigurationContainer getParent() {
463 return null;
464 }
465
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700466 Configuration getDisplayOverrideConfiguration(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700467 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700468 if (activityDisplay == null) {
469 throw new IllegalArgumentException("No display found with id: " + displayId);
470 }
471
472 return activityDisplay.getOverrideConfiguration();
473 }
474
475 void setDisplayOverrideConfiguration(Configuration overrideConfiguration, int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700476 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700477 if (activityDisplay == null) {
478 throw new IllegalArgumentException("No display found with id: " + displayId);
479 }
480
481 activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
482 }
483
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700484 /** Check if placing task or activity on specified display is allowed. */
Andrii Kulian02689a72017-07-06 14:28:59 -0700485 boolean canPlaceEntityOnDisplay(int displayId, boolean resizeable, int callingPid,
486 int callingUid, ActivityInfo activityInfo) {
487 if (displayId == DEFAULT_DISPLAY) {
488 // No restrictions for the default display.
489 return true;
490 }
491 if (!mService.mSupportsMultiDisplay) {
492 // Can't launch on secondary displays if feature is not supported.
493 return false;
494 }
495 if (!resizeable && !displayConfigMatchesGlobal(displayId)) {
496 // Can't apply wrong configuration to non-resizeable activities.
497 return false;
498 }
499 if (!isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, displayId, activityInfo)) {
500 // Can't place activities to a display that has restricted launch rules.
501 // In this case the request should be made by explicitly adding target display id and
502 // by caller with corresponding permissions. See #isCallerAllowedToLaunchOnDisplay().
503 return false;
504 }
505 return true;
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700506 }
507
508 /**
509 * Check if configuration of specified display matches current global config.
510 * Used to check if we can put a non-resizeable activity on a secondary display and it will get
511 * the same config as on the default display.
512 * @param displayId Id of the display to check.
513 * @return {@code true} if configuration matches.
514 */
515 private boolean displayConfigMatchesGlobal(int displayId) {
516 if (displayId == DEFAULT_DISPLAY) {
517 return true;
518 }
519 if (displayId == INVALID_DISPLAY) {
520 return false;
521 }
Andrii Kulian62e6f252017-05-30 22:46:53 -0700522 final ActivityDisplay targetDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700523 if (targetDisplay == null) {
524 throw new IllegalArgumentException("No display found with id: " + displayId);
525 }
526 return getConfiguration().equals(targetDisplay.getConfiguration());
527 }
528
Wale Ogunwale39381972015-12-17 17:15:29 -0800529 static class FindTaskResult {
530 ActivityRecord r;
531 boolean matchedByRootAffinity;
532 }
533 private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
534
Craig Mautneree36c772014-07-16 14:56:05 -0700535 /**
Andrii Kulian7fc22812016-12-28 13:04:11 -0800536 * Temp storage for display ids sorted in focus order.
537 * Maps position to id. Using {@link SparseIntArray} instead of {@link ArrayList} because
538 * it's more efficient, as the number of displays is usually small.
539 */
540 private SparseIntArray mTmpOrderedDisplayIds = new SparseIntArray();
541
542 /**
Jorim Jaggia0fdeec2016-01-07 14:42:28 +0100543 * Used to keep track whether app visibilities got changed since the last pause. Useful to
544 * determine whether to invoke the task stack change listener after pausing.
545 */
546 boolean mAppVisibilitiesChangedSinceLastPause;
547
548 /**
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100549 * Set of tasks that are in resizing mode during an app transition to fill the "void".
550 */
551 private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
552
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700553
554 /**
555 * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked}
556 * will be ignored. Useful for the case where the caller is handling resizing of other stack and
557 * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger
558 * like the docked stack going empty.
559 */
560 private boolean mAllowDockedStackResize = true;
561
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100562 /**
Tony Mak853304c2016-04-18 15:17:41 +0100563 * Is dock currently minimized.
564 */
565 boolean mIsDockMinimized;
566
Jorim Jaggife762342016-10-13 14:33:27 +0200567 final KeyguardController mKeyguardController;
568
chaviw59b98852017-06-13 12:05:44 -0700569 private PowerManager mPowerManager;
570 private int mDeferResumeCount;
571
Tony Mak853304c2016-04-18 15:17:41 +0100572 /**
Craig Mautneree36c772014-07-16 14:56:05 -0700573 * Description of a request to start a new activity, which has been held
574 * due to app switches being disabled.
575 */
576 static class PendingActivityLaunch {
577 final ActivityRecord r;
578 final ActivityRecord sourceRecord;
579 final int startFlags;
580 final ActivityStack stack;
Robert Carr13997f52015-10-23 13:13:39 -0700581 final ProcessRecord callerApp;
Craig Mautneree36c772014-07-16 14:56:05 -0700582
583 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
Robert Carr13997f52015-10-23 13:13:39 -0700584 int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
Craig Mautneree36c772014-07-16 14:56:05 -0700585 r = _r;
586 sourceRecord = _sourceRecord;
587 startFlags = _startFlags;
588 stack = _stack;
Robert Carr13997f52015-10-23 13:13:39 -0700589 callerApp = _callerApp;
590 }
591
592 void sendErrorResult(String message) {
593 try {
594 if (callerApp.thread != null) {
595 callerApp.thread.scheduleCrash(message);
596 }
597 } catch (RemoteException e) {
598 Slog.e(TAG, "Exception scheduling crash of failed "
599 + "activity launcher sourceRecord=" + sourceRecord, e);
600 }
Craig Mautneree36c772014-07-16 14:56:05 -0700601 }
602 }
603
Bryce Leeaf691c02017-03-20 14:20:22 -0700604 public ActivityStackSupervisor(ActivityManagerService service, Looper looper) {
Craig Mautner27084302013-03-25 08:05:25 -0700605 mService = service;
Bryce Leeaf691c02017-03-20 14:20:22 -0700606 mHandler = new ActivityStackSupervisorHandler(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800607 mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
Jorim Jaggife762342016-10-13 14:33:27 +0200608 mKeyguardController = new KeyguardController(service, this);
Jeff Brown2c43c332014-06-12 22:38:59 -0700609 }
610
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800611 void setRecentTasks(RecentTasks recentTasks) {
612 mRecentTasks = recentTasks;
613 }
614
Jeff Brown2c43c332014-06-12 22:38:59 -0700615 /**
616 * At the time when the constructor runs, the power manager has not yet been
617 * initialized. So we initialize our wakelocks afterwards.
618 */
619 void initPowerManagement() {
chaviw59b98852017-06-13 12:05:44 -0700620 mPowerManager = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
621 mGoingToSleep = mPowerManager
622 .newWakeLock(PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
623 mLaunchingActivity = mPowerManager.newWakeLock(PARTIAL_WAKE_LOCK, "*launch*");
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700624 mLaunchingActivity.setReferenceCounted(false);
Craig Mautner2219a1b2013-03-25 09:44:30 -0700625 }
626
justinzhang5286d3f2014-05-12 17:06:01 -0400627 // This function returns a IStatusBarService. The value is from ServiceManager.
628 // getService and is cached.
629 private IStatusBarService getStatusBarService() {
630 synchronized (mService) {
631 if (mStatusBarService == null) {
632 mStatusBarService = IStatusBarService.Stub.asInterface(
633 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
634 if (mStatusBarService == null) {
635 Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
636 }
637 }
638 return mStatusBarService;
639 }
640 }
641
Jason Monk35c62a42014-06-17 10:24:47 -0400642 private IDevicePolicyManager getDevicePolicyManager() {
643 synchronized (mService) {
644 if (mDevicePolicyManager == null) {
645 mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
646 ServiceManager.checkService(Context.DEVICE_POLICY_SERVICE));
647 if (mDevicePolicyManager == null) {
648 Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
649 }
650 }
651 return mDevicePolicyManager;
652 }
653 }
654
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700655 void setWindowManager(WindowManagerService wm) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800656 synchronized (mService) {
657 mWindowManager = wm;
Jorim Jaggife762342016-10-13 14:33:27 +0200658 mKeyguardController.setWindowManager(wm);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800659
660 mDisplayManager =
661 (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
662 mDisplayManager.registerDisplayListener(this, null);
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800663 mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800664
665 Display[] displays = mDisplayManager.getDisplays();
666 for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
667 final int displayId = displays[displayNdx].getDisplayId();
Craig Mautnere0a38842013-12-16 16:14:02 -0800668 ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
Craig Mautner1a70a162014-09-13 12:09:31 -0700669 if (activityDisplay.mDisplay == null) {
670 throw new IllegalStateException("Default Display does not exist");
671 }
Craig Mautnere0a38842013-12-16 16:14:02 -0800672 mActivityDisplays.put(displayId, activityDisplay);
Filip Gruszczynski7be9a8c2015-10-15 18:20:30 -0700673 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800674 }
675
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800676 mHomeStack = mFocusedStack = mLastFocusedStack =
677 getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Jeff Brownca9bc702014-02-11 14:32:56 -0800678
679 mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800680 }
Craig Mautner27084302013-03-25 08:05:25 -0700681 }
682
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700683 ActivityStack getFocusedStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800684 return mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700685 }
686
Craig Mautnerde4ef022013-04-07 19:01:33 -0700687 ActivityStack getLastStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800688 return mLastFocusedStack;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700689 }
690
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700691 boolean isFocusedStack(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700692 return stack != null && stack == mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700693 }
694
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800695 /** The top most stack on its display. */
696 boolean isFrontStackOnDisplay(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700697 return isFrontOfStackList(stack, stack.getDisplay().mStacks);
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800698 }
699
700 private boolean isFrontOfStackList(ActivityStack stack, List<ActivityStack> stackList) {
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800701 return stack == stackList.get((stackList.size() - 1));
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700702 }
703
Wale Ogunwaled046a012015-12-24 13:05:59 -0800704 /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800705 void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
706 if (!focusCandidate.isFocusable()) {
707 // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
Andrii Kulian7fc22812016-12-28 13:04:11 -0800708 focusCandidate = getNextFocusableStackLocked(focusCandidate);
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800709 }
710
711 if (focusCandidate != mFocusedStack) {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800712 mLastFocusedStack = mFocusedStack;
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800713 mFocusedStack = focusCandidate;
Wale Ogunwalecb82f302015-02-25 07:53:40 -0800714
Wale Ogunwaled046a012015-12-24 13:05:59 -0800715 EventLogTags.writeAmFocusedStack(
716 mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
717 mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
718 }
719
720 final ActivityRecord r = topRunningActivityLocked();
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800721 if (mService.mBooting || !mService.mBooted) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800722 if (r != null && r.idle) {
723 checkFinishBootingLocked();
724 }
725 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700726 }
727
Wale Ogunwale925d0d12015-09-23 15:40:07 -0700728 void moveHomeStackToFront(String reason) {
729 mHomeStack.moveToFront(reason);
730 }
731
Matthew Ng330757d2017-02-28 14:19:17 -0800732 void moveRecentsStackToFront(String reason) {
733 final ActivityStack recentsStack = getStack(RECENTS_STACK_ID);
734 if (recentsStack != null) {
735 recentsStack.moveToFront(reason);
736 }
737 }
738
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700739 /** Returns true if the focus activity was adjusted to the home stack top activity. */
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800740 boolean moveHomeStackTaskToTop(String reason) {
741 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700742
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700743 final ActivityRecord top = getHomeActivity();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700744 if (top == null) {
745 return false;
746 }
Chong Zhang6cda19c2016-06-14 19:07:56 -0700747 moveFocusableActivityStackToFrontLocked(top, reason);
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700748 return true;
Craig Mautner8e569572013-10-11 17:36:59 -0700749 }
750
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800751 boolean resumeHomeStackTask(ActivityRecord prev, String reason) {
Dianne Hackborn7622a0f2014-09-30 14:31:42 -0700752 if (!mService.mBooting && !mService.mBooted) {
753 // Not ready yet!
754 return false;
755 }
756
Craig Mautner84984fa2014-06-19 11:19:20 -0700757 if (prev != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -0700758 prev.getTask().setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
Craig Mautner84984fa2014-06-19 11:19:20 -0700759 }
760
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800761 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700762 ActivityRecord r = getHomeActivity();
Wale Ogunwaled046a012015-12-24 13:05:59 -0800763 final String myReason = reason + " resumeHomeStackTask";
764
Mark Lua56ea122015-10-08 13:31:01 +0800765 // Only resume home activity if isn't finishing.
766 if (r != null && !r.finishing) {
Chong Zhang6cda19c2016-06-14 19:07:56 -0700767 moveFocusableActivityStackToFrontLocked(r, myReason);
Wale Ogunwaled046a012015-12-24 13:05:59 -0800768 return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
Craig Mautner69ada552013-04-18 13:51:51 -0700769 }
Wale Ogunwaled046a012015-12-24 13:05:59 -0800770 return mService.startHomeActivityLocked(mCurrentUser, myReason);
Craig Mautner69ada552013-04-18 13:51:51 -0700771 }
772
Craig Mautner8d341ef2013-03-26 09:03:27 -0700773 TaskRecord anyTaskForIdLocked(int id) {
Winson Chung7900bee2017-03-10 08:59:25 -0800774 return anyTaskForIdLocked(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
775 INVALID_STACK_ID);
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700776 }
777
778 /**
Bryce Lee92b7b652017-04-03 08:33:11 -0700779 * Returns a {@link TaskRecord} for the input id if available. {@code null} otherwise.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700780 * @param id Id of the task we would like returned.
Winson Chung7900bee2017-03-10 08:59:25 -0800781 * @param matchMode The mode to match the given task id in.
Wale Ogunwale3797c222015-10-27 14:21:58 -0700782 * @param stackId The stack to restore the task to (default launch stack will be used if
Winson Chung7900bee2017-03-10 08:59:25 -0800783 * stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}). Only
784 * valid if the matchMode is
785 * {@link #MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE}.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700786 */
Winson Chung7900bee2017-03-10 08:59:25 -0800787 TaskRecord anyTaskForIdLocked(int id, @AnyTaskForIdMatchTaskMode int matchMode, int stackId) {
788 // If there is a stack id set, ensure that we are attempting to actually restore a task
789 if (matchMode != MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE &&
790 stackId != INVALID_STACK_ID) {
791 throw new IllegalArgumentException("Should not specify stackId for non-restore lookup");
792 }
793
Craig Mautnere0a38842013-12-16 16:14:02 -0800794 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800795 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800796 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800797 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
798 ActivityStack stack = stacks.get(stackNdx);
Bryce Lee92b7b652017-04-03 08:33:11 -0700799 final TaskRecord task = stack.taskForIdLocked(id);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800800 if (task != null) {
801 return task;
802 }
Craig Mautner8d341ef2013-03-26 09:03:27 -0700803 }
804 }
Wale Ogunwale7de05352014-12-12 15:21:33 -0800805
Winson Chung7900bee2017-03-10 08:59:25 -0800806 // If we are matching stack tasks only, return now
807 if (matchMode == MATCH_TASK_IN_STACKS_ONLY) {
Wale Ogunwale7de05352014-12-12 15:21:33 -0800808 return null;
809 }
810
Winson Chung7900bee2017-03-10 08:59:25 -0800811 // Otherwise, check the recent tasks and return if we find it there and we are not restoring
812 // the task from recents
813 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
Bryce Lee92b7b652017-04-03 08:33:11 -0700814 final TaskRecord task = mRecentTasks.taskForIdLocked(id);
815
816 if (task == null) {
817 if (DEBUG_RECENTS) {
Winson Chung7900bee2017-03-10 08:59:25 -0800818 Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
819 }
Bryce Lee92b7b652017-04-03 08:33:11 -0700820
821 return null;
822 }
823
824 if (matchMode == MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) {
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700825 return task;
826 }
827
Winson Chung7900bee2017-03-10 08:59:25 -0800828 // Implicitly, this case is MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
Wale Ogunwale7e8184b2015-10-05 14:37:03 -0700829 if (!restoreRecentTaskLocked(task, stackId)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700830 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
831 "Couldn't restore task id=" + id + " found in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800832 return null;
833 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700834 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800835 return task;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700836 }
837
Craig Mautner6170f732013-04-02 13:05:23 -0700838 ActivityRecord isInAnyStackLocked(IBinder token) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800839 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800840 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800841 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800842 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
843 final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
844 if (r != null) {
845 return r;
846 }
Craig Mautner6170f732013-04-02 13:05:23 -0700847 }
848 }
849 return null;
850 }
851
Tony Mak853304c2016-04-18 15:17:41 +0100852 /**
Robin Lee3fef1f22016-12-20 14:50:13 +0000853 * Detects whether we should show a lock screen in front of this task for a locked user.
854 * <p>
855 * We'll do this if either of the following holds:
856 * <ul>
857 * <li>The top activity explicitly belongs to {@param userId}.</li>
858 * <li>The top activity returns a result to an activity belonging to {@param userId}.</li>
859 * </ul>
860 *
861 * @return {@code true} if the top activity looks like it belongs to {@param userId}.
Tony Mak853304c2016-04-18 15:17:41 +0100862 */
Robin Lee3fef1f22016-12-20 14:50:13 +0000863 private boolean taskTopActivityIsUser(TaskRecord task, @UserIdInt int userId) {
864 // To handle the case that work app is in the task but just is not the top one.
865 final ActivityRecord activityRecord = task.getTopActivity();
866 final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null);
867
868 return (activityRecord != null && activityRecord.userId == userId)
869 || (resultTo != null && resultTo.userId == userId);
870 }
871
872 /**
873 * Find all visible task stacks containing {@param userId} and intercept them with an activity
874 * to block out the contents and possibly start a credential-confirming intent.
875 *
876 * @param userId user handle for the locked managed profile.
877 */
878 void lockAllProfileTasks(@UserIdInt int userId) {
879 mWindowManager.deferSurfaceLayout();
880 try {
881 final List<ActivityStack> stacks = getStacks();
882 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; stackNdx--) {
883 final List<TaskRecord> tasks = stacks.get(stackNdx).getAllTasks();
884 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) {
885 final TaskRecord task = tasks.get(taskNdx);
886
887 // Check the task for a top activity belonging to userId, or returning a result
888 // to an activity belonging to userId. Example case: a document picker for
889 // personal files, opened by a work app, should still get locked.
890 if (taskTopActivityIsUser(task, userId)) {
Robin Leec41f6ec2017-01-10 17:02:34 +0000891 mService.mTaskChangeNotificationController.notifyTaskProfileLocked(
892 task.taskId, userId);
Robin Lee3fef1f22016-12-20 14:50:13 +0000893 }
Tony Mak853304c2016-04-18 15:17:41 +0100894 }
895 }
Robin Lee3fef1f22016-12-20 14:50:13 +0000896 } finally {
897 mWindowManager.continueSurfaceLayout();
Tony Mak853304c2016-04-18 15:17:41 +0100898 }
Clara Bayarrif0649ce2016-01-14 12:30:42 +0000899 }
900
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800901 void setNextTaskIdForUserLocked(int taskId, int userId) {
902 final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
903 if (taskId > currentTaskId) {
904 mCurTaskIdForUser.put(userId, taskId);
Craig Mautneref73ee12014-04-23 11:45:37 -0700905 }
906 }
907
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700908 static int nextTaskIdForUser(int taskId, int userId) {
909 int nextTaskId = taskId + 1;
910 if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
911 // Wrap around as there will be smaller task ids that are available now.
912 nextTaskId -= MAX_TASK_IDS_PER_USER;
913 }
914 return nextTaskId;
915 }
916
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800917 int getNextTaskIdForUserLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800918 final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
919 // for a userId u, a taskId can only be in the range
920 // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
921 // 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 -0700922 int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800923 while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
Winson Chung7900bee2017-03-10 08:59:25 -0800924 || anyTaskForIdLocked(candidateTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800925 INVALID_STACK_ID) != null) {
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700926 candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800927 if (candidateTaskId == currentTaskId) {
928 // Something wrong!
929 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
930 throw new IllegalStateException("Cannot get an available task id."
931 + " Reached limit of " + MAX_TASK_IDS_PER_USER
932 + " running tasks per user.");
933 }
934 }
935 mCurTaskIdForUser.put(userId, candidateTaskId);
936 return candidateTaskId;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700937 }
938
Chong Zhang6cda19c2016-06-14 19:07:56 -0700939 ActivityRecord getResumedActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -0800940 ActivityStack stack = mFocusedStack;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700941 if (stack == null) {
942 return null;
943 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700944 ActivityRecord resumedActivity = stack.mResumedActivity;
945 if (resumedActivity == null || resumedActivity.app == null) {
946 resumedActivity = stack.mPausingActivity;
947 if (resumedActivity == null || resumedActivity.app == null) {
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -0700948 resumedActivity = stack.topRunningActivityLocked();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700949 }
950 }
951 return resumedActivity;
952 }
953
Dianne Hackbornff072722014-09-24 10:56:28 -0700954 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
Craig Mautner20e72272013-04-01 13:45:53 -0700955 final String processName = app.processName;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800956 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800957 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
958 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800959 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
960 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700961 if (!isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800962 continue;
963 }
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -0700964 ActivityRecord hr = stack.topRunningActivityLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800965 if (hr != null) {
966 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
967 && processName.equals(hr.processName)) {
968 try {
George Mount2c92c972014-03-20 09:38:23 -0700969 if (realStartActivityLocked(hr, app, true, true)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800970 didSomething = true;
971 }
Dianne Hackbornff072722014-09-24 10:56:28 -0700972 } catch (RemoteException e) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800973 Slog.w(TAG, "Exception in new application when starting activity "
974 + hr.intent.getComponent().flattenToShortString(), e);
975 throw e;
Craig Mautner20e72272013-04-01 13:45:53 -0700976 }
Craig Mautner20e72272013-04-01 13:45:53 -0700977 }
Craig Mautner20e72272013-04-01 13:45:53 -0700978 }
979 }
980 }
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700981 if (!didSomething) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700982 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700983 }
Craig Mautner20e72272013-04-01 13:45:53 -0700984 return didSomething;
985 }
986
987 boolean allResumedActivitiesIdle() {
Craig Mautnere0a38842013-12-16 16:14:02 -0800988 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
989 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800990 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
991 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700992 if (!isFocusedStack(stack) || stack.numActivities() == 0) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800993 continue;
994 }
995 final ActivityRecord resumedActivity = stack.mResumedActivity;
996 if (resumedActivity == null || !resumedActivity.idle) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700997 if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
Craig Mautner34b73df2014-01-12 21:11:08 -0800998 + stack.mStackId + " " + resumedActivity + " not idle");
Craig Mautner4a1cb222013-12-04 16:14:06 -0800999 return false;
1000 }
Craig Mautner20e72272013-04-01 13:45:53 -07001001 }
1002 }
Wei Wang65c7a152016-06-02 18:51:22 -07001003 // Send launch end powerhint when idle
1004 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
Craig Mautner20e72272013-04-01 13:45:53 -07001005 return true;
1006 }
1007
Craig Mautnerde4ef022013-04-07 19:01:33 -07001008 boolean allResumedActivitiesComplete() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001009 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1010 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001011 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1012 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001013 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001014 final ActivityRecord r = stack.mResumedActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001015 if (r != null && r.state != RESUMED) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001016 return false;
1017 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001018 }
1019 }
1020 }
1021 // TODO: Not sure if this should check if all Paused are complete too.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001022 if (DEBUG_STACK) Slog.d(TAG_STACK,
Craig Mautner4a1cb222013-12-04 16:14:06 -08001023 "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
1024 mLastFocusedStack + " to=" + mFocusedStack);
1025 mLastFocusedStack = mFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001026 return true;
1027 }
1028
1029 boolean allResumedActivitiesVisible() {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001030 boolean foundResumed = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001031 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1032 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001033 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1034 final ActivityStack stack = stacks.get(stackNdx);
1035 final ActivityRecord r = stack.mResumedActivity;
riddle_hsudb46d6b2015-04-01 18:58:07 +08001036 if (r != null) {
Bryce Lee4a194382017-04-04 14:32:48 -07001037 if (!r.nowVisible || mActivitiesWaitingForVisibleActivity.contains(r)) {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001038 return false;
1039 }
1040 foundResumed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001041 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001042 }
1043 }
riddle_hsudb46d6b2015-04-01 18:58:07 +08001044 return foundResumed;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001045 }
1046
Craig Mautner2acc3892013-09-23 10:28:14 -07001047 /**
1048 * Pause all activities in either all of the stacks or just the back stacks.
1049 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
Wale Ogunwale950faff2016-08-08 09:51:04 -07001050 * @param resuming The resuming activity.
1051 * @param dontWait The resuming activity isn't going to wait for all activities to be paused
1052 * before resuming.
Craig Mautner2acc3892013-09-23 10:28:14 -07001053 * @return true if any activity was paused as a result of this call.
1054 */
Wale Ogunwale950faff2016-08-08 09:51:04 -07001055 boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
Craig Mautnercf910b02013-04-23 11:23:27 -07001056 boolean someActivityPaused = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001057 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1058 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001059 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1060 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001061 if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001062 if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
Craig Mautner4a1cb222013-12-04 16:14:06 -08001063 " mResumedActivity=" + stack.mResumedActivity);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001064 someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
1065 dontWait);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001066 }
Craig Mautnercf910b02013-04-23 11:23:27 -07001067 }
1068 }
1069 return someActivityPaused;
1070 }
1071
Craig Mautnerde4ef022013-04-07 19:01:33 -07001072 boolean allPausedActivitiesComplete() {
Craig Mautnerac6f8432013-07-17 13:24:59 -07001073 boolean pausing = true;
Craig Mautnere0a38842013-12-16 16:14:02 -08001074 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1075 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001076 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1077 final ActivityStack stack = stacks.get(stackNdx);
1078 final ActivityRecord r = stack.mPausingActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001079 if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001080 if (DEBUG_STATES) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001081 Slog.d(TAG_STATES,
1082 "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001083 pausing = false;
1084 } else {
1085 return false;
1086 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001087 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001088 }
1089 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001090 return pausing;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001091 }
1092
Wale Ogunwale2be760d2016-02-17 11:16:10 -08001093 void cancelInitializingActivities() {
1094 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1095 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1096 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1097 stacks.get(stackNdx).cancelInitializingActivities();
1098 }
1099 }
1100 }
1101
Bryce Lee4a194382017-04-04 14:32:48 -07001102 void waitActivityVisible(ComponentName name, WaitResult result) {
1103 final WaitInfo waitInfo = new WaitInfo(name, result);
1104 mWaitingForActivityVisible.add(waitInfo);
1105 }
1106
1107 void cleanupActivity(ActivityRecord r) {
1108 // Make sure this record is no longer in the pending finishes list.
1109 // This could happen, for example, if we are trimming activities
1110 // down to the max limit while they are still waiting to finish.
1111 mFinishingActivities.remove(r);
1112 mActivitiesWaitingForVisibleActivity.remove(r);
1113
1114 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
Wale Ogunwale3270f172017-04-26 07:29:42 -07001115 if (mWaitingForActivityVisible.get(i).matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001116 mWaitingForActivityVisible.remove(i);
1117 }
1118 }
1119 }
1120
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001121 void reportActivityVisibleLocked(ActivityRecord r) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001122 sendWaitingVisibleReportLocked(r);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001123 }
1124
1125 void sendWaitingVisibleReportLocked(ActivityRecord r) {
1126 boolean changed = false;
Bryce Lee4a194382017-04-04 14:32:48 -07001127 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
1128 final WaitInfo w = mWaitingForActivityVisible.get(i);
Wale Ogunwale3270f172017-04-26 07:29:42 -07001129 if (w.matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001130 final WaitResult result = w.getResult();
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001131 changed = true;
Bryce Lee4a194382017-04-04 14:32:48 -07001132 result.timeout = false;
1133 result.who = w.getComponent();
1134 result.totalTime = SystemClock.uptimeMillis() - result.thisTime;
1135 result.thisTime = result.totalTime;
1136 mWaitingForActivityVisible.remove(w);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001137 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001138 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001139 if (changed) {
1140 mService.notifyAll();
1141 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001142 }
1143
Chong Zhang5022da32016-06-21 16:31:37 -07001144 void reportTaskToFrontNoLaunch(ActivityRecord r) {
1145 boolean changed = false;
1146 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1147 WaitResult w = mWaitingActivityLaunched.remove(i);
1148 if (w.who == null) {
1149 changed = true;
1150 // Set result to START_TASK_TO_FRONT so that startActivityMayWait() knows that
1151 // the starting activity ends up moving another activity to front, and it should
1152 // wait for this new activity to become visible instead.
1153 // Do not modify other fields.
1154 w.result = START_TASK_TO_FRONT;
1155 }
1156 }
1157 if (changed) {
1158 mService.notifyAll();
1159 }
1160 }
1161
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001162 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
1163 long thisTime, long totalTime) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001164 boolean changed = false;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001165 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
Craig Mautnerc64f73e2013-04-24 16:44:56 -07001166 WaitResult w = mWaitingActivityLaunched.remove(i);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001167 if (w.who == null) {
1168 changed = true;
1169 w.timeout = timeout;
1170 if (r != null) {
1171 w.who = new ComponentName(r.info.packageName, r.info.name);
1172 }
1173 w.thisTime = thisTime;
1174 w.totalTime = totalTime;
Chong Zhang5022da32016-06-21 16:31:37 -07001175 // Do not modify w.result.
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001176 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001177 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001178 if (changed) {
1179 mService.notifyAll();
1180 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001181 }
1182
Craig Mautner29219d92013-04-16 20:19:12 -07001183 ActivityRecord topRunningActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -08001184 final ActivityStack focusedStack = mFocusedStack;
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07001185 ActivityRecord r = focusedStack.topRunningActivityLocked();
Craig Mautner1602ec22013-05-12 10:24:27 -07001186 if (r != null) {
1187 return r;
Craig Mautner29219d92013-04-16 20:19:12 -07001188 }
Craig Mautner1602ec22013-05-12 10:24:27 -07001189
Andrii Kulian7318d632016-07-20 18:59:28 -07001190 // Look in other non-focused and non-home stacks.
Andrii Kulian7d95df42017-02-15 10:11:48 -08001191 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
1192
1193 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
1194 final int displayId = mTmpOrderedDisplayIds.get(i);
1195 final List<ActivityStack> stacks = mActivityDisplays.get(displayId).mStacks;
1196 if (stacks == null) {
1197 continue;
1198 }
1199 for (int j = stacks.size() - 1; j >= 0; --j) {
1200 final ActivityStack stack = stacks.get(j);
1201 if (stack != focusedStack && isFrontStackOnDisplay(stack) && stack.isFocusable()) {
1202 r = stack.topRunningActivityLocked();
1203 if (r != null) {
1204 return r;
1205 }
Craig Mautner29219d92013-04-16 20:19:12 -07001206 }
1207 }
1208 }
1209 return null;
1210 }
1211
Dianne Hackborn09233282014-04-30 11:33:59 -07001212 void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001213 // Gather all of the running tasks for each stack into runningTaskLists.
Craig Mautner4a1cb222013-12-04 16:14:06 -08001214 ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1215 new ArrayList<ArrayList<RunningTaskInfo>>();
Craig Mautnere0a38842013-12-16 16:14:02 -08001216 final int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001217 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08001218 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001219 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1220 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautner15df08a2015-04-01 12:17:18 -07001221 ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001222 runningTaskLists.add(stackTaskList);
Dianne Hackborn09233282014-04-30 11:33:59 -07001223 stack.getTasksLocked(stackTaskList, callingUid, allowed);
Craig Mautner20e72272013-04-01 13:45:53 -07001224 }
1225 }
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001226
1227 // The lists are already sorted from most recent to oldest. Just pull the most recent off
1228 // each list and add it to list. Stop when all lists are empty or maxNum reached.
1229 while (maxNum > 0) {
1230 long mostRecentActiveTime = Long.MIN_VALUE;
1231 ArrayList<RunningTaskInfo> selectedStackList = null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001232 final int numTaskLists = runningTaskLists.size();
1233 for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1234 ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001235 if (!stackTaskList.isEmpty()) {
1236 final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1237 if (lastActiveTime > mostRecentActiveTime) {
1238 mostRecentActiveTime = lastActiveTime;
1239 selectedStackList = stackTaskList;
1240 }
1241 }
1242 }
1243 if (selectedStackList != null) {
1244 list.add(selectedStackList.remove(0));
1245 --maxNum;
1246 } else {
1247 break;
1248 }
1249 }
Craig Mautner20e72272013-04-01 13:45:53 -07001250 }
1251
Todd Kennedy7440f172015-12-09 14:31:22 -08001252 ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1253 ProfilerInfo profilerInfo) {
1254 final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
Craig Mautner23ac33b2013-04-01 16:26:35 -07001255 if (aInfo != null) {
1256 // Store the found target back into the intent, because now that
1257 // we have it we never want to do this again. For example, if the
1258 // user navigates back to this point in the history, we should
1259 // always restart the exact same activity.
1260 intent.setComponent(new ComponentName(
1261 aInfo.applicationInfo.packageName, aInfo.name));
1262
1263 // Don't debug things in the system process
Man Caocfa78b22015-06-11 20:14:34 -07001264 if (!aInfo.processName.equals("system")) {
1265 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
Chong Zhangd25944e2016-06-09 16:15:27 -07001266 mService.setDebugApp(aInfo.processName, true, false);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001267 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001268
Tamas Berghammerdf6cb282016-01-29 12:07:00 +00001269 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1270 mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1271 }
1272
Man Caocfa78b22015-06-11 20:14:34 -07001273 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1274 mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1275 }
1276
1277 if (profilerInfo != null) {
Jeff Hao1b012d32014-08-20 10:35:34 -07001278 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001279 }
1280 }
Todd Kennedyb3b431302017-03-20 16:05:48 -07001281 final String intentLaunchToken = intent.getLaunchToken();
1282 if (aInfo.launchToken == null && intentLaunchToken != null) {
1283 aInfo.launchToken = intentLaunchToken;
1284 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001285 }
1286 return aInfo;
1287 }
1288
Todd Kennedy7440f172015-12-09 14:31:22 -08001289 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
Kenny Guyb1b30262016-02-09 16:02:35 +00001290 return resolveIntent(intent, resolvedType, userId, 0);
1291 }
1292
1293 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
Todd Kennedy4d1de7d2017-02-23 10:32:18 -08001294 synchronized (mService) {
1295 return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001296 PackageManager.MATCH_INSTANT | PackageManager.MATCH_DEFAULT_ONLY | flags
Kenny Guyb1b30262016-02-09 16:02:35 +00001297 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Todd Kennedy7440f172015-12-09 14:31:22 -08001298 }
Todd Kennedy7440f172015-12-09 14:31:22 -08001299 }
1300
1301 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1302 ProfilerInfo profilerInfo, int userId) {
1303 final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1304 return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1305 }
1306
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001307 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1308 boolean andResume, boolean checkConfig) throws RemoteException {
1309
1310 if (!allPausedActivitiesComplete()) {
1311 // While there are activities pausing we skipping starting any new activities until
1312 // pauses are complete. NOTE: that we also do this for activities that are starting in
1313 // the paused state because they will first be resumed then paused on the client side.
1314 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1315 "realStartActivityLocked: Skipping start of r=" + r
1316 + " some activities pausing...");
1317 return false;
1318 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001319
Bryce Leeaf691c02017-03-20 14:20:22 -07001320 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07001321 final ActivityStack stack = task.getStack();
chaviw59b98852017-06-13 12:05:44 -07001322
1323 beginDeferResume();
1324
Craig Mautner2420ead2013-04-01 17:13:20 -07001325 try {
chaviw59b98852017-06-13 12:05:44 -07001326 r.startFreezingScreenLocked(app, 0);
1327
1328 // schedule launch ticks to collect information about slow apps.
1329 r.startLaunchTickingLocked();
1330
1331 r.app = app;
1332
1333 // Have the window manager re-evaluate the orientation of the screen based on the new
1334 // activity order. Note that as a result of this, it can call back into the activity
1335 // manager with a new orientation. We don't care about that, because the activity is
1336 // not currently running so we are just restarting it anyway.
1337 if (checkConfig) {
1338 final int displayId = r.getDisplayId();
1339 final Configuration config = mWindowManager.updateOrientationFromAppTokens(
1340 getDisplayOverrideConfiguration(displayId),
1341 r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
1342 // Deferring resume here because we're going to launch new activity shortly.
1343 // We don't want to perform a redundant launch of the same record while ensuring
1344 // configurations and trying to resume top activity of focused stack.
1345 mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
1346 displayId);
Craig Mautner2420ead2013-04-01 17:13:20 -07001347 }
chaviw59b98852017-06-13 12:05:44 -07001348
1349 if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */,
1350 true /* isTop */)) {
1351 // We only set the visibility to true if the activity is allowed to be visible
1352 // based on
1353 // keyguard state. This avoids setting this into motion in window manager that is
1354 // later cancelled due to later calls to ensure visible activities that set
1355 // visibility back to false.
1356 r.setVisibility(true);
Craig Mautner2420ead2013-04-01 17:13:20 -07001357 }
chaviw59b98852017-06-13 12:05:44 -07001358
1359 if (mKeyguardController.isKeyguardLocked()) {
1360 r.notifyUnknownVisibilityLaunched();
Craig Mautner2420ead2013-04-01 17:13:20 -07001361 }
chaviw59b98852017-06-13 12:05:44 -07001362 final int applicationInfoUid =
1363 (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
1364 if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
1365 Slog.wtf(TAG,
1366 "User ID for activity changing for " + r
1367 + " appInfo.uid=" + r.appInfo.uid
1368 + " info.ai.uid=" + applicationInfoUid
1369 + " old=" + r.app + " new=" + app);
1370 }
1371
1372 app.waitingToKill = null;
1373 r.launchCount++;
1374 r.lastLaunchTime = SystemClock.uptimeMillis();
1375
1376 if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1377
1378 int idx = app.activities.indexOf(r);
1379 if (idx < 0) {
1380 app.activities.add(r);
1381 }
1382 mService.updateLruProcessLocked(app, true, null);
1383 mService.updateOomAdjLocked();
1384
1385 if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1386 task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
1387 setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE",
1388 false);
1389 }
1390
1391 try {
1392 if (app.thread == null) {
1393 throw new RemoteException();
1394 }
1395 List<ResultInfo> results = null;
1396 List<ReferrerIntent> newIntents = null;
1397 if (andResume) {
1398 // We don't need to deliver new intents and/or set results if activity is going
1399 // to pause immediately after launch.
1400 results = r.results;
1401 newIntents = r.newIntents;
1402 }
1403 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1404 "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1405 + " newIntents=" + newIntents + " andResume=" + andResume);
1406 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
1407 System.identityHashCode(r), task.taskId, r.shortComponentName);
1408 if (r.isHomeActivity()) {
1409 // Home process is the root process of the task.
1410 mService.mHomeProcess = task.mActivities.get(0).app;
1411 }
1412 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
1413 PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
1414 r.sleeping = false;
1415 r.forceNewConfig = false;
1416 mService.showUnsupportedZoomDialogIfNeededLocked(r);
1417 mService.showAskCompatModeDialogLocked(r);
1418 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1419 ProfilerInfo profilerInfo = null;
1420 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1421 if (mService.mProfileProc == null || mService.mProfileProc == app) {
1422 mService.mProfileProc = app;
Andreas Gampe2b073a02017-06-22 17:28:57 -07001423 ProfilerInfo profilerInfoSvc = mService.mProfilerInfo;
1424 if (profilerInfoSvc != null && profilerInfoSvc.profileFile != null) {
1425 if (profilerInfoSvc.profileFd != null) {
chaviw59b98852017-06-13 12:05:44 -07001426 try {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001427 profilerInfoSvc.profileFd = profilerInfoSvc.profileFd.dup();
chaviw59b98852017-06-13 12:05:44 -07001428 } catch (IOException e) {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001429 profilerInfoSvc.closeFd();
Craig Mautner2568c3a2015-03-26 14:22:34 -07001430 }
1431 }
chaviw59b98852017-06-13 12:05:44 -07001432
Andreas Gampe2b073a02017-06-22 17:28:57 -07001433 profilerInfo = new ProfilerInfo(profilerInfoSvc);
Craig Mautner2420ead2013-04-01 17:13:20 -07001434 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001435 }
1436 }
Adam Powellcfbe9be2013-11-06 14:58:58 -08001437
chaviw59b98852017-06-13 12:05:44 -07001438 app.hasShownUi = true;
1439 app.pendingUiClean = true;
1440 app.forceProcessStateUpTo(mService.mTopProcessState);
1441 // Because we could be starting an Activity in the system process this may not go
1442 // across a Binder interface which would create a new Configuration. Consequently
1443 // we have to always create a new Configuration here.
Bryce Leea163b762017-01-24 11:05:01 -08001444
chaviw59b98852017-06-13 12:05:44 -07001445 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
1446 mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
1447 r.setLastReportedConfiguration(mergedConfiguration);
Bryce Leea163b762017-01-24 11:05:01 -08001448
chaviw59b98852017-06-13 12:05:44 -07001449 logIfTransactionTooLarge(r.intent, r.icicle);
1450 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1451 System.identityHashCode(r), r.info,
1452 // TODO: Have this take the merged configuration instead of separate global
1453 // and override configs.
1454 mergedConfiguration.getGlobalConfiguration(),
1455 mergedConfiguration.getOverrideConfiguration(), r.compat,
1456 r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1457 r.persistentState, results, newIntents, !andResume,
1458 mService.isNextTransitionForward(), profilerInfo);
Craig Mautner2420ead2013-04-01 17:13:20 -07001459
chaviw59b98852017-06-13 12:05:44 -07001460 if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1461 // This may be a heavy-weight process! Note that the package
1462 // manager will ensure that only activity can run in the main
1463 // process of the .apk, which is the only thing that will be
1464 // considered heavy-weight.
1465 if (app.processName.equals(app.info.packageName)) {
1466 if (mService.mHeavyWeightProcess != null
1467 && mService.mHeavyWeightProcess != app) {
1468 Slog.w(TAG, "Starting new heavy weight process " + app
1469 + " when already running "
1470 + mService.mHeavyWeightProcess);
1471 }
1472 mService.mHeavyWeightProcess = app;
1473 Message msg = mService.mHandler.obtainMessage(
1474 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1475 msg.obj = r;
1476 mService.mHandler.sendMessage(msg);
Craig Mautner2420ead2013-04-01 17:13:20 -07001477 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001478 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001479
chaviw59b98852017-06-13 12:05:44 -07001480 } catch (RemoteException e) {
1481 if (r.launchFailed) {
1482 // This is the second time we failed -- finish activity
1483 // and give up.
1484 Slog.e(TAG, "Second failure launching "
1485 + r.intent.getComponent().flattenToShortString()
1486 + ", giving up", e);
1487 mService.appDiedLocked(app);
1488 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1489 "2nd-crash", false);
1490 return false;
1491 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001492
chaviw59b98852017-06-13 12:05:44 -07001493 // This is the first time we failed -- restart process and
1494 // retry.
1495 r.launchFailed = true;
1496 app.activities.remove(r);
1497 throw e;
1498 }
1499 } finally {
1500 endDeferResume();
Craig Mautner2420ead2013-04-01 17:13:20 -07001501 }
1502
1503 r.launchFailed = false;
1504 if (stack.updateLRUListLocked(r)) {
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07001505 Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
Craig Mautner2420ead2013-04-01 17:13:20 -07001506 }
1507
chaviw59b98852017-06-13 12:05:44 -07001508 if (andResume && readyToResume()) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001509 // As part of the process of launching, ActivityThread also performs
1510 // a resume.
1511 stack.minimalResumeActivityLocked(r);
1512 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001513 // This activity is not starting in the resumed state... which should look like we asked
Wale Ogunwale919a05d2017-04-13 00:36:34 +00001514 // it to pause+stop (but remain visible), and it has done so and reported back the
Wale Ogunwaled046a012015-12-24 13:05:59 -08001515 // current icicle and other state.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001516 if (DEBUG_STATES) Slog.v(TAG_STATES,
Wale Ogunwaled046a012015-12-24 13:05:59 -08001517 "Moving to PAUSED: " + r + " (starting in paused state)");
1518 r.state = PAUSED;
Craig Mautner2420ead2013-04-01 17:13:20 -07001519 }
1520
1521 // Launch the new version setup screen if needed. We do this -after-
1522 // launching the initial activity (that is, home), so that it can have
1523 // a chance to initialize itself while in the background, making the
1524 // switch back to it faster and look better.
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001525 if (isFocusedStack(stack)) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001526 mService.startSetupActivityLocked();
1527 }
1528
Dianne Hackborn465fa392014-09-14 14:21:18 -07001529 // Update any services we are bound to that might care about whether
1530 // their client may have activities.
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001531 if (r.app != null) {
1532 mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1533 }
Dianne Hackborn465fa392014-09-14 14:21:18 -07001534
Craig Mautner2420ead2013-04-01 17:13:20 -07001535 return true;
1536 }
1537
Sudheer Shankafab200f2017-05-17 20:41:53 -07001538 private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
1539 int extrasSize = 0;
1540 if (intent != null) {
1541 final Bundle extras = intent.getExtras();
1542 if (extras != null) {
1543 extrasSize = extras.getSize();
1544 }
1545 }
1546 int icicleSize = (icicle == null ? 0 : icicle.getSize());
1547 if (extrasSize + icicleSize > 200000) {
1548 Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
1549 + ", icicle size: " + icicleSize);
1550 }
1551 }
1552
Craig Mautnere79d42682013-04-01 19:01:53 -07001553 void startSpecificActivityLocked(ActivityRecord r,
George Mount2c92c972014-03-20 09:38:23 -07001554 boolean andResume, boolean checkConfig) {
Craig Mautnere79d42682013-04-01 19:01:53 -07001555 // Is this activity's application already running?
1556 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001557 r.info.applicationInfo.uid, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001558
Andrii Kulian02b7a832016-10-06 23:11:56 -07001559 r.getStack().setLaunchTime(r);
Craig Mautnere79d42682013-04-01 19:01:53 -07001560
1561 if (app != null && app.thread != null) {
1562 try {
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001563 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1564 || !"android".equals(r.info.packageName)) {
1565 // Don't add this if it is a platform component that is marked
1566 // to run in multiple processes, because this is actually
1567 // part of the framework so doesn't make sense to track as a
1568 // separate apk in the process.
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001569 app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1570 mService.mProcessStats);
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001571 }
George Mount2c92c972014-03-20 09:38:23 -07001572 realStartActivityLocked(r, app, andResume, checkConfig);
Craig Mautnere79d42682013-04-01 19:01:53 -07001573 return;
1574 } catch (RemoteException e) {
1575 Slog.w(TAG, "Exception when starting activity "
1576 + r.intent.getComponent().flattenToShortString(), e);
1577 }
1578
1579 // If a dead object exception was thrown -- fall through to
1580 // restart the application.
1581 }
1582
1583 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001584 "activity", r.intent.getComponent(), false, false, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001585 }
1586
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001587 boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001588 String resultWho, int requestCode, int callingPid, int callingUid,
1589 String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
Jorim Jaggi2adba072016-03-03 13:43:39 +01001590 ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001591 final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1592 callingUid);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001593 if (startAnyPerm == PERMISSION_GRANTED) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001594 return true;
1595 }
1596 final int componentRestriction = getComponentRestrictionForCallingPackage(
1597 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1598 final int actionRestriction = getActionRestrictionForCallingPackage(
1599 intent.getAction(), callingPackage, callingPid, callingUid);
1600 if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1601 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1602 if (resultRecord != null) {
1603 resultStack.sendActivityResultLocked(-1,
1604 resultRecord, resultWho, requestCode,
1605 Activity.RESULT_CANCELED, null);
1606 }
1607 final String msg;
1608 if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1609 msg = "Permission Denial: starting " + intent.toString()
1610 + " from " + callerApp + " (pid=" + callingPid
1611 + ", uid=" + callingUid + ")" + " with revoked permission "
1612 + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1613 } else if (!aInfo.exported) {
1614 msg = "Permission Denial: starting " + intent.toString()
1615 + " from " + callerApp + " (pid=" + callingPid
1616 + ", uid=" + callingUid + ")"
1617 + " not exported from uid " + aInfo.applicationInfo.uid;
1618 } else {
1619 msg = "Permission Denial: starting " + intent.toString()
1620 + " from " + callerApp + " (pid=" + callingPid
1621 + ", uid=" + callingUid + ")"
1622 + " requires " + aInfo.permission;
1623 }
1624 Slog.w(TAG, msg);
1625 throw new SecurityException(msg);
1626 }
1627
1628 if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1629 final String message = "Appop Denial: starting " + intent.toString()
1630 + " from " + callerApp + " (pid=" + callingPid
1631 + ", uid=" + callingUid + ")"
1632 + " requires " + AppOpsManager.permissionToOp(
1633 ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1634 Slog.w(TAG, message);
1635 return false;
1636 } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1637 final String message = "Appop Denial: starting " + intent.toString()
1638 + " from " + callerApp + " (pid=" + callingPid
1639 + ", uid=" + callingUid + ")"
1640 + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1641 Slog.w(TAG, message);
1642 return false;
1643 }
Andrii Kulian16802aa2016-11-02 12:21:33 -07001644 if (options != null) {
1645 if (options.getLaunchTaskId() != INVALID_STACK_ID) {
1646 final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1647 callingPid, callingUid);
1648 if (startInTaskPerm != PERMISSION_GRANTED) {
1649 final String msg = "Permission Denial: starting " + intent.toString()
1650 + " from " + callerApp + " (pid=" + callingPid
1651 + ", uid=" + callingUid + ") with launchTaskId="
1652 + options.getLaunchTaskId();
1653 Slog.w(TAG, msg);
1654 throw new SecurityException(msg);
1655 }
1656 }
1657 // Check if someone tries to launch an activity on a private display with a different
1658 // owner.
1659 final int launchDisplayId = options.getLaunchDisplayId();
Andrii Kulian02689a72017-07-06 14:28:59 -07001660 if (launchDisplayId != INVALID_DISPLAY && !isCallerAllowedToLaunchOnDisplay(callingPid,
1661 callingUid, launchDisplayId, aInfo)) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001662 final String msg = "Permission Denial: starting " + intent.toString()
1663 + " from " + callerApp + " (pid=" + callingPid
1664 + ", uid=" + callingUid + ") with launchDisplayId="
1665 + launchDisplayId;
1666 Slog.w(TAG, msg);
1667 throw new SecurityException(msg);
Jorim Jaggi2adba072016-03-03 13:43:39 +01001668 }
1669 }
1670
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001671 return true;
1672 }
1673
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001674 /** Check if caller is allowed to launch activities on specified display. */
Andrii Kulian02689a72017-07-06 14:28:59 -07001675 boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId,
1676 ActivityInfo aInfo) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001677 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId
1678 + " callingPid=" + callingPid + " callingUid=" + callingUid);
1679
Andrii Kulian02689a72017-07-06 14:28:59 -07001680 if (callingPid == -1 && callingUid == -1) {
1681 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: no caller info, skip check");
1682 return true;
1683 }
1684
Andrii Kulian62e6f252017-05-30 22:46:53 -07001685 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(launchDisplayId);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001686 if (activityDisplay == null) {
1687 Slog.w(TAG, "Launch on display check: display not found");
1688 return false;
1689 }
1690
Andrii Kulian02689a72017-07-06 14:28:59 -07001691 // Check if the caller has enough privileges to embed activities and launch to private
1692 // displays.
Andrii Kulian3a95edc2017-06-28 16:21:07 -07001693 final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001694 callingUid);
1695 if (startAnyPerm == PERMISSION_GRANTED) {
1696 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1697 + " allow launch any on display");
1698 return true;
1699 }
1700
1701 if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL
Andrii Kulian02689a72017-07-06 14:28:59 -07001702 && activityDisplay.mDisplay.getOwnerUid() != SYSTEM_UID
1703 && activityDisplay.mDisplay.getOwnerUid() != aInfo.applicationInfo.uid) {
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001704 // Limit launching on virtual displays, because their contents can be read from Surface
1705 // by apps that created them.
Andrii Kulian02689a72017-07-06 14:28:59 -07001706 if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
1707 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1708 + " disallow launch on virtual display for not-embedded activity.");
1709 return false;
1710 }
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001711 }
1712
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001713 if (!activityDisplay.isPrivate()) {
1714 // Anyone can launch on a public display.
1715 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1716 + " allow launch on public display");
1717 return true;
1718 }
1719
1720 // Check if the caller is the owner of the display.
1721 if (activityDisplay.mDisplay.getOwnerUid() == callingUid) {
1722 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1723 + " allow launch for owner of the display");
1724 return true;
1725 }
1726
1727 // Check if caller is present on display
1728 if (activityDisplay.isUidPresent(callingUid)) {
1729 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1730 + " allow launch for caller present on the display");
1731 return true;
1732 }
1733
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001734 Slog.w(TAG, "Launch on display check: denied");
1735 return false;
1736 }
1737
1738 /** Update lists of UIDs that are present on displays and have access to them. */
1739 void updateUIDsPresentOnDisplay() {
1740 mDisplayAccessUIDs.clear();
1741 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1742 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
David Stevens82ea6cb2017-03-03 16:18:50 -08001743 // Only bother calculating the whitelist for private displays
1744 if (activityDisplay.isPrivate()) {
1745 mDisplayAccessUIDs.append(
1746 activityDisplay.mDisplayId, activityDisplay.getPresentUIDs());
1747 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001748 }
1749 // Store updated lists in DisplayManager. Callers from outside of AM should get them there.
1750 mDisplayManagerInternal.setDisplayAccessUIDs(mDisplayAccessUIDs);
1751 }
1752
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001753 UserInfo getUserInfo(int userId) {
Clara Bayarrif7fea162015-10-22 16:09:52 +01001754 final long identity = Binder.clearCallingIdentity();
1755 try {
1756 return UserManager.get(mService.mContext).getUserInfo(userId);
1757 } finally {
1758 Binder.restoreCallingIdentity(identity);
1759 }
1760 }
1761
Svet Ganov99b60432015-06-27 13:15:22 -07001762 private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001763 String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001764 if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1765 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
Svet Ganov99b60432015-06-27 13:15:22 -07001766 == PackageManager.PERMISSION_DENIED) {
1767 return ACTIVITY_RESTRICTION_PERMISSION;
1768 }
1769
Christopher Tateff7add02015-08-17 10:23:22 -07001770 if (activityInfo.permission == null) {
1771 return ACTIVITY_RESTRICTION_NONE;
1772 }
1773
Svet Ganov99b60432015-06-27 13:15:22 -07001774 final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1775 if (opCode == AppOpsManager.OP_NONE) {
1776 return ACTIVITY_RESTRICTION_NONE;
1777 }
1778
1779 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1780 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001781 if (!ignoreTargetSecurity) {
1782 return ACTIVITY_RESTRICTION_APPOP;
1783 }
Svet Ganov99b60432015-06-27 13:15:22 -07001784 }
1785
1786 return ACTIVITY_RESTRICTION_NONE;
1787 }
1788
Svetoslav7008b512015-06-24 18:47:07 -07001789 private int getActionRestrictionForCallingPackage(String action,
1790 String callingPackage, int callingPid, int callingUid) {
1791 if (action == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001792 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001793 }
1794
1795 String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1796 if (permission == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001797 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001798 }
1799
1800 final PackageInfo packageInfo;
1801 try {
1802 packageInfo = mService.mContext.getPackageManager()
1803 .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1804 } catch (PackageManager.NameNotFoundException e) {
1805 Slog.i(TAG, "Cannot find package info for " + callingPackage);
Svet Ganov99b60432015-06-27 13:15:22 -07001806 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001807 }
1808
1809 if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
Svet Ganov99b60432015-06-27 13:15:22 -07001810 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001811 }
1812
1813 if (mService.checkPermission(permission, callingPid, callingUid) ==
1814 PackageManager.PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001815 return ACTIVITY_RESTRICTION_PERMISSION;
Svetoslav7008b512015-06-24 18:47:07 -07001816 }
1817
1818 final int opCode = AppOpsManager.permissionToOpCode(permission);
1819 if (opCode == AppOpsManager.OP_NONE) {
Svet Ganov99b60432015-06-27 13:15:22 -07001820 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001821 }
1822
1823 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1824 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001825 return ACTIVITY_RESTRICTION_APPOP;
Svetoslav7008b512015-06-24 18:47:07 -07001826 }
1827
Svet Ganov99b60432015-06-27 13:15:22 -07001828 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001829 }
1830
Dianne Hackborn3d07c942015-03-13 18:02:54 -07001831 void setLaunchSource(int uid) {
1832 mLaunchingActivity.setWorkSource(new WorkSource(uid));
1833 }
1834
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001835 void acquireLaunchWakelock() {
1836 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1837 throw new IllegalStateException("Calling must be system uid");
1838 }
1839 mLaunchingActivity.acquire();
1840 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1841 // To be safe, don't allow the wake lock to be held for too long.
1842 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1843 }
1844 }
1845
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001846 /**
1847 * Called when the frontmost task is idle.
1848 * @return the state of mService.mBooting before this was called.
1849 */
1850 private boolean checkFinishBootingLocked() {
1851 final boolean booting = mService.mBooting;
1852 boolean enableScreen = false;
1853 mService.mBooting = false;
1854 if (!mService.mBooted) {
1855 mService.mBooted = true;
1856 enableScreen = true;
1857 }
1858 if (booting || enableScreen) {
1859 mService.postFinishBooting(booting, enableScreen);
1860 }
1861 return booting;
1862 }
1863
Craig Mautnerf3333272013-04-22 10:55:53 -07001864 // Checked.
1865 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
Winson Chung4dabf232017-01-25 13:25:22 -08001866 boolean processPausingActivities, Configuration config) {
Wale Ogunwalee23149f2015-03-06 15:39:44 -08001867 if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001868
Craig Mautnerf3333272013-04-22 10:55:53 -07001869 ArrayList<ActivityRecord> finishes = null;
Amith Yamasani37a40c22015-06-17 13:25:42 -07001870 ArrayList<UserState> startingUsers = null;
Craig Mautnerf3333272013-04-22 10:55:53 -07001871 int NS = 0;
1872 int NF = 0;
Craig Mautnerf3333272013-04-22 10:55:53 -07001873 boolean booting = false;
Craig Mautnerf3333272013-04-22 10:55:53 -07001874 boolean activityRemoved = false;
1875
Wale Ogunwale7d701172015-03-11 15:36:30 -07001876 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001877 if (r != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001878 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1879 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07001880 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1881 r.finishLaunchTickingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001882 if (fromTimeout) {
1883 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
Craig Mautnerf3333272013-04-22 10:55:53 -07001884 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001885
1886 // This is a hack to semi-deal with a race condition
1887 // in the client where it can be constructed with a
1888 // newer configuration from when we asked it to launch.
1889 // We'll update with whatever configuration it now says
1890 // it used to launch.
1891 if (config != null) {
Bryce Leea163b762017-01-24 11:05:01 -08001892 r.setLastReportedGlobalConfiguration(config);
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001893 }
1894
1895 // We are now idle. If someone is waiting for a thumbnail from
1896 // us, we can now deliver.
1897 r.idle = true;
1898
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001899 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001900 if (isFocusedStack(r.getStack()) || fromTimeout) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001901 booting = checkFinishBootingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001902 }
1903 }
1904
1905 if (allResumedActivitiesIdle()) {
1906 if (r != null) {
1907 mService.scheduleAppGcsLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001908 }
1909
1910 if (mLaunchingActivity.isHeld()) {
1911 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1912 if (VALIDATE_WAKE_LOCK_CALLER &&
1913 Binder.getCallingUid() != Process.myUid()) {
1914 throw new IllegalStateException("Calling must be system uid");
1915 }
1916 mLaunchingActivity.release();
1917 }
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07001918 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerf3333272013-04-22 10:55:53 -07001919 }
1920
1921 // Atomically retrieve all of the other things to do.
Winson Chung4dabf232017-01-25 13:25:22 -08001922 final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
1923 true /* remove */, processPausingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001924 NS = stops != null ? stops.size() : 0;
Wale Ogunwale7d701172015-03-11 15:36:30 -07001925 if ((NF = mFinishingActivities.size()) > 0) {
1926 finishes = new ArrayList<>(mFinishingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001927 mFinishingActivities.clear();
1928 }
1929
Craig Mautnerf3333272013-04-22 10:55:53 -07001930 if (mStartingUsers.size() > 0) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07001931 startingUsers = new ArrayList<>(mStartingUsers);
Craig Mautnerf3333272013-04-22 10:55:53 -07001932 mStartingUsers.clear();
1933 }
1934
Craig Mautnerf3333272013-04-22 10:55:53 -07001935 // Stop any activities that are scheduled to do so but have been
1936 // waiting for the next one to start.
1937 for (int i = 0; i < NS; i++) {
1938 r = stops.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001939 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001940 if (stack != null) {
1941 if (r.finishing) {
1942 stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1943 } else {
1944 stack.stopActivityLocked(r);
1945 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001946 }
1947 }
1948
1949 // Finish any activities that are scheduled to do so but have been
1950 // waiting for the next one to start.
1951 for (int i = 0; i < NF; i++) {
1952 r = finishes.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001953 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001954 if (stack != null) {
1955 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1956 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001957 }
1958
Dianne Hackborn7622a0f2014-09-30 14:31:42 -07001959 if (!booting) {
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001960 // Complete user switch
1961 if (startingUsers != null) {
1962 for (int i = 0; i < startingUsers.size(); i++) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001963 mService.mUserController.finishUserSwitch(startingUsers.get(i));
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001964 }
1965 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001966 }
1967
1968 mService.trimApplications();
1969 //dump();
1970 //mWindowManager.dump();
1971
Craig Mautnerf3333272013-04-22 10:55:53 -07001972 if (activityRemoved) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001973 resumeFocusedStackTopActivityLocked();
Craig Mautnerf3333272013-04-22 10:55:53 -07001974 }
1975
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001976 return r;
Craig Mautnerf3333272013-04-22 10:55:53 -07001977 }
1978
Craig Mautner8e569572013-10-11 17:36:59 -07001979 boolean handleAppDiedLocked(ProcessRecord app) {
Craig Mautner19091252013-10-05 00:03:53 -07001980 boolean hasVisibleActivities = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001981 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1982 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001983 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1984 hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
1985 }
Craig Mautner6b74cb52013-09-27 17:02:21 -07001986 }
Craig Mautner19091252013-10-05 00:03:53 -07001987 return hasVisibleActivities;
Craig Mautner8d341ef2013-03-26 09:03:27 -07001988 }
1989
1990 void closeSystemDialogsLocked() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001991 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1992 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001993 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1994 stacks.get(stackNdx).closeSystemDialogsLocked();
1995 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07001996 }
1997 }
1998
Craig Mautner93529a42013-10-04 15:03:13 -07001999 void removeUserLocked(int userId) {
Craig Mautner4f1df4f2013-10-15 15:44:14 -07002000 mUserStackInFront.delete(userId);
Craig Mautner93529a42013-10-04 15:03:13 -07002001 }
2002
Craig Mautner8d341ef2013-03-26 09:03:27 -07002003 /**
Chong Zhang45c25ce2015-08-10 22:18:26 -07002004 * Update the last used stack id for non-current user (current user's last
2005 * used stack is the focused stack)
2006 */
2007 void updateUserStackLocked(int userId, ActivityStack stack) {
2008 if (userId != mCurrentUser) {
2009 mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
2010 }
2011 }
2012
2013 /**
Craig Mautner8d341ef2013-03-26 09:03:27 -07002014 * @return true if some activity was finished (or would have finished if doit were true).
2015 */
Wale Ogunwale540e1232015-05-01 15:35:39 -07002016 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
2017 boolean doit, boolean evenPersistent, int userId) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07002018 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08002019 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2020 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
louis_chang8f0555a2015-10-27 10:45:53 +08002021 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002022 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002023 if (stack.finishDisabledPackageActivitiesLocked(
2024 packageName, filterByClasses, doit, evenPersistent, userId)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002025 didSomething = true;
2026 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002027 }
2028 }
2029 return didSomething;
2030 }
2031
Dianne Hackborna413dc02013-07-12 12:02:55 -07002032 void updatePreviousProcessLocked(ActivityRecord r) {
2033 // Now that this process has stopped, we may want to consider
2034 // it to be the previous app to try to keep around in case
2035 // the user wants to return to it.
2036
2037 // First, found out what is currently the foreground app, so that
2038 // we don't blow away the previous app if this activity is being
2039 // hosted by the process that is actually still the foreground.
2040 ProcessRecord fgApp = null;
Craig Mautnere0a38842013-12-16 16:14:02 -08002041 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2042 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002043 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2044 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07002045 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002046 if (stack.mResumedActivity != null) {
2047 fgApp = stack.mResumedActivity.app;
2048 } else if (stack.mPausingActivity != null) {
2049 fgApp = stack.mPausingActivity.app;
2050 }
2051 break;
Dianne Hackborna413dc02013-07-12 12:02:55 -07002052 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07002053 }
2054 }
2055
2056 // Now set this one as the previous process, only if that really
2057 // makes sense to.
2058 if (r.app != null && fgApp != null && r.app != fgApp
2059 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
Craig Mautner4ef26932013-09-18 15:15:52 -07002060 && r.app != mService.mHomeProcess) {
Dianne Hackborna413dc02013-07-12 12:02:55 -07002061 mService.mPreviousProcess = r.app;
2062 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
2063 }
2064 }
2065
Wale Ogunwaled046a012015-12-24 13:05:59 -08002066 boolean resumeFocusedStackTopActivityLocked() {
2067 return resumeFocusedStackTopActivityLocked(null, null, null);
Craig Mautner05d29032013-05-03 13:40:13 -07002068 }
2069
Wale Ogunwaled046a012015-12-24 13:05:59 -08002070 boolean resumeFocusedStackTopActivityLocked(
Chong Zhang280d3322015-11-03 17:27:26 -08002071 ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
chaviw59b98852017-06-13 12:05:44 -07002072
2073 if (!readyToResume()) {
2074 return false;
2075 }
2076
Wale Ogunwaled046a012015-12-24 13:05:59 -08002077 if (targetStack != null && isFocusedStack(targetStack)) {
2078 return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
Craig Mautner05d29032013-05-03 13:40:13 -07002079 }
chaviw59b98852017-06-13 12:05:44 -07002080
Wale Ogunwale06579d62016-04-30 15:29:06 -07002081 final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2082 if (r == null || r.state != RESUMED) {
2083 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
skuhne@google.com1b974dc2016-12-09 13:41:29 -08002084 } else if (r.state == RESUMED) {
2085 // Kick off any lingering app transitions form the MoveTaskToFront operation.
2086 mFocusedStack.executeAppTransition(targetOptions);
Wale Ogunwale06579d62016-04-30 15:29:06 -07002087 }
chaviw59b98852017-06-13 12:05:44 -07002088
Wale Ogunwaled046a012015-12-24 13:05:59 -08002089 return false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002090 }
2091
Todd Kennedy39bfee52016-02-24 10:28:21 -08002092 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
2093 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2094 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2095 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2096 stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
2097 }
2098 }
2099 }
2100
Adrian Roos20d7df32016-01-12 18:59:43 +01002101 TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
2102 TaskRecord finishedTask = null;
2103 ActivityStack focusedStack = getFocusedStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08002104 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2105 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002106 final int numStacks = stacks.size();
2107 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2108 final ActivityStack stack = stacks.get(stackNdx);
Adrian Roos20d7df32016-01-12 18:59:43 +01002109 TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
2110 if (stack == focusedStack || finishedTask == null) {
2111 finishedTask = t;
2112 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08002113 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002114 }
Adrian Roos20d7df32016-01-12 18:59:43 +01002115 return finishedTask;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002116 }
2117
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07002118 void finishVoiceTask(IVoiceInteractionSession session) {
2119 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2120 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2121 final int numStacks = stacks.size();
2122 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2123 final ActivityStack stack = stacks.get(stackNdx);
2124 stack.finishVoiceTask(session);
2125 }
2126 }
2127 }
2128
Andrii Kulianc27916642016-04-12 17:59:27 -07002129 void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
2130 String reason, boolean forceNonResizeable) {
Craig Mautneraea74a52014-03-08 14:23:10 -08002131 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
2132 mUserLeaving = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002133 }
Craig Mautneraea74a52014-03-08 14:23:10 -08002134 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
2135 // Caller wants the home activity moved with it. To accomplish this,
2136 // we'll just indicate that this task returns to the home task.
Craig Mautner84984fa2014-06-19 11:19:20 -07002137 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
Craig Mautneraea74a52014-03-08 14:23:10 -08002138 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002139 ActivityStack currentStack = task.getStack();
2140 if (currentStack == null) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07002141 Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
2142 + task + " to front. Stack is null");
2143 return;
2144 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002145
Wale Ogunwaleb1faf602016-01-27 09:12:31 -08002146 if (task.isResizeable() && options != null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002147 int stackId = options.getLaunchStackId();
2148 if (canUseActivityOptionsLaunchBounds(options, stackId)) {
Filip Gruszczynskidce2d162016-01-12 15:40:13 -08002149 final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
Chong Zhang0fa656b2015-08-31 15:17:21 -07002150 task.updateOverrideConfiguration(bounds);
Wale Ogunwale854809c2015-12-27 16:18:19 -08002151 if (stackId == INVALID_STACK_ID) {
2152 stackId = task.getLaunchStackId();
2153 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002154 if (stackId != currentStack.mStackId) {
Winson Chung74666102017-02-22 17:49:24 -08002155 task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE,
2156 DEFER_RESUME, "findTaskToMoveToFrontLocked");
Andrii Kulian02b7a832016-10-06 23:11:56 -07002157 stackId = currentStack.mStackId;
Chong Zhang112eb8c2015-11-02 11:17:00 -08002158 // moveTaskToStackUncheckedLocked() should already placed the task on top,
2159 // still need moveTaskToFrontLocked() below for any transition settings.
2160 }
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002161 if (StackId.resizeStackWithLaunchBounds(stackId)) {
2162 resizeStackLocked(stackId, bounds,
2163 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002164 !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002165 } else {
2166 // WM resizeTask must be done after the task is moved to the correct stack,
2167 // because Task's setBounds() also updates dim layer's bounds, but that has
2168 // dependency on the stack.
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002169 task.resizeWindowContainer();
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002170 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002171 }
2172 }
2173
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002174 final ActivityRecord r = task.getTopActivity();
Andrii Kulian02b7a832016-10-06 23:11:56 -07002175 currentStack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002176 r == null ? null : r.appTimeTracker, reason);
2177
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002178 if (DEBUG_STACK) Slog.d(TAG_STACK,
Andrii Kulian02b7a832016-10-06 23:11:56 -07002179 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
Jorim Jaggi2adba072016-03-03 13:43:39 +01002180
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002181 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
2182 currentStack.mStackId, forceNonResizeable);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002183 }
2184
Wale Ogunwale854809c2015-12-27 16:18:19 -08002185 boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002186 // We use the launch bounds in the activity options is the device supports freeform
Wale Ogunwale854809c2015-12-27 16:18:19 -08002187 // window management or is launching into the pinned stack.
Wale Ogunwale5122df02016-01-29 22:33:38 -08002188 if (options.getLaunchBounds() == null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002189 return false;
2190 }
2191 return (mService.mSupportsPictureInPicture && launchStackId == PINNED_STACK_ID)
2192 || mService.mSupportsFreeformWindowManagement;
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002193 }
2194
Winson Chung55893332017-02-17 17:13:10 -08002195 protected <T extends ActivityStack> T getStack(int stackId) {
Wale Ogunwale040b4702015-08-06 18:10:50 -07002196 return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002197 }
2198
Winson Chung55893332017-02-17 17:13:10 -08002199 protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
2200 boolean createOnTop) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002201 final ActivityStack stack = mStacks.get(stackId);
2202 if (stack != null) {
2203 return (T) stack;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002204 }
Wale Ogunwale3797c222015-10-27 14:21:58 -07002205 if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002206 return null;
2207 }
Matthew Ng330757d2017-02-28 14:19:17 -08002208 if (stackId == DOCKED_STACK_ID) {
2209 // Make sure recents stack exist when creating a dock stack as it normally need to be on
2210 // the other side of the docked stack and we make visibility decisions based on that.
2211 getStack(RECENTS_STACK_ID, CREATE_IF_NEEDED, createOnTop);
2212 }
Winson Chung55893332017-02-17 17:13:10 -08002213 return (T) createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002214 }
2215
Andrii Kulian16802aa2016-11-02 12:21:33 -07002216 /**
2217 * Get a topmost stack on the display, that is a valid launch stack for specified activity.
2218 * If there is no such stack, new dynamic stack can be created.
2219 * @param displayId Target display.
2220 * @param r Activity that should be launched there.
2221 * @return Existing stack if there is a valid one, new dynamic stack if it is valid or null.
2222 */
2223 ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002224 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian16802aa2016-11-02 12:21:33 -07002225 if (activityDisplay == null) {
2226 throw new IllegalArgumentException(
2227 "Display with displayId=" + displayId + " not found.");
2228 }
2229
2230 // Return the topmost valid stack on the display.
2231 for (int i = activityDisplay.mStacks.size() - 1; i >= 0; --i) {
2232 final ActivityStack stack = activityDisplay.mStacks.get(i);
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002233 if (mService.mActivityStarter.isValidLaunchStackId(stack.mStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002234 return stack;
2235 }
2236 }
2237
2238 // If there is no valid stack on the external display - check if new dynamic stack will do.
2239 if (displayId != Display.DEFAULT_DISPLAY) {
2240 final int newDynamicStackId = getNextStackId();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002241 if (mService.mActivityStarter.isValidLaunchStackId(newDynamicStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002242 return createStackOnDisplay(newDynamicStackId, displayId, true /*onTop*/);
2243 }
2244 }
2245
2246 Slog.w(TAG, "getValidLaunchStackOnDisplay: can't launch on displayId " + displayId);
2247 return null;
2248 }
2249
Craig Mautner967212c2013-04-13 21:10:58 -07002250 ArrayList<ActivityStack> getStacks() {
Wale Ogunwale3797c222015-10-27 14:21:58 -07002251 ArrayList<ActivityStack> allStacks = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08002252 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2253 allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002254 }
2255 return allStacks;
Craig Mautner967212c2013-04-13 21:10:58 -07002256 }
2257
Jorim Jaggife762342016-10-13 14:33:27 +02002258 ArrayList<ActivityStack> getStacksOnDefaultDisplay() {
2259 return mActivityDisplays.valueAt(DEFAULT_DISPLAY).mStacks;
2260 }
2261
Andrii Kulian7fc22812016-12-28 13:04:11 -08002262 /**
2263 * Get next focusable stack in the system. This will search across displays and stacks
2264 * in last-focused order for a focusable and visible stack, different from the target stack.
2265 *
2266 * @param currentFocus The stack that previously had focus and thus needs to be ignored when
2267 * searching for next candidate.
2268 * @return Next focusable {@link ActivityStack}, null if not found.
2269 */
2270 ActivityStack getNextFocusableStackLocked(ActivityStack currentFocus) {
2271 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2272
2273 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2274 final int displayId = mTmpOrderedDisplayIds.get(i);
Andrii Kulian62e6f252017-05-30 22:46:53 -07002275 // If a display is registered in WM, it must also be available in AM.
2276 @SuppressWarnings("ConstantConditions")
2277 final List<ActivityStack> stacks = getActivityDisplayOrCreateLocked(displayId).mStacks;
Andrii Kulian7fc22812016-12-28 13:04:11 -08002278 for (int j = stacks.size() - 1; j >= 0; --j) {
2279 final ActivityStack stack = stacks.get(j);
2280 if (stack != currentFocus && stack.isFocusable()
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002281 && stack.shouldBeVisible(null) != STACK_INVISIBLE) {
Andrii Kulian7fc22812016-12-28 13:04:11 -08002282 return stack;
2283 }
2284 }
2285 }
2286
2287 return null;
2288 }
2289
Andrii Kuliana8fe3df2017-06-16 15:29:26 -07002290 /**
2291 * Get next valid stack for launching provided activity in the system. This will search across
2292 * displays and stacks in last-focused order for a focusable and visible stack, except those
2293 * that are on a currently focused display.
2294 *
2295 * @param r The activity that is being launched.
2296 * @param currentFocus The display that previously had focus and thus needs to be ignored when
2297 * searching for the next candidate.
2298 * @return Next valid {@link ActivityStack}, null if not found.
2299 */
2300 ActivityStack getNextValidLaunchStackLocked(@NonNull ActivityRecord r, int currentFocus) {
2301 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2302 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2303 final int displayId = mTmpOrderedDisplayIds.get(i);
2304 if (displayId == currentFocus) {
2305 continue;
2306 }
2307 final ActivityStack stack = getValidLaunchStackOnDisplay(displayId, r);
2308 if (stack != null) {
2309 return stack;
2310 }
2311 }
2312 return null;
2313 }
2314
Craig Mautneree2e45a2014-06-27 12:10:03 -07002315 ActivityRecord getHomeActivity() {
Craig Mautnerdb49fec2015-05-21 15:33:30 -07002316 return getHomeActivityForUser(mCurrentUser);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002317 }
2318
2319 ActivityRecord getHomeActivityForUser(int userId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002320 final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
2321 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
2322 final TaskRecord task = tasks.get(taskNdx);
2323 if (task.isHomeTask()) {
2324 final ArrayList<ActivityRecord> activities = task.mActivities;
2325 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2326 final ActivityRecord r = activities.get(activityNdx);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002327 if (r.isHomeActivity()
2328 && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
Craig Mautneree2e45a2014-06-27 12:10:03 -07002329 return r;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002330 }
2331 }
2332 }
2333 }
2334 return null;
2335 }
2336
Chong Zhangb15758a2015-11-17 12:12:03 -08002337 /**
2338 * Returns if a stack should be treated as if it's docked. Returns true if the stack is
2339 * the docked stack itself, or if it's side-by-side to the docked stack.
2340 */
2341 boolean isStackDockedInEffect(int stackId) {
2342 return stackId == DOCKED_STACK_ID ||
2343 (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
2344 }
2345
Jorim Jaggidc249c42015-12-15 14:57:31 -08002346 void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002347 boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
Jorim Jaggidc249c42015-12-15 14:57:31 -08002348 if (stackId == DOCKED_STACK_ID) {
2349 resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002350 preserveWindows, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002351 return;
2352 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08002353 final ActivityStack stack = getStack(stackId);
2354 if (stack == null) {
2355 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2356 return;
2357 }
Wale Ogunwale9d3de4c2015-02-01 16:49:44 -08002358
Winson Chunga2249ac2017-03-30 18:15:30 -07002359 if (!allowResizeInDockedMode && !StackId.tasksAreFloating(stackId) &&
2360 getStack(DOCKED_STACK_ID) != null) {
2361 // If the docked stack exists, don't resize non-floating stacks independently of the
2362 // size computed from the docked stack size (otherwise they will be out of sync)
Wale Ogunwaleffc11bb2015-10-10 13:05:45 -07002363 return;
2364 }
2365
Wale Ogunwalecad05a02015-09-25 10:41:44 -07002366 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
Jorim Jaggic4025202015-10-22 16:43:34 +02002367 mWindowManager.deferSurfaceLayout();
2368 try {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002369 stack.resize(bounds, tempTaskBounds, tempTaskInsetBounds);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002370 if (!deferResume) {
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002371 stack.ensureVisibleActivitiesConfigurationLocked(
2372 stack.topRunningActivityLocked(), preserveWindows);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002373 }
Jorim Jaggic4025202015-10-22 16:43:34 +02002374 } finally {
2375 mWindowManager.continueSurfaceLayout();
2376 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07002377 }
2378 }
2379
Jorim Jaggi192086e2016-03-11 17:17:03 +01002380 void deferUpdateBounds(int stackId) {
2381 final ActivityStack stack = getStack(stackId);
2382 if (stack != null) {
2383 stack.deferUpdateBounds();
2384 }
2385 }
2386
2387 void continueUpdateBounds(int stackId) {
2388 final ActivityStack stack = getStack(stackId);
2389 if (stack != null) {
2390 stack.continueUpdateBounds();
2391 }
2392 }
2393
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002394 void notifyAppTransitionDone() {
Matthew Ng606dd802017-06-05 14:06:32 -07002395 continueUpdateBounds(RECENTS_STACK_ID);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002396 for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2397 final int taskId = mResizingTasksDuringAnimation.valueAt(i);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002398 final TaskRecord task =
Winson Chung7900bee2017-03-10 08:59:25 -08002399 anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002400 if (task != null) {
2401 task.setTaskDockedResizing(false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002402 }
2403 }
2404 mResizingTasksDuringAnimation.clear();
2405 }
2406
Robert Carre7cc44d2017-03-20 19:04:30 -07002407 private void moveTasksToFullscreenStackInSurfaceTransaction(int fromStackId,
2408 boolean onTop) {
Robert Carr6914f082017-03-20 19:04:30 -07002409
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002410 final ActivityStack stack = getStack(fromStackId);
2411 if (stack == null) {
2412 return;
2413 }
2414
2415 mWindowManager.deferSurfaceLayout();
2416 try {
2417 if (fromStackId == DOCKED_STACK_ID) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002418 // We are moving all tasks from the docked stack to the fullscreen stack,
2419 // which is dismissing the docked stack, so resize all other stacks to
2420 // fullscreen here already so we don't end up with resize trashing.
2421 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2422 if (StackId.isResizeableByDockedStack(i)) {
2423 ActivityStack otherStack = getStack(i);
2424 if (otherStack != null) {
2425 resizeStackLocked(i, null, null, null, PRESERVE_WINDOWS,
2426 true /* allowResizeInDockedMode */, DEFER_RESUME);
2427 }
2428 }
2429 }
2430
2431 // Also disable docked stack resizing since we have manually adjusted the
2432 // size of other stacks above and we don't want to trigger a docked stack
2433 // resize when we remove task from it below and it is detached from the
2434 // display because it no longer contains any tasks.
2435 mAllowDockedStackResize = false;
Winson Chung47900652017-04-06 18:44:25 -07002436 } else if (fromStackId == PINNED_STACK_ID) {
2437 if (onTop) {
2438 // Log if we are expanding the PiP to fullscreen
2439 MetricsLogger.action(mService.mContext,
2440 ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN);
2441 }
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002442 }
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002443 ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
Winson Chungc85d9ce2017-01-03 11:59:52 -08002444 final boolean isFullscreenStackVisible = fullscreenStack != null &&
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002445 fullscreenStack.shouldBeVisible(null) == STACK_VISIBLE;
Winson Chung5af42fc2017-03-24 17:11:33 -07002446 // If we are moving from the pinned stack, then the animation takes care of updating
2447 // the picture-in-picture mode.
Winson Chung47900652017-04-06 18:44:25 -07002448 final boolean schedulePictureInPictureModeChange = (fromStackId == PINNED_STACK_ID);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002449 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2450 final int size = tasks.size();
2451 if (onTop) {
2452 for (int i = 0; i < size; i++) {
Winson Chung0c1ca092016-11-10 17:40:34 -08002453 final TaskRecord task = tasks.get(i);
Winson Chung74666102017-02-22 17:49:24 -08002454 final boolean isTopTask = i == (size - 1);
Winson Chung0c1ca092016-11-10 17:40:34 -08002455 if (fromStackId == PINNED_STACK_ID) {
2456 // Update the return-to to reflect where the pinned stack task was moved
2457 // from so that we retain the stack that was previously visible if the
2458 // pinned stack is recreated. See moveActivityToPinnedStackLocked().
Winson Chungc85d9ce2017-01-03 11:59:52 -08002459 task.setTaskToReturnTo(isFullscreenStackVisible && onTop ?
2460 APPLICATION_ACTIVITY_TYPE : HOME_ACTIVITY_TYPE);
Winson Chung0c1ca092016-11-10 17:40:34 -08002461 }
Winson Chung74666102017-02-22 17:49:24 -08002462 // Defer resume until all the tasks have been moved to the fullscreen stack
2463 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
2464 REPARENT_MOVE_STACK_TO_FRONT, isTopTask /* animate */, DEFER_RESUME,
Winson Chung5af42fc2017-03-24 17:11:33 -07002465 schedulePictureInPictureModeChange,
Winson Chung74666102017-02-22 17:49:24 -08002466 "moveTasksToFullscreenStack - onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002467 }
2468 } else {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002469 for (int i = 0; i < size; i++) {
Wale Ogunwalec5cc3012017-01-13 13:26:16 -08002470 final TaskRecord task = tasks.get(i);
Winson Chung3a649982017-04-19 10:16:17 -07002471 // Position the tasks in the fullscreen stack in order at the bottom of the
2472 // stack. Also defer resume until all the tasks have been moved to the
2473 // fullscreen stack.
2474 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, i /* position */,
Winson Chung5af42fc2017-03-24 17:11:33 -07002475 REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME,
2476 schedulePictureInPictureModeChange,
2477 "moveTasksToFullscreenStack - NOT_onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002478 }
2479 }
Winson Chung74666102017-02-22 17:49:24 -08002480
2481 ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2482 resumeFocusedStackTopActivityLocked();
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002483 } finally {
2484 mAllowDockedStackResize = true;
2485 mWindowManager.continueSurfaceLayout();
2486 }
2487 }
2488
Robert Carr6914f082017-03-20 19:04:30 -07002489 void moveTasksToFullscreenStackLocked(int fromStackId, boolean onTop) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002490 mWindowManager.inSurfaceTransaction(
2491 () -> moveTasksToFullscreenStackInSurfaceTransaction(fromStackId, onTop));
Robert Carr6914f082017-03-20 19:04:30 -07002492 }
2493
Jorim Jaggidc249c42015-12-15 14:57:31 -08002494 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002495 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2496 boolean preserveWindows) {
2497 resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
2498 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows,
2499 false /* deferResume */);
2500 }
2501
2502 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2503 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2504 boolean preserveWindows, boolean deferResume) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002505
2506 if (!mAllowDockedStackResize) {
2507 // Docked stack resize currently disabled.
2508 return;
2509 }
2510
Jorim Jaggidc249c42015-12-15 14:57:31 -08002511 final ActivityStack stack = getStack(DOCKED_STACK_ID);
2512 if (stack == null) {
2513 Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2514 return;
2515 }
2516
2517 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2518 mWindowManager.deferSurfaceLayout();
2519 try {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002520 // Don't allow re-entry while resizing. E.g. due to docked stack detaching.
2521 mAllowDockedStackResize = false;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002522 ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwale1666e312016-12-16 11:27:18 -08002523 stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002524
Andrii Kulian69fb5e42016-04-05 16:47:29 -07002525 // TODO: Checking for isAttached might not be needed as if the user passes in null
2526 // dockedBounds then they want the docked stack to be dismissed.
2527 if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2528 // The dock stack either was dismissed or went fullscreen, which is kinda the same.
Jorim Jaggidc249c42015-12-15 14:57:31 -08002529 // In this case we make all other static stacks fullscreen and move all
2530 // docked stack tasks to the fullscreen stack.
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002531 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, ON_TOP);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002532
2533 // stack shouldn't contain anymore activities, so nothing to resume.
2534 r = null;
2535 } else {
2536 // Docked stacks occupy a dedicated region on screen so the size of all other
2537 // static stacks need to be adjusted so they don't overlap with the docked stack.
2538 // We get the bounds to use from window manager which has been adjusted for any
2539 // screen controls and is also the same for all stacks.
Matthew Ngaa2b6202017-02-10 14:48:21 -08002540 final Rect otherTaskRect = new Rect();
Jorim Jaggidc249c42015-12-15 14:57:31 -08002541 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002542 final ActivityStack current = getStack(i);
2543 if (current != null && StackId.isResizeableByDockedStack(i)) {
Matthew Ngaa2b6202017-02-10 14:48:21 -08002544 current.getStackDockedModeBounds(
2545 tempOtherTaskBounds /* currentTempTaskBounds */,
2546 tempRect /* outStackBounds */,
2547 otherTaskRect /* outTempTaskBounds */, true /* ignoreVisibility */);
2548
Andrii Kuliane48b7d82017-04-28 14:51:05 -07002549 resizeStackLocked(i, !tempRect.isEmpty() ? tempRect : null,
Matthew Ngaa2b6202017-02-10 14:48:21 -08002550 !otherTaskRect.isEmpty() ? otherTaskRect : tempOtherTaskBounds,
2551 tempOtherTaskInsetBounds, preserveWindows,
2552 true /* allowResizeInDockedMode */, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002553 }
2554 }
2555 }
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002556 if (!deferResume) {
2557 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows);
2558 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002559 } finally {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002560 mAllowDockedStackResize = true;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002561 mWindowManager.continueSurfaceLayout();
2562 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2563 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002564 }
2565
Robert Carr0d00c2e2016-02-29 17:45:02 -08002566 void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Winson Chung19953ca2017-04-11 11:19:23 -07002567 final PinnedActivityStack stack = getStack(PINNED_STACK_ID);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002568 if (stack == null) {
2569 Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2570 return;
2571 }
Winson Chung19953ca2017-04-11 11:19:23 -07002572
2573 // It is possible for the bounds animation from the WM to call this but be delayed by
2574 // another AM call that is holding the AMS lock. In such a case, the pinnedBounds may be
2575 // incorrect if AMS.resizeStackWithBoundsFromWindowManager() is already called while waiting
2576 // for the AMS lock to be freed. So check and make sure these bounds are still good.
2577 final PinnedStackWindowController stackController = stack.getWindowContainerController();
Winson Chung8bca9e42017-04-16 15:59:43 -07002578 if (stackController.pinnedStackResizeDisallowed()) {
Winson Chung19953ca2017-04-11 11:19:23 -07002579 return;
2580 }
2581
Robert Carr0d00c2e2016-02-29 17:45:02 -08002582 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2583 mWindowManager.deferSurfaceLayout();
2584 try {
2585 ActivityRecord r = stack.topRunningActivityLocked();
Robert Carr7e4c90e2017-02-15 19:52:38 -08002586 Rect insetBounds = null;
2587 if (tempPinnedTaskBounds != null) {
2588 // We always use 0,0 as the position for the inset rect because
2589 // if we are getting insets at all in the pinned stack it must mean
2590 // we are headed for fullscreen.
2591 insetBounds = tempRect;
2592 insetBounds.top = 0;
2593 insetBounds.left = 0;
2594 insetBounds.right = tempPinnedTaskBounds.width();
2595 insetBounds.bottom = tempPinnedTaskBounds.height();
2596 }
2597 stack.resize(pinnedBounds, tempPinnedTaskBounds, insetBounds);
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002598 stack.ensureVisibleActivitiesConfigurationLocked(r, false);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002599 } finally {
2600 mWindowManager.continueSurfaceLayout();
2601 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2602 }
2603 }
2604
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002605 ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002606 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Craig Mautnere0a38842013-12-16 16:14:02 -08002607 if (activityDisplay == null) {
Todd Kennedy4900bf92015-01-16 16:05:14 -08002608 return null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002609 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002610 return createStack(stackId, activityDisplay, onTop);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002611
Craig Mautner4a1cb222013-12-04 16:14:06 -08002612 }
2613
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002614 ActivityStack createStack(int stackId, ActivityDisplay display, boolean onTop) {
2615 switch (stackId) {
2616 case PINNED_STACK_ID:
2617 return new PinnedActivityStack(display, stackId, this, mRecentTasks, onTop);
2618 default:
2619 return new ActivityStack(display, stackId, this, mRecentTasks, onTop);
2620 }
2621 }
Robert Carr6914f082017-03-20 19:04:30 -07002622
Robert Carre7cc44d2017-03-20 19:04:30 -07002623 void removeStackInSurfaceTransaction(int stackId) {
Winson Chung010927a2016-12-15 16:12:35 -08002624 final ActivityStack stack = getStack(stackId);
2625 if (stack == null) {
2626 return;
2627 }
2628
2629 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2630 if (stack.getStackId() == PINNED_STACK_ID) {
Winson Chung47900652017-04-06 18:44:25 -07002631 /**
2632 * Workaround: Force-stop all the activities in the pinned stack before we reparent them
2633 * to the fullscreen stack. This is to guarantee that when we are removing a stack,
2634 * that the client receives onStop() before it is reparented. We do this by detaching
2635 * the stack from the display so that it will be considered invisible when
2636 * ensureActivitiesVisibleLocked() is called, and all of its activitys will be marked
2637 * invisible as well and added to the stopping list. After which we process the
2638 * stopping list by handling the idle.
2639 */
2640 final PinnedActivityStack pinnedStack = (PinnedActivityStack) stack;
2641 pinnedStack.mForceHidden = true;
2642 pinnedStack.ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2643 pinnedStack.mForceHidden = false;
2644 activityIdleInternalLocked(null, false /* fromTimeout */,
2645 true /* processPausingActivites */, null /* configuration */);
2646
2647 // Move all the tasks to the bottom of the fullscreen stack
2648 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
Winson Chung010927a2016-12-15 16:12:35 -08002649 } else {
2650 for (int i = tasks.size() - 1; i >= 0; i--) {
2651 removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */,
2652 REMOVE_FROM_RECENTS);
2653 }
2654 }
2655 }
2656
2657 /**
Robert Carr6914f082017-03-20 19:04:30 -07002658 * Removes the stack associated with the given {@param stackId}. If the {@param stackId} is the
2659 * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
2660 * instead moved back onto the fullscreen stack.
2661 */
2662 void removeStackLocked(int stackId) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002663 mWindowManager.inSurfaceTransaction(
2664 () -> removeStackInSurfaceTransaction(stackId));
Robert Carr6914f082017-03-20 19:04:30 -07002665 }
2666
2667 /**
Winson Chung6954fc92017-03-24 16:22:12 -07002668 * See {@link #removeTaskByIdLocked(int, boolean, boolean, boolean)}
2669 */
2670 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents) {
2671 return removeTaskByIdLocked(taskId, killProcess, removeFromRecents, !PAUSE_IMMEDIATELY);
2672 }
2673
2674 /**
Winson Chung010927a2016-12-15 16:12:35 -08002675 * Removes the task with the specified task id.
2676 *
2677 * @param taskId Identifier of the task to be removed.
2678 * @param killProcess Kill any process associated with the task if possible.
2679 * @param removeFromRecents Whether to also remove the task from recents.
Winson Chung6954fc92017-03-24 16:22:12 -07002680 * @param pauseImmediately Pauses all task activities immediately without waiting for the
2681 * pause-complete callback from the activity.
Winson Chung010927a2016-12-15 16:12:35 -08002682 * @return Returns true if the given task was found and removed.
2683 */
Winson Chung6954fc92017-03-24 16:22:12 -07002684 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents,
2685 boolean pauseImmediately) {
Winson Chung7900bee2017-03-10 08:59:25 -08002686 final TaskRecord tr = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
2687 INVALID_STACK_ID);
Winson Chung010927a2016-12-15 16:12:35 -08002688 if (tr != null) {
Winson Chung6954fc92017-03-24 16:22:12 -07002689 tr.removeTaskActivitiesLocked(pauseImmediately);
Winson Chung010927a2016-12-15 16:12:35 -08002690 cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents);
2691 if (tr.isPersistable) {
2692 mService.notifyTaskPersisterLocked(null, true);
2693 }
2694 return true;
2695 }
2696 Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
2697 return false;
2698 }
2699
2700 void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) {
2701 if (removeFromRecents) {
2702 mRecentTasks.remove(tr);
2703 tr.removedFromRecents();
2704 }
2705 ComponentName component = tr.getBaseIntent().getComponent();
2706 if (component == null) {
2707 Slog.w(TAG, "No component for base intent of task: " + tr);
2708 return;
2709 }
2710
2711 // Find any running services associated with this app and stop if needed.
2712 mService.mServices.cleanUpRemovedTaskLocked(tr, component, new Intent(tr.getBaseIntent()));
2713
2714 if (!killProcess) {
2715 return;
2716 }
2717
2718 // Determine if the process(es) for this task should be killed.
2719 final String pkg = component.getPackageName();
2720 ArrayList<ProcessRecord> procsToKill = new ArrayList<>();
2721 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mService.mProcessNames.getMap();
2722 for (int i = 0; i < pmap.size(); i++) {
2723
2724 SparseArray<ProcessRecord> uids = pmap.valueAt(i);
2725 for (int j = 0; j < uids.size(); j++) {
2726 ProcessRecord proc = uids.valueAt(j);
2727 if (proc.userId != tr.userId) {
2728 // Don't kill process for a different user.
2729 continue;
2730 }
2731 if (proc == mService.mHomeProcess) {
2732 // Don't kill the home process along with tasks from the same package.
2733 continue;
2734 }
2735 if (!proc.pkgList.containsKey(pkg)) {
2736 // Don't kill process that is not associated with this task.
2737 continue;
2738 }
2739
2740 for (int k = 0; k < proc.activities.size(); k++) {
Bryce Leeaf691c02017-03-20 14:20:22 -07002741 TaskRecord otherTask = proc.activities.get(k).getTask();
Winson Chung010927a2016-12-15 16:12:35 -08002742 if (tr.taskId != otherTask.taskId && otherTask.inRecents) {
2743 // Don't kill process(es) that has an activity in a different task that is
2744 // also in recents.
2745 return;
2746 }
2747 }
2748
2749 if (proc.foregroundServices) {
2750 // Don't kill process(es) with foreground service.
2751 return;
2752 }
2753
2754 // Add process to kill list.
2755 procsToKill.add(proc);
2756 }
2757 }
2758
2759 // Kill the running processes.
2760 for (int i = 0; i < procsToKill.size(); i++) {
2761 ProcessRecord pr = procsToKill.get(i);
2762 if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
2763 && pr.curReceivers.isEmpty()) {
2764 pr.kill("remove task", true);
2765 } else {
2766 // We delay killing processes that are not in the background or running a receiver.
2767 pr.waitingToKill = "remove task";
2768 }
2769 }
2770 }
2771
Craig Mautner4a1cb222013-12-04 16:14:06 -08002772 int getNextStackId() {
Craig Mautner858d8a62013-04-23 17:08:34 -07002773 while (true) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002774 if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2775 && getStack(mNextFreeStackId) == null) {
Craig Mautner858d8a62013-04-23 17:08:34 -07002776 break;
2777 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002778 mNextFreeStackId++;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002779 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002780 return mNextFreeStackId;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002781 }
2782
Chong Zhang5dcb2752015-08-18 13:50:26 -07002783 /**
2784 * Restores a recent task to a stack
2785 * @param task The recent task to be restored.
2786 * @param stackId The stack to restore the task to (default launch stack will be used
Andrii Kulian16802aa2016-11-02 12:21:33 -07002787 * if stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}
2788 * or is not a static stack).
Chong Zhang5dcb2752015-08-18 13:50:26 -07002789 * @return true if the task has been restored successfully.
2790 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002791 boolean restoreRecentTaskLocked(TaskRecord task, int stackId) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002792 if (!StackId.isStaticStack(stackId)) {
2793 // If stack is not static (or stack id is invalid) - use the default one.
2794 // This means that tasks that were on external displays will be restored on the
2795 // primary display.
Wale Ogunwale8b06a582015-10-22 14:38:21 -07002796 stackId = task.getLaunchStackId();
Winson Chungd3395382016-12-13 11:49:09 -08002797 } else if (stackId == DOCKED_STACK_ID && !task.supportsSplitScreen()) {
Wale Ogunwale513346d2016-01-27 10:55:01 -08002798 // Preferred stack is the docked stack, but the task can't go in the docked stack.
2799 // Put it in the fullscreen stack.
2800 stackId = FULLSCREEN_WORKSPACE_STACK_ID;
Chong Zhang5dcb2752015-08-18 13:50:26 -07002801 }
Wale Ogunwale513346d2016-01-27 10:55:01 -08002802
Andrii Kulian02b7a832016-10-06 23:11:56 -07002803 final ActivityStack currentStack = task.getStack();
2804 if (currentStack != null) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002805 // Task has already been restored once. See if we need to do anything more
Andrii Kulian02b7a832016-10-06 23:11:56 -07002806 if (currentStack.mStackId == stackId) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002807 // Nothing else to do since it is already restored in the right stack.
2808 return true;
2809 }
2810 // Remove current stack association, so we can re-associate the task with the
2811 // right stack below.
Andrii Kulian02b7a832016-10-06 23:11:56 -07002812 currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING);
Wale Ogunwale706ed792015-08-02 10:29:44 -07002813 }
2814
Wale Ogunwale6c5eb1c2015-11-10 07:52:22 -08002815 final ActivityStack stack =
Wale Ogunwale040b4702015-08-06 18:10:50 -07002816 getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002817
2818 if (stack == null) {
2819 // What does this mean??? Not sure how we would get here...
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002820 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2821 "Unable to find/create stack to restore recent task=" + task);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002822 return false;
2823 }
2824
Wale Ogunwale72919d22016-12-08 18:58:50 -08002825 stack.addTask(task, false /* toTop */, "restoreRecentTask");
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002826 // TODO: move call for creation here and other place into Stack.addTask()
2827 task.createWindowContainer(false /* toTop */, true /* showForAllUsers */);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002828 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2829 "Added restored task=" + task + " to stack=" + stack);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002830 final ArrayList<ActivityRecord> activities = task.mActivities;
2831 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002832 activities.get(activityNdx).createWindowContainer();
Wale Ogunwale7de05352014-12-12 15:21:33 -08002833 }
2834 return true;
Craig Mautneref73ee12014-04-23 11:45:37 -07002835 }
2836
Wale Ogunwale040b4702015-08-06 18:10:50 -07002837 /**
Andrii Kulian839def92016-11-02 10:58:58 -07002838 * Move stack with all its existing content to specified display.
2839 * @param stackId Id of stack to move.
2840 * @param displayId Id of display to move stack to.
Andrii Kulian250d6532017-02-08 23:30:45 -08002841 * @param onTop Indicates whether container should be place on top or on bottom.
Andrii Kulian839def92016-11-02 10:58:58 -07002842 */
Andrii Kulian250d6532017-02-08 23:30:45 -08002843 void moveStackToDisplayLocked(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002844 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian839def92016-11-02 10:58:58 -07002845 if (activityDisplay == null) {
2846 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown displayId="
2847 + displayId);
2848 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002849 final ActivityStack stack = mStacks.get(stackId);
2850 if (stack == null) {
Andrii Kulian839def92016-11-02 10:58:58 -07002851 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
2852 + stackId);
2853 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002854
2855 final ActivityDisplay currentDisplay = stack.getDisplay();
2856 if (currentDisplay == null) {
2857 throw new IllegalStateException("moveStackToDisplayLocked: Stack with stack=" + stack
2858 + " is not attached to any display.");
2859 }
2860
2861 if (currentDisplay.mDisplayId == displayId) {
2862 throw new IllegalArgumentException("Trying to move stack=" + stack
2863 + " to its current displayId=" + displayId);
2864 }
2865
2866 stack.reparent(activityDisplay, onTop);
Andrii Kulian839def92016-11-02 10:58:58 -07002867 // TODO(multi-display): resize stacks properly if moved from split-screen.
2868 }
2869
2870 /**
Winson Chung74666102017-02-22 17:49:24 -08002871 * Returns the reparent target stack, creating the stack if necessary. This call also enforces
2872 * the various checks on tasks that are going to be reparented from one stack to another.
Wale Ogunwale040b4702015-08-06 18:10:50 -07002873 */
Winson Chung74666102017-02-22 17:49:24 -08002874 ActivityStack getReparentTargetStack(TaskRecord task, int stackId, boolean toTop) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07002875 final ActivityStack prevStack = task.getStack();
Chong Zhang02898352015-08-21 17:27:14 -07002876
Winson Chung74666102017-02-22 17:49:24 -08002877 // Check that we aren't reparenting to the same stack that the task is already in
2878 if (prevStack != null && prevStack.mStackId == stackId) {
2879 Slog.w(TAG, "Can not reparent to same stack, task=" + task
2880 + " already in stackId=" + stackId);
2881 return prevStack;
Wale Ogunwale513346d2016-01-27 10:55:01 -08002882 }
2883
Winson Chung74666102017-02-22 17:49:24 -08002884 // Ensure that we aren't trying to move into a multi-window stack without multi-window
2885 // support
2886 if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
2887 throw new IllegalArgumentException("Device doesn't support multi-window, can not"
2888 + " reparent task=" + task + " to stackId=" + stackId);
Winson Chungc2baac02017-01-11 13:34:47 -08002889 }
2890
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002891 // Ensure that we're not moving a task to a dynamic stack if device doesn't support
2892 // multi-display.
2893 // TODO(multi-display): Support non-dynamic stacks on secondary displays.
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002894 if (StackId.isDynamicStack(stackId) && !mService.mSupportsMultiDisplay) {
2895 throw new IllegalArgumentException("Device doesn't support multi-display, can not"
2896 + " reparent task=" + task + " to stackId=" + stackId);
2897 }
2898
Winson Chung74666102017-02-22 17:49:24 -08002899 // Ensure that we aren't trying to move into a freeform stack without freeform
2900 // support
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002901 if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
Winson Chung74666102017-02-22 17:49:24 -08002902 throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
2903 + " task=" + task);
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002904 }
2905
Winson Chung74666102017-02-22 17:49:24 -08002906 // We don't allow moving a unresizeable task to the docked stack since the docked stack is
2907 // used for split-screen mode and will cause things like the docked divider to show up. We
2908 // instead leave the task in its current stack or move it to the fullscreen stack if it
2909 // isn't currently in a stack.
2910 if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
2911 stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
2912 Slog.w(TAG, "Can not move unresizeable task=" + task + " to docked stack."
2913 + " Moving to stackId=" + stackId + " instead.");
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07002914 }
Wale Ogunwale961f4852016-02-01 20:25:54 -08002915
Winson Chung74666102017-02-22 17:49:24 -08002916 // Temporarily disable resizeablility of the task as we don't want it to be resized if, for
2917 // example, a docked stack is created which will lead to the stack we are moving from being
2918 // resized and and its resizeable tasks being resized.
Wale Ogunwale961f4852016-02-01 20:25:54 -08002919 try {
Winson Chung74666102017-02-22 17:49:24 -08002920 task.mTemporarilyUnresizable = true;
2921 return getStack(stackId, CREATE_IF_NEEDED, toTop);
Wale Ogunwale961f4852016-02-01 20:25:54 -08002922 } finally {
Winson Chung74666102017-02-22 17:49:24 -08002923 task.mTemporarilyUnresizable = false;
Chong Zhangf596cd52016-01-05 13:42:44 -08002924 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002925 }
2926
Winson Chung08f81892017-03-02 15:40:51 -08002927 boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect destBounds) {
Wale Ogunwale079a0042015-10-24 11:44:07 -07002928 final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2929 if (stack == null) {
2930 throw new IllegalArgumentException(
2931 "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
2932 }
2933
2934 final ActivityRecord r = stack.topRunningActivityLocked();
2935 if (r == null) {
2936 Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
2937 + " in stack=" + stack);
2938 return false;
2939 }
2940
Wale Ogunwale6cae7652015-12-26 07:36:26 -08002941 if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
Wale Ogunwaleb60692e2015-10-24 12:35:56 -07002942 Slog.w(TAG,
2943 "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
Filip Gruszczynski77d94482015-12-11 13:59:52 -08002944 + " r=" + r);
Wale Ogunwale079a0042015-10-24 11:44:07 -07002945 return false;
2946 }
2947
Winson Chung3a682872017-04-10 14:38:05 -07002948 moveActivityToPinnedStackLocked(r, null /* sourceBounds */, 0f /* aspectRatio */,
Winson Chung08f81892017-03-02 15:40:51 -08002949 true /* moveHomeStackToFront */, "moveTopActivityToPinnedStack");
Wale Ogunwale9c604c72015-12-06 18:42:57 -08002950 return true;
2951 }
2952
Winson Chung8bca9e42017-04-16 15:59:43 -07002953 void moveActivityToPinnedStackLocked(ActivityRecord r, Rect sourceHintBounds, float aspectRatio,
Winson Chung08f81892017-03-02 15:40:51 -08002954 boolean moveHomeStackToFront, String reason) {
2955
Wale Ogunwale480dca02016-02-06 13:58:29 -08002956 mWindowManager.deferSurfaceLayout();
Winson Chung74666102017-02-22 17:49:24 -08002957
Bryce Lee04ab3462017-04-10 15:06:33 -07002958 // This will clear the pinned stack by moving an existing task to the full screen stack,
2959 // ensuring only one task is present.
2960 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
2961
Wale Ogunwale1666e312016-12-16 11:27:18 -08002962 // Need to make sure the pinned stack exist so we can resize it below...
Winson Chung55893332017-02-17 17:13:10 -08002963 final PinnedActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Wale Ogunwale1666e312016-12-16 11:27:18 -08002964
Wale Ogunwale480dca02016-02-06 13:58:29 -08002965 try {
Bryce Leeaf691c02017-03-20 14:20:22 -07002966 final TaskRecord task = r.getTask();
Wale Ogunwale480dca02016-02-06 13:58:29 -08002967 // Resize the pinned stack to match the current size of the task the activity we are
2968 // going to be moving is currently contained in. We do this to have the right starting
2969 // animation bounds for the pinned stack to the desired bounds the caller wants.
2970 resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
2971 null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002972 true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002973
2974 if (task.mActivities.size() == 1) {
2975 // There is only one activity in the task. So, we can just move the task over to
Winson Chungc2baac02017-01-11 13:34:47 -08002976 // the stack without re-parenting the activity in a different task. We don't
2977 // move the home stack forward if we are currently entering picture-in-picture
2978 // while pausing because that changes the focused stack and may prevent the new
2979 // starting activity from resuming.
2980 if (moveHomeStackToFront && task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE
Winson Chung105ae5f2017-03-06 15:06:28 -08002981 && (r.state == RESUMED || !r.supportsPictureInPictureWhilePausing)) {
Wale Ogunwaleda4ba962016-03-11 09:33:17 -08002982 // Move the home stack forward if the task we just moved to the pinned stack
2983 // was launched from home so home should be visible behind it.
2984 moveHomeStackToFront(reason);
2985 }
Winson Chung5af42fc2017-03-24 17:11:33 -07002986 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08002987 task.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07002988 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002989 } else {
Winson Chungb5c41b72016-12-07 15:00:47 -08002990 // There are multiple activities in the task and moving the top activity should
Winson Chung74666102017-02-22 17:49:24 -08002991 // reveal/leave the other activities in their original task.
2992
2993 // Currently, we don't support reparenting activities across tasks in two different
2994 // stacks, so instead, just create a new task in the same stack, reparent the
2995 // activity into that task, and then reparent the whole task to the new stack. This
2996 // ensures that all the necessary work to migrate states in the old and new stacks
2997 // is also done.
2998 final TaskRecord newTask = task.getStack().createTaskRecord(
2999 getNextTaskIdForUserLocked(r.userId), r.info, r.intent, null, null, true,
3000 r.mActivityType);
3001 r.reparent(newTask, MAX_VALUE, "moveActivityToStack");
3002
Winson Chung5af42fc2017-03-24 17:11:33 -07003003 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08003004 newTask.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07003005 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08003006 }
Winson Chungc2baac02017-01-11 13:34:47 -08003007
3008 // Reset the state that indicates it can enter PiP while pausing after we've moved it
3009 // to the pinned stack
3010 r.supportsPictureInPictureWhilePausing = false;
Wale Ogunwale480dca02016-02-06 13:58:29 -08003011 } finally {
3012 mWindowManager.continueSurfaceLayout();
Wale Ogunwale079a0042015-10-24 11:44:07 -07003013 }
3014
Winson Chunge7ba6862017-05-24 12:13:33 -07003015 // Calculate the default bounds (don't use existing stack bounds as we may have just created
3016 // the stack, and schedule the start of the animation into PiP (the bounds animator that
3017 // is triggered by this is posted on another thread)
Winson Chunga71febe2017-05-22 11:14:22 -07003018 final Rect destBounds = stack.getDefaultPictureInPictureBounds(aspectRatio);
3019
Winson Chunge7ba6862017-05-24 12:13:33 -07003020 stack.animateResizePinnedStack(sourceHintBounds, destBounds, -1 /* animationDuration */,
3021 true /* fromFullscreen */);
3022
3023 // Update the visibility of all activities after the they have been reparented to the new
3024 // stack. This MUST run after the animation above is scheduled to ensure that the windows
3025 // drawn signal is scheduled after the bounds animation start call on the bounds animator
3026 // thread.
Wale Ogunwale079a0042015-10-24 11:44:07 -07003027 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwaled046a012015-12-24 13:05:59 -08003028 resumeFocusedStackTopActivityLocked();
Wale Ogunwale03ce8632015-12-29 16:15:22 -08003029
Winson Chungb5026902017-05-03 12:45:13 -07003030 mService.mTaskChangeNotificationController.notifyActivityPinned(r.packageName,
3031 r.getTask().taskId);
Wale Ogunwale079a0042015-10-24 11:44:07 -07003032 }
3033
Andrii Kulian0864bbb2017-02-16 15:45:58 -08003034 /** Move activity with its stack to front and make the stack focused. */
Chong Zhang6cda19c2016-06-14 19:07:56 -07003035 boolean moveFocusableActivityStackToFrontLocked(ActivityRecord r, String reason) {
3036 if (r == null || !r.isFocusable()) {
3037 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3038 "moveActivityStackToFront: unfocusable r=" + r);
3039 return false;
3040 }
3041
Bryce Leeaf691c02017-03-20 14:20:22 -07003042 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003043 final ActivityStack stack = r.getStack();
3044 if (stack == null) {
Chong Zhang6cda19c2016-06-14 19:07:56 -07003045 Slog.w(TAG, "moveActivityStackToFront: invalid task or stack: r="
3046 + r + " task=" + task);
3047 return false;
3048 }
3049
Chong Zhang6cda19c2016-06-14 19:07:56 -07003050 if (stack == mFocusedStack && stack.topRunningActivityLocked() == r) {
3051 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3052 "moveActivityStackToFront: already on top, r=" + r);
3053 return false;
3054 }
3055
3056 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3057 "moveActivityStackToFront: r=" + r);
3058
3059 stack.moveToFront(reason, task);
3060 return true;
3061 }
3062
David Stevensc6b91c62017-02-08 14:23:58 -08003063 ActivityRecord findTaskLocked(ActivityRecord r, int displayId) {
Wale Ogunwale39381972015-12-17 17:15:29 -08003064 mTmpFindTaskResult.r = null;
3065 mTmpFindTaskResult.matchedByRootAffinity = false;
David Stevensc6b91c62017-02-08 14:23:58 -08003066 ActivityRecord affinityMatch = null;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003067 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
Craig Mautnere0a38842013-12-16 16:14:02 -08003068 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3069 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003070 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3071 final ActivityStack stack = stacks.get(stackNdx);
Winson Chung91e5c882017-04-21 14:44:38 -07003072 if (!checkActivityBelongsInStack(r, stack)) {
3073 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) "
3074 + stack);
Craig Mautner1b4bf852014-05-26 15:06:32 -07003075 continue;
3076 }
Wale Ogunwale39381972015-12-17 17:15:29 -08003077 stack.findTaskLocked(r, mTmpFindTaskResult);
David Stevensc6b91c62017-02-08 14:23:58 -08003078 // It is possible to have tasks in multiple stacks with the same root affinity, so
3079 // we should keep looking after finding an affinity match to see if there is a
3080 // better match in another stack. Also, task affinity isn't a good enough reason
3081 // to target a display which isn't the source of the intent, so skip any affinity
3082 // matches not on the specified display.
3083 if (mTmpFindTaskResult.r != null) {
3084 if (!mTmpFindTaskResult.matchedByRootAffinity) {
3085 return mTmpFindTaskResult.r;
3086 } else if (mTmpFindTaskResult.r.getDisplayId() == displayId) {
Winson Chung5b895b72017-05-01 13:46:25 -07003087 // Note: since the traversing through the stacks is top down, the floating
3088 // tasks should always have lower priority than any affinity-matching tasks
3089 // in the fullscreen stacks
David Stevensc6b91c62017-02-08 14:23:58 -08003090 affinityMatch = mTmpFindTaskResult.r;
3091 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003092 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003093 }
3094 }
Winson Chung5b895b72017-05-01 13:46:25 -07003095
David Stevensc6b91c62017-02-08 14:23:58 -08003096 if (DEBUG_TASKS && affinityMatch == null) Slog.d(TAG_TASKS, "No task found");
3097 return affinityMatch;
Craig Mautner8849a5e2013-04-02 16:41:03 -07003098 }
3099
Winson Chung91e5c882017-04-21 14:44:38 -07003100 /**
3101 * Checks that for the given activity {@param r}, its activity type matches the {@param stack}
3102 * type.
3103 */
3104 private boolean checkActivityBelongsInStack(ActivityRecord r, ActivityStack stack) {
3105 if (r.isHomeActivity()) {
3106 return stack.isHomeStack();
3107 } else if (r.isRecentsActivity()) {
3108 return stack.isRecentsStack();
3109 } else if (r.isAssistantActivity()) {
3110 return stack.isAssistantStack();
3111 }
3112 return true;
3113 }
3114
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003115 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
3116 boolean compareIntentFilters) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003117 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3118 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003119 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003120 final ActivityRecord ar = stacks.get(stackNdx)
3121 .findActivityLocked(intent, info, compareIntentFilters);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003122 if (ar != null) {
3123 return ar;
3124 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003125 }
3126 }
3127 return null;
3128 }
3129
David Stevens9440dc82017-03-16 19:00:20 -07003130 boolean hasAwakeDisplay() {
3131 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3132 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3133 if (!display.shouldSleep()) {
3134 return true;
3135 }
3136 }
3137 return false;
3138 }
3139
Craig Mautner8d341ef2013-03-26 09:03:27 -07003140 void goingToSleepLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003141 scheduleSleepTimeout();
3142 if (!mGoingToSleep.isHeld()) {
3143 mGoingToSleep.acquire();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003144 if (mLaunchingActivity.isHeld()) {
3145 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
3146 throw new IllegalStateException("Calling must be system uid");
Craig Mautner0eea92c2013-05-16 13:35:39 -07003147 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003148 mLaunchingActivity.release();
3149 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003150 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003151 }
David Stevens9440dc82017-03-16 19:00:20 -07003152
3153 applySleepTokensLocked(false /* applyToStacks */);
3154
3155 checkReadyForSleepLocked(true /* allowDelay */);
3156 }
3157
3158 void prepareForShutdownLocked() {
3159 for (int i = 0; i < mActivityDisplays.size(); i++) {
3160 createSleepTokenLocked("shutdown", mActivityDisplays.keyAt(i));
3161 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003162 }
3163
3164 boolean shutdownLocked(int timeout) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003165 goingToSleepLocked();
Craig Mautner0eea92c2013-05-16 13:35:39 -07003166
Craig Mautnerf4c909b2014-04-17 18:39:38 -07003167 boolean timedout = false;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003168 final long endTime = System.currentTimeMillis() + timeout;
3169 while (true) {
3170 boolean cantShutdown = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003171 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3172 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003173 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
David Stevens9440dc82017-03-16 19:00:20 -07003174 cantShutdown |=
3175 stacks.get(stackNdx).goToSleepIfPossible(true /* shuttingDown */);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003176 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003177 }
3178 if (cantShutdown) {
3179 long timeRemaining = endTime - System.currentTimeMillis();
3180 if (timeRemaining > 0) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003181 try {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003182 mService.wait(timeRemaining);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003183 } catch (InterruptedException e) {
3184 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003185 } else {
3186 Slog.w(TAG, "Activity manager shutdown timed out");
3187 timedout = true;
3188 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003189 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003190 } else {
3191 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003192 }
3193 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003194
3195 // Force checkReadyForSleep to complete.
David Stevens9440dc82017-03-16 19:00:20 -07003196 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003197
Craig Mautner8d341ef2013-03-26 09:03:27 -07003198 return timedout;
3199 }
3200
3201 void comeOutOfSleepIfNeededLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003202 removeSleepTimeouts();
3203 if (mGoingToSleep.isHeld()) {
3204 mGoingToSleep.release();
3205 }
David Stevens9440dc82017-03-16 19:00:20 -07003206 }
3207
3208 void applySleepTokensLocked(boolean applyToStacks) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003209 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
David Stevens9440dc82017-03-16 19:00:20 -07003210 // Set the sleeping state of the display.
3211 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3212 final boolean displayShouldSleep = display.shouldSleep();
3213 if (displayShouldSleep == display.isSleeping()) {
3214 continue;
3215 }
3216 display.setIsSleeping(displayShouldSleep);
3217
3218 if (!applyToStacks) {
3219 continue;
3220 }
3221
3222 // Set the sleeping state of the stacks on the display.
3223 final ArrayList<ActivityStack> stacks = display.mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003224 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3225 final ActivityStack stack = stacks.get(stackNdx);
David Stevens9440dc82017-03-16 19:00:20 -07003226 if (displayShouldSleep) {
3227 stack.goToSleepIfPossible(false /* shuttingDown */);
3228 } else {
3229 stack.awakeFromSleepingLocked();
3230 if (isFocusedStack(stack)) {
3231 resumeFocusedStackTopActivityLocked();
3232 }
3233 }
3234 }
3235
3236 if (displayShouldSleep || mGoingToSleepActivities.isEmpty()) {
3237 continue;
3238 }
3239 // The display is awake now, so clean up the going to sleep list.
3240 for (Iterator<ActivityRecord> it = mGoingToSleepActivities.iterator(); it.hasNext(); ) {
3241 final ActivityRecord r = it.next();
3242 if (r.getDisplayId() == display.mDisplayId) {
3243 it.remove();
Craig Mautner4a1cb222013-12-04 16:14:06 -08003244 }
Craig Mautner5314a402013-09-26 12:40:16 -07003245 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003246 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003247 }
3248
3249 void activitySleptLocked(ActivityRecord r) {
3250 mGoingToSleepActivities.remove(r);
David Stevens9440dc82017-03-16 19:00:20 -07003251 final ActivityStack s = r.getStack();
3252 if (s != null) {
3253 s.checkReadyForSleep();
3254 } else {
3255 checkReadyForSleepLocked(true);
3256 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003257 }
3258
David Stevens9440dc82017-03-16 19:00:20 -07003259 void checkReadyForSleepLocked(boolean allowDelay) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07003260 if (!mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003261 // Do not care.
3262 return;
3263 }
3264
David Stevens9440dc82017-03-16 19:00:20 -07003265 if (allowDelay) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003266 boolean dontSleep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003267 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
David Stevens9440dc82017-03-16 19:00:20 -07003268 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3269 final ArrayList<ActivityStack> stacks = display.mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003270 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
David Stevens9440dc82017-03-16 19:00:20 -07003271 dontSleep |= stacks.get(stackNdx).goToSleepIfPossible(false /* shuttingDown */);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003272 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003273 }
3274
Craig Mautner0eea92c2013-05-16 13:35:39 -07003275 if (dontSleep) {
3276 return;
3277 }
3278 }
3279
Wei Wang65c7a152016-06-02 18:51:22 -07003280 // Send launch end powerhint before going sleep
3281 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
3282
Craig Mautner0eea92c2013-05-16 13:35:39 -07003283 removeSleepTimeouts();
3284
3285 if (mGoingToSleep.isHeld()) {
3286 mGoingToSleep.release();
3287 }
3288 if (mService.mShuttingDown) {
3289 mService.notifyAll();
3290 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003291 }
3292
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003293 boolean reportResumedActivityLocked(ActivityRecord r) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07003294 final ActivityStack stack = r.getStack();
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003295 if (isFocusedStack(stack)) {
Jeff Sharkey5782da72013-04-25 14:32:30 -07003296 mService.updateUsageStats(r, true);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003297 }
3298 if (allResumedActivitiesComplete()) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003299 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003300 mWindowManager.executeAppTransition();
3301 return true;
3302 }
3303 return false;
3304 }
3305
Craig Mautner8d341ef2013-03-26 09:03:27 -07003306 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003307 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3308 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Wale Ogunwale28b23972015-07-29 16:01:50 -07003309 int stackNdx = stacks.size() - 1;
3310 while (stackNdx >= 0) {
3311 stacks.get(stackNdx).handleAppCrashLocked(app);
3312 stackNdx--;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003313 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003314 }
3315 }
3316
Craig Mautnerbb742462014-07-07 15:28:55 -07003317 // Called when WindowManager has finished animating the launchingBehind activity to the back.
Andrii Kulian21713ac2016-10-12 22:05:05 -07003318 private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003319 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003320 final ActivityStack stack = task.getStack();
Winson730bf062016-03-31 18:04:56 -07003321
3322 r.mLaunchTaskBehind = false;
Andrii Kulian21713ac2016-10-12 22:05:05 -07003323 task.setLastThumbnailLocked(r.screenshotActivityLocked());
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08003324 mRecentTasks.addLocked(task);
Yorke Leebd54c2a2016-10-25 13:49:23 -07003325 mService.mTaskChangeNotificationController.notifyTaskStackChanged();
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003326 r.setVisibility(false);
Winson730bf062016-03-31 18:04:56 -07003327
3328 // When launching tasks behind, update the last active time of the top task after the new
3329 // task has been shown briefly
3330 final ActivityRecord top = stack.topActivity();
3331 if (top != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003332 top.getTask().touchActiveTime();
Winson730bf062016-03-31 18:04:56 -07003333 }
Craig Mautnerbb742462014-07-07 15:28:55 -07003334 }
3335
3336 void scheduleLaunchTaskBehindComplete(IBinder token) {
3337 mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
3338 }
3339
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003340 void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
3341 boolean preserveWindows) {
Jorim Jaggife762342016-10-13 14:33:27 +02003342 mKeyguardController.beginActivityVisibilityUpdate();
3343 try {
3344 // First the front stacks. In case any are not fullscreen and are in front of home.
3345 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3346 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3347 final int topStackNdx = stacks.size() - 1;
3348 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3349 final ActivityStack stack = stacks.get(stackNdx);
3350 stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
3351 }
Craig Mautner580ea812013-04-25 12:58:38 -07003352 }
Jorim Jaggife762342016-10-13 14:33:27 +02003353 } finally {
3354 mKeyguardController.endActivityVisibilityUpdate();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003355 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003356 }
3357
Jorim Jaggi8b702ed2017-01-20 16:59:03 +01003358 void addStartingWindowsForVisibleActivities(boolean taskSwitch) {
3359 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3360 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3361 final int topStackNdx = stacks.size() - 1;
3362 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3363 final ActivityStack stack = stacks.get(stackNdx);
3364 stack.addStartingWindowsForVisibleActivities(taskSwitch);
3365 }
3366 }
3367 }
3368
Chong Zhangfdcc4d42015-10-14 16:50:12 -07003369 void invalidateTaskLayers() {
3370 mTaskLayersChanged = true;
3371 }
3372
3373 void rankTaskLayersIfNeeded() {
3374 if (!mTaskLayersChanged) {
3375 return;
3376 }
3377 mTaskLayersChanged = false;
3378 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
3379 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3380 int baseLayer = 0;
3381 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3382 baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
3383 }
3384 }
3385 }
3386
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07003387 void clearOtherAppTimeTrackers(AppTimeTracker except) {
3388 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3389 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3390 final int topStackNdx = stacks.size() - 1;
3391 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3392 final ActivityStack stack = stacks.get(stackNdx);
3393 stack.clearOtherAppTimeTrackers(except);
3394 }
3395 }
3396 }
3397
Craig Mautner8d341ef2013-03-26 09:03:27 -07003398 void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003399 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3400 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003401 final int numStacks = stacks.size();
3402 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
3403 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003404 stack.scheduleDestroyActivities(app, reason);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003405 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003406 }
3407 }
3408
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003409 void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
3410 // Examine all activities currently running in the process.
3411 TaskRecord firstTask = null;
3412 // Tasks is non-null only if two or more tasks are found.
3413 ArraySet<TaskRecord> tasks = null;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003414 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
3415 for (int i = 0; i < app.activities.size(); i++) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003416 ActivityRecord r = app.activities.get(i);
3417 // First, if we find an activity that is in the process of being destroyed,
3418 // then we just aren't going to do anything for now; we want things to settle
3419 // down before we try to prune more activities.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003420 if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003421 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003422 return;
3423 }
3424 // Don't consider any activies that are currently not in a state where they
3425 // can be destroyed.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003426 if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
3427 || r.state == PAUSED || r.state == STOPPING) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003428 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003429 continue;
3430 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003431
3432 final TaskRecord task = r.getTask();
3433 if (task != null) {
3434 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + task
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003435 + " from " + r);
3436 if (firstTask == null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003437 firstTask = task;
3438 } else if (firstTask != task) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003439 if (tasks == null) {
3440 tasks = new ArraySet<>();
3441 tasks.add(firstTask);
3442 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003443 tasks.add(task);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003444 }
3445 }
3446 }
3447 if (tasks == null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003448 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003449 return;
3450 }
3451 // If we have activities in multiple tasks that are in a position to be destroyed,
3452 // let's iterate through the tasks and release the oldest one.
3453 final int numDisplays = mActivityDisplays.size();
3454 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3455 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3456 // Step through all stacks starting from behind, to hit the oldest things first.
3457 for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
3458 final ActivityStack stack = stacks.get(stackNdx);
3459 // Try to release activities in this stack; if we manage to, we are done.
3460 if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
3461 return;
3462 }
3463 }
3464 }
3465 }
3466
Amith Yamasani37a40c22015-06-17 13:25:42 -07003467 boolean switchUserLocked(int userId, UserState uss) {
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003468 final int focusStackId = mFocusedStack.getStackId();
3469 // We dismiss the docked stack whenever we switch users.
3470 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, focusStackId == DOCKED_STACK_ID);
Winson Chungc2b23a52017-01-09 15:44:55 -08003471 // Also dismiss the pinned stack whenever we switch users. Removing the pinned stack will
3472 // also cause all tasks to be moved to the fullscreen stack at a position that is
3473 // appropriate.
3474 removeStackLocked(PINNED_STACK_ID);
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003475
3476 mUserStackInFront.put(mCurrentUser, focusStackId);
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003477 final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
Craig Mautner2420ead2013-04-01 17:13:20 -07003478 mCurrentUser = userId;
Craig Mautnerac6f8432013-07-17 13:24:59 -07003479
Craig Mautner858d8a62013-04-23 17:08:34 -07003480 mStartingUsers.add(uss);
Craig Mautnere0a38842013-12-16 16:14:02 -08003481 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3482 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003483 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003484 final ActivityStack stack = stacks.get(stackNdx);
3485 stack.switchUserLocked(userId);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003486 TaskRecord task = stack.topTask();
3487 if (task != null) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08003488 stack.positionChildWindowContainerAtTop(task);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003489 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003490 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07003491 }
Craig Mautner858d8a62013-04-23 17:08:34 -07003492
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003493 ActivityStack stack = getStack(restoreStackId);
3494 if (stack == null) {
3495 stack = mHomeStack;
3496 }
3497 final boolean homeInFront = stack.isHomeStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08003498 if (stack.isOnHomeDisplay()) {
Wale Ogunwale925d0d12015-09-23 15:40:07 -07003499 stack.moveToFront("switchUserOnHomeDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003500 } else {
3501 // Stack was moved to another display while user was swapped out.
Matthew Ngae1ff4f2016-11-10 15:49:14 -08003502 resumeHomeStackTask(null, "switchUserOnOtherDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003503 }
Craig Mautner93529a42013-10-04 15:03:13 -07003504 return homeInFront;
Craig Mautner2219a1b2013-03-25 09:44:30 -07003505 }
3506
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003507 /** Checks whether the userid is a profile of the current user. */
3508 boolean isCurrentProfileLocked(int userId) {
3509 if (userId == mCurrentUser) return true;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07003510 return mService.mUserController.isCurrentProfileLocked(userId);
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003511 }
3512
Bryce Leeb7c9b802017-05-02 14:20:24 -07003513 /**
3514 * Returns whether a stopping activity is present that should be stopped after visible, rather
3515 * than idle.
3516 * @return {@code true} if such activity is present. {@code false} otherwise.
3517 */
3518 boolean isStoppingNoHistoryActivity() {
3519 // Activities that are marked as nohistory should be stopped immediately after the resumed
3520 // activity has become visible.
3521 for (ActivityRecord record : mStoppingActivities) {
3522 if (record.isNoHistory()) {
3523 return true;
3524 }
3525 }
3526
3527 return false;
3528 }
3529
Winson Chung4dabf232017-01-25 13:25:22 -08003530 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
3531 boolean remove, boolean processPausingActivities) {
Craig Mautnerde4ef022013-04-07 19:01:33 -07003532 ArrayList<ActivityRecord> stops = null;
3533
3534 final boolean nowVisible = allResumedActivitiesVisible();
Craig Mautner8c14c152015-01-15 17:32:07 -08003535 for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3536 ActivityRecord s = mStoppingActivities.get(activityNdx);
Bryce Lee4a194382017-04-04 14:32:48 -07003537 boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003538 if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
Craig Mautner8c14c152015-01-15 17:32:07 -08003539 + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
3540 if (waitingVisible && nowVisible) {
Bryce Lee4a194382017-04-04 14:32:48 -07003541 mActivitiesWaitingForVisibleActivity.remove(s);
Andrii Kulianee056812016-09-21 15:34:45 -07003542 waitingVisible = false;
Craig Mautnerde4ef022013-04-07 19:01:33 -07003543 if (s.finishing) {
3544 // If this activity is finishing, it is sitting on top of
3545 // everyone else but we now know it is no longer needed...
3546 // so get rid of it. Otherwise, we need to go through the
3547 // normal flow and hide it once we determine that it is
3548 // hidden by the activities in front of it.
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003549 if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003550 s.setVisibility(false);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003551 }
3552 }
David Stevens9440dc82017-03-16 19:00:20 -07003553 if (remove) {
3554 final ActivityStack stack = s.getStack();
3555 final boolean shouldSleepOrShutDown = stack != null
3556 ? stack.shouldSleepOrShutDownActivities()
3557 : mService.isSleepingOrShuttingDownLocked();
3558 if (!waitingVisible || shouldSleepOrShutDown) {
3559 if (!processPausingActivities && s.state == PAUSING) {
3560 // Defer processing pausing activities in this iteration and reschedule
3561 // a delayed idle to reprocess it again
3562 removeTimeoutsForActivityLocked(idleActivity);
3563 scheduleIdleTimeoutLocked(idleActivity);
3564 continue;
3565 }
Winson Chung4dabf232017-01-25 13:25:22 -08003566
David Stevens9440dc82017-03-16 19:00:20 -07003567 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
3568 if (stops == null) {
3569 stops = new ArrayList<>();
3570 }
3571 stops.add(s);
3572 mStoppingActivities.remove(activityNdx);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003573 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07003574 }
3575 }
3576
3577 return stops;
3578 }
3579
Craig Mautnercf910b02013-04-23 11:23:27 -07003580 void validateTopActivitiesLocked() {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003581 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3582 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3583 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3584 final ActivityStack stack = stacks.get(stackNdx);
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07003585 final ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003586 final ActivityState state = r == null ? DESTROYED : r.state;
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003587 if (isFocusedStack(stack)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003588 if (r == null) Slog.e(TAG,
3589 "validateTop...: null top activity, stack=" + stack);
3590 else {
3591 final ActivityRecord pausing = stack.mPausingActivity;
3592 if (pausing != null && pausing == r) Slog.e(TAG,
3593 "validateTop...: top stack has pausing activity r=" + r
3594 + " state=" + state);
3595 if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3596 "validateTop...: activity in front not resumed r=" + r
3597 + " state=" + state);
3598 }
Craig Mautnercf910b02013-04-23 11:23:27 -07003599 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003600 final ActivityRecord resumed = stack.mResumedActivity;
3601 if (resumed != null && resumed == r) Slog.e(TAG,
3602 "validateTop...: back stack has resumed activity r=" + r
3603 + " state=" + state);
3604 if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3605 "validateTop...: activity in back resumed r=" + r + " state=" + state);
Craig Mautnercf910b02013-04-23 11:23:27 -07003606 }
3607 }
3608 }
Craig Mautner76ea2242013-05-15 11:40:05 -07003609 }
3610
Craig Mautnere0570202015-05-13 13:06:11 -07003611 private String lockTaskModeToString() {
3612 switch (mLockTaskModeState) {
3613 case LOCK_TASK_MODE_LOCKED:
3614 return "LOCKED";
3615 case LOCK_TASK_MODE_PINNED:
3616 return "PINNED";
3617 case LOCK_TASK_MODE_NONE:
3618 return "NONE";
3619 default: return "unknown=" + mLockTaskModeState;
3620 }
3621 }
3622
Craig Mautner27084302013-03-25 08:05:25 -07003623 public void dump(PrintWriter pw, String prefix) {
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003624 pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003625 pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
Suprabh Shukla09a88f52015-12-02 14:36:31 -08003626 pw.print(prefix);
3627 pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003628 pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003629 pw.print(prefix); pw.println("mStacks=" + mStacks);
Craig Mautnere0570202015-05-13 13:06:11 -07003630 pw.print(prefix); pw.print("mLockTaskModeState=" + lockTaskModeToString());
Jorim Jaggi8d786932016-10-26 19:08:36 -07003631 final SparseArray<String[]> packages = mService.mLockTaskPackages;
3632 if (packages.size() > 0) {
3633 pw.print(prefix); pw.println("mLockTaskPackages (userId:packages)=");
3634 for (int i = 0; i < packages.size(); ++i) {
3635 pw.print(prefix); pw.print(prefix); pw.print(packages.keyAt(i));
3636 pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
3637 }
3638 }
Bryce Lee4a194382017-04-04 14:32:48 -07003639 if (!mWaitingForActivityVisible.isEmpty()) {
3640 pw.print(prefix); pw.println("mWaitingForActivityVisible=");
3641 for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
3642 pw.print(prefix); pw.print(prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
3643 }
3644 }
3645
Jorim Jaggi8d786932016-10-26 19:08:36 -07003646 pw.println(" mLockTaskModeTasks" + mLockTaskModeTasks);
3647 mKeyguardController.dump(pw, prefix);
Craig Mautner27084302013-03-25 08:05:25 -07003648 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003649
Winson43d1f262016-06-14 16:05:55 -07003650 /**
Andrii Kulian5406e7a2016-10-21 11:55:23 -07003651 * Dump all connected displays' configurations.
3652 * @param prefix Prefix to apply to each line of the dump.
3653 */
3654 void dumpDisplayConfigs(PrintWriter pw, String prefix) {
3655 pw.print(prefix); pw.println("Display override configurations:");
3656 final int displayCount = mActivityDisplays.size();
3657 for (int i = 0; i < displayCount; i++) {
3658 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(i);
3659 pw.print(prefix); pw.print(" "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
3660 pw.println(activityDisplay.getOverrideConfiguration());
3661 }
3662 }
3663
3664 /**
Winson43d1f262016-06-14 16:05:55 -07003665 * Dumps the activities matching the given {@param name} in the either the focused stack
3666 * or all visible stacks if {@param dumpVisibleStacks} is true.
3667 */
Winson Chung6998bc42017-02-28 17:07:05 -08003668 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name, boolean dumpVisibleStacksOnly,
3669 boolean dumpFocusedStackOnly) {
3670 if (dumpFocusedStackOnly) {
3671 return mFocusedStack.getDumpActivitiesLocked(name);
3672 } else {
Winson43d1f262016-06-14 16:05:55 -07003673 ArrayList<ActivityRecord> activities = new ArrayList<>();
3674 int numDisplays = mActivityDisplays.size();
3675 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3676 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3677 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3678 ActivityStack stack = stacks.get(stackNdx);
Winson Chung6998bc42017-02-28 17:07:05 -08003679 if (!dumpVisibleStacksOnly ||
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07003680 stack.shouldBeVisible(null) == STACK_VISIBLE) {
Winson43d1f262016-06-14 16:05:55 -07003681 activities.addAll(stack.getDumpActivitiesLocked(name));
3682 }
3683 }
3684 }
3685 return activities;
Winson43d1f262016-06-14 16:05:55 -07003686 }
Craig Mautner20e72272013-04-01 13:45:53 -07003687 }
3688
Dianne Hackborn390517b2013-05-30 15:03:32 -07003689 static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3690 boolean needSep, String prefix) {
3691 if (activity != null) {
3692 if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3693 if (needSep) {
3694 pw.println();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003695 }
3696 pw.print(prefix);
3697 pw.println(activity);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003698 return true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003699 }
3700 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003701 return false;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003702 }
3703
Craig Mautner8d341ef2013-03-26 09:03:27 -07003704 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3705 boolean dumpClient, String dumpPackage) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003706 boolean printed = false;
3707 boolean needSep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003708 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3709 ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003710 pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
Craig Mautner737fae22014-10-15 12:52:10 -07003711 pw.println(" (activities from top to bottom):");
Craig Mautnere0a38842013-12-16 16:14:02 -08003712 ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
Craig Mautner737fae22014-10-15 12:52:10 -07003713 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003714 final ActivityStack stack = stacks.get(stackNdx);
3715 StringBuilder stackHeader = new StringBuilder(128);
3716 stackHeader.append(" Stack #");
3717 stackHeader.append(stack.mStackId);
3718 stackHeader.append(":");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003719 stackHeader.append("\n");
3720 stackHeader.append(" mFullscreen=" + stack.mFullscreen);
3721 stackHeader.append("\n");
David Stevens9440dc82017-03-16 19:00:20 -07003722 stackHeader.append(" isSleeping=" + stack.shouldSleepActivities());
3723 stackHeader.append("\n");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003724 stackHeader.append(" mBounds=" + stack.mBounds);
Winson Chungabb433b2017-03-24 09:35:42 -07003725
3726 final boolean printedStackHeader = stack.dumpActivitiesLocked(fd, pw, dumpAll,
3727 dumpClient, dumpPackage, needSep, stackHeader.toString());
3728 printed |= printedStackHeader;
3729 if (!printedStackHeader) {
3730 // Ensure we always dump the stack header even if there are no activities
3731 pw.println();
3732 pw.println(stackHeader);
3733 }
3734
Craig Mautner4a1cb222013-12-04 16:14:06 -08003735 printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, " ", "Run", false,
3736 !dumpAll, false, dumpPackage, true,
3737 " Running activities (most recent first):", null);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003738
Craig Mautner4a1cb222013-12-04 16:14:06 -08003739 needSep = printed;
3740 boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3741 " mPausingActivity: ");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003742 if (pr) {
3743 printed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003744 needSep = false;
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003745 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003746 pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3747 " mResumedActivity: ");
3748 if (pr) {
3749 printed = true;
3750 needSep = false;
3751 }
3752 if (dumpAll) {
3753 pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3754 " mLastPausedActivity: ");
3755 if (pr) {
3756 printed = true;
3757 needSep = true;
3758 }
3759 printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3760 needSep, " mLastNoHistoryActivity: ");
3761 }
3762 needSep = printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003763 }
3764 }
3765
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003766 printed |= dumpHistoryList(fd, pw, mFinishingActivities, " ", "Fin", false, !dumpAll,
3767 false, dumpPackage, true, " Activities waiting to finish:", null);
3768 printed |= dumpHistoryList(fd, pw, mStoppingActivities, " ", "Stop", false, !dumpAll,
3769 false, dumpPackage, true, " Activities waiting to stop:", null);
Bryce Lee4a194382017-04-04 14:32:48 -07003770 printed |= dumpHistoryList(fd, pw, mActivitiesWaitingForVisibleActivity, " ", "Wait",
3771 false, !dumpAll, false, dumpPackage, true,
3772 " Activities waiting for another to become visible:", null);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003773 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3774 false, dumpPackage, true, " Activities waiting to sleep:", null);
Craig Mautnerf3333272013-04-22 10:55:53 -07003775
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003776 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003777 }
3778
Dianne Hackborn390517b2013-05-30 15:03:32 -07003779 static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
Craig Mautner8d341ef2013-03-26 09:03:27 -07003780 String prefix, String label, boolean complete, boolean brief, boolean client,
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003781 String dumpPackage, boolean needNL, String header1, String header2) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003782 TaskRecord lastTask = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003783 String innerPrefix = null;
3784 String[] args = null;
3785 boolean printed = false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003786 for (int i=list.size()-1; i>=0; i--) {
3787 final ActivityRecord r = list.get(i);
3788 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3789 continue;
3790 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003791 if (innerPrefix == null) {
3792 innerPrefix = prefix + " ";
3793 args = new String[0];
3794 }
3795 printed = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003796 final boolean full = !brief && (complete || !r.isInHistory());
3797 if (needNL) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003798 pw.println("");
Craig Mautner8d341ef2013-03-26 09:03:27 -07003799 needNL = false;
3800 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003801 if (header1 != null) {
3802 pw.println(header1);
3803 header1 = null;
3804 }
3805 if (header2 != null) {
3806 pw.println(header2);
3807 header2 = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003808 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003809 if (lastTask != r.getTask()) {
3810 lastTask = r.getTask();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003811 pw.print(prefix);
3812 pw.print(full ? "* " : " ");
3813 pw.println(lastTask);
3814 if (full) {
3815 lastTask.dump(pw, prefix + " ");
3816 } else if (complete) {
3817 // Complete + brief == give a summary. Isn't that obvious?!?
3818 if (lastTask.intent != null) {
3819 pw.print(prefix); pw.print(" ");
3820 pw.println(lastTask.intent.toInsecureStringWithClip());
3821 }
3822 }
3823 }
3824 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
3825 pw.print(" #"); pw.print(i); pw.print(": ");
3826 pw.println(r);
3827 if (full) {
3828 r.dump(pw, innerPrefix);
3829 } else if (complete) {
3830 // Complete + brief == give a summary. Isn't that obvious?!?
3831 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3832 if (r.app != null) {
3833 pw.print(innerPrefix); pw.println(r.app);
3834 }
3835 }
3836 if (client && r.app != null && r.app.thread != null) {
3837 // flush anything that is already in the PrintWriter since the thread is going
3838 // to write to the file descriptor directly
3839 pw.flush();
3840 try {
3841 TransferPipe tp = new TransferPipe();
3842 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003843 r.app.thread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003844 // Short timeout, since blocking here can
3845 // deadlock with the application.
3846 tp.go(fd, 2000);
3847 } finally {
3848 tp.kill();
3849 }
3850 } catch (IOException e) {
3851 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3852 } catch (RemoteException e) {
3853 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3854 }
3855 needNL = true;
3856 }
3857 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003858 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003859 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003860
Craig Mautnerf3333272013-04-22 10:55:53 -07003861 void scheduleIdleTimeoutLocked(ActivityRecord next) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003862 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3863 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
Craig Mautnerc64f73e2013-04-24 16:44:56 -07003864 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
3865 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
Craig Mautnerf3333272013-04-22 10:55:53 -07003866 }
3867
3868 final void scheduleIdleLocked() {
Craig Mautner05d29032013-05-03 13:40:13 -07003869 mHandler.sendEmptyMessage(IDLE_NOW_MSG);
Craig Mautnerf3333272013-04-22 10:55:53 -07003870 }
3871
3872 void removeTimeoutsForActivityLocked(ActivityRecord r) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003873 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
3874 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07003875 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3876 }
3877
Craig Mautner05d29032013-05-03 13:40:13 -07003878 final void scheduleResumeTopActivities() {
Craig Mautner34b73df2014-01-12 21:11:08 -08003879 if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
3880 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
3881 }
Craig Mautner05d29032013-05-03 13:40:13 -07003882 }
3883
Craig Mautner0eea92c2013-05-16 13:35:39 -07003884 void removeSleepTimeouts() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003885 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
3886 }
3887
3888 final void scheduleSleepTimeout() {
3889 removeSleepTimeouts();
3890 mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
3891 }
3892
Craig Mautner4a1cb222013-12-04 16:14:06 -08003893 @Override
3894 public void onDisplayAdded(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003895 if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003896 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
3897 }
3898
3899 @Override
3900 public void onDisplayRemoved(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003901 if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003902 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
3903 }
3904
3905 @Override
3906 public void onDisplayChanged(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003907 if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003908 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
3909 }
3910
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003911 private void handleDisplayAdded(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003912 synchronized (mService) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003913 getActivityDisplayOrCreateLocked(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003914 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003915 }
3916
Andrii Kulianca007a62016-11-22 16:33:28 -08003917 /** Check if display with specified id is added to the list. */
3918 boolean isDisplayAdded(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003919 return getActivityDisplayOrCreateLocked(displayId) != null;
3920 }
3921
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003922 ActivityDisplay getActivityDisplay(int displayId) {
3923 return mActivityDisplays.get(displayId);
3924 }
3925
Andrii Kulian62e6f252017-05-30 22:46:53 -07003926 /**
3927 * Get an existing instance of {@link ActivityDisplay} or create new if there is a
3928 * corresponding record in display manager.
3929 */
3930 private ActivityDisplay getActivityDisplayOrCreateLocked(int displayId) {
3931 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3932 if (activityDisplay != null) {
3933 return activityDisplay;
3934 }
3935 if (mDisplayManager == null) {
3936 // The system isn't fully initialized yet.
3937 return null;
3938 }
3939 final Display display = mDisplayManager.getDisplay(displayId);
3940 if (display == null) {
3941 // The display is not registered in DisplayManager.
3942 return null;
3943 }
3944 // The display hasn't been added to ActivityManager yet, create a new record now.
3945 activityDisplay = new ActivityDisplay(displayId);
3946 if (activityDisplay.mDisplay == null) {
3947 Slog.w(TAG, "Display " + displayId + " gone before initialization complete");
3948 return null;
3949 }
3950 mActivityDisplays.put(displayId, activityDisplay);
3951 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
3952 mWindowManager.onDisplayAdded(displayId);
3953 return activityDisplay;
Andrii Kulianca007a62016-11-22 16:33:28 -08003954 }
3955
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003956 private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
Andrii Kulianf66a83d2016-05-17 12:17:44 -07003957 mDefaultMinSizeOfResizeableTask =
Jorim Jaggi19cf2972016-04-07 23:26:10 -07003958 mService.mContext.getResources().getDimensionPixelSize(
3959 com.android.internal.R.dimen.default_minimal_size_resizable_task);
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003960 }
3961
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003962 private void handleDisplayRemoved(int displayId) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003963 if (displayId == DEFAULT_DISPLAY) {
3964 throw new IllegalArgumentException("Can't remove the primary display.");
3965 }
3966
Craig Mautner4a1cb222013-12-04 16:14:06 -08003967 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003968 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3969 if (activityDisplay != null) {
Andrii Kulian250d6532017-02-08 23:30:45 -08003970 final boolean destroyContentOnRemoval
3971 = activityDisplay.shouldDestroyContentOnRemove();
Andrii Kuliana33818c2017-02-16 16:11:30 -08003972 final ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3973 while (!stacks.isEmpty()) {
3974 final ActivityStack stack = stacks.get(0);
Andrii Kulian250d6532017-02-08 23:30:45 -08003975 if (destroyContentOnRemoval) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003976 moveStackToDisplayLocked(stack.mStackId, DEFAULT_DISPLAY,
3977 false /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003978 stack.finishAllActivitiesLocked(true /* immediately */);
Andrii Kuliana33818c2017-02-16 16:11:30 -08003979 } else {
3980 // Moving all tasks to fullscreen stack, because it's guaranteed to be
3981 // a valid launch stack for all activities. This way the task history from
3982 // external display will be preserved on primary after move.
3983 moveTasksToFullscreenStackLocked(stack.getStackId(), true /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003984 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003985 }
David Stevens9440dc82017-03-16 19:00:20 -07003986
3987 releaseSleepTokens(activityDisplay);
3988
Craig Mautnere0a38842013-12-16 16:14:02 -08003989 mActivityDisplays.remove(displayId);
Bryce Leeaf3a4002017-03-20 10:37:12 -07003990 mWindowManager.onDisplayRemoved(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003991 }
3992 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003993 }
3994
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003995 private void handleDisplayChanged(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003996 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003997 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3998 if (activityDisplay != null) {
David Stevens9440dc82017-03-16 19:00:20 -07003999 // The window policy is responsible for stopping activities on the default display
4000 if (displayId != Display.DEFAULT_DISPLAY) {
4001 int displayState = activityDisplay.mDisplay.getState();
4002 if (displayState == Display.STATE_OFF && activityDisplay.mOffToken == null) {
4003 activityDisplay.mOffToken =
4004 mService.acquireSleepToken("Display-off", displayId);
4005 } else if (displayState == Display.STATE_ON
4006 && activityDisplay.mOffToken != null) {
4007 activityDisplay.mOffToken.release();
4008 activityDisplay.mOffToken = null;
4009 }
4010 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004011 // TODO: Update the bounds.
4012 }
Bryce Leeaf3a4002017-03-20 10:37:12 -07004013 mWindowManager.onDisplayChanged(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004014 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004015 }
4016
David Stevens9440dc82017-03-16 19:00:20 -07004017 SleepToken createSleepTokenLocked(String tag, int displayId) {
4018 ActivityDisplay display = mActivityDisplays.get(displayId);
4019 if (display == null) {
4020 throw new IllegalArgumentException("Invalid display: " + displayId);
4021 }
4022
4023 final SleepTokenImpl token = new SleepTokenImpl(tag, displayId);
4024 mSleepTokens.add(token);
4025 display.mAllSleepTokens.add(token);
4026 return token;
4027 }
4028
4029 private void removeSleepTokenLocked(SleepTokenImpl token) {
4030 mSleepTokens.remove(token);
4031
4032 ActivityDisplay display = mActivityDisplays.get(token.mDisplayId);
4033 if (display != null) {
4034 display.mAllSleepTokens.remove(token);
4035 if (display.mAllSleepTokens.isEmpty()) {
4036 mService.updateSleepIfNeededLocked();
4037 }
4038 }
4039 }
4040
4041 private void releaseSleepTokens(ActivityDisplay display) {
4042 if (display.mAllSleepTokens.isEmpty()) {
4043 return;
4044 }
4045 for (SleepTokenImpl token : display.mAllSleepTokens) {
4046 mSleepTokens.remove(token);
4047 }
4048 display.mAllSleepTokens.clear();
4049
4050 mService.updateSleepIfNeededLocked();
4051 }
4052
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004053 private StackInfo getStackInfoLocked(ActivityStack stack) {
Andrii Kulian7e215d72017-04-26 18:33:28 -07004054 final int displayId = stack.mDisplayId;
4055 final ActivityDisplay display = mActivityDisplays.get(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004056 StackInfo info = new StackInfo();
Wale Ogunwale1666e312016-12-16 11:27:18 -08004057 stack.getWindowContainerBounds(info.bounds);
Andrii Kulian7e215d72017-04-26 18:33:28 -07004058 info.displayId = displayId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004059 info.stackId = stack.mStackId;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004060 info.userId = stack.mCurrentUser;
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004061 info.visible = stack.shouldBeVisible(null) == STACK_VISIBLE;
Andrii Kulian62e6f252017-05-30 22:46:53 -07004062 // A stack might be not attached to a display.
Winson529c8e42016-05-17 11:08:40 -07004063 info.position = display != null
4064 ? display.mStacks.indexOf(stack)
4065 : 0;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004066
4067 ArrayList<TaskRecord> tasks = stack.getAllTasks();
4068 final int numTasks = tasks.size();
4069 int[] taskIds = new int[numTasks];
4070 String[] taskNames = new String[numTasks];
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004071 Rect[] taskBounds = new Rect[numTasks];
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004072 int[] taskUserIds = new int[numTasks];
Craig Mautner4a1cb222013-12-04 16:14:06 -08004073 for (int i = 0; i < numTasks; ++i) {
4074 final TaskRecord task = tasks.get(i);
4075 taskIds[i] = task.taskId;
4076 taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
4077 : task.realActivity != null ? task.realActivity.flattenToString()
4078 : task.getTopActivity() != null ? task.getTopActivity().packageName
4079 : "unknown";
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004080 taskBounds[i] = new Rect();
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004081 task.getWindowContainerBounds(taskBounds[i]);
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004082 taskUserIds[i] = task.userId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004083 }
4084 info.taskIds = taskIds;
4085 info.taskNames = taskNames;
Wale Ogunwale868a5e12015-08-02 16:19:20 -07004086 info.taskBounds = taskBounds;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004087 info.taskUserIds = taskUserIds;
Winsond46b7272016-04-20 11:54:27 -07004088
4089 final ActivityRecord top = stack.topRunningActivityLocked();
4090 info.topActivity = top != null ? top.intent.getComponent() : null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004091 return info;
4092 }
4093
4094 StackInfo getStackInfoLocked(int stackId) {
4095 ActivityStack stack = getStack(stackId);
4096 if (stack != null) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004097 return getStackInfoLocked(stack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004098 }
4099 return null;
4100 }
4101
4102 ArrayList<StackInfo> getAllStackInfosLocked() {
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004103 ArrayList<StackInfo> list = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08004104 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
4105 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004106 for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004107 list.add(getStackInfoLocked(stacks.get(ndx)));
Craig Mautner4a1cb222013-12-04 16:14:06 -08004108 }
4109 }
4110 return list;
4111 }
4112
Craig Mautner15df08a2015-04-01 12:17:18 -07004113 TaskRecord getLockedTaskLocked() {
4114 final int top = mLockTaskModeTasks.size() - 1;
4115 if (top >= 0) {
4116 return mLockTaskModeTasks.get(top);
4117 }
4118 return null;
4119 }
4120
4121 boolean isLockedTask(TaskRecord task) {
4122 return mLockTaskModeTasks.contains(task);
4123 }
4124
4125 boolean isLastLockedTask(TaskRecord task) {
4126 return mLockTaskModeTasks.size() == 1 && mLockTaskModeTasks.contains(task);
4127 }
4128
4129 void removeLockedTaskLocked(final TaskRecord task) {
Craig Mautner432f64e2015-05-20 14:59:57 -07004130 if (!mLockTaskModeTasks.remove(task)) {
4131 return;
4132 }
4133 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "removeLockedTaskLocked: removed " + task);
4134 if (mLockTaskModeTasks.isEmpty()) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004135 // Last one.
Craig Mautnere0570202015-05-13 13:06:11 -07004136 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
4137 " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
Craig Mautner15df08a2015-04-01 12:17:18 -07004138 final Message lockTaskMsg = Message.obtain();
4139 lockTaskMsg.arg1 = task.userId;
4140 lockTaskMsg.what = LOCK_TASK_END_MSG;
4141 mHandler.sendMessage(lockTaskMsg);
4142 }
4143 }
4144
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004145 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4146 int preferredDisplayId, int actualStackId) {
4147 handleNonResizableTaskIfNeeded(task, preferredStackId, preferredDisplayId, actualStackId,
Andrii Kulianc27916642016-04-12 17:59:27 -07004148 false /* forceNonResizable */);
4149 }
4150
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004151 private void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4152 int preferredDisplayId, int actualStackId, boolean forceNonResizable) {
4153 final boolean isSecondaryDisplayPreferred =
4154 (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY)
4155 || StackId.isDynamicStack(preferredStackId);
4156 if (((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
4157 && !isSecondaryDisplayPreferred) || task.isHomeTask()) {
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004158 return;
4159 }
4160
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004161 // Handle incorrect launch/move to secondary display if needed.
4162 final boolean launchOnSecondaryDisplayFailed;
4163 if (isSecondaryDisplayPreferred) {
4164 final int actualDisplayId = task.getStack().mDisplayId;
4165 if (!task.canBeLaunchedOnDisplay(actualDisplayId)) {
4166 // The task landed on an inappropriate display somehow, move it to the default
4167 // display.
4168 // TODO(multi-display): Find proper stack for the task on the default display.
4169 mService.moveTaskToStack(task.taskId, FULLSCREEN_WORKSPACE_STACK_ID,
4170 true /* toTop */);
4171 launchOnSecondaryDisplayFailed = true;
4172 } else {
4173 // The task might have landed on a display different from requested.
4174 launchOnSecondaryDisplayFailed = actualDisplayId == DEFAULT_DISPLAY
4175 || (preferredDisplayId != INVALID_DISPLAY
4176 && preferredDisplayId != actualDisplayId);
4177 }
4178 } else {
4179 // The task wasn't requested to be on a secondary display.
4180 launchOnSecondaryDisplayFailed = false;
4181 }
4182
Jorim Jaggicd13d332016-04-27 15:40:20 -07004183 final ActivityRecord topActivity = task.getTopActivity();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004184 if (launchOnSecondaryDisplayFailed || !task.supportsSplitScreen() || forceNonResizable) {
4185 if (launchOnSecondaryDisplayFailed) {
4186 // Display a warning toast that we tried to put a non-resizeable task on a secondary
4187 // display with config different from global config.
4188 mService.mTaskChangeNotificationController
4189 .notifyActivityLaunchOnSecondaryDisplayFailed();
4190 } else {
4191 // Display a warning toast that we tried to put a non-dockable task in the docked
4192 // stack.
4193 mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
4194 }
Jorim Jaggid53f0922016-04-06 22:16:23 -07004195
Andrii Kulianc27916642016-04-12 17:59:27 -07004196 // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
4197 // we need to move it to top of fullscreen stack, otherwise it will be covered.
Wale Ogunwale9a98c522016-04-27 09:23:55 -07004198 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
Winson Chungd3395382016-12-13 11:49:09 -08004199 } else if (topActivity != null && topActivity.isNonResizableOrForcedResizable()
Jorim Jaggicd13d332016-04-27 15:40:20 -07004200 && !topActivity.noDisplay) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004201 final String packageName = topActivity.appInfo.packageName;
4202 final int reason = isSecondaryDisplayPreferred
4203 ? FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY
4204 : FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Yorke Leebd54c2a2016-10-25 13:49:23 -07004205 mService.mTaskChangeNotificationController.notifyActivityForcedResizable(
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004206 task.taskId, reason, packageName);
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004207 }
Chong Zhangb15758a2015-11-17 12:12:03 -08004208 }
4209
Craig Mautner6cd6cec2015-04-01 00:02:12 -07004210 void showLockTaskToast() {
Hall Liu45784f12016-05-31 15:50:48 -07004211 if (mLockTaskNotify != null) {
4212 mLockTaskNotify.showToast(mLockTaskModeState);
4213 }
Jason Monka8f569c2014-07-07 12:15:21 -04004214 }
4215
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004216 void showLockTaskEscapeMessageLocked(TaskRecord task) {
4217 if (mLockTaskModeTasks.contains(task)) {
4218 mHandler.sendEmptyMessage(SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG);
4219 }
4220 }
4221
Craig Mautner432f64e2015-05-20 14:59:57 -07004222 void setLockTaskModeLocked(TaskRecord task, int lockTaskModeState, String reason,
4223 boolean andResume) {
Craig Mautneraea74a52014-03-08 14:23:10 -08004224 if (task == null) {
Christopher Tate3bd90612014-06-18 16:37:52 -07004225 // Take out of lock task mode if necessary
Craig Mautner15df08a2015-04-01 12:17:18 -07004226 final TaskRecord lockedTask = getLockedTaskLocked();
4227 if (lockedTask != null) {
4228 removeLockedTaskLocked(lockedTask);
4229 if (!mLockTaskModeTasks.isEmpty()) {
4230 // There are locked tasks remaining, can only finish this task, not unlock it.
Craig Mautnere0570202015-05-13 13:06:11 -07004231 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4232 "setLockTaskModeLocked: Tasks remaining, can't unlock");
Craig Mautner15df08a2015-04-01 12:17:18 -07004233 lockedTask.performClearTaskLocked();
Wale Ogunwaled046a012015-12-24 13:05:59 -08004234 resumeFocusedStackTopActivityLocked();
Craig Mautner15df08a2015-04-01 12:17:18 -07004235 return;
4236 }
Christopher Tate3bd90612014-06-18 16:37:52 -07004237 }
Craig Mautnere0570202015-05-13 13:06:11 -07004238 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4239 "setLockTaskModeLocked: No tasks to unlock. Callers=" + Debug.getCallers(4));
Craig Mautneraea74a52014-03-08 14:23:10 -08004240 return;
4241 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004242
4243 // Should have already been checked, but do it again.
4244 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
Craig Mautnere0570202015-05-13 13:06:11 -07004245 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4246 "setLockTaskModeLocked: Can't lock due to auth");
Craig Mautneraea74a52014-03-08 14:23:10 -08004247 return;
4248 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004249 if (isLockTaskModeViolation(task)) {
Craig Mautnere0570202015-05-13 13:06:11 -07004250 Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
Craig Mautner15df08a2015-04-01 12:17:18 -07004251 return;
4252 }
4253
4254 if (mLockTaskModeTasks.isEmpty()) {
4255 // First locktask.
4256 final Message lockTaskMsg = Message.obtain();
4257 lockTaskMsg.obj = task.intent.getComponent().getPackageName();
4258 lockTaskMsg.arg1 = task.userId;
4259 lockTaskMsg.what = LOCK_TASK_START_MSG;
4260 lockTaskMsg.arg2 = lockTaskModeState;
4261 mHandler.sendMessage(lockTaskMsg);
4262 }
4263 // Add it or move it to the top.
Craig Mautnere0570202015-05-13 13:06:11 -07004264 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskModeLocked: Locking to " + task +
4265 " Callers=" + Debug.getCallers(4));
Craig Mautner15df08a2015-04-01 12:17:18 -07004266 mLockTaskModeTasks.remove(task);
4267 mLockTaskModeTasks.add(task);
4268
4269 if (task.mLockTaskUid == -1) {
Wale Ogunwale5c18d052015-10-12 10:34:14 -07004270 task.mLockTaskUid = task.effectiveUid;
Craig Mautner15df08a2015-04-01 12:17:18 -07004271 }
Craig Mautner432f64e2015-05-20 14:59:57 -07004272
4273 if (andResume) {
Andrii Kulianc27916642016-04-12 17:59:27 -07004274 findTaskToMoveToFrontLocked(task, 0, null, reason,
4275 lockTaskModeState != LOCK_TASK_MODE_NONE);
Wale Ogunwaled046a012015-12-24 13:05:59 -08004276 resumeFocusedStackTopActivityLocked();
Jorim Jaggia42938e2016-11-22 14:31:38 +01004277 mWindowManager.executeAppTransition();
Andrii Kulianc27916642016-04-12 17:59:27 -07004278 } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004279 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
4280 task.getStackId(), true /* forceNonResizable */);
Craig Mautner432f64e2015-05-20 14:59:57 -07004281 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004282 }
4283
4284 boolean isLockTaskModeViolation(TaskRecord task) {
Jason Monk25d237b2015-06-19 10:39:39 -04004285 return isLockTaskModeViolation(task, false);
4286 }
4287
4288 boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) {
4289 if (getLockedTaskLocked() == task && !isNewClearTask) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004290 return false;
4291 }
4292 final int lockTaskAuth = task.mLockTaskAuth;
4293 switch (lockTaskAuth) {
4294 case LOCK_TASK_AUTH_DONT_LOCK:
4295 return !mLockTaskModeTasks.isEmpty();
Benjamin Franz469dd582015-06-09 14:24:36 +01004296 case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
Craig Mautner15df08a2015-04-01 12:17:18 -07004297 case LOCK_TASK_AUTH_LAUNCHABLE:
4298 case LOCK_TASK_AUTH_WHITELISTED:
4299 return false;
4300 case LOCK_TASK_AUTH_PINNABLE:
4301 // Pinnable tasks can't be launched on top of locktask tasks.
4302 return !mLockTaskModeTasks.isEmpty();
4303 default:
4304 Slog.w(TAG, "isLockTaskModeViolation: invalid lockTaskAuth value=" + lockTaskAuth);
4305 return true;
4306 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004307 }
4308
Craig Mautner15df08a2015-04-01 12:17:18 -07004309 void onLockTaskPackagesUpdatedLocked() {
4310 boolean didSomething = false;
4311 for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
4312 final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx);
Benjamin Franz469dd582015-06-09 14:24:36 +01004313 final boolean wasWhitelisted =
4314 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4315 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
Craig Mautner15df08a2015-04-01 12:17:18 -07004316 lockedTask.setLockTaskAuth();
Benjamin Franz469dd582015-06-09 14:24:36 +01004317 final boolean isWhitelisted =
4318 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4319 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
4320 if (wasWhitelisted && !isWhitelisted) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004321 // Lost whitelisting authorization. End it now.
Craig Mautner432f64e2015-05-20 14:59:57 -07004322 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "onLockTaskPackagesUpdated: removing " +
4323 lockedTask + " mLockTaskAuth=" + lockedTask.lockTaskAuthToString());
Craig Mautner15df08a2015-04-01 12:17:18 -07004324 removeLockedTaskLocked(lockedTask);
4325 lockedTask.performClearTaskLocked();
4326 didSomething = true;
4327 }
4328 }
4329 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
4330 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
4331 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
4332 final ActivityStack stack = stacks.get(stackNdx);
4333 stack.onLockTaskPackagesUpdatedLocked();
4334 }
4335 }
Craig Mautnere0570202015-05-13 13:06:11 -07004336 final ActivityRecord r = topRunningActivityLocked();
Bryce Leeaf691c02017-03-20 14:20:22 -07004337 final TaskRecord task = r != null ? r.getTask() : null;
Craig Mautnere0570202015-05-13 13:06:11 -07004338 if (mLockTaskModeTasks.isEmpty() && task != null
4339 && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
4340 // This task must have just been authorized.
Craig Mautner432f64e2015-05-20 14:59:57 -07004341 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK,
4342 "onLockTaskPackagesUpdated: starting new locktask task=" + task);
4343 setLockTaskModeLocked(task, ActivityManager.LOCK_TASK_MODE_LOCKED, "package updated",
4344 false);
4345 didSomething = true;
Craig Mautnere0570202015-05-13 13:06:11 -07004346 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004347 if (didSomething) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004348 resumeFocusedStackTopActivityLocked();
Craig Mautneraea74a52014-03-08 14:23:10 -08004349 }
4350 }
4351
Benjamin Franz43261142015-02-11 15:59:44 +00004352 int getLockTaskModeState() {
4353 return mLockTaskModeState;
Craig Mautneraea74a52014-03-08 14:23:10 -08004354 }
4355
Jorim Jaggife89d122015-12-22 16:28:44 +01004356 void activityRelaunchedLocked(IBinder token) {
4357 mWindowManager.notifyAppRelaunchingFinished(token);
David Stevens9440dc82017-03-16 19:00:20 -07004358 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4359 if (r != null) {
4360 if (r.getStack().shouldSleepOrShutDownActivities()) {
Wale Ogunwale3e997362016-09-06 10:37:56 -07004361 r.setSleeping(true, true);
4362 }
4363 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004364 }
4365
4366 void activityRelaunchingLocked(ActivityRecord r) {
4367 mWindowManager.notifyAppRelaunching(r.appToken);
4368 }
4369
Filip Gruszczynski77d94482015-12-11 13:59:52 -08004370 void logStackState() {
4371 mActivityMetricsLogger.logWindowState();
4372 }
4373
Winson Chung5af42fc2017-03-24 17:11:33 -07004374 void scheduleUpdateMultiWindowMode(TaskRecord task) {
Winson Chung8bca9e42017-04-16 15:59:43 -07004375 // If the stack is animating in a way where we will be forcing a multi-mode change at the
4376 // end, then ensure that we defer all in between multi-window mode changes
4377 if (task.getStack().deferScheduleMultiWindowModeChanged()) {
4378 return;
4379 }
4380
Wale Ogunwale22e25262016-02-01 10:32:02 -08004381 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4382 final ActivityRecord r = task.mActivities.get(i);
4383 if (r.app != null && r.app.thread != null) {
4384 mMultiWindowModeChangedActivities.add(r);
4385 }
4386 }
4387
4388 if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
4389 mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
4390 }
4391 }
4392
Winson Chung5af42fc2017-03-24 17:11:33 -07004393 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07004394 final ActivityStack stack = task.getStack();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004395 if (prevStack == null || prevStack == stack
4396 || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
4397 return;
4398 }
4399
Winson Chung5af42fc2017-03-24 17:11:33 -07004400 scheduleUpdatePictureInPictureModeIfNeeded(task, stack.mBounds, false /* immediate */);
4401 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004402
Winson Chung5af42fc2017-03-24 17:11:33 -07004403 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds,
4404 boolean immediate) {
4405
4406 if (immediate) {
4407 mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG);
4408 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4409 final ActivityRecord r = task.mActivities.get(i);
4410 if (r.app != null && r.app.thread != null) {
4411 r.updatePictureInPictureMode(targetStackBounds);
4412 }
4413 }
4414 } else {
4415 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4416 final ActivityRecord r = task.mActivities.get(i);
4417 if (r.app != null && r.app.thread != null) {
4418 mPipModeChangedActivities.add(r);
4419 }
4420 }
4421 mPipModeChangedTargetStackBounds = targetStackBounds;
4422
4423 if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
4424 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
4425 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004426 }
4427 }
4428
Tony Mak853304c2016-04-18 15:17:41 +01004429 void setDockedStackMinimized(boolean minimized) {
4430 mIsDockMinimized = minimized;
Tony Mak853304c2016-04-18 15:17:41 +01004431 }
4432
chaviw59b98852017-06-13 12:05:44 -07004433 void wakeUp(String reason) {
4434 mPowerManager.wakeUp(SystemClock.uptimeMillis(), "android.server.am:TURN_ON:" + reason);
4435 }
4436
4437 /**
4438 * Begin deferring resume to avoid duplicate resumes in one pass.
4439 */
4440 private void beginDeferResume() {
4441 mDeferResumeCount++;
4442 }
4443
4444 /**
4445 * End deferring resume and determine if resume can be called.
4446 */
4447 private void endDeferResume() {
4448 mDeferResumeCount--;
4449 }
4450
4451 /**
4452 * @return True if resume can be called.
4453 */
4454 private boolean readyToResume() {
4455 return mDeferResumeCount == 0;
4456 }
4457
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004458 private final class ActivityStackSupervisorHandler extends Handler {
Craig Mautnerf3333272013-04-22 10:55:53 -07004459
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004460 public ActivityStackSupervisorHandler(Looper looper) {
4461 super(looper);
4462 }
4463
Winson Chung4dabf232017-01-25 13:25:22 -08004464 void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) {
Craig Mautnerf3333272013-04-22 10:55:53 -07004465 synchronized (mService) {
Winson Chung4dabf232017-01-25 13:25:22 -08004466 activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */,
4467 processPausingActivities, null);
Craig Mautnerf3333272013-04-22 10:55:53 -07004468 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004469 }
4470
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004471 @Override
4472 public void handleMessage(Message msg) {
4473 switch (msg.what) {
Wale Ogunwale22e25262016-02-01 10:32:02 -08004474 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
4475 synchronized (mService) {
4476 for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
4477 final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004478 r.updateMultiWindowMode();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004479 }
4480 }
4481 } break;
4482 case REPORT_PIP_MODE_CHANGED_MSG: {
4483 synchronized (mService) {
4484 for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
4485 final ActivityRecord r = mPipModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004486 r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds);
Wale Ogunwale22e25262016-02-01 10:32:02 -08004487 }
4488 }
4489 } break;
Craig Mautnerf3333272013-04-22 10:55:53 -07004490 case IDLE_TIMEOUT_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004491 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
4492 "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
Craig Mautnerf3333272013-04-22 10:55:53 -07004493 // We don't at this point know if the activity is fullscreen,
4494 // so we need to be conservative and assume it isn't.
Winson Chung4dabf232017-01-25 13:25:22 -08004495 activityIdleInternal((ActivityRecord) msg.obj,
4496 true /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004497 } break;
4498 case IDLE_NOW_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004499 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
Winson Chung4dabf232017-01-25 13:25:22 -08004500 activityIdleInternal((ActivityRecord) msg.obj,
4501 false /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004502 } break;
Craig Mautner05d29032013-05-03 13:40:13 -07004503 case RESUME_TOP_ACTIVITY_MSG: {
4504 synchronized (mService) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004505 resumeFocusedStackTopActivityLocked();
Craig Mautner05d29032013-05-03 13:40:13 -07004506 }
4507 } break;
Craig Mautner0eea92c2013-05-16 13:35:39 -07004508 case SLEEP_TIMEOUT_MSG: {
4509 synchronized (mService) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07004510 if (mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07004511 Slog.w(TAG, "Sleep timeout! Sleeping now.");
David Stevens9440dc82017-03-16 19:00:20 -07004512 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07004513 }
4514 }
4515 } break;
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004516 case LAUNCH_TIMEOUT_MSG: {
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004517 synchronized (mService) {
4518 if (mLaunchingActivity.isHeld()) {
4519 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
4520 if (VALIDATE_WAKE_LOCK_CALLER
4521 && Binder.getCallingUid() != Process.myUid()) {
4522 throw new IllegalStateException("Calling must be system uid");
4523 }
4524 mLaunchingActivity.release();
4525 }
4526 }
4527 } break;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004528 case HANDLE_DISPLAY_ADDED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004529 handleDisplayAdded(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004530 } break;
4531 case HANDLE_DISPLAY_CHANGED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004532 handleDisplayChanged(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004533 } break;
4534 case HANDLE_DISPLAY_REMOVED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004535 handleDisplayRemoved(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004536 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004537 case LOCK_TASK_START_MSG: {
4538 // When lock task starts, we disable the status bars.
4539 try {
Jason Monk62515be2014-05-21 16:06:19 -04004540 if (mLockTaskNotify == null) {
4541 mLockTaskNotify = new LockTaskNotify(mService.mContext);
justinzhang5286d3f2014-05-12 17:06:01 -04004542 }
Jason Monk62515be2014-05-21 16:06:19 -04004543 mLockTaskNotify.show(true);
Benjamin Franz43261142015-02-11 15:59:44 +00004544 mLockTaskModeState = msg.arg2;
Jason Monk62515be2014-05-21 16:06:19 -04004545 if (getStatusBarService() != null) {
Benjamin Franz43261142015-02-11 15:59:44 +00004546 int flags = 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004547 if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004548 flags = StatusBarManager.DISABLE_MASK
4549 & (~StatusBarManager.DISABLE_BACK);
Craig Mautner15df08a2015-04-01 12:17:18 -07004550 } else if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004551 flags = StatusBarManager.DISABLE_MASK
4552 & (~StatusBarManager.DISABLE_BACK)
4553 & (~StatusBarManager.DISABLE_HOME)
4554 & (~StatusBarManager.DISABLE_RECENT);
Jason Monk62515be2014-05-21 16:06:19 -04004555 }
4556 getStatusBarService().disable(flags, mToken,
4557 mService.mContext.getPackageName());
4558 }
4559 mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
Jason Monk35c62a42014-06-17 10:24:47 -04004560 if (getDevicePolicyManager() != null) {
4561 getDevicePolicyManager().notifyLockTaskModeChanged(true,
Jason Monk62515be2014-05-21 16:06:19 -04004562 (String)msg.obj, msg.arg1);
Jason Monk35c62a42014-06-17 10:24:47 -04004563 }
justinzhang5286d3f2014-05-12 17:06:01 -04004564 } catch (RemoteException ex) {
4565 throw new RuntimeException(ex);
4566 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004567 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004568 case LOCK_TASK_END_MSG: {
4569 // When lock task ends, we enable the status bars.
4570 try {
Jason Monk62515be2014-05-21 16:06:19 -04004571 if (getStatusBarService() != null) {
4572 getStatusBarService().disable(StatusBarManager.DISABLE_NONE, mToken,
4573 mService.mContext.getPackageName());
4574 }
4575 mWindowManager.reenableKeyguard(mToken);
Jason Monk35c62a42014-06-17 10:24:47 -04004576 if (getDevicePolicyManager() != null) {
4577 getDevicePolicyManager().notifyLockTaskModeChanged(false, null,
4578 msg.arg1);
4579 }
Jason Monk62515be2014-05-21 16:06:19 -04004580 if (mLockTaskNotify == null) {
4581 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4582 }
4583 mLockTaskNotify.show(false);
4584 try {
Jason Monk94cfd9d2014-10-31 13:18:21 -04004585 boolean shouldLockKeyguard = Settings.Secure.getInt(
Jason Monk62515be2014-05-21 16:06:19 -04004586 mService.mContext.getContentResolver(),
Jason Monk94cfd9d2014-10-31 13:18:21 -04004587 Settings.Secure.LOCK_TO_APP_EXIT_LOCKED) != 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004588 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED && shouldLockKeyguard) {
Jason Monk62515be2014-05-21 16:06:19 -04004589 mWindowManager.lockNow(null);
Jorim Jaggi241ae102016-11-02 21:57:33 -07004590 mWindowManager.dismissKeyguard(null /* callback */);
Jason Monke0697792014-08-04 16:28:09 -04004591 new LockPatternUtils(mService.mContext)
4592 .requireCredentialEntry(UserHandle.USER_ALL);
Jason Monk62515be2014-05-21 16:06:19 -04004593 }
4594 } catch (SettingNotFoundException e) {
4595 // No setting, don't lock.
4596 }
justinzhang5286d3f2014-05-12 17:06:01 -04004597 } catch (RemoteException ex) {
4598 throw new RuntimeException(ex);
Benjamin Franz43261142015-02-11 15:59:44 +00004599 } finally {
Craig Mautner15df08a2015-04-01 12:17:18 -07004600 mLockTaskModeState = LOCK_TASK_MODE_NONE;
justinzhang5286d3f2014-05-12 17:06:01 -04004601 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004602 } break;
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004603 case SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG: {
4604 if (mLockTaskNotify == null) {
4605 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4606 }
4607 mLockTaskNotify.showToast(LOCK_TASK_MODE_PINNED);
4608 } break;
Craig Mautnerbb742462014-07-07 15:28:55 -07004609 case LAUNCH_TASK_BEHIND_COMPLETE: {
4610 synchronized (mService) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07004611 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
Craig Mautnerbb742462014-07-07 15:28:55 -07004612 if (r != null) {
4613 handleLaunchTaskBehindCompleteLocked(r);
4614 }
4615 }
4616 } break;
Chong Zhangc806d902015-11-30 09:44:27 -08004617
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004618 }
4619 }
4620 }
Craig Mautnered6649f2013-12-02 14:08:25 -08004621
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004622 // TODO: Move to its own file.
Craig Mautner4a1cb222013-12-04 16:14:06 -08004623 /** Exactly one of these classes per Display in the system. Capable of holding zero or more
4624 * attached {@link ActivityStack}s */
Andrii Kulian1779e612016-10-12 21:58:25 -07004625 class ActivityDisplay extends ConfigurationContainer {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004626 /** Actual Display this object tracks. */
Craig Mautner34b73df2014-01-12 21:11:08 -08004627 int mDisplayId;
4628 Display mDisplay;
Craig Mautnered6649f2013-12-02 14:08:25 -08004629
Craig Mautner4a1cb222013-12-04 16:14:06 -08004630 /** All of the stacks on this display. Order matters, topmost stack is in front of all other
4631 * stacks, bottommost behind. Accessed directly by ActivityManager package classes */
Wale Ogunwale1f544be2015-12-17 10:27:23 -08004632 final ArrayList<ActivityStack> mStacks = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004633
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004634 /** Array of all UIDs that are present on the display. */
4635 private IntArray mDisplayAccessUIDs = new IntArray();
4636
David Stevens9440dc82017-03-16 19:00:20 -07004637 /** All tokens used to put activities on this stack to sleep (including mOffToken) */
4638 final ArrayList<SleepTokenImpl> mAllSleepTokens = new ArrayList<>();
4639 /** The token acquired by ActivityStackSupervisor to put stacks on the display to sleep */
4640 SleepToken mOffToken;
4641
4642 private boolean mSleeping;
4643
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004644 @VisibleForTesting
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004645 ActivityDisplay() {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004646 mActivityDisplays.put(mDisplayId, this);
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004647 }
Craig Mautner4504de52013-12-20 09:06:56 -08004648
Craig Mautner1a70a162014-09-13 12:09:31 -07004649 // After instantiation, check that mDisplay is not null before using this. The alternative
4650 // is for this to throw an exception if mDisplayManager.getDisplay() returns null.
Craig Mautnere0a38842013-12-16 16:14:02 -08004651 ActivityDisplay(int displayId) {
Craig Mautner1a70a162014-09-13 12:09:31 -07004652 final Display display = mDisplayManager.getDisplay(displayId);
4653 if (display == null) {
4654 return;
4655 }
4656 init(display);
Craig Mautner4504de52013-12-20 09:06:56 -08004657 }
4658
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004659 void init(Display display) {
Craig Mautner4504de52013-12-20 09:06:56 -08004660 mDisplay = display;
4661 mDisplayId = display.getDisplayId();
Craig Mautnered6649f2013-12-02 14:08:25 -08004662 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004663
Winson Chung7c3ede32017-03-14 14:18:34 -07004664 void attachStack(ActivityStack stack, int position) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08004665 if (DEBUG_STACK) Slog.v(TAG_STACK, "attachStack: attaching " + stack
Winson Chung7c3ede32017-03-14 14:18:34 -07004666 + " to displayId=" + mDisplayId + " position=" + position);
4667 mStacks.add(position, stack);
David Stevens9440dc82017-03-16 19:00:20 -07004668 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004669 }
4670
Wale Ogunwale1666e312016-12-16 11:27:18 -08004671 void detachStack(ActivityStack stack) {
4672 if (DEBUG_STACK) Slog.v(TAG_STACK, "detachStack: detaching " + stack
Craig Mautnere0a38842013-12-16 16:14:02 -08004673 + " from displayId=" + mDisplayId);
4674 mStacks.remove(stack);
David Stevens9440dc82017-03-16 19:00:20 -07004675 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004676 }
4677
Craig Mautner34b73df2014-01-12 21:11:08 -08004678 @Override
4679 public String toString() {
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004680 return "ActivityDisplay={" + mDisplayId + " numStacks=" + mStacks.size() + "}";
4681 }
Andrii Kulian1779e612016-10-12 21:58:25 -07004682
4683 @Override
4684 protected int getChildCount() {
4685 return mStacks.size();
4686 }
4687
4688 @Override
4689 protected ConfigurationContainer getChildAt(int index) {
4690 return mStacks.get(index);
4691 }
4692
4693 @Override
4694 protected ConfigurationContainer getParent() {
4695 return ActivityStackSupervisor.this;
4696 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004697
4698 boolean isPrivate() {
4699 return (mDisplay.getFlags() & FLAG_PRIVATE) != 0;
4700 }
4701
4702 boolean isUidPresent(int uid) {
4703 for (ActivityStack stack : mStacks) {
4704 if (stack.isUidPresent(uid)) {
4705 return true;
4706 }
4707 }
4708 return false;
4709 }
4710
4711 /** Update and get all UIDs that are present on the display and have access to it. */
4712 private IntArray getPresentUIDs() {
4713 mDisplayAccessUIDs.clear();
4714 for (ActivityStack stack : mStacks) {
4715 stack.getPresentUIDs(mDisplayAccessUIDs);
4716 }
4717 return mDisplayAccessUIDs;
4718 }
Andrii Kulian250d6532017-02-08 23:30:45 -08004719
4720 boolean shouldDestroyContentOnRemove() {
4721 return mDisplay.getRemoveMode() == REMOVE_MODE_DESTROY_CONTENT;
4722 }
David Stevens9440dc82017-03-16 19:00:20 -07004723
4724 boolean shouldSleep() {
4725 return (mStacks.isEmpty() || !mAllSleepTokens.isEmpty())
4726 && (mService.mRunningVoice == null);
4727 }
4728
4729 boolean isSleeping() {
4730 return mSleeping;
4731 }
4732
4733 void setIsSleeping(boolean asleep) {
4734 mSleeping = asleep;
4735 }
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004736 }
4737
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004738 ActivityStack findStackBehind(ActivityStack stack) {
4739 // TODO(multi-display): We are only looking for stacks on the default display.
Jorim Jaggife762342016-10-13 14:33:27 +02004740 final ActivityDisplay display = mActivityDisplays.get(DEFAULT_DISPLAY);
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004741 if (display == null) {
4742 return null;
4743 }
4744 final ArrayList<ActivityStack> stacks = display.mStacks;
4745 for (int i = stacks.size() - 1; i >= 0; i--) {
4746 if (stacks.get(i) == stack && i > 0) {
4747 return stacks.get(i - 1);
4748 }
4749 }
4750 throw new IllegalStateException("Failed to find a stack behind stack=" + stack
4751 + " in=" + stacks);
4752 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004753
Jorim Jaggic69bd222016-03-15 14:38:37 +01004754 /**
4755 * Puts a task into resizing mode during the next app transition.
4756 *
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004757 * @param task The task to put into resizing mode
Jorim Jaggic69bd222016-03-15 14:38:37 +01004758 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004759 private void setResizingDuringAnimation(TaskRecord task) {
4760 mResizingTasksDuringAnimation.add(task.taskId);
4761 task.setTaskDockedResizing(true);
Jorim Jaggic69bd222016-03-15 14:38:37 +01004762 }
4763
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004764 final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
4765 final TaskRecord task;
4766 final int callingUid;
4767 final String callingPackage;
4768 final Intent intent;
4769 final int userId;
4770 final ActivityOptions activityOptions = (bOptions != null)
4771 ? new ActivityOptions(bOptions) : null;
4772 final int launchStackId = (activityOptions != null)
4773 ? activityOptions.getLaunchStackId() : INVALID_STACK_ID;
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004774 if (StackId.isHomeOrRecentsStack(launchStackId)) {
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004775 throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004776 + taskId + " can't be launch in the home/recents stack.");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004777 }
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004778
Matthew Ng606dd802017-06-05 14:06:32 -07004779 mWindowManager.deferSurfaceLayout();
4780 try {
4781 if (launchStackId == DOCKED_STACK_ID) {
4782 mWindowManager.setDockedStackCreateState(
4783 activityOptions.getDockCreateMode(), null /* initialBounds */);
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004784
Matthew Ng606dd802017-06-05 14:06:32 -07004785 // Defer updating the stack in which recents is until the app transition is done, to
4786 // not run into issues where we still need to draw the task in recents but the
4787 // docked stack is already created.
4788 deferUpdateBounds(RECENTS_STACK_ID);
4789 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004790 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004791
Matthew Ng606dd802017-06-05 14:06:32 -07004792 task = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
4793 launchStackId);
4794 if (task == null) {
4795 continueUpdateBounds(RECENTS_STACK_ID);
4796 mWindowManager.executeAppTransition();
4797 throw new IllegalArgumentException(
4798 "startActivityFromRecentsInner: Task " + taskId + " not found.");
4799 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004800
Matthew Ng606dd802017-06-05 14:06:32 -07004801 // Since we don't have an actual source record here, we assume that the currently
4802 // focused activity was the source.
4803 final ActivityStack focusedStack = getFocusedStack();
4804 final ActivityRecord sourceRecord =
4805 focusedStack != null ? focusedStack.topActivity() : null;
4806
4807 if (launchStackId != INVALID_STACK_ID) {
4808 if (task.getStackId() != launchStackId) {
4809 task.reparent(launchStackId, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE,
4810 DEFER_RESUME, "startActivityFromRecents");
4811 }
4812 }
4813
4814 // If the user must confirm credentials (e.g. when first launching a work app and the
4815 // Work Challenge is present) let startActivityInPackage handle the intercepting.
4816 if (!mService.mUserController.shouldConfirmCredentials(task.userId)
4817 && task.getRootActivity() != null) {
Bryce Lee28d80422017-07-21 13:25:13 -07004818 final ActivityRecord targetActivity = task.getTopActivity();
4819
4820 mService.mActivityStarter.sendPowerHintForLaunchStartIfNeeded(true /* forceSend */,
4821 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004822 mActivityMetricsLogger.notifyActivityLaunching();
Jorim Jaggi42befc62017-06-13 11:54:04 -07004823 mService.moveTaskToFrontLocked(task.taskId, 0, bOptions, true /* fromRecents */);
Matthew Ng606dd802017-06-05 14:06:32 -07004824 mActivityMetricsLogger.notifyActivityLaunched(ActivityManager.START_TASK_TO_FRONT,
Bryce Lee28d80422017-07-21 13:25:13 -07004825 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004826
4827 // If we are launching the task in the docked stack, put it into resizing mode so
4828 // the window renders full-screen with the background filling the void. Also only
4829 // call this at the end to make sure that tasks exists on the window manager side.
4830 if (launchStackId == DOCKED_STACK_ID) {
4831 setResizingDuringAnimation(task);
4832 }
4833
4834 mService.mActivityStarter.postStartActivityProcessing(task.getTopActivity(),
4835 ActivityManager.START_TASK_TO_FRONT,
4836 sourceRecord != null
4837 ? sourceRecord.getTask().getStackId() : INVALID_STACK_ID,
4838 sourceRecord, task.getStack());
4839 return ActivityManager.START_TASK_TO_FRONT;
4840 }
4841 callingUid = task.mCallingUid;
4842 callingPackage = task.mCallingPackage;
4843 intent = task.intent;
4844 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4845 userId = task.userId;
4846 int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004847 null, null, 0, 0, bOptions, userId, task, "startActivityFromRecents");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004848 if (launchStackId == DOCKED_STACK_ID) {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004849 setResizingDuringAnimation(task);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004850 }
Matthew Ng606dd802017-06-05 14:06:32 -07004851 return result;
4852 } finally {
4853 mWindowManager.continueSurfaceLayout();
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004854 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004855 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004856
4857 /**
4858 * @return a list of activities which are the top ones in each visible stack. The first
4859 * entry will be the focused activity.
4860 */
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004861 List<IBinder> getTopVisibleActivities() {
4862 final ArrayList<IBinder> topActivityTokens = new ArrayList<>();
4863 // Traverse all displays.
Robert Carr22374c02017-02-21 13:01:47 -08004864 for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004865 final ActivityDisplay display = mActivityDisplays.valueAt(i);
4866 // Traverse all stacks on a display.
4867 for (int j = display.mStacks.size() - 1; j >= 0; j--) {
4868 final ActivityStack stack = display.mStacks.get(j);
4869 // Get top activity from a visible stack and add it to the list.
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004870 if (stack.shouldBeVisible(null /* starting */)
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004871 == ActivityStack.STACK_VISIBLE) {
4872 final ActivityRecord top = stack.topActivity();
4873 if (top != null) {
4874 if (stack == mFocusedStack) {
4875 topActivityTokens.add(0, top.appToken);
4876 } else {
4877 topActivityTokens.add(top.appToken);
4878 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004879 }
4880 }
4881 }
4882 }
4883 return topActivityTokens;
4884 }
Bryce Lee4a194382017-04-04 14:32:48 -07004885
4886 /**
4887 * Internal container to store a match qualifier alongside a WaitResult.
4888 */
4889 static class WaitInfo {
4890 private final ComponentName mTargetComponent;
4891 private final WaitResult mResult;
4892
4893 public WaitInfo(ComponentName targetComponent, WaitResult result) {
4894 this.mTargetComponent = targetComponent;
4895 this.mResult = result;
4896 }
4897
Wale Ogunwale3270f172017-04-26 07:29:42 -07004898 public boolean matches(ComponentName targetComponent) {
4899 return mTargetComponent == null || mTargetComponent.equals(targetComponent);
Bryce Lee4a194382017-04-04 14:32:48 -07004900 }
4901
4902 public WaitResult getResult() {
4903 return mResult;
4904 }
4905
4906 public ComponentName getComponent() {
4907 return mTargetComponent;
4908 }
4909
4910 public void dump(PrintWriter pw, String prefix) {
4911 pw.println(prefix + "WaitInfo:");
4912 pw.println(prefix + " mTargetComponent=" + mTargetComponent);
4913 pw.println(prefix + " mResult=");
4914 mResult.dump(pw, prefix);
4915 }
4916 }
David Stevens9440dc82017-03-16 19:00:20 -07004917
4918 private final class SleepTokenImpl extends SleepToken {
4919 private final String mTag;
4920 private final long mAcquireTime;
4921 private final int mDisplayId;
4922
4923 public SleepTokenImpl(String tag, int displayId) {
4924 mTag = tag;
4925 mDisplayId = displayId;
4926 mAcquireTime = SystemClock.uptimeMillis();
4927 }
4928
4929 @Override
4930 public void release() {
4931 synchronized (mService) {
4932 removeSleepTokenLocked(this);
4933 }
4934 }
4935
4936 @Override
4937 public String toString() {
4938 return "{\"" + mTag + "\", display " + mDisplayId
4939 + ", acquire at " + TimeUtils.formatUptime(mAcquireTime) + "}";
4940 }
4941 }
4942
Craig Mautner27084302013-03-25 08:05:25 -07004943}