blob: ab6e6025e60259071a9a75a02d91cfe37baa8a14 [file] [log] [blame]
Craig Mautner27084302013-03-25 08:05:25 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Andrii Kulian3c9ad072017-08-01 11:45:22 -070019import static android.Manifest.permission.ACTIVITY_EMBEDDING;
Andrii Kulian3a95edc2017-06-28 16:21:07 -070020import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Jorim Jaggife762342016-10-13 14:33:27 +020021import static android.Manifest.permission.START_ANY_ACTIVITY;
22import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
23import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
24import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
25import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
Jorim Jaggife762342016-10-13 14:33:27 +020026import static android.app.ActivityManager.START_TASK_TO_FRONT;
27import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
28import static android.app.ActivityManager.StackId.FIRST_DYNAMIC_STACK_ID;
29import static android.app.ActivityManager.StackId.FIRST_STATIC_STACK_ID;
30import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
31import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
32import static android.app.ActivityManager.StackId.HOME_STACK_ID;
33import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
34import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
35import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
Matthew Ng330757d2017-02-28 14:19:17 -080036import static android.app.ActivityManager.StackId.RECENTS_STACK_ID;
Andrii Kulian036e3ad2017-04-19 10:55:10 -070037import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
38import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Andrii Kulian3c9ad072017-08-01 11:45:22 -070039import static android.content.pm.PackageManager.PERMISSION_DENIED;
Jorim Jaggife762342016-10-13 14:33:27 +020040import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070041import static android.os.Process.SYSTEM_UID;
chaviw59b98852017-06-13 12:05:44 -070042import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
Jorim Jaggife762342016-10-13 14:33:27 +020043import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
44import static android.view.Display.DEFAULT_DISPLAY;
Andrii Kulian16802aa2016-11-02 12:21:33 -070045import static android.view.Display.FLAG_PRIVATE;
46import static android.view.Display.INVALID_DISPLAY;
Andrii Kulian250d6532017-02-08 23:30:45 -080047import static android.view.Display.REMOVE_MODE_DESTROY_CONTENT;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070048import static android.view.Display.TYPE_VIRTUAL;
Jorim Jaggife762342016-10-13 14:33:27 +020049
Winson Chung47900652017-04-06 18:44:25 -070050import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN;
Jorim Jaggife762342016-10-13 14:33:27 +020051import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
Jorim Jaggife762342016-10-13 14:33:27 +020052import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
53import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
54import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
55import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
56import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
57import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
58import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
59import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
60import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
61import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020062import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
63import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IDLE;
64import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
65import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
66import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
67import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
68import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
69import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
70import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
71import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020072import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
73import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
74import static com.android.server.am.ActivityManagerService.ANIMATE;
75import static com.android.server.am.ActivityManagerService.FIRST_SUPERVISOR_STACK_MSG;
76import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
77import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
Jorim Jaggife762342016-10-13 14:33:27 +020078import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
79import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
80import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
81import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
82import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
83import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
84import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
85import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
86import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
87import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
88import static com.android.server.am.ActivityStack.STACK_VISIBLE;
89import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
90import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
91import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
92import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
93import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
Winson Chung74666102017-02-22 17:49:24 -080094import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
95import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
96import static com.android.server.am.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
Jorim Jaggife762342016-10-13 14:33:27 +020097import static com.android.server.wm.AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS;
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -080098import static java.lang.Integer.MAX_VALUE;
Jorim Jaggife762342016-10-13 14:33:27 +020099
Svetoslav7008b512015-06-24 18:47:07 -0700100import android.Manifest;
Winson Chung7900bee2017-03-10 08:59:25 -0800101import android.annotation.IntDef;
Andrii Kulian16802aa2016-11-02 12:21:33 -0700102import android.annotation.NonNull;
Tony Mak853304c2016-04-18 15:17:41 +0100103import android.annotation.UserIdInt;
Craig Mautner2420ead2013-04-01 17:13:20 -0700104import android.app.Activity;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700105import android.app.ActivityManager;
Filip Gruszczynski80e29f12015-12-14 14:58:30 -0800106import android.app.ActivityManager.RunningTaskInfo;
Wale Ogunwale3797c222015-10-27 14:21:58 -0700107import android.app.ActivityManager.StackId;
Craig Mautnered6649f2013-12-02 14:08:25 -0800108import android.app.ActivityManager.StackInfo;
David Stevensf62360c2017-03-16 19:00:20 -0700109import android.app.ActivityManagerInternal.SleepToken;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700110import android.app.ActivityOptions;
Svetoslav7008b512015-06-24 18:47:07 -0700111import android.app.AppOpsManager;
Jeff Hao1b012d32014-08-20 10:35:34 -0700112import android.app.ProfilerInfo;
Craig Mautner2420ead2013-04-01 17:13:20 -0700113import android.app.ResultInfo;
justinzhang5286d3f2014-05-12 17:06:01 -0400114import android.app.StatusBarManager;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700115import android.app.WaitResult;
Jason Monk35c62a42014-06-17 10:24:47 -0400116import android.app.admin.IDevicePolicyManager;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700117import android.content.ComponentName;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700118import android.content.Context;
119import android.content.Intent;
120import android.content.pm.ActivityInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700121import android.content.pm.ApplicationInfo;
Svetoslav7008b512015-06-24 18:47:07 -0700122import android.content.pm.PackageInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700123import android.content.pm.PackageManager;
124import android.content.pm.ResolveInfo;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100125import android.content.pm.UserInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700126import android.content.res.Configuration;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800127import android.graphics.Rect;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800128import android.hardware.display.DisplayManager;
129import android.hardware.display.DisplayManager.DisplayListener;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800130import android.hardware.display.DisplayManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800131import android.hardware.input.InputManagerInternal;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700132import android.os.Binder;
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100133import android.os.Bundle;
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700134import android.os.Debug;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700135import android.os.Handler;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700136import android.os.IBinder;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700137import android.os.Looper;
Craig Mautner2420ead2013-04-01 17:13:20 -0700138import android.os.Message;
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 Stevensf62360c2017-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 Stevensf62360c2017-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 Stevensf62360c2017-03-16 19:00:20 -0700396 /**
397 * A list of tokens that cause the top activity to be put to sleep.
398 * They are used by components that may hide and block interaction with underlying
399 * activities.
400 */
401 final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>();
402
Craig Mautner4f1df4f2013-10-15 15:44:14 -0700403 /** Stack id of the front stack when user switched, indexed by userId. */
404 SparseIntArray mUserStackInFront = new SparseIntArray(2);
Craig Mautner93529a42013-10-04 15:03:13 -0700405
Craig Mautner4504de52013-12-20 09:06:56 -0800406 // TODO: Add listener for removal of references.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800407 /** Mapping from (ActivityStack/TaskStack).mStackId to their current state */
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700408 SparseArray<ActivityStack> mStacks = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800409
Bryce Leeaf3a4002017-03-20 10:37:12 -0700410 // TODO: There should be an ActivityDisplayController coordinating am/wm interaction.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800411 /** Mapping from displayId to display current state */
Craig Mautner15df08a2015-04-01 12:17:18 -0700412 private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800413
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800414 private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>();
415
416 private DisplayManagerInternal mDisplayManagerInternal;
417 private InputManagerInternal mInputManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800418
Craig Mautner15df08a2015-04-01 12:17:18 -0700419 /** The chain of tasks in lockTask mode. The current frontmost task is at the top, and tasks
420 * may be finished until there is only one entry left. If this is empty the system is not
421 * in lockTask mode. */
422 ArrayList<TaskRecord> mLockTaskModeTasks = new ArrayList<>();
Benjamin Franz43261142015-02-11 15:59:44 +0000423 /** Store the current lock task mode. Possible values:
Craig Mautner2568c3a2015-03-26 14:22:34 -0700424 * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
425 * {@link ActivityManager#LOCK_TASK_MODE_PINNED}
Benjamin Franz43261142015-02-11 15:59:44 +0000426 */
427 private int mLockTaskModeState;
Jason Monk62515be2014-05-21 16:06:19 -0400428 /**
429 * Notifies the user when entering/exiting lock-task.
430 */
431 private LockTaskNotify mLockTaskNotify;
Craig Mautneraea74a52014-03-08 14:23:10 -0800432
Wale Ogunwaled046a012015-12-24 13:05:59 -0800433 /** Used to keep resumeTopActivityUncheckedLocked() from being entered recursively */
Craig Mautner42d04db2014-11-06 12:13:23 -0800434 boolean inResumeTopActivity;
435
Andrii Kulian1e32e022016-09-16 15:29:34 -0700436 /**
437 * Temporary rect used during docked stack resize calculation so we don't need to create a new
438 * object each time.
439 */
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700440 private final Rect tempRect = new Rect();
Filip Gruszczynskiebcc8752015-08-25 16:51:05 -0700441
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700442 // The default minimal size that will be used if the activity doesn't specify its minimal size.
443 // It will be calculated when the default display gets added.
Andrii Kulianf66a83d2016-05-17 12:17:44 -0700444 int mDefaultMinSizeOfResizeableTask = -1;
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700445
Chong Zhangfdcc4d42015-10-14 16:50:12 -0700446 // Whether tasks have moved and we need to rank the tasks before next OOM scoring
447 private boolean mTaskLayersChanged = true;
448
Jorim Jaggi275561a2016-02-23 10:11:02 -0500449 final ActivityMetricsLogger mActivityMetricsLogger;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800450
Jorim Jaggiea039a82017-08-02 14:37:49 +0200451 private final ArrayList<ActivityRecord> mTmpActivityList = new ArrayList<>();
452
Andrii Kulian1779e612016-10-12 21:58:25 -0700453 @Override
454 protected int getChildCount() {
455 return mActivityDisplays.size();
456 }
457
458 @Override
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700459 protected ActivityDisplay getChildAt(int index) {
Andrii Kulian1779e612016-10-12 21:58:25 -0700460 return mActivityDisplays.valueAt(index);
461 }
462
463 @Override
464 protected ConfigurationContainer getParent() {
465 return null;
466 }
467
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700468 Configuration getDisplayOverrideConfiguration(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700469 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700470 if (activityDisplay == null) {
471 throw new IllegalArgumentException("No display found with id: " + displayId);
472 }
473
474 return activityDisplay.getOverrideConfiguration();
475 }
476
477 void setDisplayOverrideConfiguration(Configuration overrideConfiguration, int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700478 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700479 if (activityDisplay == null) {
480 throw new IllegalArgumentException("No display found with id: " + displayId);
481 }
482
483 activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
484 }
485
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700486 /** Check if placing task or activity on specified display is allowed. */
Andrii Kulian02689a72017-07-06 14:28:59 -0700487 boolean canPlaceEntityOnDisplay(int displayId, boolean resizeable, int callingPid,
488 int callingUid, ActivityInfo activityInfo) {
489 if (displayId == DEFAULT_DISPLAY) {
490 // No restrictions for the default display.
491 return true;
492 }
493 if (!mService.mSupportsMultiDisplay) {
494 // Can't launch on secondary displays if feature is not supported.
495 return false;
496 }
497 if (!resizeable && !displayConfigMatchesGlobal(displayId)) {
498 // Can't apply wrong configuration to non-resizeable activities.
499 return false;
500 }
501 if (!isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, displayId, activityInfo)) {
502 // Can't place activities to a display that has restricted launch rules.
503 // In this case the request should be made by explicitly adding target display id and
504 // by caller with corresponding permissions. See #isCallerAllowedToLaunchOnDisplay().
505 return false;
506 }
507 return true;
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700508 }
509
510 /**
511 * Check if configuration of specified display matches current global config.
512 * Used to check if we can put a non-resizeable activity on a secondary display and it will get
513 * the same config as on the default display.
514 * @param displayId Id of the display to check.
515 * @return {@code true} if configuration matches.
516 */
517 private boolean displayConfigMatchesGlobal(int displayId) {
518 if (displayId == DEFAULT_DISPLAY) {
519 return true;
520 }
521 if (displayId == INVALID_DISPLAY) {
522 return false;
523 }
Andrii Kulian62e6f252017-05-30 22:46:53 -0700524 final ActivityDisplay targetDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700525 if (targetDisplay == null) {
526 throw new IllegalArgumentException("No display found with id: " + displayId);
527 }
528 return getConfiguration().equals(targetDisplay.getConfiguration());
529 }
530
Wale Ogunwale39381972015-12-17 17:15:29 -0800531 static class FindTaskResult {
532 ActivityRecord r;
533 boolean matchedByRootAffinity;
534 }
535 private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
536
Craig Mautneree36c772014-07-16 14:56:05 -0700537 /**
Andrii Kulian7fc22812016-12-28 13:04:11 -0800538 * Temp storage for display ids sorted in focus order.
539 * Maps position to id. Using {@link SparseIntArray} instead of {@link ArrayList} because
540 * it's more efficient, as the number of displays is usually small.
541 */
542 private SparseIntArray mTmpOrderedDisplayIds = new SparseIntArray();
543
544 /**
Jorim Jaggia0fdeec2016-01-07 14:42:28 +0100545 * Used to keep track whether app visibilities got changed since the last pause. Useful to
546 * determine whether to invoke the task stack change listener after pausing.
547 */
548 boolean mAppVisibilitiesChangedSinceLastPause;
549
550 /**
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100551 * Set of tasks that are in resizing mode during an app transition to fill the "void".
552 */
553 private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
554
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700555
556 /**
557 * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked}
558 * will be ignored. Useful for the case where the caller is handling resizing of other stack and
559 * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger
560 * like the docked stack going empty.
561 */
562 private boolean mAllowDockedStackResize = true;
563
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100564 /**
Tony Mak853304c2016-04-18 15:17:41 +0100565 * Is dock currently minimized.
566 */
567 boolean mIsDockMinimized;
568
Jorim Jaggife762342016-10-13 14:33:27 +0200569 final KeyguardController mKeyguardController;
570
chaviw59b98852017-06-13 12:05:44 -0700571 private PowerManager mPowerManager;
572 private int mDeferResumeCount;
573
Tony Mak853304c2016-04-18 15:17:41 +0100574 /**
Craig Mautneree36c772014-07-16 14:56:05 -0700575 * Description of a request to start a new activity, which has been held
576 * due to app switches being disabled.
577 */
578 static class PendingActivityLaunch {
579 final ActivityRecord r;
580 final ActivityRecord sourceRecord;
581 final int startFlags;
582 final ActivityStack stack;
Robert Carr13997f52015-10-23 13:13:39 -0700583 final ProcessRecord callerApp;
Craig Mautneree36c772014-07-16 14:56:05 -0700584
585 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
Robert Carr13997f52015-10-23 13:13:39 -0700586 int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
Craig Mautneree36c772014-07-16 14:56:05 -0700587 r = _r;
588 sourceRecord = _sourceRecord;
589 startFlags = _startFlags;
590 stack = _stack;
Robert Carr13997f52015-10-23 13:13:39 -0700591 callerApp = _callerApp;
592 }
593
594 void sendErrorResult(String message) {
595 try {
596 if (callerApp.thread != null) {
597 callerApp.thread.scheduleCrash(message);
598 }
599 } catch (RemoteException e) {
600 Slog.e(TAG, "Exception scheduling crash of failed "
601 + "activity launcher sourceRecord=" + sourceRecord, e);
602 }
Craig Mautneree36c772014-07-16 14:56:05 -0700603 }
604 }
605
Bryce Leeaf691c02017-03-20 14:20:22 -0700606 public ActivityStackSupervisor(ActivityManagerService service, Looper looper) {
Craig Mautner27084302013-03-25 08:05:25 -0700607 mService = service;
Bryce Leeaf691c02017-03-20 14:20:22 -0700608 mHandler = new ActivityStackSupervisorHandler(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800609 mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
Jorim Jaggife762342016-10-13 14:33:27 +0200610 mKeyguardController = new KeyguardController(service, this);
Jeff Brown2c43c332014-06-12 22:38:59 -0700611 }
612
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800613 void setRecentTasks(RecentTasks recentTasks) {
614 mRecentTasks = recentTasks;
615 }
616
Jeff Brown2c43c332014-06-12 22:38:59 -0700617 /**
618 * At the time when the constructor runs, the power manager has not yet been
619 * initialized. So we initialize our wakelocks afterwards.
620 */
621 void initPowerManagement() {
chaviw59b98852017-06-13 12:05:44 -0700622 mPowerManager = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
623 mGoingToSleep = mPowerManager
624 .newWakeLock(PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
625 mLaunchingActivity = mPowerManager.newWakeLock(PARTIAL_WAKE_LOCK, "*launch*");
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700626 mLaunchingActivity.setReferenceCounted(false);
Craig Mautner2219a1b2013-03-25 09:44:30 -0700627 }
628
justinzhang5286d3f2014-05-12 17:06:01 -0400629 // This function returns a IStatusBarService. The value is from ServiceManager.
630 // getService and is cached.
631 private IStatusBarService getStatusBarService() {
632 synchronized (mService) {
633 if (mStatusBarService == null) {
634 mStatusBarService = IStatusBarService.Stub.asInterface(
635 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
636 if (mStatusBarService == null) {
637 Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
638 }
639 }
640 return mStatusBarService;
641 }
642 }
643
Jason Monk35c62a42014-06-17 10:24:47 -0400644 private IDevicePolicyManager getDevicePolicyManager() {
645 synchronized (mService) {
646 if (mDevicePolicyManager == null) {
647 mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
648 ServiceManager.checkService(Context.DEVICE_POLICY_SERVICE));
649 if (mDevicePolicyManager == null) {
650 Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
651 }
652 }
653 return mDevicePolicyManager;
654 }
655 }
656
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700657 void setWindowManager(WindowManagerService wm) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800658 synchronized (mService) {
659 mWindowManager = wm;
Jorim Jaggife762342016-10-13 14:33:27 +0200660 mKeyguardController.setWindowManager(wm);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800661
662 mDisplayManager =
663 (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
664 mDisplayManager.registerDisplayListener(this, null);
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800665 mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800666
667 Display[] displays = mDisplayManager.getDisplays();
668 for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
669 final int displayId = displays[displayNdx].getDisplayId();
Craig Mautnere0a38842013-12-16 16:14:02 -0800670 ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
Craig Mautner1a70a162014-09-13 12:09:31 -0700671 if (activityDisplay.mDisplay == null) {
672 throw new IllegalStateException("Default Display does not exist");
673 }
Craig Mautnere0a38842013-12-16 16:14:02 -0800674 mActivityDisplays.put(displayId, activityDisplay);
Filip Gruszczynski7be9a8c2015-10-15 18:20:30 -0700675 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800676 }
677
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800678 mHomeStack = mFocusedStack = mLastFocusedStack =
679 getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Jeff Brownca9bc702014-02-11 14:32:56 -0800680
681 mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800682 }
Craig Mautner27084302013-03-25 08:05:25 -0700683 }
684
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700685 ActivityStack getFocusedStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800686 return mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700687 }
688
Craig Mautnerde4ef022013-04-07 19:01:33 -0700689 ActivityStack getLastStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800690 return mLastFocusedStack;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700691 }
692
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700693 boolean isFocusedStack(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700694 return stack != null && stack == mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700695 }
696
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800697 /** The top most stack on its display. */
698 boolean isFrontStackOnDisplay(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700699 return isFrontOfStackList(stack, stack.getDisplay().mStacks);
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800700 }
701
702 private boolean isFrontOfStackList(ActivityStack stack, List<ActivityStack> stackList) {
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800703 return stack == stackList.get((stackList.size() - 1));
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700704 }
705
Wale Ogunwaled046a012015-12-24 13:05:59 -0800706 /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800707 void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
708 if (!focusCandidate.isFocusable()) {
709 // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
Andrii Kulian7fc22812016-12-28 13:04:11 -0800710 focusCandidate = getNextFocusableStackLocked(focusCandidate);
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800711 }
712
713 if (focusCandidate != mFocusedStack) {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800714 mLastFocusedStack = mFocusedStack;
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800715 mFocusedStack = focusCandidate;
Wale Ogunwalecb82f302015-02-25 07:53:40 -0800716
Wale Ogunwaled046a012015-12-24 13:05:59 -0800717 EventLogTags.writeAmFocusedStack(
718 mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
719 mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
720 }
721
722 final ActivityRecord r = topRunningActivityLocked();
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800723 if (mService.mBooting || !mService.mBooted) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800724 if (r != null && r.idle) {
725 checkFinishBootingLocked();
726 }
727 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700728 }
729
Wale Ogunwale925d0d12015-09-23 15:40:07 -0700730 void moveHomeStackToFront(String reason) {
731 mHomeStack.moveToFront(reason);
732 }
733
Matthew Ng330757d2017-02-28 14:19:17 -0800734 void moveRecentsStackToFront(String reason) {
735 final ActivityStack recentsStack = getStack(RECENTS_STACK_ID);
736 if (recentsStack != null) {
737 recentsStack.moveToFront(reason);
738 }
739 }
740
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700741 /** Returns true if the focus activity was adjusted to the home stack top activity. */
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800742 boolean moveHomeStackTaskToTop(String reason) {
743 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700744
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700745 final ActivityRecord top = getHomeActivity();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700746 if (top == null) {
747 return false;
748 }
Chong Zhang6cda19c2016-06-14 19:07:56 -0700749 moveFocusableActivityStackToFrontLocked(top, reason);
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700750 return true;
Craig Mautner8e569572013-10-11 17:36:59 -0700751 }
752
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800753 boolean resumeHomeStackTask(ActivityRecord prev, String reason) {
Dianne Hackborn7622a0f2014-09-30 14:31:42 -0700754 if (!mService.mBooting && !mService.mBooted) {
755 // Not ready yet!
756 return false;
757 }
758
Craig Mautner84984fa2014-06-19 11:19:20 -0700759 if (prev != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -0700760 prev.getTask().setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
Craig Mautner84984fa2014-06-19 11:19:20 -0700761 }
762
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800763 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700764 ActivityRecord r = getHomeActivity();
Wale Ogunwaled046a012015-12-24 13:05:59 -0800765 final String myReason = reason + " resumeHomeStackTask";
766
Mark Lua56ea122015-10-08 13:31:01 +0800767 // Only resume home activity if isn't finishing.
768 if (r != null && !r.finishing) {
Chong Zhang6cda19c2016-06-14 19:07:56 -0700769 moveFocusableActivityStackToFrontLocked(r, myReason);
Wale Ogunwaled046a012015-12-24 13:05:59 -0800770 return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
Craig Mautner69ada552013-04-18 13:51:51 -0700771 }
Wale Ogunwaled046a012015-12-24 13:05:59 -0800772 return mService.startHomeActivityLocked(mCurrentUser, myReason);
Craig Mautner69ada552013-04-18 13:51:51 -0700773 }
774
Craig Mautner8d341ef2013-03-26 09:03:27 -0700775 TaskRecord anyTaskForIdLocked(int id) {
Winson Chung7900bee2017-03-10 08:59:25 -0800776 return anyTaskForIdLocked(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
777 INVALID_STACK_ID);
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700778 }
779
780 /**
Bryce Lee92b7b652017-04-03 08:33:11 -0700781 * Returns a {@link TaskRecord} for the input id if available. {@code null} otherwise.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700782 * @param id Id of the task we would like returned.
Winson Chung7900bee2017-03-10 08:59:25 -0800783 * @param matchMode The mode to match the given task id in.
Wale Ogunwale3797c222015-10-27 14:21:58 -0700784 * @param stackId The stack to restore the task to (default launch stack will be used if
Winson Chung7900bee2017-03-10 08:59:25 -0800785 * stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}). Only
786 * valid if the matchMode is
787 * {@link #MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE}.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700788 */
Winson Chung7900bee2017-03-10 08:59:25 -0800789 TaskRecord anyTaskForIdLocked(int id, @AnyTaskForIdMatchTaskMode int matchMode, int stackId) {
790 // If there is a stack id set, ensure that we are attempting to actually restore a task
791 if (matchMode != MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE &&
792 stackId != INVALID_STACK_ID) {
793 throw new IllegalArgumentException("Should not specify stackId for non-restore lookup");
794 }
795
Craig Mautnere0a38842013-12-16 16:14:02 -0800796 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800797 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800798 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800799 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
800 ActivityStack stack = stacks.get(stackNdx);
Bryce Lee92b7b652017-04-03 08:33:11 -0700801 final TaskRecord task = stack.taskForIdLocked(id);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800802 if (task != null) {
803 return task;
804 }
Craig Mautner8d341ef2013-03-26 09:03:27 -0700805 }
806 }
Wale Ogunwale7de05352014-12-12 15:21:33 -0800807
Winson Chung7900bee2017-03-10 08:59:25 -0800808 // If we are matching stack tasks only, return now
809 if (matchMode == MATCH_TASK_IN_STACKS_ONLY) {
Wale Ogunwale7de05352014-12-12 15:21:33 -0800810 return null;
811 }
812
Winson Chung7900bee2017-03-10 08:59:25 -0800813 // Otherwise, check the recent tasks and return if we find it there and we are not restoring
814 // the task from recents
815 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
Bryce Lee92b7b652017-04-03 08:33:11 -0700816 final TaskRecord task = mRecentTasks.taskForIdLocked(id);
817
818 if (task == null) {
819 if (DEBUG_RECENTS) {
Winson Chung7900bee2017-03-10 08:59:25 -0800820 Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
821 }
Bryce Lee92b7b652017-04-03 08:33:11 -0700822
823 return null;
824 }
825
826 if (matchMode == MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) {
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700827 return task;
828 }
829
Winson Chung7900bee2017-03-10 08:59:25 -0800830 // Implicitly, this case is MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
Wale Ogunwale7e8184b2015-10-05 14:37:03 -0700831 if (!restoreRecentTaskLocked(task, stackId)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700832 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
833 "Couldn't restore task id=" + id + " found in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800834 return null;
835 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700836 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800837 return task;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700838 }
839
Craig Mautner6170f732013-04-02 13:05:23 -0700840 ActivityRecord isInAnyStackLocked(IBinder token) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800841 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800842 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800843 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800844 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
845 final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
846 if (r != null) {
847 return r;
848 }
Craig Mautner6170f732013-04-02 13:05:23 -0700849 }
850 }
851 return null;
852 }
853
Tony Mak853304c2016-04-18 15:17:41 +0100854 /**
Robin Lee3fef1f22016-12-20 14:50:13 +0000855 * Detects whether we should show a lock screen in front of this task for a locked user.
856 * <p>
857 * We'll do this if either of the following holds:
858 * <ul>
859 * <li>The top activity explicitly belongs to {@param userId}.</li>
860 * <li>The top activity returns a result to an activity belonging to {@param userId}.</li>
861 * </ul>
862 *
863 * @return {@code true} if the top activity looks like it belongs to {@param userId}.
Tony Mak853304c2016-04-18 15:17:41 +0100864 */
Robin Lee3fef1f22016-12-20 14:50:13 +0000865 private boolean taskTopActivityIsUser(TaskRecord task, @UserIdInt int userId) {
866 // To handle the case that work app is in the task but just is not the top one.
867 final ActivityRecord activityRecord = task.getTopActivity();
868 final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null);
869
870 return (activityRecord != null && activityRecord.userId == userId)
871 || (resultTo != null && resultTo.userId == userId);
872 }
873
874 /**
875 * Find all visible task stacks containing {@param userId} and intercept them with an activity
876 * to block out the contents and possibly start a credential-confirming intent.
877 *
878 * @param userId user handle for the locked managed profile.
879 */
880 void lockAllProfileTasks(@UserIdInt int userId) {
881 mWindowManager.deferSurfaceLayout();
882 try {
883 final List<ActivityStack> stacks = getStacks();
884 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; stackNdx--) {
885 final List<TaskRecord> tasks = stacks.get(stackNdx).getAllTasks();
886 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) {
887 final TaskRecord task = tasks.get(taskNdx);
888
889 // Check the task for a top activity belonging to userId, or returning a result
890 // to an activity belonging to userId. Example case: a document picker for
891 // personal files, opened by a work app, should still get locked.
892 if (taskTopActivityIsUser(task, userId)) {
Robin Leec41f6ec2017-01-10 17:02:34 +0000893 mService.mTaskChangeNotificationController.notifyTaskProfileLocked(
894 task.taskId, userId);
Robin Lee3fef1f22016-12-20 14:50:13 +0000895 }
Tony Mak853304c2016-04-18 15:17:41 +0100896 }
897 }
Robin Lee3fef1f22016-12-20 14:50:13 +0000898 } finally {
899 mWindowManager.continueSurfaceLayout();
Tony Mak853304c2016-04-18 15:17:41 +0100900 }
Clara Bayarrif0649ce2016-01-14 12:30:42 +0000901 }
902
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800903 void setNextTaskIdForUserLocked(int taskId, int userId) {
904 final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
905 if (taskId > currentTaskId) {
906 mCurTaskIdForUser.put(userId, taskId);
Craig Mautneref73ee12014-04-23 11:45:37 -0700907 }
908 }
909
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700910 static int nextTaskIdForUser(int taskId, int userId) {
911 int nextTaskId = taskId + 1;
912 if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
913 // Wrap around as there will be smaller task ids that are available now.
914 nextTaskId -= MAX_TASK_IDS_PER_USER;
915 }
916 return nextTaskId;
917 }
918
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800919 int getNextTaskIdForUserLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800920 final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
921 // for a userId u, a taskId can only be in the range
922 // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
923 // was 10, user 0 could only have taskIds 0 to 9, user 1: 10 to 19, user 2: 20 to 29, so on.
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700924 int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800925 while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
Winson Chung7900bee2017-03-10 08:59:25 -0800926 || anyTaskForIdLocked(candidateTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800927 INVALID_STACK_ID) != null) {
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700928 candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800929 if (candidateTaskId == currentTaskId) {
930 // Something wrong!
931 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
932 throw new IllegalStateException("Cannot get an available task id."
933 + " Reached limit of " + MAX_TASK_IDS_PER_USER
934 + " running tasks per user.");
935 }
936 }
937 mCurTaskIdForUser.put(userId, candidateTaskId);
938 return candidateTaskId;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700939 }
940
Chong Zhang6cda19c2016-06-14 19:07:56 -0700941 ActivityRecord getResumedActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -0800942 ActivityStack stack = mFocusedStack;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700943 if (stack == null) {
944 return null;
945 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700946 ActivityRecord resumedActivity = stack.mResumedActivity;
947 if (resumedActivity == null || resumedActivity.app == null) {
948 resumedActivity = stack.mPausingActivity;
949 if (resumedActivity == null || resumedActivity.app == null) {
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -0700950 resumedActivity = stack.topRunningActivityLocked();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700951 }
952 }
953 return resumedActivity;
954 }
955
Dianne Hackbornff072722014-09-24 10:56:28 -0700956 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
Craig Mautner20e72272013-04-01 13:45:53 -0700957 final String processName = app.processName;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800958 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800959 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
960 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800961 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
962 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700963 if (!isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800964 continue;
965 }
Jorim Jaggiea039a82017-08-02 14:37:49 +0200966 stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
967 final ActivityRecord top = stack.topRunningActivityLocked();
968 final int size = mTmpActivityList.size();
969 for (int i = 0; i < size; i++) {
970 final ActivityRecord activity = mTmpActivityList.get(i);
971 if (activity.app == null && app.uid == activity.info.applicationInfo.uid
972 && processName.equals(activity.processName)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800973 try {
Jorim Jaggiea039a82017-08-02 14:37:49 +0200974 if (realStartActivityLocked(activity, app,
975 top == activity /* andResume */, true /* checkConfig */)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800976 didSomething = true;
977 }
Dianne Hackbornff072722014-09-24 10:56:28 -0700978 } catch (RemoteException e) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800979 Slog.w(TAG, "Exception in new application when starting activity "
Jorim Jaggiea039a82017-08-02 14:37:49 +0200980 + top.intent.getComponent().flattenToShortString(), e);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800981 throw e;
Craig Mautner20e72272013-04-01 13:45:53 -0700982 }
Craig Mautner20e72272013-04-01 13:45:53 -0700983 }
Craig Mautner20e72272013-04-01 13:45:53 -0700984 }
985 }
986 }
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700987 if (!didSomething) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700988 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700989 }
Craig Mautner20e72272013-04-01 13:45:53 -0700990 return didSomething;
991 }
992
993 boolean allResumedActivitiesIdle() {
Craig Mautnere0a38842013-12-16 16:14:02 -0800994 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
995 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800996 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
997 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700998 if (!isFocusedStack(stack) || stack.numActivities() == 0) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800999 continue;
1000 }
1001 final ActivityRecord resumedActivity = stack.mResumedActivity;
1002 if (resumedActivity == null || !resumedActivity.idle) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001003 if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
Craig Mautner34b73df2014-01-12 21:11:08 -08001004 + stack.mStackId + " " + resumedActivity + " not idle");
Craig Mautner4a1cb222013-12-04 16:14:06 -08001005 return false;
1006 }
Craig Mautner20e72272013-04-01 13:45:53 -07001007 }
1008 }
Wei Wang65c7a152016-06-02 18:51:22 -07001009 // Send launch end powerhint when idle
1010 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
Craig Mautner20e72272013-04-01 13:45:53 -07001011 return true;
1012 }
1013
Craig Mautnerde4ef022013-04-07 19:01:33 -07001014 boolean allResumedActivitiesComplete() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001015 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1016 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001017 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1018 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001019 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001020 final ActivityRecord r = stack.mResumedActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001021 if (r != null && r.state != RESUMED) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001022 return false;
1023 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001024 }
1025 }
1026 }
1027 // TODO: Not sure if this should check if all Paused are complete too.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001028 if (DEBUG_STACK) Slog.d(TAG_STACK,
Craig Mautner4a1cb222013-12-04 16:14:06 -08001029 "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
1030 mLastFocusedStack + " to=" + mFocusedStack);
1031 mLastFocusedStack = mFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001032 return true;
1033 }
1034
1035 boolean allResumedActivitiesVisible() {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001036 boolean foundResumed = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001037 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1038 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001039 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1040 final ActivityStack stack = stacks.get(stackNdx);
1041 final ActivityRecord r = stack.mResumedActivity;
riddle_hsudb46d6b2015-04-01 18:58:07 +08001042 if (r != null) {
Bryce Lee4a194382017-04-04 14:32:48 -07001043 if (!r.nowVisible || mActivitiesWaitingForVisibleActivity.contains(r)) {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001044 return false;
1045 }
1046 foundResumed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001047 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001048 }
1049 }
riddle_hsudb46d6b2015-04-01 18:58:07 +08001050 return foundResumed;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001051 }
1052
Craig Mautner2acc3892013-09-23 10:28:14 -07001053 /**
1054 * Pause all activities in either all of the stacks or just the back stacks.
1055 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
Wale Ogunwale950faff2016-08-08 09:51:04 -07001056 * @param resuming The resuming activity.
1057 * @param dontWait The resuming activity isn't going to wait for all activities to be paused
1058 * before resuming.
Craig Mautner2acc3892013-09-23 10:28:14 -07001059 * @return true if any activity was paused as a result of this call.
1060 */
Wale Ogunwale950faff2016-08-08 09:51:04 -07001061 boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
Craig Mautnercf910b02013-04-23 11:23:27 -07001062 boolean someActivityPaused = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001063 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1064 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001065 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1066 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001067 if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001068 if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
Craig Mautner4a1cb222013-12-04 16:14:06 -08001069 " mResumedActivity=" + stack.mResumedActivity);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001070 someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
1071 dontWait);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001072 }
Craig Mautnercf910b02013-04-23 11:23:27 -07001073 }
1074 }
1075 return someActivityPaused;
1076 }
1077
Craig Mautnerde4ef022013-04-07 19:01:33 -07001078 boolean allPausedActivitiesComplete() {
Craig Mautnerac6f8432013-07-17 13:24:59 -07001079 boolean pausing = true;
Craig Mautnere0a38842013-12-16 16:14:02 -08001080 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1081 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001082 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1083 final ActivityStack stack = stacks.get(stackNdx);
1084 final ActivityRecord r = stack.mPausingActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001085 if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001086 if (DEBUG_STATES) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001087 Slog.d(TAG_STATES,
1088 "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001089 pausing = false;
1090 } else {
1091 return false;
1092 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001093 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001094 }
1095 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001096 return pausing;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001097 }
1098
Wale Ogunwale2be760d2016-02-17 11:16:10 -08001099 void cancelInitializingActivities() {
1100 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1101 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1102 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1103 stacks.get(stackNdx).cancelInitializingActivities();
1104 }
1105 }
1106 }
1107
Bryce Lee4a194382017-04-04 14:32:48 -07001108 void waitActivityVisible(ComponentName name, WaitResult result) {
1109 final WaitInfo waitInfo = new WaitInfo(name, result);
1110 mWaitingForActivityVisible.add(waitInfo);
1111 }
1112
1113 void cleanupActivity(ActivityRecord r) {
1114 // Make sure this record is no longer in the pending finishes list.
1115 // This could happen, for example, if we are trimming activities
1116 // down to the max limit while they are still waiting to finish.
1117 mFinishingActivities.remove(r);
1118 mActivitiesWaitingForVisibleActivity.remove(r);
1119
1120 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
Wale Ogunwale3270f172017-04-26 07:29:42 -07001121 if (mWaitingForActivityVisible.get(i).matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001122 mWaitingForActivityVisible.remove(i);
1123 }
1124 }
1125 }
1126
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001127 void reportActivityVisibleLocked(ActivityRecord r) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001128 sendWaitingVisibleReportLocked(r);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001129 }
1130
1131 void sendWaitingVisibleReportLocked(ActivityRecord r) {
1132 boolean changed = false;
Bryce Lee4a194382017-04-04 14:32:48 -07001133 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
1134 final WaitInfo w = mWaitingForActivityVisible.get(i);
Wale Ogunwale3270f172017-04-26 07:29:42 -07001135 if (w.matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001136 final WaitResult result = w.getResult();
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001137 changed = true;
Bryce Lee4a194382017-04-04 14:32:48 -07001138 result.timeout = false;
1139 result.who = w.getComponent();
1140 result.totalTime = SystemClock.uptimeMillis() - result.thisTime;
1141 result.thisTime = result.totalTime;
1142 mWaitingForActivityVisible.remove(w);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001143 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001144 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001145 if (changed) {
1146 mService.notifyAll();
1147 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001148 }
1149
Chong Zhang5022da32016-06-21 16:31:37 -07001150 void reportTaskToFrontNoLaunch(ActivityRecord r) {
1151 boolean changed = false;
1152 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1153 WaitResult w = mWaitingActivityLaunched.remove(i);
1154 if (w.who == null) {
1155 changed = true;
1156 // Set result to START_TASK_TO_FRONT so that startActivityMayWait() knows that
1157 // the starting activity ends up moving another activity to front, and it should
1158 // wait for this new activity to become visible instead.
1159 // Do not modify other fields.
1160 w.result = START_TASK_TO_FRONT;
1161 }
1162 }
1163 if (changed) {
1164 mService.notifyAll();
1165 }
1166 }
1167
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001168 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
1169 long thisTime, long totalTime) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001170 boolean changed = false;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001171 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
Craig Mautnerc64f73e2013-04-24 16:44:56 -07001172 WaitResult w = mWaitingActivityLaunched.remove(i);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001173 if (w.who == null) {
1174 changed = true;
1175 w.timeout = timeout;
1176 if (r != null) {
1177 w.who = new ComponentName(r.info.packageName, r.info.name);
1178 }
1179 w.thisTime = thisTime;
1180 w.totalTime = totalTime;
Chong Zhang5022da32016-06-21 16:31:37 -07001181 // Do not modify w.result.
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001182 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001183 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001184 if (changed) {
1185 mService.notifyAll();
1186 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001187 }
1188
Craig Mautner29219d92013-04-16 20:19:12 -07001189 ActivityRecord topRunningActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -08001190 final ActivityStack focusedStack = mFocusedStack;
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07001191 ActivityRecord r = focusedStack.topRunningActivityLocked();
Craig Mautner1602ec22013-05-12 10:24:27 -07001192 if (r != null) {
1193 return r;
Craig Mautner29219d92013-04-16 20:19:12 -07001194 }
Craig Mautner1602ec22013-05-12 10:24:27 -07001195
Andrii Kulian7318d632016-07-20 18:59:28 -07001196 // Look in other non-focused and non-home stacks.
Andrii Kulian7d95df42017-02-15 10:11:48 -08001197 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
1198
1199 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
1200 final int displayId = mTmpOrderedDisplayIds.get(i);
1201 final List<ActivityStack> stacks = mActivityDisplays.get(displayId).mStacks;
1202 if (stacks == null) {
1203 continue;
1204 }
1205 for (int j = stacks.size() - 1; j >= 0; --j) {
1206 final ActivityStack stack = stacks.get(j);
1207 if (stack != focusedStack && isFrontStackOnDisplay(stack) && stack.isFocusable()) {
1208 r = stack.topRunningActivityLocked();
1209 if (r != null) {
1210 return r;
1211 }
Craig Mautner29219d92013-04-16 20:19:12 -07001212 }
1213 }
1214 }
1215 return null;
1216 }
1217
Dianne Hackborn09233282014-04-30 11:33:59 -07001218 void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001219 // Gather all of the running tasks for each stack into runningTaskLists.
Craig Mautner4a1cb222013-12-04 16:14:06 -08001220 ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1221 new ArrayList<ArrayList<RunningTaskInfo>>();
Craig Mautnere0a38842013-12-16 16:14:02 -08001222 final int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001223 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08001224 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001225 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1226 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautner15df08a2015-04-01 12:17:18 -07001227 ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001228 runningTaskLists.add(stackTaskList);
Dianne Hackborn09233282014-04-30 11:33:59 -07001229 stack.getTasksLocked(stackTaskList, callingUid, allowed);
Craig Mautner20e72272013-04-01 13:45:53 -07001230 }
1231 }
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001232
1233 // The lists are already sorted from most recent to oldest. Just pull the most recent off
1234 // each list and add it to list. Stop when all lists are empty or maxNum reached.
1235 while (maxNum > 0) {
1236 long mostRecentActiveTime = Long.MIN_VALUE;
1237 ArrayList<RunningTaskInfo> selectedStackList = null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001238 final int numTaskLists = runningTaskLists.size();
1239 for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1240 ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001241 if (!stackTaskList.isEmpty()) {
1242 final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1243 if (lastActiveTime > mostRecentActiveTime) {
1244 mostRecentActiveTime = lastActiveTime;
1245 selectedStackList = stackTaskList;
1246 }
1247 }
1248 }
1249 if (selectedStackList != null) {
1250 list.add(selectedStackList.remove(0));
1251 --maxNum;
1252 } else {
1253 break;
1254 }
1255 }
Craig Mautner20e72272013-04-01 13:45:53 -07001256 }
1257
Todd Kennedy7440f172015-12-09 14:31:22 -08001258 ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1259 ProfilerInfo profilerInfo) {
1260 final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
Craig Mautner23ac33b2013-04-01 16:26:35 -07001261 if (aInfo != null) {
1262 // Store the found target back into the intent, because now that
1263 // we have it we never want to do this again. For example, if the
1264 // user navigates back to this point in the history, we should
1265 // always restart the exact same activity.
1266 intent.setComponent(new ComponentName(
1267 aInfo.applicationInfo.packageName, aInfo.name));
1268
1269 // Don't debug things in the system process
Man Caocfa78b22015-06-11 20:14:34 -07001270 if (!aInfo.processName.equals("system")) {
1271 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
Chong Zhangd25944e2016-06-09 16:15:27 -07001272 mService.setDebugApp(aInfo.processName, true, false);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001273 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001274
Tamas Berghammerdf6cb282016-01-29 12:07:00 +00001275 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1276 mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1277 }
1278
Man Caocfa78b22015-06-11 20:14:34 -07001279 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1280 mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1281 }
1282
1283 if (profilerInfo != null) {
Jeff Hao1b012d32014-08-20 10:35:34 -07001284 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001285 }
1286 }
Todd Kennedyb3b431302017-03-20 16:05:48 -07001287 final String intentLaunchToken = intent.getLaunchToken();
1288 if (aInfo.launchToken == null && intentLaunchToken != null) {
1289 aInfo.launchToken = intentLaunchToken;
1290 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001291 }
1292 return aInfo;
1293 }
1294
Todd Kennedy7440f172015-12-09 14:31:22 -08001295 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
Kenny Guyb1b30262016-02-09 16:02:35 +00001296 return resolveIntent(intent, resolvedType, userId, 0);
1297 }
1298
1299 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
Todd Kennedy4d1de7d2017-02-23 10:32:18 -08001300 synchronized (mService) {
1301 return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001302 PackageManager.MATCH_INSTANT | PackageManager.MATCH_DEFAULT_ONLY | flags
Kenny Guyb1b30262016-02-09 16:02:35 +00001303 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Todd Kennedy7440f172015-12-09 14:31:22 -08001304 }
Todd Kennedy7440f172015-12-09 14:31:22 -08001305 }
1306
1307 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1308 ProfilerInfo profilerInfo, int userId) {
1309 final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1310 return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1311 }
1312
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001313 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1314 boolean andResume, boolean checkConfig) throws RemoteException {
1315
1316 if (!allPausedActivitiesComplete()) {
1317 // While there are activities pausing we skipping starting any new activities until
1318 // pauses are complete. NOTE: that we also do this for activities that are starting in
1319 // the paused state because they will first be resumed then paused on the client side.
1320 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1321 "realStartActivityLocked: Skipping start of r=" + r
1322 + " some activities pausing...");
1323 return false;
1324 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001325
Bryce Leeaf691c02017-03-20 14:20:22 -07001326 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07001327 final ActivityStack stack = task.getStack();
chaviw59b98852017-06-13 12:05:44 -07001328
1329 beginDeferResume();
1330
Craig Mautner2420ead2013-04-01 17:13:20 -07001331 try {
chaviw59b98852017-06-13 12:05:44 -07001332 r.startFreezingScreenLocked(app, 0);
1333
1334 // schedule launch ticks to collect information about slow apps.
1335 r.startLaunchTickingLocked();
1336
1337 r.app = app;
1338
Jorim Jaggiedede6d2017-08-28 15:44:43 +02001339 if (mKeyguardController.isKeyguardLocked()) {
1340 r.notifyUnknownVisibilityLaunched();
1341 }
1342
chaviw59b98852017-06-13 12:05:44 -07001343 // Have the window manager re-evaluate the orientation of the screen based on the new
1344 // activity order. Note that as a result of this, it can call back into the activity
1345 // manager with a new orientation. We don't care about that, because the activity is
1346 // not currently running so we are just restarting it anyway.
1347 if (checkConfig) {
1348 final int displayId = r.getDisplayId();
1349 final Configuration config = mWindowManager.updateOrientationFromAppTokens(
1350 getDisplayOverrideConfiguration(displayId),
1351 r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
1352 // Deferring resume here because we're going to launch new activity shortly.
1353 // We don't want to perform a redundant launch of the same record while ensuring
1354 // configurations and trying to resume top activity of focused stack.
1355 mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
1356 displayId);
Craig Mautner2420ead2013-04-01 17:13:20 -07001357 }
chaviw59b98852017-06-13 12:05:44 -07001358
1359 if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */,
1360 true /* isTop */)) {
1361 // We only set the visibility to true if the activity is allowed to be visible
1362 // based on
1363 // keyguard state. This avoids setting this into motion in window manager that is
1364 // later cancelled due to later calls to ensure visible activities that set
1365 // visibility back to false.
1366 r.setVisibility(true);
Craig Mautner2420ead2013-04-01 17:13:20 -07001367 }
chaviw59b98852017-06-13 12:05:44 -07001368
chaviw59b98852017-06-13 12:05:44 -07001369 final int applicationInfoUid =
1370 (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
1371 if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
1372 Slog.wtf(TAG,
1373 "User ID for activity changing for " + r
1374 + " appInfo.uid=" + r.appInfo.uid
1375 + " info.ai.uid=" + applicationInfoUid
1376 + " old=" + r.app + " new=" + app);
1377 }
1378
1379 app.waitingToKill = null;
1380 r.launchCount++;
1381 r.lastLaunchTime = SystemClock.uptimeMillis();
1382
1383 if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1384
1385 int idx = app.activities.indexOf(r);
1386 if (idx < 0) {
1387 app.activities.add(r);
1388 }
1389 mService.updateLruProcessLocked(app, true, null);
1390 mService.updateOomAdjLocked();
1391
1392 if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1393 task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
1394 setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE",
1395 false);
1396 }
1397
1398 try {
1399 if (app.thread == null) {
1400 throw new RemoteException();
1401 }
1402 List<ResultInfo> results = null;
1403 List<ReferrerIntent> newIntents = null;
1404 if (andResume) {
1405 // We don't need to deliver new intents and/or set results if activity is going
1406 // to pause immediately after launch.
1407 results = r.results;
1408 newIntents = r.newIntents;
1409 }
1410 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1411 "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1412 + " newIntents=" + newIntents + " andResume=" + andResume);
1413 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
1414 System.identityHashCode(r), task.taskId, r.shortComponentName);
1415 if (r.isHomeActivity()) {
1416 // Home process is the root process of the task.
1417 mService.mHomeProcess = task.mActivities.get(0).app;
1418 }
1419 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
1420 PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
1421 r.sleeping = false;
1422 r.forceNewConfig = false;
1423 mService.showUnsupportedZoomDialogIfNeededLocked(r);
1424 mService.showAskCompatModeDialogLocked(r);
1425 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1426 ProfilerInfo profilerInfo = null;
1427 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1428 if (mService.mProfileProc == null || mService.mProfileProc == app) {
1429 mService.mProfileProc = app;
Andreas Gampe2b073a02017-06-22 17:28:57 -07001430 ProfilerInfo profilerInfoSvc = mService.mProfilerInfo;
1431 if (profilerInfoSvc != null && profilerInfoSvc.profileFile != null) {
1432 if (profilerInfoSvc.profileFd != null) {
chaviw59b98852017-06-13 12:05:44 -07001433 try {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001434 profilerInfoSvc.profileFd = profilerInfoSvc.profileFd.dup();
chaviw59b98852017-06-13 12:05:44 -07001435 } catch (IOException e) {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001436 profilerInfoSvc.closeFd();
Craig Mautner2568c3a2015-03-26 14:22:34 -07001437 }
1438 }
chaviw59b98852017-06-13 12:05:44 -07001439
Andreas Gampe2b073a02017-06-22 17:28:57 -07001440 profilerInfo = new ProfilerInfo(profilerInfoSvc);
Craig Mautner2420ead2013-04-01 17:13:20 -07001441 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001442 }
1443 }
Adam Powellcfbe9be2013-11-06 14:58:58 -08001444
chaviw59b98852017-06-13 12:05:44 -07001445 app.hasShownUi = true;
1446 app.pendingUiClean = true;
1447 app.forceProcessStateUpTo(mService.mTopProcessState);
1448 // Because we could be starting an Activity in the system process this may not go
1449 // across a Binder interface which would create a new Configuration. Consequently
1450 // we have to always create a new Configuration here.
Bryce Leea163b762017-01-24 11:05:01 -08001451
chaviw59b98852017-06-13 12:05:44 -07001452 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
1453 mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
1454 r.setLastReportedConfiguration(mergedConfiguration);
Bryce Leea163b762017-01-24 11:05:01 -08001455
chaviw59b98852017-06-13 12:05:44 -07001456 logIfTransactionTooLarge(r.intent, r.icicle);
1457 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1458 System.identityHashCode(r), r.info,
1459 // TODO: Have this take the merged configuration instead of separate global
1460 // and override configs.
1461 mergedConfiguration.getGlobalConfiguration(),
1462 mergedConfiguration.getOverrideConfiguration(), r.compat,
1463 r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1464 r.persistentState, results, newIntents, !andResume,
1465 mService.isNextTransitionForward(), profilerInfo);
Craig Mautner2420ead2013-04-01 17:13:20 -07001466
chaviw59b98852017-06-13 12:05:44 -07001467 if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1468 // This may be a heavy-weight process! Note that the package
1469 // manager will ensure that only activity can run in the main
1470 // process of the .apk, which is the only thing that will be
1471 // considered heavy-weight.
1472 if (app.processName.equals(app.info.packageName)) {
1473 if (mService.mHeavyWeightProcess != null
1474 && mService.mHeavyWeightProcess != app) {
1475 Slog.w(TAG, "Starting new heavy weight process " + app
1476 + " when already running "
1477 + mService.mHeavyWeightProcess);
1478 }
1479 mService.mHeavyWeightProcess = app;
1480 Message msg = mService.mHandler.obtainMessage(
1481 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1482 msg.obj = r;
1483 mService.mHandler.sendMessage(msg);
Craig Mautner2420ead2013-04-01 17:13:20 -07001484 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001485 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001486
chaviw59b98852017-06-13 12:05:44 -07001487 } catch (RemoteException e) {
1488 if (r.launchFailed) {
1489 // This is the second time we failed -- finish activity
1490 // and give up.
1491 Slog.e(TAG, "Second failure launching "
1492 + r.intent.getComponent().flattenToShortString()
1493 + ", giving up", e);
1494 mService.appDiedLocked(app);
1495 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1496 "2nd-crash", false);
1497 return false;
1498 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001499
chaviw59b98852017-06-13 12:05:44 -07001500 // This is the first time we failed -- restart process and
1501 // retry.
1502 r.launchFailed = true;
1503 app.activities.remove(r);
1504 throw e;
1505 }
1506 } finally {
1507 endDeferResume();
Craig Mautner2420ead2013-04-01 17:13:20 -07001508 }
1509
1510 r.launchFailed = false;
1511 if (stack.updateLRUListLocked(r)) {
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07001512 Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
Craig Mautner2420ead2013-04-01 17:13:20 -07001513 }
1514
chaviw59b98852017-06-13 12:05:44 -07001515 if (andResume && readyToResume()) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001516 // As part of the process of launching, ActivityThread also performs
1517 // a resume.
1518 stack.minimalResumeActivityLocked(r);
1519 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001520 // This activity is not starting in the resumed state... which should look like we asked
Wale Ogunwale919a05d2017-04-13 00:36:34 +00001521 // it to pause+stop (but remain visible), and it has done so and reported back the
Wale Ogunwaled046a012015-12-24 13:05:59 -08001522 // current icicle and other state.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001523 if (DEBUG_STATES) Slog.v(TAG_STATES,
Wale Ogunwaled046a012015-12-24 13:05:59 -08001524 "Moving to PAUSED: " + r + " (starting in paused state)");
1525 r.state = PAUSED;
Craig Mautner2420ead2013-04-01 17:13:20 -07001526 }
1527
1528 // Launch the new version setup screen if needed. We do this -after-
1529 // launching the initial activity (that is, home), so that it can have
1530 // a chance to initialize itself while in the background, making the
1531 // switch back to it faster and look better.
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001532 if (isFocusedStack(stack)) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001533 mService.startSetupActivityLocked();
1534 }
1535
Dianne Hackborn465fa392014-09-14 14:21:18 -07001536 // Update any services we are bound to that might care about whether
1537 // their client may have activities.
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001538 if (r.app != null) {
1539 mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1540 }
Dianne Hackborn465fa392014-09-14 14:21:18 -07001541
Craig Mautner2420ead2013-04-01 17:13:20 -07001542 return true;
1543 }
1544
Sudheer Shankafab200f2017-05-17 20:41:53 -07001545 private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
1546 int extrasSize = 0;
1547 if (intent != null) {
1548 final Bundle extras = intent.getExtras();
1549 if (extras != null) {
1550 extrasSize = extras.getSize();
1551 }
1552 }
1553 int icicleSize = (icicle == null ? 0 : icicle.getSize());
1554 if (extrasSize + icicleSize > 200000) {
1555 Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
1556 + ", icicle size: " + icicleSize);
1557 }
1558 }
1559
Craig Mautnere79d42682013-04-01 19:01:53 -07001560 void startSpecificActivityLocked(ActivityRecord r,
George Mount2c92c972014-03-20 09:38:23 -07001561 boolean andResume, boolean checkConfig) {
Craig Mautnere79d42682013-04-01 19:01:53 -07001562 // Is this activity's application already running?
1563 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001564 r.info.applicationInfo.uid, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001565
Andrii Kulian02b7a832016-10-06 23:11:56 -07001566 r.getStack().setLaunchTime(r);
Craig Mautnere79d42682013-04-01 19:01:53 -07001567
1568 if (app != null && app.thread != null) {
1569 try {
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001570 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1571 || !"android".equals(r.info.packageName)) {
1572 // Don't add this if it is a platform component that is marked
1573 // to run in multiple processes, because this is actually
1574 // part of the framework so doesn't make sense to track as a
1575 // separate apk in the process.
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001576 app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1577 mService.mProcessStats);
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001578 }
George Mount2c92c972014-03-20 09:38:23 -07001579 realStartActivityLocked(r, app, andResume, checkConfig);
Craig Mautnere79d42682013-04-01 19:01:53 -07001580 return;
1581 } catch (RemoteException e) {
1582 Slog.w(TAG, "Exception when starting activity "
1583 + r.intent.getComponent().flattenToShortString(), e);
1584 }
1585
1586 // If a dead object exception was thrown -- fall through to
1587 // restart the application.
1588 }
1589
1590 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001591 "activity", r.intent.getComponent(), false, false, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001592 }
1593
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001594 boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001595 String resultWho, int requestCode, int callingPid, int callingUid,
1596 String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
Jorim Jaggi2adba072016-03-03 13:43:39 +01001597 ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001598 final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1599 callingUid);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001600 if (startAnyPerm == PERMISSION_GRANTED) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001601 return true;
1602 }
1603 final int componentRestriction = getComponentRestrictionForCallingPackage(
1604 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1605 final int actionRestriction = getActionRestrictionForCallingPackage(
1606 intent.getAction(), callingPackage, callingPid, callingUid);
1607 if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1608 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1609 if (resultRecord != null) {
1610 resultStack.sendActivityResultLocked(-1,
1611 resultRecord, resultWho, requestCode,
1612 Activity.RESULT_CANCELED, null);
1613 }
1614 final String msg;
1615 if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1616 msg = "Permission Denial: starting " + intent.toString()
1617 + " from " + callerApp + " (pid=" + callingPid
1618 + ", uid=" + callingUid + ")" + " with revoked permission "
1619 + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1620 } else if (!aInfo.exported) {
1621 msg = "Permission Denial: starting " + intent.toString()
1622 + " from " + callerApp + " (pid=" + callingPid
1623 + ", uid=" + callingUid + ")"
1624 + " not exported from uid " + aInfo.applicationInfo.uid;
1625 } else {
1626 msg = "Permission Denial: starting " + intent.toString()
1627 + " from " + callerApp + " (pid=" + callingPid
1628 + ", uid=" + callingUid + ")"
1629 + " requires " + aInfo.permission;
1630 }
1631 Slog.w(TAG, msg);
1632 throw new SecurityException(msg);
1633 }
1634
1635 if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1636 final String message = "Appop Denial: starting " + intent.toString()
1637 + " from " + callerApp + " (pid=" + callingPid
1638 + ", uid=" + callingUid + ")"
1639 + " requires " + AppOpsManager.permissionToOp(
1640 ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1641 Slog.w(TAG, message);
1642 return false;
1643 } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1644 final String message = "Appop Denial: starting " + intent.toString()
1645 + " from " + callerApp + " (pid=" + callingPid
1646 + ", uid=" + callingUid + ")"
1647 + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1648 Slog.w(TAG, message);
1649 return false;
1650 }
Andrii Kulian16802aa2016-11-02 12:21:33 -07001651 if (options != null) {
1652 if (options.getLaunchTaskId() != INVALID_STACK_ID) {
1653 final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1654 callingPid, callingUid);
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001655 if (startInTaskPerm == PERMISSION_DENIED) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07001656 final String msg = "Permission Denial: starting " + intent.toString()
1657 + " from " + callerApp + " (pid=" + callingPid
1658 + ", uid=" + callingUid + ") with launchTaskId="
1659 + options.getLaunchTaskId();
1660 Slog.w(TAG, msg);
1661 throw new SecurityException(msg);
1662 }
1663 }
1664 // Check if someone tries to launch an activity on a private display with a different
1665 // owner.
1666 final int launchDisplayId = options.getLaunchDisplayId();
Andrii Kulian02689a72017-07-06 14:28:59 -07001667 if (launchDisplayId != INVALID_DISPLAY && !isCallerAllowedToLaunchOnDisplay(callingPid,
1668 callingUid, launchDisplayId, aInfo)) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001669 final String msg = "Permission Denial: starting " + intent.toString()
1670 + " from " + callerApp + " (pid=" + callingPid
1671 + ", uid=" + callingUid + ") with launchDisplayId="
1672 + launchDisplayId;
1673 Slog.w(TAG, msg);
1674 throw new SecurityException(msg);
Jorim Jaggi2adba072016-03-03 13:43:39 +01001675 }
1676 }
1677
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001678 return true;
1679 }
1680
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001681 /** Check if caller is allowed to launch activities on specified display. */
Andrii Kulian02689a72017-07-06 14:28:59 -07001682 boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId,
1683 ActivityInfo aInfo) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001684 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId
1685 + " callingPid=" + callingPid + " callingUid=" + callingUid);
1686
Andrii Kulian02689a72017-07-06 14:28:59 -07001687 if (callingPid == -1 && callingUid == -1) {
1688 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: no caller info, skip check");
1689 return true;
1690 }
1691
Andrii Kulian62e6f252017-05-30 22:46:53 -07001692 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(launchDisplayId);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001693 if (activityDisplay == null) {
1694 Slog.w(TAG, "Launch on display check: display not found");
1695 return false;
1696 }
1697
Andrii Kulian02689a72017-07-06 14:28:59 -07001698 // Check if the caller has enough privileges to embed activities and launch to private
1699 // displays.
Andrii Kulian3a95edc2017-06-28 16:21:07 -07001700 final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001701 callingUid);
1702 if (startAnyPerm == PERMISSION_GRANTED) {
1703 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1704 + " allow launch any on display");
1705 return true;
1706 }
1707
Andrii Kulian8f070292017-09-12 22:56:49 -07001708 // Check if caller is already present on display
1709 final boolean uidPresentOnDisplay = activityDisplay.isUidPresent(callingUid);
1710
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001711 final int displayOwnerUid = activityDisplay.mDisplay.getOwnerUid();
1712 if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL && displayOwnerUid != SYSTEM_UID
1713 && displayOwnerUid != aInfo.applicationInfo.uid) {
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001714 // Limit launching on virtual displays, because their contents can be read from Surface
1715 // by apps that created them.
Andrii Kulian02689a72017-07-06 14:28:59 -07001716 if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
1717 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1718 + " disallow launch on virtual display for not-embedded activity.");
1719 return false;
1720 }
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001721 // Check if the caller is allowed to embed activities from other apps.
1722 if (mService.checkPermission(ACTIVITY_EMBEDDING, callingPid, callingUid)
Andrii Kulian8f070292017-09-12 22:56:49 -07001723 == PERMISSION_DENIED && !uidPresentOnDisplay) {
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001724 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1725 + " disallow activity embedding without permission.");
1726 return false;
1727 }
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001728 }
1729
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001730 if (!activityDisplay.isPrivate()) {
1731 // Anyone can launch on a public display.
1732 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1733 + " allow launch on public display");
1734 return true;
1735 }
1736
1737 // Check if the caller is the owner of the display.
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001738 if (displayOwnerUid == callingUid) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001739 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1740 + " allow launch for owner of the display");
1741 return true;
1742 }
1743
Andrii Kulian8f070292017-09-12 22:56:49 -07001744 if (uidPresentOnDisplay) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001745 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1746 + " allow launch for caller present on the display");
1747 return true;
1748 }
1749
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001750 Slog.w(TAG, "Launch on display check: denied");
1751 return false;
1752 }
1753
1754 /** Update lists of UIDs that are present on displays and have access to them. */
1755 void updateUIDsPresentOnDisplay() {
1756 mDisplayAccessUIDs.clear();
1757 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1758 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
David Stevens82ea6cb2017-03-03 16:18:50 -08001759 // Only bother calculating the whitelist for private displays
1760 if (activityDisplay.isPrivate()) {
1761 mDisplayAccessUIDs.append(
1762 activityDisplay.mDisplayId, activityDisplay.getPresentUIDs());
1763 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001764 }
1765 // Store updated lists in DisplayManager. Callers from outside of AM should get them there.
1766 mDisplayManagerInternal.setDisplayAccessUIDs(mDisplayAccessUIDs);
1767 }
1768
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001769 UserInfo getUserInfo(int userId) {
Clara Bayarrif7fea162015-10-22 16:09:52 +01001770 final long identity = Binder.clearCallingIdentity();
1771 try {
1772 return UserManager.get(mService.mContext).getUserInfo(userId);
1773 } finally {
1774 Binder.restoreCallingIdentity(identity);
1775 }
1776 }
1777
Svet Ganov99b60432015-06-27 13:15:22 -07001778 private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001779 String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001780 if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1781 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001782 == PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001783 return ACTIVITY_RESTRICTION_PERMISSION;
1784 }
1785
Christopher Tateff7add02015-08-17 10:23:22 -07001786 if (activityInfo.permission == null) {
1787 return ACTIVITY_RESTRICTION_NONE;
1788 }
1789
Svet Ganov99b60432015-06-27 13:15:22 -07001790 final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1791 if (opCode == AppOpsManager.OP_NONE) {
1792 return ACTIVITY_RESTRICTION_NONE;
1793 }
1794
1795 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1796 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001797 if (!ignoreTargetSecurity) {
1798 return ACTIVITY_RESTRICTION_APPOP;
1799 }
Svet Ganov99b60432015-06-27 13:15:22 -07001800 }
1801
1802 return ACTIVITY_RESTRICTION_NONE;
1803 }
1804
Svetoslav7008b512015-06-24 18:47:07 -07001805 private int getActionRestrictionForCallingPackage(String action,
1806 String callingPackage, int callingPid, int callingUid) {
1807 if (action == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001808 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001809 }
1810
1811 String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1812 if (permission == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001813 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001814 }
1815
1816 final PackageInfo packageInfo;
1817 try {
1818 packageInfo = mService.mContext.getPackageManager()
1819 .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1820 } catch (PackageManager.NameNotFoundException e) {
1821 Slog.i(TAG, "Cannot find package info for " + callingPackage);
Svet Ganov99b60432015-06-27 13:15:22 -07001822 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001823 }
1824
1825 if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
Svet Ganov99b60432015-06-27 13:15:22 -07001826 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001827 }
1828
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001829 if (mService.checkPermission(permission, callingPid, callingUid) == PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001830 return ACTIVITY_RESTRICTION_PERMISSION;
Svetoslav7008b512015-06-24 18:47:07 -07001831 }
1832
1833 final int opCode = AppOpsManager.permissionToOpCode(permission);
1834 if (opCode == AppOpsManager.OP_NONE) {
Svet Ganov99b60432015-06-27 13:15:22 -07001835 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001836 }
1837
1838 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1839 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001840 return ACTIVITY_RESTRICTION_APPOP;
Svetoslav7008b512015-06-24 18:47:07 -07001841 }
1842
Svet Ganov99b60432015-06-27 13:15:22 -07001843 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001844 }
1845
Dianne Hackborn3d07c942015-03-13 18:02:54 -07001846 void setLaunchSource(int uid) {
1847 mLaunchingActivity.setWorkSource(new WorkSource(uid));
1848 }
1849
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001850 void acquireLaunchWakelock() {
1851 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1852 throw new IllegalStateException("Calling must be system uid");
1853 }
1854 mLaunchingActivity.acquire();
1855 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1856 // To be safe, don't allow the wake lock to be held for too long.
1857 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1858 }
1859 }
1860
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001861 /**
1862 * Called when the frontmost task is idle.
1863 * @return the state of mService.mBooting before this was called.
1864 */
1865 private boolean checkFinishBootingLocked() {
1866 final boolean booting = mService.mBooting;
1867 boolean enableScreen = false;
1868 mService.mBooting = false;
1869 if (!mService.mBooted) {
1870 mService.mBooted = true;
1871 enableScreen = true;
1872 }
1873 if (booting || enableScreen) {
1874 mService.postFinishBooting(booting, enableScreen);
1875 }
1876 return booting;
1877 }
1878
Craig Mautnerf3333272013-04-22 10:55:53 -07001879 // Checked.
1880 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
Winson Chung4dabf232017-01-25 13:25:22 -08001881 boolean processPausingActivities, Configuration config) {
Wale Ogunwalee23149f2015-03-06 15:39:44 -08001882 if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001883
Craig Mautnerf3333272013-04-22 10:55:53 -07001884 ArrayList<ActivityRecord> finishes = null;
Amith Yamasani37a40c22015-06-17 13:25:42 -07001885 ArrayList<UserState> startingUsers = null;
Craig Mautnerf3333272013-04-22 10:55:53 -07001886 int NS = 0;
1887 int NF = 0;
Craig Mautnerf3333272013-04-22 10:55:53 -07001888 boolean booting = false;
Craig Mautnerf3333272013-04-22 10:55:53 -07001889 boolean activityRemoved = false;
1890
Wale Ogunwale7d701172015-03-11 15:36:30 -07001891 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001892 if (r != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001893 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1894 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07001895 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1896 r.finishLaunchTickingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001897 if (fromTimeout) {
1898 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
Craig Mautnerf3333272013-04-22 10:55:53 -07001899 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001900
1901 // This is a hack to semi-deal with a race condition
1902 // in the client where it can be constructed with a
1903 // newer configuration from when we asked it to launch.
1904 // We'll update with whatever configuration it now says
1905 // it used to launch.
1906 if (config != null) {
Bryce Leea163b762017-01-24 11:05:01 -08001907 r.setLastReportedGlobalConfiguration(config);
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001908 }
1909
1910 // We are now idle. If someone is waiting for a thumbnail from
1911 // us, we can now deliver.
1912 r.idle = true;
1913
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001914 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001915 if (isFocusedStack(r.getStack()) || fromTimeout) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001916 booting = checkFinishBootingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001917 }
1918 }
1919
1920 if (allResumedActivitiesIdle()) {
1921 if (r != null) {
1922 mService.scheduleAppGcsLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001923 }
1924
1925 if (mLaunchingActivity.isHeld()) {
1926 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1927 if (VALIDATE_WAKE_LOCK_CALLER &&
1928 Binder.getCallingUid() != Process.myUid()) {
1929 throw new IllegalStateException("Calling must be system uid");
1930 }
1931 mLaunchingActivity.release();
1932 }
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07001933 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerf3333272013-04-22 10:55:53 -07001934 }
1935
1936 // Atomically retrieve all of the other things to do.
Winson Chung4dabf232017-01-25 13:25:22 -08001937 final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
1938 true /* remove */, processPausingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001939 NS = stops != null ? stops.size() : 0;
Wale Ogunwale7d701172015-03-11 15:36:30 -07001940 if ((NF = mFinishingActivities.size()) > 0) {
1941 finishes = new ArrayList<>(mFinishingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001942 mFinishingActivities.clear();
1943 }
1944
Craig Mautnerf3333272013-04-22 10:55:53 -07001945 if (mStartingUsers.size() > 0) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07001946 startingUsers = new ArrayList<>(mStartingUsers);
Craig Mautnerf3333272013-04-22 10:55:53 -07001947 mStartingUsers.clear();
1948 }
1949
Craig Mautnerf3333272013-04-22 10:55:53 -07001950 // Stop any activities that are scheduled to do so but have been
1951 // waiting for the next one to start.
1952 for (int i = 0; i < NS; i++) {
1953 r = stops.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001954 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001955 if (stack != null) {
1956 if (r.finishing) {
1957 stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1958 } else {
1959 stack.stopActivityLocked(r);
1960 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001961 }
1962 }
1963
1964 // Finish any activities that are scheduled to do so but have been
1965 // waiting for the next one to start.
1966 for (int i = 0; i < NF; i++) {
1967 r = finishes.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001968 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001969 if (stack != null) {
1970 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1971 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001972 }
1973
Dianne Hackborn7622a0f2014-09-30 14:31:42 -07001974 if (!booting) {
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001975 // Complete user switch
1976 if (startingUsers != null) {
1977 for (int i = 0; i < startingUsers.size(); i++) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001978 mService.mUserController.finishUserSwitch(startingUsers.get(i));
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001979 }
1980 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001981 }
1982
1983 mService.trimApplications();
1984 //dump();
1985 //mWindowManager.dump();
1986
Craig Mautnerf3333272013-04-22 10:55:53 -07001987 if (activityRemoved) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001988 resumeFocusedStackTopActivityLocked();
Craig Mautnerf3333272013-04-22 10:55:53 -07001989 }
1990
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001991 return r;
Craig Mautnerf3333272013-04-22 10:55:53 -07001992 }
1993
Craig Mautner8e569572013-10-11 17:36:59 -07001994 boolean handleAppDiedLocked(ProcessRecord app) {
Craig Mautner19091252013-10-05 00:03:53 -07001995 boolean hasVisibleActivities = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001996 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1997 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001998 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1999 hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
2000 }
Craig Mautner6b74cb52013-09-27 17:02:21 -07002001 }
Craig Mautner19091252013-10-05 00:03:53 -07002002 return hasVisibleActivities;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002003 }
2004
2005 void closeSystemDialogsLocked() {
Craig Mautnere0a38842013-12-16 16:14:02 -08002006 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2007 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002008 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2009 stacks.get(stackNdx).closeSystemDialogsLocked();
2010 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002011 }
2012 }
2013
Craig Mautner93529a42013-10-04 15:03:13 -07002014 void removeUserLocked(int userId) {
Craig Mautner4f1df4f2013-10-15 15:44:14 -07002015 mUserStackInFront.delete(userId);
Craig Mautner93529a42013-10-04 15:03:13 -07002016 }
2017
Craig Mautner8d341ef2013-03-26 09:03:27 -07002018 /**
Chong Zhang45c25ce2015-08-10 22:18:26 -07002019 * Update the last used stack id for non-current user (current user's last
2020 * used stack is the focused stack)
2021 */
2022 void updateUserStackLocked(int userId, ActivityStack stack) {
2023 if (userId != mCurrentUser) {
2024 mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
2025 }
2026 }
2027
2028 /**
Craig Mautner8d341ef2013-03-26 09:03:27 -07002029 * @return true if some activity was finished (or would have finished if doit were true).
2030 */
Wale Ogunwale540e1232015-05-01 15:35:39 -07002031 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
2032 boolean doit, boolean evenPersistent, int userId) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07002033 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08002034 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2035 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
louis_chang8f0555a2015-10-27 10:45:53 +08002036 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002037 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002038 if (stack.finishDisabledPackageActivitiesLocked(
2039 packageName, filterByClasses, doit, evenPersistent, userId)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002040 didSomething = true;
2041 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002042 }
2043 }
2044 return didSomething;
2045 }
2046
Dianne Hackborna413dc02013-07-12 12:02:55 -07002047 void updatePreviousProcessLocked(ActivityRecord r) {
2048 // Now that this process has stopped, we may want to consider
2049 // it to be the previous app to try to keep around in case
2050 // the user wants to return to it.
2051
2052 // First, found out what is currently the foreground app, so that
2053 // we don't blow away the previous app if this activity is being
2054 // hosted by the process that is actually still the foreground.
2055 ProcessRecord fgApp = null;
Craig Mautnere0a38842013-12-16 16:14:02 -08002056 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2057 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002058 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2059 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07002060 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002061 if (stack.mResumedActivity != null) {
2062 fgApp = stack.mResumedActivity.app;
2063 } else if (stack.mPausingActivity != null) {
2064 fgApp = stack.mPausingActivity.app;
2065 }
2066 break;
Dianne Hackborna413dc02013-07-12 12:02:55 -07002067 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07002068 }
2069 }
2070
2071 // Now set this one as the previous process, only if that really
2072 // makes sense to.
2073 if (r.app != null && fgApp != null && r.app != fgApp
2074 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
Craig Mautner4ef26932013-09-18 15:15:52 -07002075 && r.app != mService.mHomeProcess) {
Dianne Hackborna413dc02013-07-12 12:02:55 -07002076 mService.mPreviousProcess = r.app;
2077 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
2078 }
2079 }
2080
Wale Ogunwaled046a012015-12-24 13:05:59 -08002081 boolean resumeFocusedStackTopActivityLocked() {
2082 return resumeFocusedStackTopActivityLocked(null, null, null);
Craig Mautner05d29032013-05-03 13:40:13 -07002083 }
2084
Wale Ogunwaled046a012015-12-24 13:05:59 -08002085 boolean resumeFocusedStackTopActivityLocked(
Chong Zhang280d3322015-11-03 17:27:26 -08002086 ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
chaviw59b98852017-06-13 12:05:44 -07002087
2088 if (!readyToResume()) {
2089 return false;
2090 }
2091
Wale Ogunwaled046a012015-12-24 13:05:59 -08002092 if (targetStack != null && isFocusedStack(targetStack)) {
2093 return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
Craig Mautner05d29032013-05-03 13:40:13 -07002094 }
chaviw59b98852017-06-13 12:05:44 -07002095
Wale Ogunwale06579d62016-04-30 15:29:06 -07002096 final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2097 if (r == null || r.state != RESUMED) {
2098 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
skuhne@google.com1b974dc2016-12-09 13:41:29 -08002099 } else if (r.state == RESUMED) {
2100 // Kick off any lingering app transitions form the MoveTaskToFront operation.
2101 mFocusedStack.executeAppTransition(targetOptions);
Wale Ogunwale06579d62016-04-30 15:29:06 -07002102 }
chaviw59b98852017-06-13 12:05:44 -07002103
Wale Ogunwaled046a012015-12-24 13:05:59 -08002104 return false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002105 }
2106
Todd Kennedy39bfee52016-02-24 10:28:21 -08002107 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
2108 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2109 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2110 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2111 stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
2112 }
2113 }
2114 }
2115
Adrian Roos20d7df32016-01-12 18:59:43 +01002116 TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
2117 TaskRecord finishedTask = null;
2118 ActivityStack focusedStack = getFocusedStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08002119 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2120 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002121 final int numStacks = stacks.size();
2122 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2123 final ActivityStack stack = stacks.get(stackNdx);
Adrian Roos20d7df32016-01-12 18:59:43 +01002124 TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
2125 if (stack == focusedStack || finishedTask == null) {
2126 finishedTask = t;
2127 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08002128 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002129 }
Adrian Roos20d7df32016-01-12 18:59:43 +01002130 return finishedTask;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002131 }
2132
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07002133 void finishVoiceTask(IVoiceInteractionSession session) {
2134 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2135 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2136 final int numStacks = stacks.size();
2137 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2138 final ActivityStack stack = stacks.get(stackNdx);
2139 stack.finishVoiceTask(session);
2140 }
2141 }
2142 }
2143
Andrii Kulianc27916642016-04-12 17:59:27 -07002144 void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
2145 String reason, boolean forceNonResizeable) {
Craig Mautneraea74a52014-03-08 14:23:10 -08002146 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
2147 mUserLeaving = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002148 }
Craig Mautneraea74a52014-03-08 14:23:10 -08002149 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
2150 // Caller wants the home activity moved with it. To accomplish this,
2151 // we'll just indicate that this task returns to the home task.
Craig Mautner84984fa2014-06-19 11:19:20 -07002152 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
Craig Mautneraea74a52014-03-08 14:23:10 -08002153 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002154 ActivityStack currentStack = task.getStack();
2155 if (currentStack == null) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07002156 Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
2157 + task + " to front. Stack is null");
2158 return;
2159 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002160
Wale Ogunwaleb1faf602016-01-27 09:12:31 -08002161 if (task.isResizeable() && options != null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002162 int stackId = options.getLaunchStackId();
2163 if (canUseActivityOptionsLaunchBounds(options, stackId)) {
Filip Gruszczynskidce2d162016-01-12 15:40:13 -08002164 final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
Chong Zhang0fa656b2015-08-31 15:17:21 -07002165 task.updateOverrideConfiguration(bounds);
Wale Ogunwale854809c2015-12-27 16:18:19 -08002166 if (stackId == INVALID_STACK_ID) {
2167 stackId = task.getLaunchStackId();
2168 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002169 if (stackId != currentStack.mStackId) {
Winson Chung74666102017-02-22 17:49:24 -08002170 task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE,
2171 DEFER_RESUME, "findTaskToMoveToFrontLocked");
Andrii Kulian02b7a832016-10-06 23:11:56 -07002172 stackId = currentStack.mStackId;
Chong Zhang112eb8c2015-11-02 11:17:00 -08002173 // moveTaskToStackUncheckedLocked() should already placed the task on top,
2174 // still need moveTaskToFrontLocked() below for any transition settings.
2175 }
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002176 if (StackId.resizeStackWithLaunchBounds(stackId)) {
2177 resizeStackLocked(stackId, bounds,
2178 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002179 !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002180 } else {
2181 // WM resizeTask must be done after the task is moved to the correct stack,
2182 // because Task's setBounds() also updates dim layer's bounds, but that has
2183 // dependency on the stack.
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002184 task.resizeWindowContainer();
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002185 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002186 }
2187 }
2188
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002189 final ActivityRecord r = task.getTopActivity();
Andrii Kulian02b7a832016-10-06 23:11:56 -07002190 currentStack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002191 r == null ? null : r.appTimeTracker, reason);
2192
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002193 if (DEBUG_STACK) Slog.d(TAG_STACK,
Andrii Kulian02b7a832016-10-06 23:11:56 -07002194 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
Jorim Jaggi2adba072016-03-03 13:43:39 +01002195
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002196 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
2197 currentStack.mStackId, forceNonResizeable);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002198 }
2199
Wale Ogunwale854809c2015-12-27 16:18:19 -08002200 boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002201 // We use the launch bounds in the activity options is the device supports freeform
Wale Ogunwale854809c2015-12-27 16:18:19 -08002202 // window management or is launching into the pinned stack.
Wale Ogunwale5122df02016-01-29 22:33:38 -08002203 if (options.getLaunchBounds() == null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002204 return false;
2205 }
2206 return (mService.mSupportsPictureInPicture && launchStackId == PINNED_STACK_ID)
2207 || mService.mSupportsFreeformWindowManagement;
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002208 }
2209
Winson Chung55893332017-02-17 17:13:10 -08002210 protected <T extends ActivityStack> T getStack(int stackId) {
Wale Ogunwale040b4702015-08-06 18:10:50 -07002211 return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002212 }
2213
Winson Chung55893332017-02-17 17:13:10 -08002214 protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
2215 boolean createOnTop) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002216 final ActivityStack stack = mStacks.get(stackId);
2217 if (stack != null) {
2218 return (T) stack;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002219 }
Wale Ogunwale3797c222015-10-27 14:21:58 -07002220 if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002221 return null;
2222 }
Matthew Ng330757d2017-02-28 14:19:17 -08002223 if (stackId == DOCKED_STACK_ID) {
2224 // Make sure recents stack exist when creating a dock stack as it normally need to be on
2225 // the other side of the docked stack and we make visibility decisions based on that.
2226 getStack(RECENTS_STACK_ID, CREATE_IF_NEEDED, createOnTop);
2227 }
Winson Chung55893332017-02-17 17:13:10 -08002228 return (T) createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002229 }
2230
Andrii Kulian16802aa2016-11-02 12:21:33 -07002231 /**
2232 * Get a topmost stack on the display, that is a valid launch stack for specified activity.
2233 * If there is no such stack, new dynamic stack can be created.
2234 * @param displayId Target display.
2235 * @param r Activity that should be launched there.
2236 * @return Existing stack if there is a valid one, new dynamic stack if it is valid or null.
2237 */
2238 ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002239 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian16802aa2016-11-02 12:21:33 -07002240 if (activityDisplay == null) {
2241 throw new IllegalArgumentException(
2242 "Display with displayId=" + displayId + " not found.");
2243 }
2244
2245 // Return the topmost valid stack on the display.
2246 for (int i = activityDisplay.mStacks.size() - 1; i >= 0; --i) {
2247 final ActivityStack stack = activityDisplay.mStacks.get(i);
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002248 if (mService.mActivityStarter.isValidLaunchStackId(stack.mStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002249 return stack;
2250 }
2251 }
2252
2253 // If there is no valid stack on the external display - check if new dynamic stack will do.
2254 if (displayId != Display.DEFAULT_DISPLAY) {
2255 final int newDynamicStackId = getNextStackId();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002256 if (mService.mActivityStarter.isValidLaunchStackId(newDynamicStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002257 return createStackOnDisplay(newDynamicStackId, displayId, true /*onTop*/);
2258 }
2259 }
2260
2261 Slog.w(TAG, "getValidLaunchStackOnDisplay: can't launch on displayId " + displayId);
2262 return null;
2263 }
2264
Craig Mautner967212c2013-04-13 21:10:58 -07002265 ArrayList<ActivityStack> getStacks() {
Wale Ogunwale3797c222015-10-27 14:21:58 -07002266 ArrayList<ActivityStack> allStacks = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08002267 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2268 allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002269 }
2270 return allStacks;
Craig Mautner967212c2013-04-13 21:10:58 -07002271 }
2272
Jorim Jaggife762342016-10-13 14:33:27 +02002273 ArrayList<ActivityStack> getStacksOnDefaultDisplay() {
2274 return mActivityDisplays.valueAt(DEFAULT_DISPLAY).mStacks;
2275 }
2276
Andrii Kulian7fc22812016-12-28 13:04:11 -08002277 /**
2278 * Get next focusable stack in the system. This will search across displays and stacks
2279 * in last-focused order for a focusable and visible stack, different from the target stack.
2280 *
2281 * @param currentFocus The stack that previously had focus and thus needs to be ignored when
2282 * searching for next candidate.
2283 * @return Next focusable {@link ActivityStack}, null if not found.
2284 */
2285 ActivityStack getNextFocusableStackLocked(ActivityStack currentFocus) {
2286 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2287
2288 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2289 final int displayId = mTmpOrderedDisplayIds.get(i);
Andrii Kulian62e6f252017-05-30 22:46:53 -07002290 // If a display is registered in WM, it must also be available in AM.
2291 @SuppressWarnings("ConstantConditions")
2292 final List<ActivityStack> stacks = getActivityDisplayOrCreateLocked(displayId).mStacks;
Andrii Kulian7fc22812016-12-28 13:04:11 -08002293 for (int j = stacks.size() - 1; j >= 0; --j) {
2294 final ActivityStack stack = stacks.get(j);
2295 if (stack != currentFocus && stack.isFocusable()
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002296 && stack.shouldBeVisible(null) != STACK_INVISIBLE) {
Andrii Kulian7fc22812016-12-28 13:04:11 -08002297 return stack;
2298 }
2299 }
2300 }
2301
2302 return null;
2303 }
2304
Andrii Kuliana8fe3df2017-06-16 15:29:26 -07002305 /**
2306 * Get next valid stack for launching provided activity in the system. This will search across
2307 * displays and stacks in last-focused order for a focusable and visible stack, except those
2308 * that are on a currently focused display.
2309 *
2310 * @param r The activity that is being launched.
2311 * @param currentFocus The display that previously had focus and thus needs to be ignored when
2312 * searching for the next candidate.
2313 * @return Next valid {@link ActivityStack}, null if not found.
2314 */
2315 ActivityStack getNextValidLaunchStackLocked(@NonNull ActivityRecord r, int currentFocus) {
2316 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2317 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2318 final int displayId = mTmpOrderedDisplayIds.get(i);
2319 if (displayId == currentFocus) {
2320 continue;
2321 }
2322 final ActivityStack stack = getValidLaunchStackOnDisplay(displayId, r);
2323 if (stack != null) {
2324 return stack;
2325 }
2326 }
2327 return null;
2328 }
2329
Craig Mautneree2e45a2014-06-27 12:10:03 -07002330 ActivityRecord getHomeActivity() {
Craig Mautnerdb49fec2015-05-21 15:33:30 -07002331 return getHomeActivityForUser(mCurrentUser);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002332 }
2333
2334 ActivityRecord getHomeActivityForUser(int userId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002335 final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
2336 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
2337 final TaskRecord task = tasks.get(taskNdx);
2338 if (task.isHomeTask()) {
2339 final ArrayList<ActivityRecord> activities = task.mActivities;
2340 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2341 final ActivityRecord r = activities.get(activityNdx);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002342 if (r.isHomeActivity()
2343 && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
Craig Mautneree2e45a2014-06-27 12:10:03 -07002344 return r;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002345 }
2346 }
2347 }
2348 }
2349 return null;
2350 }
2351
Chong Zhangb15758a2015-11-17 12:12:03 -08002352 /**
2353 * Returns if a stack should be treated as if it's docked. Returns true if the stack is
2354 * the docked stack itself, or if it's side-by-side to the docked stack.
2355 */
2356 boolean isStackDockedInEffect(int stackId) {
2357 return stackId == DOCKED_STACK_ID ||
2358 (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
2359 }
2360
Jorim Jaggidc249c42015-12-15 14:57:31 -08002361 void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002362 boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
Jorim Jaggidc249c42015-12-15 14:57:31 -08002363 if (stackId == DOCKED_STACK_ID) {
2364 resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002365 preserveWindows, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002366 return;
2367 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08002368 final ActivityStack stack = getStack(stackId);
2369 if (stack == null) {
2370 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2371 return;
2372 }
Wale Ogunwale9d3de4c2015-02-01 16:49:44 -08002373
Winson Chunga2249ac2017-03-30 18:15:30 -07002374 if (!allowResizeInDockedMode && !StackId.tasksAreFloating(stackId) &&
2375 getStack(DOCKED_STACK_ID) != null) {
2376 // If the docked stack exists, don't resize non-floating stacks independently of the
2377 // size computed from the docked stack size (otherwise they will be out of sync)
Wale Ogunwaleffc11bb2015-10-10 13:05:45 -07002378 return;
2379 }
2380
Wale Ogunwalecad05a02015-09-25 10:41:44 -07002381 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
Jorim Jaggic4025202015-10-22 16:43:34 +02002382 mWindowManager.deferSurfaceLayout();
2383 try {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002384 stack.resize(bounds, tempTaskBounds, tempTaskInsetBounds);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002385 if (!deferResume) {
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002386 stack.ensureVisibleActivitiesConfigurationLocked(
2387 stack.topRunningActivityLocked(), preserveWindows);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002388 }
Jorim Jaggic4025202015-10-22 16:43:34 +02002389 } finally {
2390 mWindowManager.continueSurfaceLayout();
2391 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07002392 }
2393 }
2394
Jorim Jaggi192086e2016-03-11 17:17:03 +01002395 void deferUpdateBounds(int stackId) {
2396 final ActivityStack stack = getStack(stackId);
2397 if (stack != null) {
2398 stack.deferUpdateBounds();
2399 }
2400 }
2401
2402 void continueUpdateBounds(int stackId) {
2403 final ActivityStack stack = getStack(stackId);
2404 if (stack != null) {
2405 stack.continueUpdateBounds();
2406 }
2407 }
2408
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002409 void notifyAppTransitionDone() {
Matthew Ng606dd802017-06-05 14:06:32 -07002410 continueUpdateBounds(RECENTS_STACK_ID);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002411 for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2412 final int taskId = mResizingTasksDuringAnimation.valueAt(i);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002413 final TaskRecord task =
Winson Chung7900bee2017-03-10 08:59:25 -08002414 anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002415 if (task != null) {
2416 task.setTaskDockedResizing(false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002417 }
2418 }
2419 mResizingTasksDuringAnimation.clear();
2420 }
2421
Robert Carre7cc44d2017-03-20 19:04:30 -07002422 private void moveTasksToFullscreenStackInSurfaceTransaction(int fromStackId,
2423 boolean onTop) {
Robert Carr6914f082017-03-20 19:04:30 -07002424
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002425 final ActivityStack stack = getStack(fromStackId);
2426 if (stack == null) {
2427 return;
2428 }
2429
2430 mWindowManager.deferSurfaceLayout();
2431 try {
2432 if (fromStackId == DOCKED_STACK_ID) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002433 // We are moving all tasks from the docked stack to the fullscreen stack,
2434 // which is dismissing the docked stack, so resize all other stacks to
2435 // fullscreen here already so we don't end up with resize trashing.
2436 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2437 if (StackId.isResizeableByDockedStack(i)) {
2438 ActivityStack otherStack = getStack(i);
2439 if (otherStack != null) {
2440 resizeStackLocked(i, null, null, null, PRESERVE_WINDOWS,
2441 true /* allowResizeInDockedMode */, DEFER_RESUME);
2442 }
2443 }
2444 }
2445
2446 // Also disable docked stack resizing since we have manually adjusted the
2447 // size of other stacks above and we don't want to trigger a docked stack
2448 // resize when we remove task from it below and it is detached from the
2449 // display because it no longer contains any tasks.
2450 mAllowDockedStackResize = false;
Winson Chung47900652017-04-06 18:44:25 -07002451 } else if (fromStackId == PINNED_STACK_ID) {
2452 if (onTop) {
2453 // Log if we are expanding the PiP to fullscreen
2454 MetricsLogger.action(mService.mContext,
2455 ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN);
2456 }
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002457 }
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002458 ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
Winson Chungc85d9ce2017-01-03 11:59:52 -08002459 final boolean isFullscreenStackVisible = fullscreenStack != null &&
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002460 fullscreenStack.shouldBeVisible(null) == STACK_VISIBLE;
Winson Chung5af42fc2017-03-24 17:11:33 -07002461 // If we are moving from the pinned stack, then the animation takes care of updating
2462 // the picture-in-picture mode.
Winson Chung47900652017-04-06 18:44:25 -07002463 final boolean schedulePictureInPictureModeChange = (fromStackId == PINNED_STACK_ID);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002464 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2465 final int size = tasks.size();
2466 if (onTop) {
2467 for (int i = 0; i < size; i++) {
Winson Chung0c1ca092016-11-10 17:40:34 -08002468 final TaskRecord task = tasks.get(i);
Winson Chung74666102017-02-22 17:49:24 -08002469 final boolean isTopTask = i == (size - 1);
Winson Chung0c1ca092016-11-10 17:40:34 -08002470 if (fromStackId == PINNED_STACK_ID) {
2471 // Update the return-to to reflect where the pinned stack task was moved
2472 // from so that we retain the stack that was previously visible if the
2473 // pinned stack is recreated. See moveActivityToPinnedStackLocked().
Winson Chungc85d9ce2017-01-03 11:59:52 -08002474 task.setTaskToReturnTo(isFullscreenStackVisible && onTop ?
2475 APPLICATION_ACTIVITY_TYPE : HOME_ACTIVITY_TYPE);
Winson Chung0c1ca092016-11-10 17:40:34 -08002476 }
Winson Chung74666102017-02-22 17:49:24 -08002477 // Defer resume until all the tasks have been moved to the fullscreen stack
2478 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
2479 REPARENT_MOVE_STACK_TO_FRONT, isTopTask /* animate */, DEFER_RESUME,
Winson Chung5af42fc2017-03-24 17:11:33 -07002480 schedulePictureInPictureModeChange,
Winson Chung74666102017-02-22 17:49:24 -08002481 "moveTasksToFullscreenStack - onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002482 }
2483 } else {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002484 for (int i = 0; i < size; i++) {
Wale Ogunwalec5cc3012017-01-13 13:26:16 -08002485 final TaskRecord task = tasks.get(i);
Winson Chung3a649982017-04-19 10:16:17 -07002486 // Position the tasks in the fullscreen stack in order at the bottom of the
2487 // stack. Also defer resume until all the tasks have been moved to the
2488 // fullscreen stack.
2489 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, i /* position */,
Winson Chung5af42fc2017-03-24 17:11:33 -07002490 REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME,
2491 schedulePictureInPictureModeChange,
2492 "moveTasksToFullscreenStack - NOT_onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002493 }
2494 }
Winson Chung74666102017-02-22 17:49:24 -08002495
2496 ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2497 resumeFocusedStackTopActivityLocked();
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002498 } finally {
2499 mAllowDockedStackResize = true;
2500 mWindowManager.continueSurfaceLayout();
2501 }
2502 }
2503
Robert Carr6914f082017-03-20 19:04:30 -07002504 void moveTasksToFullscreenStackLocked(int fromStackId, boolean onTop) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002505 mWindowManager.inSurfaceTransaction(
2506 () -> moveTasksToFullscreenStackInSurfaceTransaction(fromStackId, onTop));
Robert Carr6914f082017-03-20 19:04:30 -07002507 }
2508
Jorim Jaggidc249c42015-12-15 14:57:31 -08002509 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002510 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2511 boolean preserveWindows) {
2512 resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
2513 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows,
2514 false /* deferResume */);
2515 }
2516
2517 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2518 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2519 boolean preserveWindows, boolean deferResume) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002520
2521 if (!mAllowDockedStackResize) {
2522 // Docked stack resize currently disabled.
2523 return;
2524 }
2525
Jorim Jaggidc249c42015-12-15 14:57:31 -08002526 final ActivityStack stack = getStack(DOCKED_STACK_ID);
2527 if (stack == null) {
2528 Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2529 return;
2530 }
2531
2532 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2533 mWindowManager.deferSurfaceLayout();
2534 try {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002535 // Don't allow re-entry while resizing. E.g. due to docked stack detaching.
2536 mAllowDockedStackResize = false;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002537 ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwale1666e312016-12-16 11:27:18 -08002538 stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002539
Andrii Kulian69fb5e42016-04-05 16:47:29 -07002540 // TODO: Checking for isAttached might not be needed as if the user passes in null
2541 // dockedBounds then they want the docked stack to be dismissed.
2542 if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2543 // The dock stack either was dismissed or went fullscreen, which is kinda the same.
Jorim Jaggidc249c42015-12-15 14:57:31 -08002544 // In this case we make all other static stacks fullscreen and move all
2545 // docked stack tasks to the fullscreen stack.
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002546 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, ON_TOP);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002547
2548 // stack shouldn't contain anymore activities, so nothing to resume.
2549 r = null;
2550 } else {
2551 // Docked stacks occupy a dedicated region on screen so the size of all other
2552 // static stacks need to be adjusted so they don't overlap with the docked stack.
2553 // We get the bounds to use from window manager which has been adjusted for any
2554 // screen controls and is also the same for all stacks.
Matthew Ngaa2b6202017-02-10 14:48:21 -08002555 final Rect otherTaskRect = new Rect();
Jorim Jaggidc249c42015-12-15 14:57:31 -08002556 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002557 final ActivityStack current = getStack(i);
2558 if (current != null && StackId.isResizeableByDockedStack(i)) {
Matthew Ngaa2b6202017-02-10 14:48:21 -08002559 current.getStackDockedModeBounds(
2560 tempOtherTaskBounds /* currentTempTaskBounds */,
2561 tempRect /* outStackBounds */,
2562 otherTaskRect /* outTempTaskBounds */, true /* ignoreVisibility */);
2563
Andrii Kuliane48b7d82017-04-28 14:51:05 -07002564 resizeStackLocked(i, !tempRect.isEmpty() ? tempRect : null,
Matthew Ngaa2b6202017-02-10 14:48:21 -08002565 !otherTaskRect.isEmpty() ? otherTaskRect : tempOtherTaskBounds,
2566 tempOtherTaskInsetBounds, preserveWindows,
2567 true /* allowResizeInDockedMode */, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002568 }
2569 }
2570 }
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002571 if (!deferResume) {
2572 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows);
2573 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002574 } finally {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002575 mAllowDockedStackResize = true;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002576 mWindowManager.continueSurfaceLayout();
2577 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2578 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002579 }
2580
Robert Carr0d00c2e2016-02-29 17:45:02 -08002581 void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Winson Chung19953ca2017-04-11 11:19:23 -07002582 final PinnedActivityStack stack = getStack(PINNED_STACK_ID);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002583 if (stack == null) {
2584 Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2585 return;
2586 }
Winson Chung19953ca2017-04-11 11:19:23 -07002587
2588 // It is possible for the bounds animation from the WM to call this but be delayed by
2589 // another AM call that is holding the AMS lock. In such a case, the pinnedBounds may be
2590 // incorrect if AMS.resizeStackWithBoundsFromWindowManager() is already called while waiting
2591 // for the AMS lock to be freed. So check and make sure these bounds are still good.
2592 final PinnedStackWindowController stackController = stack.getWindowContainerController();
Winson Chung8bca9e42017-04-16 15:59:43 -07002593 if (stackController.pinnedStackResizeDisallowed()) {
Winson Chung19953ca2017-04-11 11:19:23 -07002594 return;
2595 }
2596
Robert Carr0d00c2e2016-02-29 17:45:02 -08002597 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2598 mWindowManager.deferSurfaceLayout();
2599 try {
2600 ActivityRecord r = stack.topRunningActivityLocked();
Robert Carr7e4c90e2017-02-15 19:52:38 -08002601 Rect insetBounds = null;
2602 if (tempPinnedTaskBounds != null) {
2603 // We always use 0,0 as the position for the inset rect because
2604 // if we are getting insets at all in the pinned stack it must mean
2605 // we are headed for fullscreen.
2606 insetBounds = tempRect;
2607 insetBounds.top = 0;
2608 insetBounds.left = 0;
2609 insetBounds.right = tempPinnedTaskBounds.width();
2610 insetBounds.bottom = tempPinnedTaskBounds.height();
2611 }
2612 stack.resize(pinnedBounds, tempPinnedTaskBounds, insetBounds);
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002613 stack.ensureVisibleActivitiesConfigurationLocked(r, false);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002614 } finally {
2615 mWindowManager.continueSurfaceLayout();
2616 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2617 }
2618 }
2619
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002620 ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002621 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Craig Mautnere0a38842013-12-16 16:14:02 -08002622 if (activityDisplay == null) {
Todd Kennedy4900bf92015-01-16 16:05:14 -08002623 return null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002624 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002625 return createStack(stackId, activityDisplay, onTop);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002626
Craig Mautner4a1cb222013-12-04 16:14:06 -08002627 }
2628
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002629 ActivityStack createStack(int stackId, ActivityDisplay display, boolean onTop) {
2630 switch (stackId) {
2631 case PINNED_STACK_ID:
2632 return new PinnedActivityStack(display, stackId, this, mRecentTasks, onTop);
2633 default:
2634 return new ActivityStack(display, stackId, this, mRecentTasks, onTop);
2635 }
2636 }
Robert Carr6914f082017-03-20 19:04:30 -07002637
Robert Carre7cc44d2017-03-20 19:04:30 -07002638 void removeStackInSurfaceTransaction(int stackId) {
Winson Chung010927a2016-12-15 16:12:35 -08002639 final ActivityStack stack = getStack(stackId);
2640 if (stack == null) {
2641 return;
2642 }
2643
2644 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2645 if (stack.getStackId() == PINNED_STACK_ID) {
Winson Chung47900652017-04-06 18:44:25 -07002646 /**
2647 * Workaround: Force-stop all the activities in the pinned stack before we reparent them
2648 * to the fullscreen stack. This is to guarantee that when we are removing a stack,
2649 * that the client receives onStop() before it is reparented. We do this by detaching
2650 * the stack from the display so that it will be considered invisible when
2651 * ensureActivitiesVisibleLocked() is called, and all of its activitys will be marked
2652 * invisible as well and added to the stopping list. After which we process the
2653 * stopping list by handling the idle.
2654 */
2655 final PinnedActivityStack pinnedStack = (PinnedActivityStack) stack;
2656 pinnedStack.mForceHidden = true;
2657 pinnedStack.ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2658 pinnedStack.mForceHidden = false;
2659 activityIdleInternalLocked(null, false /* fromTimeout */,
2660 true /* processPausingActivites */, null /* configuration */);
2661
2662 // Move all the tasks to the bottom of the fullscreen stack
2663 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
Winson Chung010927a2016-12-15 16:12:35 -08002664 } else {
2665 for (int i = tasks.size() - 1; i >= 0; i--) {
2666 removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */,
2667 REMOVE_FROM_RECENTS);
2668 }
2669 }
2670 }
2671
2672 /**
Robert Carr6914f082017-03-20 19:04:30 -07002673 * Removes the stack associated with the given {@param stackId}. If the {@param stackId} is the
2674 * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
2675 * instead moved back onto the fullscreen stack.
2676 */
2677 void removeStackLocked(int stackId) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002678 mWindowManager.inSurfaceTransaction(
2679 () -> removeStackInSurfaceTransaction(stackId));
Robert Carr6914f082017-03-20 19:04:30 -07002680 }
2681
2682 /**
Winson Chung6954fc92017-03-24 16:22:12 -07002683 * See {@link #removeTaskByIdLocked(int, boolean, boolean, boolean)}
2684 */
2685 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents) {
2686 return removeTaskByIdLocked(taskId, killProcess, removeFromRecents, !PAUSE_IMMEDIATELY);
2687 }
2688
2689 /**
Winson Chung010927a2016-12-15 16:12:35 -08002690 * Removes the task with the specified task id.
2691 *
2692 * @param taskId Identifier of the task to be removed.
2693 * @param killProcess Kill any process associated with the task if possible.
2694 * @param removeFromRecents Whether to also remove the task from recents.
Winson Chung6954fc92017-03-24 16:22:12 -07002695 * @param pauseImmediately Pauses all task activities immediately without waiting for the
2696 * pause-complete callback from the activity.
Winson Chung010927a2016-12-15 16:12:35 -08002697 * @return Returns true if the given task was found and removed.
2698 */
Winson Chung6954fc92017-03-24 16:22:12 -07002699 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents,
2700 boolean pauseImmediately) {
Winson Chung7900bee2017-03-10 08:59:25 -08002701 final TaskRecord tr = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
2702 INVALID_STACK_ID);
Winson Chung010927a2016-12-15 16:12:35 -08002703 if (tr != null) {
Winson Chung6954fc92017-03-24 16:22:12 -07002704 tr.removeTaskActivitiesLocked(pauseImmediately);
Winson Chung010927a2016-12-15 16:12:35 -08002705 cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents);
2706 if (tr.isPersistable) {
2707 mService.notifyTaskPersisterLocked(null, true);
2708 }
2709 return true;
2710 }
2711 Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
2712 return false;
2713 }
2714
2715 void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) {
2716 if (removeFromRecents) {
2717 mRecentTasks.remove(tr);
2718 tr.removedFromRecents();
2719 }
2720 ComponentName component = tr.getBaseIntent().getComponent();
2721 if (component == null) {
2722 Slog.w(TAG, "No component for base intent of task: " + tr);
2723 return;
2724 }
2725
2726 // Find any running services associated with this app and stop if needed.
2727 mService.mServices.cleanUpRemovedTaskLocked(tr, component, new Intent(tr.getBaseIntent()));
2728
2729 if (!killProcess) {
2730 return;
2731 }
2732
2733 // Determine if the process(es) for this task should be killed.
2734 final String pkg = component.getPackageName();
2735 ArrayList<ProcessRecord> procsToKill = new ArrayList<>();
2736 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mService.mProcessNames.getMap();
2737 for (int i = 0; i < pmap.size(); i++) {
2738
2739 SparseArray<ProcessRecord> uids = pmap.valueAt(i);
2740 for (int j = 0; j < uids.size(); j++) {
2741 ProcessRecord proc = uids.valueAt(j);
2742 if (proc.userId != tr.userId) {
2743 // Don't kill process for a different user.
2744 continue;
2745 }
2746 if (proc == mService.mHomeProcess) {
2747 // Don't kill the home process along with tasks from the same package.
2748 continue;
2749 }
2750 if (!proc.pkgList.containsKey(pkg)) {
2751 // Don't kill process that is not associated with this task.
2752 continue;
2753 }
2754
2755 for (int k = 0; k < proc.activities.size(); k++) {
Bryce Leeaf691c02017-03-20 14:20:22 -07002756 TaskRecord otherTask = proc.activities.get(k).getTask();
Winson Chung010927a2016-12-15 16:12:35 -08002757 if (tr.taskId != otherTask.taskId && otherTask.inRecents) {
2758 // Don't kill process(es) that has an activity in a different task that is
2759 // also in recents.
2760 return;
2761 }
2762 }
2763
2764 if (proc.foregroundServices) {
2765 // Don't kill process(es) with foreground service.
2766 return;
2767 }
2768
2769 // Add process to kill list.
2770 procsToKill.add(proc);
2771 }
2772 }
2773
2774 // Kill the running processes.
2775 for (int i = 0; i < procsToKill.size(); i++) {
2776 ProcessRecord pr = procsToKill.get(i);
2777 if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
2778 && pr.curReceivers.isEmpty()) {
2779 pr.kill("remove task", true);
2780 } else {
2781 // We delay killing processes that are not in the background or running a receiver.
2782 pr.waitingToKill = "remove task";
2783 }
2784 }
2785 }
2786
Craig Mautner4a1cb222013-12-04 16:14:06 -08002787 int getNextStackId() {
Craig Mautner858d8a62013-04-23 17:08:34 -07002788 while (true) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002789 if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2790 && getStack(mNextFreeStackId) == null) {
Craig Mautner858d8a62013-04-23 17:08:34 -07002791 break;
2792 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002793 mNextFreeStackId++;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002794 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002795 return mNextFreeStackId;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002796 }
2797
Chong Zhang5dcb2752015-08-18 13:50:26 -07002798 /**
2799 * Restores a recent task to a stack
2800 * @param task The recent task to be restored.
2801 * @param stackId The stack to restore the task to (default launch stack will be used
Andrii Kulian16802aa2016-11-02 12:21:33 -07002802 * if stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}
2803 * or is not a static stack).
Chong Zhang5dcb2752015-08-18 13:50:26 -07002804 * @return true if the task has been restored successfully.
2805 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002806 boolean restoreRecentTaskLocked(TaskRecord task, int stackId) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002807 if (!StackId.isStaticStack(stackId)) {
2808 // If stack is not static (or stack id is invalid) - use the default one.
2809 // This means that tasks that were on external displays will be restored on the
2810 // primary display.
Wale Ogunwale8b06a582015-10-22 14:38:21 -07002811 stackId = task.getLaunchStackId();
Winson Chungd3395382016-12-13 11:49:09 -08002812 } else if (stackId == DOCKED_STACK_ID && !task.supportsSplitScreen()) {
Wale Ogunwale513346d2016-01-27 10:55:01 -08002813 // Preferred stack is the docked stack, but the task can't go in the docked stack.
2814 // Put it in the fullscreen stack.
2815 stackId = FULLSCREEN_WORKSPACE_STACK_ID;
Chong Zhang5dcb2752015-08-18 13:50:26 -07002816 }
Wale Ogunwale513346d2016-01-27 10:55:01 -08002817
Andrii Kulian02b7a832016-10-06 23:11:56 -07002818 final ActivityStack currentStack = task.getStack();
2819 if (currentStack != null) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002820 // Task has already been restored once. See if we need to do anything more
Andrii Kulian02b7a832016-10-06 23:11:56 -07002821 if (currentStack.mStackId == stackId) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002822 // Nothing else to do since it is already restored in the right stack.
2823 return true;
2824 }
2825 // Remove current stack association, so we can re-associate the task with the
2826 // right stack below.
Andrii Kulian02b7a832016-10-06 23:11:56 -07002827 currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING);
Wale Ogunwale706ed792015-08-02 10:29:44 -07002828 }
2829
Wale Ogunwale6c5eb1c2015-11-10 07:52:22 -08002830 final ActivityStack stack =
Wale Ogunwale040b4702015-08-06 18:10:50 -07002831 getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002832
2833 if (stack == null) {
2834 // What does this mean??? Not sure how we would get here...
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002835 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2836 "Unable to find/create stack to restore recent task=" + task);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002837 return false;
2838 }
2839
Wale Ogunwale72919d22016-12-08 18:58:50 -08002840 stack.addTask(task, false /* toTop */, "restoreRecentTask");
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002841 // TODO: move call for creation here and other place into Stack.addTask()
2842 task.createWindowContainer(false /* toTop */, true /* showForAllUsers */);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002843 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2844 "Added restored task=" + task + " to stack=" + stack);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002845 final ArrayList<ActivityRecord> activities = task.mActivities;
2846 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002847 activities.get(activityNdx).createWindowContainer();
Wale Ogunwale7de05352014-12-12 15:21:33 -08002848 }
2849 return true;
Craig Mautneref73ee12014-04-23 11:45:37 -07002850 }
2851
Wale Ogunwale040b4702015-08-06 18:10:50 -07002852 /**
Andrii Kulian839def92016-11-02 10:58:58 -07002853 * Move stack with all its existing content to specified display.
2854 * @param stackId Id of stack to move.
2855 * @param displayId Id of display to move stack to.
Andrii Kulian250d6532017-02-08 23:30:45 -08002856 * @param onTop Indicates whether container should be place on top or on bottom.
Andrii Kulian839def92016-11-02 10:58:58 -07002857 */
Andrii Kulian250d6532017-02-08 23:30:45 -08002858 void moveStackToDisplayLocked(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002859 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian839def92016-11-02 10:58:58 -07002860 if (activityDisplay == null) {
2861 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown displayId="
2862 + displayId);
2863 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002864 final ActivityStack stack = mStacks.get(stackId);
2865 if (stack == null) {
Andrii Kulian839def92016-11-02 10:58:58 -07002866 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
2867 + stackId);
2868 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002869
2870 final ActivityDisplay currentDisplay = stack.getDisplay();
2871 if (currentDisplay == null) {
2872 throw new IllegalStateException("moveStackToDisplayLocked: Stack with stack=" + stack
2873 + " is not attached to any display.");
2874 }
2875
2876 if (currentDisplay.mDisplayId == displayId) {
2877 throw new IllegalArgumentException("Trying to move stack=" + stack
2878 + " to its current displayId=" + displayId);
2879 }
2880
2881 stack.reparent(activityDisplay, onTop);
Andrii Kulian839def92016-11-02 10:58:58 -07002882 // TODO(multi-display): resize stacks properly if moved from split-screen.
2883 }
2884
2885 /**
Winson Chung74666102017-02-22 17:49:24 -08002886 * Returns the reparent target stack, creating the stack if necessary. This call also enforces
2887 * the various checks on tasks that are going to be reparented from one stack to another.
Wale Ogunwale040b4702015-08-06 18:10:50 -07002888 */
Winson Chung74666102017-02-22 17:49:24 -08002889 ActivityStack getReparentTargetStack(TaskRecord task, int stackId, boolean toTop) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07002890 final ActivityStack prevStack = task.getStack();
Chong Zhang02898352015-08-21 17:27:14 -07002891
Winson Chung74666102017-02-22 17:49:24 -08002892 // Check that we aren't reparenting to the same stack that the task is already in
2893 if (prevStack != null && prevStack.mStackId == stackId) {
2894 Slog.w(TAG, "Can not reparent to same stack, task=" + task
2895 + " already in stackId=" + stackId);
2896 return prevStack;
Wale Ogunwale513346d2016-01-27 10:55:01 -08002897 }
2898
Winson Chung74666102017-02-22 17:49:24 -08002899 // Ensure that we aren't trying to move into a multi-window stack without multi-window
2900 // support
2901 if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
2902 throw new IllegalArgumentException("Device doesn't support multi-window, can not"
2903 + " reparent task=" + task + " to stackId=" + stackId);
Winson Chungc2baac02017-01-11 13:34:47 -08002904 }
2905
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002906 // Ensure that we're not moving a task to a dynamic stack if device doesn't support
2907 // multi-display.
2908 // TODO(multi-display): Support non-dynamic stacks on secondary displays.
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002909 if (StackId.isDynamicStack(stackId) && !mService.mSupportsMultiDisplay) {
2910 throw new IllegalArgumentException("Device doesn't support multi-display, can not"
2911 + " reparent task=" + task + " to stackId=" + stackId);
2912 }
2913
Winson Chung74666102017-02-22 17:49:24 -08002914 // Ensure that we aren't trying to move into a freeform stack without freeform
2915 // support
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002916 if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
Winson Chung74666102017-02-22 17:49:24 -08002917 throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
2918 + " task=" + task);
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002919 }
2920
Winson Chung74666102017-02-22 17:49:24 -08002921 // We don't allow moving a unresizeable task to the docked stack since the docked stack is
2922 // used for split-screen mode and will cause things like the docked divider to show up. We
2923 // instead leave the task in its current stack or move it to the fullscreen stack if it
2924 // isn't currently in a stack.
2925 if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
2926 stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
2927 Slog.w(TAG, "Can not move unresizeable task=" + task + " to docked stack."
2928 + " Moving to stackId=" + stackId + " instead.");
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07002929 }
Wale Ogunwale961f4852016-02-01 20:25:54 -08002930
Winson Chung74666102017-02-22 17:49:24 -08002931 // Temporarily disable resizeablility of the task as we don't want it to be resized if, for
2932 // example, a docked stack is created which will lead to the stack we are moving from being
2933 // resized and and its resizeable tasks being resized.
Wale Ogunwale961f4852016-02-01 20:25:54 -08002934 try {
Winson Chung74666102017-02-22 17:49:24 -08002935 task.mTemporarilyUnresizable = true;
2936 return getStack(stackId, CREATE_IF_NEEDED, toTop);
Wale Ogunwale961f4852016-02-01 20:25:54 -08002937 } finally {
Winson Chung74666102017-02-22 17:49:24 -08002938 task.mTemporarilyUnresizable = false;
Chong Zhangf596cd52016-01-05 13:42:44 -08002939 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002940 }
2941
Winson Chung08f81892017-03-02 15:40:51 -08002942 boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect destBounds) {
Wale Ogunwale079a0042015-10-24 11:44:07 -07002943 final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2944 if (stack == null) {
2945 throw new IllegalArgumentException(
2946 "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
2947 }
2948
2949 final ActivityRecord r = stack.topRunningActivityLocked();
2950 if (r == null) {
2951 Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
2952 + " in stack=" + stack);
2953 return false;
2954 }
2955
Wale Ogunwale6cae7652015-12-26 07:36:26 -08002956 if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
Wale Ogunwaleb60692e2015-10-24 12:35:56 -07002957 Slog.w(TAG,
2958 "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
Filip Gruszczynski77d94482015-12-11 13:59:52 -08002959 + " r=" + r);
Wale Ogunwale079a0042015-10-24 11:44:07 -07002960 return false;
2961 }
2962
Winson Chung3a682872017-04-10 14:38:05 -07002963 moveActivityToPinnedStackLocked(r, null /* sourceBounds */, 0f /* aspectRatio */,
Winson Chung08f81892017-03-02 15:40:51 -08002964 true /* moveHomeStackToFront */, "moveTopActivityToPinnedStack");
Wale Ogunwale9c604c72015-12-06 18:42:57 -08002965 return true;
2966 }
2967
Winson Chung8bca9e42017-04-16 15:59:43 -07002968 void moveActivityToPinnedStackLocked(ActivityRecord r, Rect sourceHintBounds, float aspectRatio,
Winson Chung08f81892017-03-02 15:40:51 -08002969 boolean moveHomeStackToFront, String reason) {
2970
Wale Ogunwale480dca02016-02-06 13:58:29 -08002971 mWindowManager.deferSurfaceLayout();
Winson Chung74666102017-02-22 17:49:24 -08002972
Bryce Lee04ab3462017-04-10 15:06:33 -07002973 // This will clear the pinned stack by moving an existing task to the full screen stack,
2974 // ensuring only one task is present.
2975 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
2976
Wale Ogunwale1666e312016-12-16 11:27:18 -08002977 // Need to make sure the pinned stack exist so we can resize it below...
Winson Chung55893332017-02-17 17:13:10 -08002978 final PinnedActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Wale Ogunwale1666e312016-12-16 11:27:18 -08002979
Wale Ogunwale480dca02016-02-06 13:58:29 -08002980 try {
Bryce Leeaf691c02017-03-20 14:20:22 -07002981 final TaskRecord task = r.getTask();
Wale Ogunwale480dca02016-02-06 13:58:29 -08002982 // Resize the pinned stack to match the current size of the task the activity we are
2983 // going to be moving is currently contained in. We do this to have the right starting
2984 // animation bounds for the pinned stack to the desired bounds the caller wants.
2985 resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
2986 null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002987 true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002988
2989 if (task.mActivities.size() == 1) {
2990 // There is only one activity in the task. So, we can just move the task over to
Winson Chungc2baac02017-01-11 13:34:47 -08002991 // the stack without re-parenting the activity in a different task. We don't
2992 // move the home stack forward if we are currently entering picture-in-picture
2993 // while pausing because that changes the focused stack and may prevent the new
2994 // starting activity from resuming.
2995 if (moveHomeStackToFront && task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE
Winson Chungf7e03e12017-08-22 11:32:16 -07002996 && (r.state == RESUMED || !r.supportsEnterPipOnTaskSwitch)) {
Wale Ogunwaleda4ba962016-03-11 09:33:17 -08002997 // Move the home stack forward if the task we just moved to the pinned stack
2998 // was launched from home so home should be visible behind it.
2999 moveHomeStackToFront(reason);
3000 }
Winson Chung5af42fc2017-03-24 17:11:33 -07003001 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08003002 task.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07003003 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08003004 } else {
Winson Chungb5c41b72016-12-07 15:00:47 -08003005 // There are multiple activities in the task and moving the top activity should
Winson Chung74666102017-02-22 17:49:24 -08003006 // reveal/leave the other activities in their original task.
3007
3008 // Currently, we don't support reparenting activities across tasks in two different
3009 // stacks, so instead, just create a new task in the same stack, reparent the
3010 // activity into that task, and then reparent the whole task to the new stack. This
3011 // ensures that all the necessary work to migrate states in the old and new stacks
3012 // is also done.
3013 final TaskRecord newTask = task.getStack().createTaskRecord(
3014 getNextTaskIdForUserLocked(r.userId), r.info, r.intent, null, null, true,
3015 r.mActivityType);
3016 r.reparent(newTask, MAX_VALUE, "moveActivityToStack");
3017
Winson Chung5af42fc2017-03-24 17:11:33 -07003018 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08003019 newTask.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07003020 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08003021 }
Winson Chungc2baac02017-01-11 13:34:47 -08003022
3023 // Reset the state that indicates it can enter PiP while pausing after we've moved it
3024 // to the pinned stack
Winson Chungf7e03e12017-08-22 11:32:16 -07003025 r.supportsEnterPipOnTaskSwitch = false;
Wale Ogunwale480dca02016-02-06 13:58:29 -08003026 } finally {
3027 mWindowManager.continueSurfaceLayout();
Wale Ogunwale079a0042015-10-24 11:44:07 -07003028 }
3029
Winson Chunge7ba6862017-05-24 12:13:33 -07003030 // Calculate the default bounds (don't use existing stack bounds as we may have just created
3031 // the stack, and schedule the start of the animation into PiP (the bounds animator that
3032 // is triggered by this is posted on another thread)
Winson Chunga71febe2017-05-22 11:14:22 -07003033 final Rect destBounds = stack.getDefaultPictureInPictureBounds(aspectRatio);
3034
Winson Chunge7ba6862017-05-24 12:13:33 -07003035 stack.animateResizePinnedStack(sourceHintBounds, destBounds, -1 /* animationDuration */,
3036 true /* fromFullscreen */);
3037
3038 // Update the visibility of all activities after the they have been reparented to the new
3039 // stack. This MUST run after the animation above is scheduled to ensure that the windows
3040 // drawn signal is scheduled after the bounds animation start call on the bounds animator
3041 // thread.
Wale Ogunwale079a0042015-10-24 11:44:07 -07003042 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwaled046a012015-12-24 13:05:59 -08003043 resumeFocusedStackTopActivityLocked();
Wale Ogunwale03ce8632015-12-29 16:15:22 -08003044
Winson Chungb5026902017-05-03 12:45:13 -07003045 mService.mTaskChangeNotificationController.notifyActivityPinned(r.packageName,
3046 r.getTask().taskId);
Wale Ogunwale079a0042015-10-24 11:44:07 -07003047 }
3048
Andrii Kulian0864bbb2017-02-16 15:45:58 -08003049 /** Move activity with its stack to front and make the stack focused. */
Chong Zhang6cda19c2016-06-14 19:07:56 -07003050 boolean moveFocusableActivityStackToFrontLocked(ActivityRecord r, String reason) {
3051 if (r == null || !r.isFocusable()) {
3052 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3053 "moveActivityStackToFront: unfocusable r=" + r);
3054 return false;
3055 }
3056
Bryce Leeaf691c02017-03-20 14:20:22 -07003057 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003058 final ActivityStack stack = r.getStack();
3059 if (stack == null) {
Chong Zhang6cda19c2016-06-14 19:07:56 -07003060 Slog.w(TAG, "moveActivityStackToFront: invalid task or stack: r="
3061 + r + " task=" + task);
3062 return false;
3063 }
3064
Chong Zhang6cda19c2016-06-14 19:07:56 -07003065 if (stack == mFocusedStack && stack.topRunningActivityLocked() == r) {
3066 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3067 "moveActivityStackToFront: already on top, r=" + r);
3068 return false;
3069 }
3070
3071 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3072 "moveActivityStackToFront: r=" + r);
3073
3074 stack.moveToFront(reason, task);
3075 return true;
3076 }
3077
David Stevensc6b91c62017-02-08 14:23:58 -08003078 ActivityRecord findTaskLocked(ActivityRecord r, int displayId) {
Wale Ogunwale39381972015-12-17 17:15:29 -08003079 mTmpFindTaskResult.r = null;
3080 mTmpFindTaskResult.matchedByRootAffinity = false;
David Stevensc6b91c62017-02-08 14:23:58 -08003081 ActivityRecord affinityMatch = null;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003082 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
Craig Mautnere0a38842013-12-16 16:14:02 -08003083 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3084 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003085 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3086 final ActivityStack stack = stacks.get(stackNdx);
Winson Chung91e5c882017-04-21 14:44:38 -07003087 if (!checkActivityBelongsInStack(r, stack)) {
3088 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) "
3089 + stack);
Craig Mautner1b4bf852014-05-26 15:06:32 -07003090 continue;
3091 }
Wale Ogunwale39381972015-12-17 17:15:29 -08003092 stack.findTaskLocked(r, mTmpFindTaskResult);
David Stevensc6b91c62017-02-08 14:23:58 -08003093 // It is possible to have tasks in multiple stacks with the same root affinity, so
3094 // we should keep looking after finding an affinity match to see if there is a
3095 // better match in another stack. Also, task affinity isn't a good enough reason
3096 // to target a display which isn't the source of the intent, so skip any affinity
3097 // matches not on the specified display.
3098 if (mTmpFindTaskResult.r != null) {
3099 if (!mTmpFindTaskResult.matchedByRootAffinity) {
3100 return mTmpFindTaskResult.r;
3101 } else if (mTmpFindTaskResult.r.getDisplayId() == displayId) {
Winson Chung5b895b72017-05-01 13:46:25 -07003102 // Note: since the traversing through the stacks is top down, the floating
3103 // tasks should always have lower priority than any affinity-matching tasks
3104 // in the fullscreen stacks
David Stevensc6b91c62017-02-08 14:23:58 -08003105 affinityMatch = mTmpFindTaskResult.r;
3106 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003107 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003108 }
3109 }
Winson Chung5b895b72017-05-01 13:46:25 -07003110
David Stevensc6b91c62017-02-08 14:23:58 -08003111 if (DEBUG_TASKS && affinityMatch == null) Slog.d(TAG_TASKS, "No task found");
3112 return affinityMatch;
Craig Mautner8849a5e2013-04-02 16:41:03 -07003113 }
3114
Winson Chung91e5c882017-04-21 14:44:38 -07003115 /**
3116 * Checks that for the given activity {@param r}, its activity type matches the {@param stack}
3117 * type.
3118 */
3119 private boolean checkActivityBelongsInStack(ActivityRecord r, ActivityStack stack) {
3120 if (r.isHomeActivity()) {
3121 return stack.isHomeStack();
3122 } else if (r.isRecentsActivity()) {
3123 return stack.isRecentsStack();
3124 } else if (r.isAssistantActivity()) {
3125 return stack.isAssistantStack();
3126 }
3127 return true;
3128 }
3129
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003130 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
3131 boolean compareIntentFilters) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003132 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3133 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003134 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003135 final ActivityRecord ar = stacks.get(stackNdx)
3136 .findActivityLocked(intent, info, compareIntentFilters);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003137 if (ar != null) {
3138 return ar;
3139 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003140 }
3141 }
3142 return null;
3143 }
3144
David Stevensf62360c2017-03-16 19:00:20 -07003145 boolean hasAwakeDisplay() {
3146 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3147 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3148 if (!display.shouldSleep()) {
3149 return true;
3150 }
3151 }
3152 return false;
3153 }
3154
Craig Mautner8d341ef2013-03-26 09:03:27 -07003155 void goingToSleepLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003156 scheduleSleepTimeout();
3157 if (!mGoingToSleep.isHeld()) {
3158 mGoingToSleep.acquire();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003159 if (mLaunchingActivity.isHeld()) {
3160 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
3161 throw new IllegalStateException("Calling must be system uid");
Craig Mautner0eea92c2013-05-16 13:35:39 -07003162 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003163 mLaunchingActivity.release();
3164 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003165 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003166 }
David Stevensf62360c2017-03-16 19:00:20 -07003167
3168 applySleepTokensLocked(false /* applyToStacks */);
3169
3170 checkReadyForSleepLocked(true /* allowDelay */);
3171 }
3172
3173 void prepareForShutdownLocked() {
3174 for (int i = 0; i < mActivityDisplays.size(); i++) {
3175 createSleepTokenLocked("shutdown", mActivityDisplays.keyAt(i));
3176 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003177 }
3178
3179 boolean shutdownLocked(int timeout) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003180 goingToSleepLocked();
Craig Mautner0eea92c2013-05-16 13:35:39 -07003181
Craig Mautnerf4c909b2014-04-17 18:39:38 -07003182 boolean timedout = false;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003183 final long endTime = System.currentTimeMillis() + timeout;
3184 while (true) {
David Stevens18abd0e2017-08-17 14:55:47 -07003185 if (!putStacksToSleepLocked(true /* allowDelay */, true /* shuttingDown */)) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003186 long timeRemaining = endTime - System.currentTimeMillis();
3187 if (timeRemaining > 0) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003188 try {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003189 mService.wait(timeRemaining);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003190 } catch (InterruptedException e) {
3191 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003192 } else {
3193 Slog.w(TAG, "Activity manager shutdown timed out");
3194 timedout = true;
3195 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003196 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003197 } else {
3198 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003199 }
3200 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003201
3202 // Force checkReadyForSleep to complete.
David Stevensf62360c2017-03-16 19:00:20 -07003203 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003204
Craig Mautner8d341ef2013-03-26 09:03:27 -07003205 return timedout;
3206 }
3207
3208 void comeOutOfSleepIfNeededLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003209 removeSleepTimeouts();
3210 if (mGoingToSleep.isHeld()) {
3211 mGoingToSleep.release();
3212 }
David Stevensf62360c2017-03-16 19:00:20 -07003213 }
3214
3215 void applySleepTokensLocked(boolean applyToStacks) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003216 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
David Stevensf62360c2017-03-16 19:00:20 -07003217 // Set the sleeping state of the display.
3218 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3219 final boolean displayShouldSleep = display.shouldSleep();
3220 if (displayShouldSleep == display.isSleeping()) {
3221 continue;
3222 }
3223 display.setIsSleeping(displayShouldSleep);
3224
3225 if (!applyToStacks) {
3226 continue;
3227 }
3228
3229 // Set the sleeping state of the stacks on the display.
3230 final ArrayList<ActivityStack> stacks = display.mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003231 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3232 final ActivityStack stack = stacks.get(stackNdx);
David Stevensf62360c2017-03-16 19:00:20 -07003233 if (displayShouldSleep) {
3234 stack.goToSleepIfPossible(false /* shuttingDown */);
3235 } else {
3236 stack.awakeFromSleepingLocked();
3237 if (isFocusedStack(stack)) {
3238 resumeFocusedStackTopActivityLocked();
3239 }
3240 }
3241 }
3242
3243 if (displayShouldSleep || mGoingToSleepActivities.isEmpty()) {
3244 continue;
3245 }
3246 // The display is awake now, so clean up the going to sleep list.
3247 for (Iterator<ActivityRecord> it = mGoingToSleepActivities.iterator(); it.hasNext(); ) {
3248 final ActivityRecord r = it.next();
3249 if (r.getDisplayId() == display.mDisplayId) {
3250 it.remove();
Craig Mautner4a1cb222013-12-04 16:14:06 -08003251 }
Craig Mautner5314a402013-09-26 12:40:16 -07003252 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003253 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003254 }
3255
3256 void activitySleptLocked(ActivityRecord r) {
3257 mGoingToSleepActivities.remove(r);
David Stevensf62360c2017-03-16 19:00:20 -07003258 final ActivityStack s = r.getStack();
3259 if (s != null) {
3260 s.checkReadyForSleep();
3261 } else {
3262 checkReadyForSleepLocked(true);
3263 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003264 }
3265
David Stevensf62360c2017-03-16 19:00:20 -07003266 void checkReadyForSleepLocked(boolean allowDelay) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07003267 if (!mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003268 // Do not care.
3269 return;
3270 }
3271
David Stevens18abd0e2017-08-17 14:55:47 -07003272 if (!putStacksToSleepLocked(allowDelay, false /* shuttingDown */)) {
3273 return;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003274 }
3275
Wei Wang65c7a152016-06-02 18:51:22 -07003276 // Send launch end powerhint before going sleep
3277 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
3278
Craig Mautner0eea92c2013-05-16 13:35:39 -07003279 removeSleepTimeouts();
3280
3281 if (mGoingToSleep.isHeld()) {
3282 mGoingToSleep.release();
3283 }
3284 if (mService.mShuttingDown) {
3285 mService.notifyAll();
3286 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003287 }
3288
David Stevens18abd0e2017-08-17 14:55:47 -07003289 // Tries to put all activity stacks to sleep. Returns true if all stacks were
3290 // successfully put to sleep.
3291 private boolean putStacksToSleepLocked(boolean allowDelay, boolean shuttingDown) {
3292 boolean allSleep = true;
3293 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3294 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3295 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3296 if (allowDelay) {
3297 allSleep &= stacks.get(stackNdx).goToSleepIfPossible(shuttingDown);
3298 } else {
3299 stacks.get(stackNdx).goToSleep();
3300 }
3301 }
3302 }
3303 return allSleep;
3304 }
3305
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003306 boolean reportResumedActivityLocked(ActivityRecord r) {
Bryce Lee29a649d2017-08-18 13:52:31 -07003307 // A resumed activity cannot be stopping. remove from list
3308 mStoppingActivities.remove(r);
3309
Andrii Kulian02b7a832016-10-06 23:11:56 -07003310 final ActivityStack stack = r.getStack();
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003311 if (isFocusedStack(stack)) {
Jeff Sharkey5782da72013-04-25 14:32:30 -07003312 mService.updateUsageStats(r, true);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003313 }
3314 if (allResumedActivitiesComplete()) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003315 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003316 mWindowManager.executeAppTransition();
3317 return true;
3318 }
3319 return false;
3320 }
3321
Craig Mautner8d341ef2013-03-26 09:03:27 -07003322 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003323 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3324 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Wale Ogunwale28b23972015-07-29 16:01:50 -07003325 int stackNdx = stacks.size() - 1;
3326 while (stackNdx >= 0) {
3327 stacks.get(stackNdx).handleAppCrashLocked(app);
3328 stackNdx--;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003329 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003330 }
3331 }
3332
Craig Mautnerbb742462014-07-07 15:28:55 -07003333 // Called when WindowManager has finished animating the launchingBehind activity to the back.
Andrii Kulian21713ac2016-10-12 22:05:05 -07003334 private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003335 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003336 final ActivityStack stack = task.getStack();
Winson730bf062016-03-31 18:04:56 -07003337
3338 r.mLaunchTaskBehind = false;
Andrii Kulian21713ac2016-10-12 22:05:05 -07003339 task.setLastThumbnailLocked(r.screenshotActivityLocked());
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08003340 mRecentTasks.addLocked(task);
Yorke Leebd54c2a2016-10-25 13:49:23 -07003341 mService.mTaskChangeNotificationController.notifyTaskStackChanged();
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003342 r.setVisibility(false);
Winson730bf062016-03-31 18:04:56 -07003343
3344 // When launching tasks behind, update the last active time of the top task after the new
3345 // task has been shown briefly
3346 final ActivityRecord top = stack.topActivity();
3347 if (top != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003348 top.getTask().touchActiveTime();
Winson730bf062016-03-31 18:04:56 -07003349 }
Craig Mautnerbb742462014-07-07 15:28:55 -07003350 }
3351
3352 void scheduleLaunchTaskBehindComplete(IBinder token) {
3353 mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
3354 }
3355
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003356 void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
3357 boolean preserveWindows) {
Jorim Jaggife762342016-10-13 14:33:27 +02003358 mKeyguardController.beginActivityVisibilityUpdate();
3359 try {
3360 // First the front stacks. In case any are not fullscreen and are in front of home.
3361 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3362 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3363 final int topStackNdx = stacks.size() - 1;
3364 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3365 final ActivityStack stack = stacks.get(stackNdx);
3366 stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
3367 }
Craig Mautner580ea812013-04-25 12:58:38 -07003368 }
Jorim Jaggife762342016-10-13 14:33:27 +02003369 } finally {
3370 mKeyguardController.endActivityVisibilityUpdate();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003371 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003372 }
3373
Jorim Jaggi8b702ed2017-01-20 16:59:03 +01003374 void addStartingWindowsForVisibleActivities(boolean taskSwitch) {
3375 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3376 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3377 final int topStackNdx = stacks.size() - 1;
3378 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3379 final ActivityStack stack = stacks.get(stackNdx);
3380 stack.addStartingWindowsForVisibleActivities(taskSwitch);
3381 }
3382 }
3383 }
3384
Chong Zhangfdcc4d42015-10-14 16:50:12 -07003385 void invalidateTaskLayers() {
3386 mTaskLayersChanged = true;
3387 }
3388
3389 void rankTaskLayersIfNeeded() {
3390 if (!mTaskLayersChanged) {
3391 return;
3392 }
3393 mTaskLayersChanged = false;
3394 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
3395 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3396 int baseLayer = 0;
3397 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3398 baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
3399 }
3400 }
3401 }
3402
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07003403 void clearOtherAppTimeTrackers(AppTimeTracker except) {
3404 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3405 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3406 final int topStackNdx = stacks.size() - 1;
3407 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3408 final ActivityStack stack = stacks.get(stackNdx);
3409 stack.clearOtherAppTimeTrackers(except);
3410 }
3411 }
3412 }
3413
Craig Mautner8d341ef2013-03-26 09:03:27 -07003414 void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003415 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3416 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003417 final int numStacks = stacks.size();
3418 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
3419 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003420 stack.scheduleDestroyActivities(app, reason);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003421 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003422 }
3423 }
3424
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003425 void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
3426 // Examine all activities currently running in the process.
3427 TaskRecord firstTask = null;
3428 // Tasks is non-null only if two or more tasks are found.
3429 ArraySet<TaskRecord> tasks = null;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003430 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
3431 for (int i = 0; i < app.activities.size(); i++) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003432 ActivityRecord r = app.activities.get(i);
3433 // First, if we find an activity that is in the process of being destroyed,
3434 // then we just aren't going to do anything for now; we want things to settle
3435 // down before we try to prune more activities.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003436 if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003437 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003438 return;
3439 }
3440 // Don't consider any activies that are currently not in a state where they
3441 // can be destroyed.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003442 if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
3443 || r.state == PAUSED || r.state == STOPPING) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003444 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003445 continue;
3446 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003447
3448 final TaskRecord task = r.getTask();
3449 if (task != null) {
3450 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + task
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003451 + " from " + r);
3452 if (firstTask == null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003453 firstTask = task;
3454 } else if (firstTask != task) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003455 if (tasks == null) {
3456 tasks = new ArraySet<>();
3457 tasks.add(firstTask);
3458 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003459 tasks.add(task);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003460 }
3461 }
3462 }
3463 if (tasks == null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003464 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003465 return;
3466 }
3467 // If we have activities in multiple tasks that are in a position to be destroyed,
3468 // let's iterate through the tasks and release the oldest one.
3469 final int numDisplays = mActivityDisplays.size();
3470 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3471 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3472 // Step through all stacks starting from behind, to hit the oldest things first.
3473 for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
3474 final ActivityStack stack = stacks.get(stackNdx);
3475 // Try to release activities in this stack; if we manage to, we are done.
3476 if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
3477 return;
3478 }
3479 }
3480 }
3481 }
3482
Amith Yamasani37a40c22015-06-17 13:25:42 -07003483 boolean switchUserLocked(int userId, UserState uss) {
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003484 final int focusStackId = mFocusedStack.getStackId();
3485 // We dismiss the docked stack whenever we switch users.
3486 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, focusStackId == DOCKED_STACK_ID);
Winson Chungc2b23a52017-01-09 15:44:55 -08003487 // Also dismiss the pinned stack whenever we switch users. Removing the pinned stack will
3488 // also cause all tasks to be moved to the fullscreen stack at a position that is
3489 // appropriate.
3490 removeStackLocked(PINNED_STACK_ID);
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003491
3492 mUserStackInFront.put(mCurrentUser, focusStackId);
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003493 final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
Craig Mautner2420ead2013-04-01 17:13:20 -07003494 mCurrentUser = userId;
Craig Mautnerac6f8432013-07-17 13:24:59 -07003495
Craig Mautner858d8a62013-04-23 17:08:34 -07003496 mStartingUsers.add(uss);
Craig Mautnere0a38842013-12-16 16:14:02 -08003497 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3498 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003499 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003500 final ActivityStack stack = stacks.get(stackNdx);
3501 stack.switchUserLocked(userId);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003502 TaskRecord task = stack.topTask();
3503 if (task != null) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08003504 stack.positionChildWindowContainerAtTop(task);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003505 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003506 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07003507 }
Craig Mautner858d8a62013-04-23 17:08:34 -07003508
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003509 ActivityStack stack = getStack(restoreStackId);
3510 if (stack == null) {
3511 stack = mHomeStack;
3512 }
3513 final boolean homeInFront = stack.isHomeStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08003514 if (stack.isOnHomeDisplay()) {
Wale Ogunwale925d0d12015-09-23 15:40:07 -07003515 stack.moveToFront("switchUserOnHomeDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003516 } else {
3517 // Stack was moved to another display while user was swapped out.
Matthew Ngae1ff4f2016-11-10 15:49:14 -08003518 resumeHomeStackTask(null, "switchUserOnOtherDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003519 }
Craig Mautner93529a42013-10-04 15:03:13 -07003520 return homeInFront;
Craig Mautner2219a1b2013-03-25 09:44:30 -07003521 }
3522
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003523 /** Checks whether the userid is a profile of the current user. */
3524 boolean isCurrentProfileLocked(int userId) {
3525 if (userId == mCurrentUser) return true;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07003526 return mService.mUserController.isCurrentProfileLocked(userId);
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003527 }
3528
Bryce Leeb7c9b802017-05-02 14:20:24 -07003529 /**
3530 * Returns whether a stopping activity is present that should be stopped after visible, rather
3531 * than idle.
3532 * @return {@code true} if such activity is present. {@code false} otherwise.
3533 */
3534 boolean isStoppingNoHistoryActivity() {
3535 // Activities that are marked as nohistory should be stopped immediately after the resumed
3536 // activity has become visible.
3537 for (ActivityRecord record : mStoppingActivities) {
3538 if (record.isNoHistory()) {
3539 return true;
3540 }
3541 }
3542
3543 return false;
3544 }
3545
Winson Chung4dabf232017-01-25 13:25:22 -08003546 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
3547 boolean remove, boolean processPausingActivities) {
Craig Mautnerde4ef022013-04-07 19:01:33 -07003548 ArrayList<ActivityRecord> stops = null;
3549
3550 final boolean nowVisible = allResumedActivitiesVisible();
Craig Mautner8c14c152015-01-15 17:32:07 -08003551 for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3552 ActivityRecord s = mStoppingActivities.get(activityNdx);
Bryce Lee4a194382017-04-04 14:32:48 -07003553 boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003554 if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
Craig Mautner8c14c152015-01-15 17:32:07 -08003555 + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
3556 if (waitingVisible && nowVisible) {
Bryce Lee4a194382017-04-04 14:32:48 -07003557 mActivitiesWaitingForVisibleActivity.remove(s);
Andrii Kulianee056812016-09-21 15:34:45 -07003558 waitingVisible = false;
Craig Mautnerde4ef022013-04-07 19:01:33 -07003559 if (s.finishing) {
3560 // If this activity is finishing, it is sitting on top of
3561 // everyone else but we now know it is no longer needed...
3562 // so get rid of it. Otherwise, we need to go through the
3563 // normal flow and hide it once we determine that it is
3564 // hidden by the activities in front of it.
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003565 if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003566 s.setVisibility(false);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003567 }
3568 }
David Stevensf62360c2017-03-16 19:00:20 -07003569 if (remove) {
3570 final ActivityStack stack = s.getStack();
3571 final boolean shouldSleepOrShutDown = stack != null
3572 ? stack.shouldSleepOrShutDownActivities()
3573 : mService.isSleepingOrShuttingDownLocked();
3574 if (!waitingVisible || shouldSleepOrShutDown) {
3575 if (!processPausingActivities && s.state == PAUSING) {
3576 // Defer processing pausing activities in this iteration and reschedule
3577 // a delayed idle to reprocess it again
3578 removeTimeoutsForActivityLocked(idleActivity);
3579 scheduleIdleTimeoutLocked(idleActivity);
3580 continue;
3581 }
Winson Chung4dabf232017-01-25 13:25:22 -08003582
David Stevensf62360c2017-03-16 19:00:20 -07003583 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
3584 if (stops == null) {
3585 stops = new ArrayList<>();
3586 }
3587 stops.add(s);
3588 mStoppingActivities.remove(activityNdx);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003589 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07003590 }
3591 }
3592
3593 return stops;
3594 }
3595
Craig Mautnercf910b02013-04-23 11:23:27 -07003596 void validateTopActivitiesLocked() {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003597 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3598 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3599 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3600 final ActivityStack stack = stacks.get(stackNdx);
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07003601 final ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003602 final ActivityState state = r == null ? DESTROYED : r.state;
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003603 if (isFocusedStack(stack)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003604 if (r == null) Slog.e(TAG,
3605 "validateTop...: null top activity, stack=" + stack);
3606 else {
3607 final ActivityRecord pausing = stack.mPausingActivity;
3608 if (pausing != null && pausing == r) Slog.e(TAG,
3609 "validateTop...: top stack has pausing activity r=" + r
3610 + " state=" + state);
3611 if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3612 "validateTop...: activity in front not resumed r=" + r
3613 + " state=" + state);
3614 }
Craig Mautnercf910b02013-04-23 11:23:27 -07003615 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003616 final ActivityRecord resumed = stack.mResumedActivity;
3617 if (resumed != null && resumed == r) Slog.e(TAG,
3618 "validateTop...: back stack has resumed activity r=" + r
3619 + " state=" + state);
3620 if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3621 "validateTop...: activity in back resumed r=" + r + " state=" + state);
Craig Mautnercf910b02013-04-23 11:23:27 -07003622 }
3623 }
3624 }
Craig Mautner76ea2242013-05-15 11:40:05 -07003625 }
3626
Craig Mautnere0570202015-05-13 13:06:11 -07003627 private String lockTaskModeToString() {
3628 switch (mLockTaskModeState) {
3629 case LOCK_TASK_MODE_LOCKED:
3630 return "LOCKED";
3631 case LOCK_TASK_MODE_PINNED:
3632 return "PINNED";
3633 case LOCK_TASK_MODE_NONE:
3634 return "NONE";
3635 default: return "unknown=" + mLockTaskModeState;
3636 }
3637 }
3638
Craig Mautner27084302013-03-25 08:05:25 -07003639 public void dump(PrintWriter pw, String prefix) {
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003640 pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003641 pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
Suprabh Shukla09a88f52015-12-02 14:36:31 -08003642 pw.print(prefix);
3643 pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003644 pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003645 pw.print(prefix); pw.println("mStacks=" + mStacks);
Craig Mautnere0570202015-05-13 13:06:11 -07003646 pw.print(prefix); pw.print("mLockTaskModeState=" + lockTaskModeToString());
Jorim Jaggi8d786932016-10-26 19:08:36 -07003647 final SparseArray<String[]> packages = mService.mLockTaskPackages;
3648 if (packages.size() > 0) {
3649 pw.print(prefix); pw.println("mLockTaskPackages (userId:packages)=");
3650 for (int i = 0; i < packages.size(); ++i) {
3651 pw.print(prefix); pw.print(prefix); pw.print(packages.keyAt(i));
3652 pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
3653 }
3654 }
Bryce Lee4a194382017-04-04 14:32:48 -07003655 if (!mWaitingForActivityVisible.isEmpty()) {
3656 pw.print(prefix); pw.println("mWaitingForActivityVisible=");
3657 for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
3658 pw.print(prefix); pw.print(prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
3659 }
3660 }
3661
Jorim Jaggi8d786932016-10-26 19:08:36 -07003662 pw.println(" mLockTaskModeTasks" + mLockTaskModeTasks);
3663 mKeyguardController.dump(pw, prefix);
Craig Mautner27084302013-03-25 08:05:25 -07003664 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003665
Winson43d1f262016-06-14 16:05:55 -07003666 /**
Andrii Kulian5406e7a2016-10-21 11:55:23 -07003667 * Dump all connected displays' configurations.
3668 * @param prefix Prefix to apply to each line of the dump.
3669 */
3670 void dumpDisplayConfigs(PrintWriter pw, String prefix) {
3671 pw.print(prefix); pw.println("Display override configurations:");
3672 final int displayCount = mActivityDisplays.size();
3673 for (int i = 0; i < displayCount; i++) {
3674 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(i);
3675 pw.print(prefix); pw.print(" "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
3676 pw.println(activityDisplay.getOverrideConfiguration());
3677 }
3678 }
3679
3680 /**
Winson43d1f262016-06-14 16:05:55 -07003681 * Dumps the activities matching the given {@param name} in the either the focused stack
3682 * or all visible stacks if {@param dumpVisibleStacks} is true.
3683 */
Winson Chung6998bc42017-02-28 17:07:05 -08003684 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name, boolean dumpVisibleStacksOnly,
3685 boolean dumpFocusedStackOnly) {
3686 if (dumpFocusedStackOnly) {
3687 return mFocusedStack.getDumpActivitiesLocked(name);
3688 } else {
Winson43d1f262016-06-14 16:05:55 -07003689 ArrayList<ActivityRecord> activities = new ArrayList<>();
3690 int numDisplays = mActivityDisplays.size();
3691 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3692 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3693 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3694 ActivityStack stack = stacks.get(stackNdx);
Winson Chung6998bc42017-02-28 17:07:05 -08003695 if (!dumpVisibleStacksOnly ||
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07003696 stack.shouldBeVisible(null) == STACK_VISIBLE) {
Winson43d1f262016-06-14 16:05:55 -07003697 activities.addAll(stack.getDumpActivitiesLocked(name));
3698 }
3699 }
3700 }
3701 return activities;
Winson43d1f262016-06-14 16:05:55 -07003702 }
Craig Mautner20e72272013-04-01 13:45:53 -07003703 }
3704
Dianne Hackborn390517b2013-05-30 15:03:32 -07003705 static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3706 boolean needSep, String prefix) {
3707 if (activity != null) {
3708 if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3709 if (needSep) {
3710 pw.println();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003711 }
3712 pw.print(prefix);
3713 pw.println(activity);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003714 return true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003715 }
3716 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003717 return false;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003718 }
3719
Craig Mautner8d341ef2013-03-26 09:03:27 -07003720 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3721 boolean dumpClient, String dumpPackage) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003722 boolean printed = false;
3723 boolean needSep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003724 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3725 ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003726 pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
Craig Mautner737fae22014-10-15 12:52:10 -07003727 pw.println(" (activities from top to bottom):");
Craig Mautnere0a38842013-12-16 16:14:02 -08003728 ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
Craig Mautner737fae22014-10-15 12:52:10 -07003729 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003730 final ActivityStack stack = stacks.get(stackNdx);
3731 StringBuilder stackHeader = new StringBuilder(128);
3732 stackHeader.append(" Stack #");
3733 stackHeader.append(stack.mStackId);
3734 stackHeader.append(":");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003735 stackHeader.append("\n");
3736 stackHeader.append(" mFullscreen=" + stack.mFullscreen);
3737 stackHeader.append("\n");
David Stevensf62360c2017-03-16 19:00:20 -07003738 stackHeader.append(" isSleeping=" + stack.shouldSleepActivities());
3739 stackHeader.append("\n");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003740 stackHeader.append(" mBounds=" + stack.mBounds);
Winson Chungabb433b2017-03-24 09:35:42 -07003741
3742 final boolean printedStackHeader = stack.dumpActivitiesLocked(fd, pw, dumpAll,
3743 dumpClient, dumpPackage, needSep, stackHeader.toString());
3744 printed |= printedStackHeader;
3745 if (!printedStackHeader) {
3746 // Ensure we always dump the stack header even if there are no activities
3747 pw.println();
3748 pw.println(stackHeader);
3749 }
3750
Craig Mautner4a1cb222013-12-04 16:14:06 -08003751 printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, " ", "Run", false,
3752 !dumpAll, false, dumpPackage, true,
3753 " Running activities (most recent first):", null);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003754
Craig Mautner4a1cb222013-12-04 16:14:06 -08003755 needSep = printed;
3756 boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3757 " mPausingActivity: ");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003758 if (pr) {
3759 printed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003760 needSep = false;
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003761 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003762 pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3763 " mResumedActivity: ");
3764 if (pr) {
3765 printed = true;
3766 needSep = false;
3767 }
3768 if (dumpAll) {
3769 pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3770 " mLastPausedActivity: ");
3771 if (pr) {
3772 printed = true;
3773 needSep = true;
3774 }
3775 printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3776 needSep, " mLastNoHistoryActivity: ");
3777 }
3778 needSep = printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003779 }
3780 }
3781
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003782 printed |= dumpHistoryList(fd, pw, mFinishingActivities, " ", "Fin", false, !dumpAll,
3783 false, dumpPackage, true, " Activities waiting to finish:", null);
3784 printed |= dumpHistoryList(fd, pw, mStoppingActivities, " ", "Stop", false, !dumpAll,
3785 false, dumpPackage, true, " Activities waiting to stop:", null);
Bryce Lee4a194382017-04-04 14:32:48 -07003786 printed |= dumpHistoryList(fd, pw, mActivitiesWaitingForVisibleActivity, " ", "Wait",
3787 false, !dumpAll, false, dumpPackage, true,
3788 " Activities waiting for another to become visible:", null);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003789 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3790 false, dumpPackage, true, " Activities waiting to sleep:", null);
Craig Mautnerf3333272013-04-22 10:55:53 -07003791
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003792 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003793 }
3794
Dianne Hackborn390517b2013-05-30 15:03:32 -07003795 static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
Craig Mautner8d341ef2013-03-26 09:03:27 -07003796 String prefix, String label, boolean complete, boolean brief, boolean client,
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003797 String dumpPackage, boolean needNL, String header1, String header2) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003798 TaskRecord lastTask = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003799 String innerPrefix = null;
3800 String[] args = null;
3801 boolean printed = false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003802 for (int i=list.size()-1; i>=0; i--) {
3803 final ActivityRecord r = list.get(i);
3804 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3805 continue;
3806 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003807 if (innerPrefix == null) {
3808 innerPrefix = prefix + " ";
3809 args = new String[0];
3810 }
3811 printed = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003812 final boolean full = !brief && (complete || !r.isInHistory());
3813 if (needNL) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003814 pw.println("");
Craig Mautner8d341ef2013-03-26 09:03:27 -07003815 needNL = false;
3816 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003817 if (header1 != null) {
3818 pw.println(header1);
3819 header1 = null;
3820 }
3821 if (header2 != null) {
3822 pw.println(header2);
3823 header2 = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003824 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003825 if (lastTask != r.getTask()) {
3826 lastTask = r.getTask();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003827 pw.print(prefix);
3828 pw.print(full ? "* " : " ");
3829 pw.println(lastTask);
3830 if (full) {
3831 lastTask.dump(pw, prefix + " ");
3832 } else if (complete) {
3833 // Complete + brief == give a summary. Isn't that obvious?!?
3834 if (lastTask.intent != null) {
3835 pw.print(prefix); pw.print(" ");
3836 pw.println(lastTask.intent.toInsecureStringWithClip());
3837 }
3838 }
3839 }
3840 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
3841 pw.print(" #"); pw.print(i); pw.print(": ");
3842 pw.println(r);
3843 if (full) {
3844 r.dump(pw, innerPrefix);
3845 } else if (complete) {
3846 // Complete + brief == give a summary. Isn't that obvious?!?
3847 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3848 if (r.app != null) {
3849 pw.print(innerPrefix); pw.println(r.app);
3850 }
3851 }
3852 if (client && r.app != null && r.app.thread != null) {
3853 // flush anything that is already in the PrintWriter since the thread is going
3854 // to write to the file descriptor directly
3855 pw.flush();
3856 try {
3857 TransferPipe tp = new TransferPipe();
3858 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003859 r.app.thread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003860 // Short timeout, since blocking here can
3861 // deadlock with the application.
3862 tp.go(fd, 2000);
3863 } finally {
3864 tp.kill();
3865 }
3866 } catch (IOException e) {
3867 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3868 } catch (RemoteException e) {
3869 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3870 }
3871 needNL = true;
3872 }
3873 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003874 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003875 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003876
Craig Mautnerf3333272013-04-22 10:55:53 -07003877 void scheduleIdleTimeoutLocked(ActivityRecord next) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003878 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3879 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
Craig Mautnerc64f73e2013-04-24 16:44:56 -07003880 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
3881 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
Craig Mautnerf3333272013-04-22 10:55:53 -07003882 }
3883
3884 final void scheduleIdleLocked() {
Craig Mautner05d29032013-05-03 13:40:13 -07003885 mHandler.sendEmptyMessage(IDLE_NOW_MSG);
Craig Mautnerf3333272013-04-22 10:55:53 -07003886 }
3887
3888 void removeTimeoutsForActivityLocked(ActivityRecord r) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003889 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
3890 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07003891 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3892 }
3893
Craig Mautner05d29032013-05-03 13:40:13 -07003894 final void scheduleResumeTopActivities() {
Craig Mautner34b73df2014-01-12 21:11:08 -08003895 if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
3896 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
3897 }
Craig Mautner05d29032013-05-03 13:40:13 -07003898 }
3899
Craig Mautner0eea92c2013-05-16 13:35:39 -07003900 void removeSleepTimeouts() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003901 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
3902 }
3903
3904 final void scheduleSleepTimeout() {
3905 removeSleepTimeouts();
3906 mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
3907 }
3908
Craig Mautner4a1cb222013-12-04 16:14:06 -08003909 @Override
3910 public void onDisplayAdded(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003911 if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003912 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
3913 }
3914
3915 @Override
3916 public void onDisplayRemoved(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003917 if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003918 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
3919 }
3920
3921 @Override
3922 public void onDisplayChanged(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003923 if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003924 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
3925 }
3926
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003927 private void handleDisplayAdded(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003928 synchronized (mService) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003929 getActivityDisplayOrCreateLocked(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003930 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003931 }
3932
Andrii Kulianca007a62016-11-22 16:33:28 -08003933 /** Check if display with specified id is added to the list. */
3934 boolean isDisplayAdded(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003935 return getActivityDisplayOrCreateLocked(displayId) != null;
3936 }
3937
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003938 ActivityDisplay getActivityDisplay(int displayId) {
3939 return mActivityDisplays.get(displayId);
3940 }
3941
Andrii Kulian62e6f252017-05-30 22:46:53 -07003942 /**
3943 * Get an existing instance of {@link ActivityDisplay} or create new if there is a
3944 * corresponding record in display manager.
3945 */
3946 private ActivityDisplay getActivityDisplayOrCreateLocked(int displayId) {
3947 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3948 if (activityDisplay != null) {
3949 return activityDisplay;
3950 }
3951 if (mDisplayManager == null) {
3952 // The system isn't fully initialized yet.
3953 return null;
3954 }
3955 final Display display = mDisplayManager.getDisplay(displayId);
3956 if (display == null) {
3957 // The display is not registered in DisplayManager.
3958 return null;
3959 }
3960 // The display hasn't been added to ActivityManager yet, create a new record now.
3961 activityDisplay = new ActivityDisplay(displayId);
3962 if (activityDisplay.mDisplay == null) {
3963 Slog.w(TAG, "Display " + displayId + " gone before initialization complete");
3964 return null;
3965 }
3966 mActivityDisplays.put(displayId, activityDisplay);
3967 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
3968 mWindowManager.onDisplayAdded(displayId);
3969 return activityDisplay;
Andrii Kulianca007a62016-11-22 16:33:28 -08003970 }
3971
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003972 private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
Andrii Kulianf66a83d2016-05-17 12:17:44 -07003973 mDefaultMinSizeOfResizeableTask =
Jorim Jaggi19cf2972016-04-07 23:26:10 -07003974 mService.mContext.getResources().getDimensionPixelSize(
3975 com.android.internal.R.dimen.default_minimal_size_resizable_task);
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003976 }
3977
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003978 private void handleDisplayRemoved(int displayId) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003979 if (displayId == DEFAULT_DISPLAY) {
3980 throw new IllegalArgumentException("Can't remove the primary display.");
3981 }
3982
Craig Mautner4a1cb222013-12-04 16:14:06 -08003983 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003984 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3985 if (activityDisplay != null) {
Andrii Kulian250d6532017-02-08 23:30:45 -08003986 final boolean destroyContentOnRemoval
3987 = activityDisplay.shouldDestroyContentOnRemove();
Andrii Kuliana33818c2017-02-16 16:11:30 -08003988 final ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3989 while (!stacks.isEmpty()) {
3990 final ActivityStack stack = stacks.get(0);
Andrii Kulian250d6532017-02-08 23:30:45 -08003991 if (destroyContentOnRemoval) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003992 moveStackToDisplayLocked(stack.mStackId, DEFAULT_DISPLAY,
3993 false /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003994 stack.finishAllActivitiesLocked(true /* immediately */);
Andrii Kuliana33818c2017-02-16 16:11:30 -08003995 } else {
3996 // Moving all tasks to fullscreen stack, because it's guaranteed to be
3997 // a valid launch stack for all activities. This way the task history from
3998 // external display will be preserved on primary after move.
3999 moveTasksToFullscreenStackLocked(stack.getStackId(), true /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08004000 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004001 }
David Stevensf62360c2017-03-16 19:00:20 -07004002
4003 releaseSleepTokens(activityDisplay);
4004
Craig Mautnere0a38842013-12-16 16:14:02 -08004005 mActivityDisplays.remove(displayId);
Bryce Leeaf3a4002017-03-20 10:37:12 -07004006 mWindowManager.onDisplayRemoved(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004007 }
4008 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004009 }
4010
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004011 private void handleDisplayChanged(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004012 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08004013 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
4014 if (activityDisplay != null) {
David Stevensf62360c2017-03-16 19:00:20 -07004015 // The window policy is responsible for stopping activities on the default display
4016 if (displayId != Display.DEFAULT_DISPLAY) {
4017 int displayState = activityDisplay.mDisplay.getState();
4018 if (displayState == Display.STATE_OFF && activityDisplay.mOffToken == null) {
4019 activityDisplay.mOffToken =
4020 mService.acquireSleepToken("Display-off", displayId);
4021 } else if (displayState == Display.STATE_ON
4022 && activityDisplay.mOffToken != null) {
4023 activityDisplay.mOffToken.release();
4024 activityDisplay.mOffToken = null;
4025 }
4026 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004027 // TODO: Update the bounds.
4028 }
Bryce Leeaf3a4002017-03-20 10:37:12 -07004029 mWindowManager.onDisplayChanged(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004030 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004031 }
4032
David Stevensf62360c2017-03-16 19:00:20 -07004033 SleepToken createSleepTokenLocked(String tag, int displayId) {
4034 ActivityDisplay display = mActivityDisplays.get(displayId);
4035 if (display == null) {
4036 throw new IllegalArgumentException("Invalid display: " + displayId);
4037 }
4038
4039 final SleepTokenImpl token = new SleepTokenImpl(tag, displayId);
4040 mSleepTokens.add(token);
4041 display.mAllSleepTokens.add(token);
4042 return token;
4043 }
4044
4045 private void removeSleepTokenLocked(SleepTokenImpl token) {
4046 mSleepTokens.remove(token);
4047
4048 ActivityDisplay display = mActivityDisplays.get(token.mDisplayId);
4049 if (display != null) {
4050 display.mAllSleepTokens.remove(token);
4051 if (display.mAllSleepTokens.isEmpty()) {
4052 mService.updateSleepIfNeededLocked();
4053 }
4054 }
4055 }
4056
4057 private void releaseSleepTokens(ActivityDisplay display) {
4058 if (display.mAllSleepTokens.isEmpty()) {
4059 return;
4060 }
4061 for (SleepTokenImpl token : display.mAllSleepTokens) {
4062 mSleepTokens.remove(token);
4063 }
4064 display.mAllSleepTokens.clear();
4065
4066 mService.updateSleepIfNeededLocked();
4067 }
4068
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004069 private StackInfo getStackInfoLocked(ActivityStack stack) {
Andrii Kulian7e215d72017-04-26 18:33:28 -07004070 final int displayId = stack.mDisplayId;
4071 final ActivityDisplay display = mActivityDisplays.get(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004072 StackInfo info = new StackInfo();
Wale Ogunwale1666e312016-12-16 11:27:18 -08004073 stack.getWindowContainerBounds(info.bounds);
Andrii Kulian7e215d72017-04-26 18:33:28 -07004074 info.displayId = displayId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004075 info.stackId = stack.mStackId;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004076 info.userId = stack.mCurrentUser;
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004077 info.visible = stack.shouldBeVisible(null) == STACK_VISIBLE;
Andrii Kulian62e6f252017-05-30 22:46:53 -07004078 // A stack might be not attached to a display.
Winson529c8e42016-05-17 11:08:40 -07004079 info.position = display != null
4080 ? display.mStacks.indexOf(stack)
4081 : 0;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004082
4083 ArrayList<TaskRecord> tasks = stack.getAllTasks();
4084 final int numTasks = tasks.size();
4085 int[] taskIds = new int[numTasks];
4086 String[] taskNames = new String[numTasks];
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004087 Rect[] taskBounds = new Rect[numTasks];
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004088 int[] taskUserIds = new int[numTasks];
Craig Mautner4a1cb222013-12-04 16:14:06 -08004089 for (int i = 0; i < numTasks; ++i) {
4090 final TaskRecord task = tasks.get(i);
4091 taskIds[i] = task.taskId;
4092 taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
4093 : task.realActivity != null ? task.realActivity.flattenToString()
4094 : task.getTopActivity() != null ? task.getTopActivity().packageName
4095 : "unknown";
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004096 taskBounds[i] = new Rect();
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004097 task.getWindowContainerBounds(taskBounds[i]);
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004098 taskUserIds[i] = task.userId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004099 }
4100 info.taskIds = taskIds;
4101 info.taskNames = taskNames;
Wale Ogunwale868a5e12015-08-02 16:19:20 -07004102 info.taskBounds = taskBounds;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004103 info.taskUserIds = taskUserIds;
Winsond46b7272016-04-20 11:54:27 -07004104
4105 final ActivityRecord top = stack.topRunningActivityLocked();
4106 info.topActivity = top != null ? top.intent.getComponent() : null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004107 return info;
4108 }
4109
4110 StackInfo getStackInfoLocked(int stackId) {
4111 ActivityStack stack = getStack(stackId);
4112 if (stack != null) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004113 return getStackInfoLocked(stack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004114 }
4115 return null;
4116 }
4117
4118 ArrayList<StackInfo> getAllStackInfosLocked() {
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004119 ArrayList<StackInfo> list = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08004120 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
4121 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004122 for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004123 list.add(getStackInfoLocked(stacks.get(ndx)));
Craig Mautner4a1cb222013-12-04 16:14:06 -08004124 }
4125 }
4126 return list;
4127 }
4128
Craig Mautner15df08a2015-04-01 12:17:18 -07004129 TaskRecord getLockedTaskLocked() {
4130 final int top = mLockTaskModeTasks.size() - 1;
4131 if (top >= 0) {
4132 return mLockTaskModeTasks.get(top);
4133 }
4134 return null;
4135 }
4136
4137 boolean isLockedTask(TaskRecord task) {
4138 return mLockTaskModeTasks.contains(task);
4139 }
4140
4141 boolean isLastLockedTask(TaskRecord task) {
4142 return mLockTaskModeTasks.size() == 1 && mLockTaskModeTasks.contains(task);
4143 }
4144
4145 void removeLockedTaskLocked(final TaskRecord task) {
Craig Mautner432f64e2015-05-20 14:59:57 -07004146 if (!mLockTaskModeTasks.remove(task)) {
4147 return;
4148 }
4149 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "removeLockedTaskLocked: removed " + task);
4150 if (mLockTaskModeTasks.isEmpty()) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004151 // Last one.
Craig Mautnere0570202015-05-13 13:06:11 -07004152 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
4153 " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
Craig Mautner15df08a2015-04-01 12:17:18 -07004154 final Message lockTaskMsg = Message.obtain();
4155 lockTaskMsg.arg1 = task.userId;
4156 lockTaskMsg.what = LOCK_TASK_END_MSG;
4157 mHandler.sendMessage(lockTaskMsg);
4158 }
4159 }
4160
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004161 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4162 int preferredDisplayId, int actualStackId) {
4163 handleNonResizableTaskIfNeeded(task, preferredStackId, preferredDisplayId, actualStackId,
Andrii Kulianc27916642016-04-12 17:59:27 -07004164 false /* forceNonResizable */);
4165 }
4166
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004167 private void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4168 int preferredDisplayId, int actualStackId, boolean forceNonResizable) {
4169 final boolean isSecondaryDisplayPreferred =
4170 (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY)
4171 || StackId.isDynamicStack(preferredStackId);
4172 if (((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
4173 && !isSecondaryDisplayPreferred) || task.isHomeTask()) {
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004174 return;
4175 }
4176
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004177 // Handle incorrect launch/move to secondary display if needed.
4178 final boolean launchOnSecondaryDisplayFailed;
4179 if (isSecondaryDisplayPreferred) {
4180 final int actualDisplayId = task.getStack().mDisplayId;
4181 if (!task.canBeLaunchedOnDisplay(actualDisplayId)) {
4182 // The task landed on an inappropriate display somehow, move it to the default
4183 // display.
4184 // TODO(multi-display): Find proper stack for the task on the default display.
4185 mService.moveTaskToStack(task.taskId, FULLSCREEN_WORKSPACE_STACK_ID,
4186 true /* toTop */);
4187 launchOnSecondaryDisplayFailed = true;
4188 } else {
4189 // The task might have landed on a display different from requested.
4190 launchOnSecondaryDisplayFailed = actualDisplayId == DEFAULT_DISPLAY
4191 || (preferredDisplayId != INVALID_DISPLAY
4192 && preferredDisplayId != actualDisplayId);
4193 }
4194 } else {
4195 // The task wasn't requested to be on a secondary display.
4196 launchOnSecondaryDisplayFailed = false;
4197 }
4198
Jorim Jaggicd13d332016-04-27 15:40:20 -07004199 final ActivityRecord topActivity = task.getTopActivity();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004200 if (launchOnSecondaryDisplayFailed || !task.supportsSplitScreen() || forceNonResizable) {
4201 if (launchOnSecondaryDisplayFailed) {
4202 // Display a warning toast that we tried to put a non-resizeable task on a secondary
4203 // display with config different from global config.
4204 mService.mTaskChangeNotificationController
4205 .notifyActivityLaunchOnSecondaryDisplayFailed();
4206 } else {
4207 // Display a warning toast that we tried to put a non-dockable task in the docked
4208 // stack.
4209 mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
4210 }
Jorim Jaggid53f0922016-04-06 22:16:23 -07004211
Andrii Kulianc27916642016-04-12 17:59:27 -07004212 // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
4213 // we need to move it to top of fullscreen stack, otherwise it will be covered.
Wale Ogunwale9a98c522016-04-27 09:23:55 -07004214 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
Winson Chungd3395382016-12-13 11:49:09 -08004215 } else if (topActivity != null && topActivity.isNonResizableOrForcedResizable()
Jorim Jaggicd13d332016-04-27 15:40:20 -07004216 && !topActivity.noDisplay) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004217 final String packageName = topActivity.appInfo.packageName;
4218 final int reason = isSecondaryDisplayPreferred
4219 ? FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY
4220 : FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Yorke Leebd54c2a2016-10-25 13:49:23 -07004221 mService.mTaskChangeNotificationController.notifyActivityForcedResizable(
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004222 task.taskId, reason, packageName);
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004223 }
Chong Zhangb15758a2015-11-17 12:12:03 -08004224 }
4225
Craig Mautner6cd6cec2015-04-01 00:02:12 -07004226 void showLockTaskToast() {
Hall Liu45784f12016-05-31 15:50:48 -07004227 if (mLockTaskNotify != null) {
4228 mLockTaskNotify.showToast(mLockTaskModeState);
4229 }
Jason Monka8f569c2014-07-07 12:15:21 -04004230 }
4231
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004232 void showLockTaskEscapeMessageLocked(TaskRecord task) {
4233 if (mLockTaskModeTasks.contains(task)) {
4234 mHandler.sendEmptyMessage(SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG);
4235 }
4236 }
4237
Craig Mautner432f64e2015-05-20 14:59:57 -07004238 void setLockTaskModeLocked(TaskRecord task, int lockTaskModeState, String reason,
4239 boolean andResume) {
Craig Mautneraea74a52014-03-08 14:23:10 -08004240 if (task == null) {
Christopher Tate3bd90612014-06-18 16:37:52 -07004241 // Take out of lock task mode if necessary
Craig Mautner15df08a2015-04-01 12:17:18 -07004242 final TaskRecord lockedTask = getLockedTaskLocked();
4243 if (lockedTask != null) {
4244 removeLockedTaskLocked(lockedTask);
4245 if (!mLockTaskModeTasks.isEmpty()) {
4246 // There are locked tasks remaining, can only finish this task, not unlock it.
Craig Mautnere0570202015-05-13 13:06:11 -07004247 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4248 "setLockTaskModeLocked: Tasks remaining, can't unlock");
Craig Mautner15df08a2015-04-01 12:17:18 -07004249 lockedTask.performClearTaskLocked();
Wale Ogunwaled046a012015-12-24 13:05:59 -08004250 resumeFocusedStackTopActivityLocked();
Craig Mautner15df08a2015-04-01 12:17:18 -07004251 return;
4252 }
Christopher Tate3bd90612014-06-18 16:37:52 -07004253 }
Craig Mautnere0570202015-05-13 13:06:11 -07004254 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4255 "setLockTaskModeLocked: No tasks to unlock. Callers=" + Debug.getCallers(4));
Craig Mautneraea74a52014-03-08 14:23:10 -08004256 return;
4257 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004258
4259 // Should have already been checked, but do it again.
4260 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
Craig Mautnere0570202015-05-13 13:06:11 -07004261 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4262 "setLockTaskModeLocked: Can't lock due to auth");
Craig Mautneraea74a52014-03-08 14:23:10 -08004263 return;
4264 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004265 if (isLockTaskModeViolation(task)) {
Craig Mautnere0570202015-05-13 13:06:11 -07004266 Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
Craig Mautner15df08a2015-04-01 12:17:18 -07004267 return;
4268 }
4269
4270 if (mLockTaskModeTasks.isEmpty()) {
4271 // First locktask.
4272 final Message lockTaskMsg = Message.obtain();
4273 lockTaskMsg.obj = task.intent.getComponent().getPackageName();
4274 lockTaskMsg.arg1 = task.userId;
4275 lockTaskMsg.what = LOCK_TASK_START_MSG;
4276 lockTaskMsg.arg2 = lockTaskModeState;
4277 mHandler.sendMessage(lockTaskMsg);
4278 }
4279 // Add it or move it to the top.
Craig Mautnere0570202015-05-13 13:06:11 -07004280 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskModeLocked: Locking to " + task +
4281 " Callers=" + Debug.getCallers(4));
Craig Mautner15df08a2015-04-01 12:17:18 -07004282 mLockTaskModeTasks.remove(task);
4283 mLockTaskModeTasks.add(task);
4284
4285 if (task.mLockTaskUid == -1) {
Wale Ogunwale5c18d052015-10-12 10:34:14 -07004286 task.mLockTaskUid = task.effectiveUid;
Craig Mautner15df08a2015-04-01 12:17:18 -07004287 }
Craig Mautner432f64e2015-05-20 14:59:57 -07004288
4289 if (andResume) {
Andrii Kulianc27916642016-04-12 17:59:27 -07004290 findTaskToMoveToFrontLocked(task, 0, null, reason,
4291 lockTaskModeState != LOCK_TASK_MODE_NONE);
Wale Ogunwaled046a012015-12-24 13:05:59 -08004292 resumeFocusedStackTopActivityLocked();
Jorim Jaggia42938e2016-11-22 14:31:38 +01004293 mWindowManager.executeAppTransition();
Andrii Kulianc27916642016-04-12 17:59:27 -07004294 } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004295 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
4296 task.getStackId(), true /* forceNonResizable */);
Craig Mautner432f64e2015-05-20 14:59:57 -07004297 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004298 }
4299
4300 boolean isLockTaskModeViolation(TaskRecord task) {
Jason Monk25d237b2015-06-19 10:39:39 -04004301 return isLockTaskModeViolation(task, false);
4302 }
4303
4304 boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) {
4305 if (getLockedTaskLocked() == task && !isNewClearTask) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004306 return false;
4307 }
4308 final int lockTaskAuth = task.mLockTaskAuth;
4309 switch (lockTaskAuth) {
4310 case LOCK_TASK_AUTH_DONT_LOCK:
4311 return !mLockTaskModeTasks.isEmpty();
Benjamin Franz469dd582015-06-09 14:24:36 +01004312 case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
Craig Mautner15df08a2015-04-01 12:17:18 -07004313 case LOCK_TASK_AUTH_LAUNCHABLE:
4314 case LOCK_TASK_AUTH_WHITELISTED:
4315 return false;
4316 case LOCK_TASK_AUTH_PINNABLE:
4317 // Pinnable tasks can't be launched on top of locktask tasks.
4318 return !mLockTaskModeTasks.isEmpty();
4319 default:
4320 Slog.w(TAG, "isLockTaskModeViolation: invalid lockTaskAuth value=" + lockTaskAuth);
4321 return true;
4322 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004323 }
4324
Craig Mautner15df08a2015-04-01 12:17:18 -07004325 void onLockTaskPackagesUpdatedLocked() {
4326 boolean didSomething = false;
4327 for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
4328 final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx);
Benjamin Franz469dd582015-06-09 14:24:36 +01004329 final boolean wasWhitelisted =
4330 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4331 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
Craig Mautner15df08a2015-04-01 12:17:18 -07004332 lockedTask.setLockTaskAuth();
Benjamin Franz469dd582015-06-09 14:24:36 +01004333 final boolean isWhitelisted =
4334 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4335 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
4336 if (wasWhitelisted && !isWhitelisted) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004337 // Lost whitelisting authorization. End it now.
Craig Mautner432f64e2015-05-20 14:59:57 -07004338 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "onLockTaskPackagesUpdated: removing " +
4339 lockedTask + " mLockTaskAuth=" + lockedTask.lockTaskAuthToString());
Craig Mautner15df08a2015-04-01 12:17:18 -07004340 removeLockedTaskLocked(lockedTask);
4341 lockedTask.performClearTaskLocked();
4342 didSomething = true;
4343 }
4344 }
4345 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
4346 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
4347 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
4348 final ActivityStack stack = stacks.get(stackNdx);
4349 stack.onLockTaskPackagesUpdatedLocked();
4350 }
4351 }
Craig Mautnere0570202015-05-13 13:06:11 -07004352 final ActivityRecord r = topRunningActivityLocked();
Bryce Leeaf691c02017-03-20 14:20:22 -07004353 final TaskRecord task = r != null ? r.getTask() : null;
Craig Mautnere0570202015-05-13 13:06:11 -07004354 if (mLockTaskModeTasks.isEmpty() && task != null
4355 && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
4356 // This task must have just been authorized.
Craig Mautner432f64e2015-05-20 14:59:57 -07004357 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK,
4358 "onLockTaskPackagesUpdated: starting new locktask task=" + task);
4359 setLockTaskModeLocked(task, ActivityManager.LOCK_TASK_MODE_LOCKED, "package updated",
4360 false);
4361 didSomething = true;
Craig Mautnere0570202015-05-13 13:06:11 -07004362 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004363 if (didSomething) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004364 resumeFocusedStackTopActivityLocked();
Craig Mautneraea74a52014-03-08 14:23:10 -08004365 }
4366 }
4367
Benjamin Franz43261142015-02-11 15:59:44 +00004368 int getLockTaskModeState() {
4369 return mLockTaskModeState;
Craig Mautneraea74a52014-03-08 14:23:10 -08004370 }
4371
Jorim Jaggife89d122015-12-22 16:28:44 +01004372 void activityRelaunchedLocked(IBinder token) {
4373 mWindowManager.notifyAppRelaunchingFinished(token);
David Stevensf62360c2017-03-16 19:00:20 -07004374 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4375 if (r != null) {
4376 if (r.getStack().shouldSleepOrShutDownActivities()) {
Wale Ogunwale3e997362016-09-06 10:37:56 -07004377 r.setSleeping(true, true);
4378 }
4379 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004380 }
4381
4382 void activityRelaunchingLocked(ActivityRecord r) {
4383 mWindowManager.notifyAppRelaunching(r.appToken);
4384 }
4385
Filip Gruszczynski77d94482015-12-11 13:59:52 -08004386 void logStackState() {
4387 mActivityMetricsLogger.logWindowState();
4388 }
4389
Winson Chung5af42fc2017-03-24 17:11:33 -07004390 void scheduleUpdateMultiWindowMode(TaskRecord task) {
Winson Chung8bca9e42017-04-16 15:59:43 -07004391 // If the stack is animating in a way where we will be forcing a multi-mode change at the
4392 // end, then ensure that we defer all in between multi-window mode changes
4393 if (task.getStack().deferScheduleMultiWindowModeChanged()) {
4394 return;
4395 }
4396
Wale Ogunwale22e25262016-02-01 10:32:02 -08004397 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4398 final ActivityRecord r = task.mActivities.get(i);
4399 if (r.app != null && r.app.thread != null) {
4400 mMultiWindowModeChangedActivities.add(r);
4401 }
4402 }
4403
4404 if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
4405 mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
4406 }
4407 }
4408
Winson Chung5af42fc2017-03-24 17:11:33 -07004409 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07004410 final ActivityStack stack = task.getStack();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004411 if (prevStack == null || prevStack == stack
4412 || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
4413 return;
4414 }
4415
Winson Chungab76bbc2017-08-14 13:33:51 -07004416 scheduleUpdatePictureInPictureModeIfNeeded(task, stack.mBounds);
Winson Chung5af42fc2017-03-24 17:11:33 -07004417 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004418
Winson Chungab76bbc2017-08-14 13:33:51 -07004419 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds) {
4420 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4421 final ActivityRecord r = task.mActivities.get(i);
4422 if (r.app != null && r.app.thread != null) {
4423 mPipModeChangedActivities.add(r);
Winson Chung5af42fc2017-03-24 17:11:33 -07004424 }
Winson Chungab76bbc2017-08-14 13:33:51 -07004425 }
4426 mPipModeChangedTargetStackBounds = targetStackBounds;
Winson Chung5af42fc2017-03-24 17:11:33 -07004427
Winson Chungab76bbc2017-08-14 13:33:51 -07004428 if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
4429 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
4430 }
4431 }
4432
4433 void updatePictureInPictureMode(TaskRecord task, Rect targetStackBounds, boolean forceUpdate) {
4434 mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG);
4435 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4436 final ActivityRecord r = task.mActivities.get(i);
4437 if (r.app != null && r.app.thread != null) {
4438 r.updatePictureInPictureMode(targetStackBounds, forceUpdate);
Winson Chung5af42fc2017-03-24 17:11:33 -07004439 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004440 }
4441 }
4442
Tony Mak853304c2016-04-18 15:17:41 +01004443 void setDockedStackMinimized(boolean minimized) {
4444 mIsDockMinimized = minimized;
Tony Mak853304c2016-04-18 15:17:41 +01004445 }
4446
chaviw59b98852017-06-13 12:05:44 -07004447 void wakeUp(String reason) {
4448 mPowerManager.wakeUp(SystemClock.uptimeMillis(), "android.server.am:TURN_ON:" + reason);
4449 }
4450
4451 /**
4452 * Begin deferring resume to avoid duplicate resumes in one pass.
4453 */
4454 private void beginDeferResume() {
4455 mDeferResumeCount++;
4456 }
4457
4458 /**
4459 * End deferring resume and determine if resume can be called.
4460 */
4461 private void endDeferResume() {
4462 mDeferResumeCount--;
4463 }
4464
4465 /**
4466 * @return True if resume can be called.
4467 */
4468 private boolean readyToResume() {
4469 return mDeferResumeCount == 0;
4470 }
4471
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004472 private final class ActivityStackSupervisorHandler extends Handler {
Craig Mautnerf3333272013-04-22 10:55:53 -07004473
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004474 public ActivityStackSupervisorHandler(Looper looper) {
4475 super(looper);
4476 }
4477
Winson Chung4dabf232017-01-25 13:25:22 -08004478 void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) {
Craig Mautnerf3333272013-04-22 10:55:53 -07004479 synchronized (mService) {
Winson Chung4dabf232017-01-25 13:25:22 -08004480 activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */,
4481 processPausingActivities, null);
Craig Mautnerf3333272013-04-22 10:55:53 -07004482 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004483 }
4484
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004485 @Override
4486 public void handleMessage(Message msg) {
4487 switch (msg.what) {
Wale Ogunwale22e25262016-02-01 10:32:02 -08004488 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
4489 synchronized (mService) {
4490 for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
4491 final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004492 r.updateMultiWindowMode();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004493 }
4494 }
4495 } break;
4496 case REPORT_PIP_MODE_CHANGED_MSG: {
4497 synchronized (mService) {
4498 for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
4499 final ActivityRecord r = mPipModeChangedActivities.remove(i);
Winson Chungab76bbc2017-08-14 13:33:51 -07004500 r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds,
4501 false /* forceUpdate */);
Wale Ogunwale22e25262016-02-01 10:32:02 -08004502 }
4503 }
4504 } break;
Craig Mautnerf3333272013-04-22 10:55:53 -07004505 case IDLE_TIMEOUT_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004506 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
4507 "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
Craig Mautnerf3333272013-04-22 10:55:53 -07004508 // We don't at this point know if the activity is fullscreen,
4509 // so we need to be conservative and assume it isn't.
Winson Chung4dabf232017-01-25 13:25:22 -08004510 activityIdleInternal((ActivityRecord) msg.obj,
4511 true /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004512 } break;
4513 case IDLE_NOW_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004514 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
Winson Chung4dabf232017-01-25 13:25:22 -08004515 activityIdleInternal((ActivityRecord) msg.obj,
4516 false /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004517 } break;
Craig Mautner05d29032013-05-03 13:40:13 -07004518 case RESUME_TOP_ACTIVITY_MSG: {
4519 synchronized (mService) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004520 resumeFocusedStackTopActivityLocked();
Craig Mautner05d29032013-05-03 13:40:13 -07004521 }
4522 } break;
Craig Mautner0eea92c2013-05-16 13:35:39 -07004523 case SLEEP_TIMEOUT_MSG: {
4524 synchronized (mService) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07004525 if (mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07004526 Slog.w(TAG, "Sleep timeout! Sleeping now.");
David Stevensf62360c2017-03-16 19:00:20 -07004527 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07004528 }
4529 }
4530 } break;
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004531 case LAUNCH_TIMEOUT_MSG: {
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004532 synchronized (mService) {
4533 if (mLaunchingActivity.isHeld()) {
4534 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
4535 if (VALIDATE_WAKE_LOCK_CALLER
4536 && Binder.getCallingUid() != Process.myUid()) {
4537 throw new IllegalStateException("Calling must be system uid");
4538 }
4539 mLaunchingActivity.release();
4540 }
4541 }
4542 } break;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004543 case HANDLE_DISPLAY_ADDED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004544 handleDisplayAdded(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004545 } break;
4546 case HANDLE_DISPLAY_CHANGED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004547 handleDisplayChanged(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004548 } break;
4549 case HANDLE_DISPLAY_REMOVED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004550 handleDisplayRemoved(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004551 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004552 case LOCK_TASK_START_MSG: {
4553 // When lock task starts, we disable the status bars.
4554 try {
Jason Monk62515be2014-05-21 16:06:19 -04004555 if (mLockTaskNotify == null) {
4556 mLockTaskNotify = new LockTaskNotify(mService.mContext);
justinzhang5286d3f2014-05-12 17:06:01 -04004557 }
Jason Monk62515be2014-05-21 16:06:19 -04004558 mLockTaskNotify.show(true);
Benjamin Franz43261142015-02-11 15:59:44 +00004559 mLockTaskModeState = msg.arg2;
Jason Monk62515be2014-05-21 16:06:19 -04004560 if (getStatusBarService() != null) {
Benjamin Franz43261142015-02-11 15:59:44 +00004561 int flags = 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004562 if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004563 flags = StatusBarManager.DISABLE_MASK
4564 & (~StatusBarManager.DISABLE_BACK);
Craig Mautner15df08a2015-04-01 12:17:18 -07004565 } else if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004566 flags = StatusBarManager.DISABLE_MASK
4567 & (~StatusBarManager.DISABLE_BACK)
4568 & (~StatusBarManager.DISABLE_HOME)
4569 & (~StatusBarManager.DISABLE_RECENT);
Jason Monk62515be2014-05-21 16:06:19 -04004570 }
4571 getStatusBarService().disable(flags, mToken,
4572 mService.mContext.getPackageName());
4573 }
4574 mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
Jason Monk35c62a42014-06-17 10:24:47 -04004575 if (getDevicePolicyManager() != null) {
4576 getDevicePolicyManager().notifyLockTaskModeChanged(true,
Jason Monk62515be2014-05-21 16:06:19 -04004577 (String)msg.obj, msg.arg1);
Jason Monk35c62a42014-06-17 10:24:47 -04004578 }
justinzhang5286d3f2014-05-12 17:06:01 -04004579 } catch (RemoteException ex) {
4580 throw new RuntimeException(ex);
4581 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004582 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004583 case LOCK_TASK_END_MSG: {
4584 // When lock task ends, we enable the status bars.
4585 try {
Jason Monk62515be2014-05-21 16:06:19 -04004586 if (getStatusBarService() != null) {
4587 getStatusBarService().disable(StatusBarManager.DISABLE_NONE, mToken,
4588 mService.mContext.getPackageName());
4589 }
4590 mWindowManager.reenableKeyguard(mToken);
Jason Monk35c62a42014-06-17 10:24:47 -04004591 if (getDevicePolicyManager() != null) {
4592 getDevicePolicyManager().notifyLockTaskModeChanged(false, null,
4593 msg.arg1);
4594 }
Jason Monk62515be2014-05-21 16:06:19 -04004595 if (mLockTaskNotify == null) {
4596 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4597 }
4598 mLockTaskNotify.show(false);
4599 try {
Amith Yamasani3ab9b4d2017-08-28 09:41:22 -07004600 boolean shouldLockKeyguard = Settings.Secure.getIntForUser(
Jason Monk62515be2014-05-21 16:06:19 -04004601 mService.mContext.getContentResolver(),
Amith Yamasani3ab9b4d2017-08-28 09:41:22 -07004602 Settings.Secure.LOCK_TO_APP_EXIT_LOCKED,
4603 UserHandle.USER_CURRENT) != 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004604 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED && shouldLockKeyguard) {
Jason Monk62515be2014-05-21 16:06:19 -04004605 mWindowManager.lockNow(null);
Jorim Jaggi241ae102016-11-02 21:57:33 -07004606 mWindowManager.dismissKeyguard(null /* callback */);
Jason Monke0697792014-08-04 16:28:09 -04004607 new LockPatternUtils(mService.mContext)
4608 .requireCredentialEntry(UserHandle.USER_ALL);
Jason Monk62515be2014-05-21 16:06:19 -04004609 }
4610 } catch (SettingNotFoundException e) {
4611 // No setting, don't lock.
4612 }
justinzhang5286d3f2014-05-12 17:06:01 -04004613 } catch (RemoteException ex) {
4614 throw new RuntimeException(ex);
Benjamin Franz43261142015-02-11 15:59:44 +00004615 } finally {
Craig Mautner15df08a2015-04-01 12:17:18 -07004616 mLockTaskModeState = LOCK_TASK_MODE_NONE;
justinzhang5286d3f2014-05-12 17:06:01 -04004617 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004618 } break;
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004619 case SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG: {
4620 if (mLockTaskNotify == null) {
4621 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4622 }
4623 mLockTaskNotify.showToast(LOCK_TASK_MODE_PINNED);
4624 } break;
Craig Mautnerbb742462014-07-07 15:28:55 -07004625 case LAUNCH_TASK_BEHIND_COMPLETE: {
4626 synchronized (mService) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07004627 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
Craig Mautnerbb742462014-07-07 15:28:55 -07004628 if (r != null) {
4629 handleLaunchTaskBehindCompleteLocked(r);
4630 }
4631 }
4632 } break;
Chong Zhangc806d902015-11-30 09:44:27 -08004633
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004634 }
4635 }
4636 }
Craig Mautnered6649f2013-12-02 14:08:25 -08004637
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004638 // TODO: Move to its own file.
Craig Mautner4a1cb222013-12-04 16:14:06 -08004639 /** Exactly one of these classes per Display in the system. Capable of holding zero or more
4640 * attached {@link ActivityStack}s */
Andrii Kulian1779e612016-10-12 21:58:25 -07004641 class ActivityDisplay extends ConfigurationContainer {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004642 /** Actual Display this object tracks. */
Craig Mautner34b73df2014-01-12 21:11:08 -08004643 int mDisplayId;
4644 Display mDisplay;
Craig Mautnered6649f2013-12-02 14:08:25 -08004645
Craig Mautner4a1cb222013-12-04 16:14:06 -08004646 /** All of the stacks on this display. Order matters, topmost stack is in front of all other
4647 * stacks, bottommost behind. Accessed directly by ActivityManager package classes */
Wale Ogunwale1f544be2015-12-17 10:27:23 -08004648 final ArrayList<ActivityStack> mStacks = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004649
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004650 /** Array of all UIDs that are present on the display. */
4651 private IntArray mDisplayAccessUIDs = new IntArray();
4652
David Stevensf62360c2017-03-16 19:00:20 -07004653 /** All tokens used to put activities on this stack to sleep (including mOffToken) */
4654 final ArrayList<SleepTokenImpl> mAllSleepTokens = new ArrayList<>();
4655 /** The token acquired by ActivityStackSupervisor to put stacks on the display to sleep */
4656 SleepToken mOffToken;
4657
4658 private boolean mSleeping;
4659
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004660 @VisibleForTesting
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004661 ActivityDisplay() {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004662 mActivityDisplays.put(mDisplayId, this);
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004663 }
Craig Mautner4504de52013-12-20 09:06:56 -08004664
Craig Mautner1a70a162014-09-13 12:09:31 -07004665 // After instantiation, check that mDisplay is not null before using this. The alternative
4666 // is for this to throw an exception if mDisplayManager.getDisplay() returns null.
Craig Mautnere0a38842013-12-16 16:14:02 -08004667 ActivityDisplay(int displayId) {
Craig Mautner1a70a162014-09-13 12:09:31 -07004668 final Display display = mDisplayManager.getDisplay(displayId);
4669 if (display == null) {
4670 return;
4671 }
4672 init(display);
Craig Mautner4504de52013-12-20 09:06:56 -08004673 }
4674
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004675 void init(Display display) {
Craig Mautner4504de52013-12-20 09:06:56 -08004676 mDisplay = display;
4677 mDisplayId = display.getDisplayId();
Craig Mautnered6649f2013-12-02 14:08:25 -08004678 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004679
Winson Chung7c3ede32017-03-14 14:18:34 -07004680 void attachStack(ActivityStack stack, int position) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08004681 if (DEBUG_STACK) Slog.v(TAG_STACK, "attachStack: attaching " + stack
Winson Chung7c3ede32017-03-14 14:18:34 -07004682 + " to displayId=" + mDisplayId + " position=" + position);
4683 mStacks.add(position, stack);
David Stevensf62360c2017-03-16 19:00:20 -07004684 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004685 }
4686
Wale Ogunwale1666e312016-12-16 11:27:18 -08004687 void detachStack(ActivityStack stack) {
4688 if (DEBUG_STACK) Slog.v(TAG_STACK, "detachStack: detaching " + stack
Craig Mautnere0a38842013-12-16 16:14:02 -08004689 + " from displayId=" + mDisplayId);
4690 mStacks.remove(stack);
David Stevensf62360c2017-03-16 19:00:20 -07004691 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004692 }
4693
Craig Mautner34b73df2014-01-12 21:11:08 -08004694 @Override
4695 public String toString() {
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004696 return "ActivityDisplay={" + mDisplayId + " numStacks=" + mStacks.size() + "}";
4697 }
Andrii Kulian1779e612016-10-12 21:58:25 -07004698
4699 @Override
4700 protected int getChildCount() {
4701 return mStacks.size();
4702 }
4703
4704 @Override
4705 protected ConfigurationContainer getChildAt(int index) {
4706 return mStacks.get(index);
4707 }
4708
4709 @Override
4710 protected ConfigurationContainer getParent() {
4711 return ActivityStackSupervisor.this;
4712 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004713
4714 boolean isPrivate() {
4715 return (mDisplay.getFlags() & FLAG_PRIVATE) != 0;
4716 }
4717
4718 boolean isUidPresent(int uid) {
4719 for (ActivityStack stack : mStacks) {
4720 if (stack.isUidPresent(uid)) {
4721 return true;
4722 }
4723 }
4724 return false;
4725 }
4726
4727 /** Update and get all UIDs that are present on the display and have access to it. */
4728 private IntArray getPresentUIDs() {
4729 mDisplayAccessUIDs.clear();
4730 for (ActivityStack stack : mStacks) {
4731 stack.getPresentUIDs(mDisplayAccessUIDs);
4732 }
4733 return mDisplayAccessUIDs;
4734 }
Andrii Kulian250d6532017-02-08 23:30:45 -08004735
4736 boolean shouldDestroyContentOnRemove() {
4737 return mDisplay.getRemoveMode() == REMOVE_MODE_DESTROY_CONTENT;
4738 }
David Stevensf62360c2017-03-16 19:00:20 -07004739
4740 boolean shouldSleep() {
4741 return (mStacks.isEmpty() || !mAllSleepTokens.isEmpty())
4742 && (mService.mRunningVoice == null);
4743 }
4744
4745 boolean isSleeping() {
4746 return mSleeping;
4747 }
4748
4749 void setIsSleeping(boolean asleep) {
4750 mSleeping = asleep;
4751 }
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004752 }
4753
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004754 ActivityStack findStackBehind(ActivityStack stack) {
4755 // TODO(multi-display): We are only looking for stacks on the default display.
Jorim Jaggife762342016-10-13 14:33:27 +02004756 final ActivityDisplay display = mActivityDisplays.get(DEFAULT_DISPLAY);
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004757 if (display == null) {
4758 return null;
4759 }
4760 final ArrayList<ActivityStack> stacks = display.mStacks;
4761 for (int i = stacks.size() - 1; i >= 0; i--) {
4762 if (stacks.get(i) == stack && i > 0) {
4763 return stacks.get(i - 1);
4764 }
4765 }
4766 throw new IllegalStateException("Failed to find a stack behind stack=" + stack
4767 + " in=" + stacks);
4768 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004769
Jorim Jaggic69bd222016-03-15 14:38:37 +01004770 /**
4771 * Puts a task into resizing mode during the next app transition.
4772 *
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004773 * @param task The task to put into resizing mode
Jorim Jaggic69bd222016-03-15 14:38:37 +01004774 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004775 private void setResizingDuringAnimation(TaskRecord task) {
4776 mResizingTasksDuringAnimation.add(task.taskId);
4777 task.setTaskDockedResizing(true);
Jorim Jaggic69bd222016-03-15 14:38:37 +01004778 }
4779
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004780 final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
4781 final TaskRecord task;
4782 final int callingUid;
4783 final String callingPackage;
4784 final Intent intent;
4785 final int userId;
4786 final ActivityOptions activityOptions = (bOptions != null)
4787 ? new ActivityOptions(bOptions) : null;
4788 final int launchStackId = (activityOptions != null)
4789 ? activityOptions.getLaunchStackId() : INVALID_STACK_ID;
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004790 if (StackId.isHomeOrRecentsStack(launchStackId)) {
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004791 throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004792 + taskId + " can't be launch in the home/recents stack.");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004793 }
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004794
Matthew Ng606dd802017-06-05 14:06:32 -07004795 mWindowManager.deferSurfaceLayout();
4796 try {
4797 if (launchStackId == DOCKED_STACK_ID) {
4798 mWindowManager.setDockedStackCreateState(
4799 activityOptions.getDockCreateMode(), null /* initialBounds */);
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004800
Matthew Ng606dd802017-06-05 14:06:32 -07004801 // Defer updating the stack in which recents is until the app transition is done, to
4802 // not run into issues where we still need to draw the task in recents but the
4803 // docked stack is already created.
4804 deferUpdateBounds(RECENTS_STACK_ID);
4805 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004806 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004807
Matthew Ng606dd802017-06-05 14:06:32 -07004808 task = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
4809 launchStackId);
4810 if (task == null) {
4811 continueUpdateBounds(RECENTS_STACK_ID);
4812 mWindowManager.executeAppTransition();
4813 throw new IllegalArgumentException(
4814 "startActivityFromRecentsInner: Task " + taskId + " not found.");
4815 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004816
Matthew Ng606dd802017-06-05 14:06:32 -07004817 // Since we don't have an actual source record here, we assume that the currently
4818 // focused activity was the source.
4819 final ActivityStack focusedStack = getFocusedStack();
4820 final ActivityRecord sourceRecord =
4821 focusedStack != null ? focusedStack.topActivity() : null;
4822
4823 if (launchStackId != INVALID_STACK_ID) {
4824 if (task.getStackId() != launchStackId) {
4825 task.reparent(launchStackId, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE,
4826 DEFER_RESUME, "startActivityFromRecents");
4827 }
4828 }
4829
4830 // If the user must confirm credentials (e.g. when first launching a work app and the
4831 // Work Challenge is present) let startActivityInPackage handle the intercepting.
4832 if (!mService.mUserController.shouldConfirmCredentials(task.userId)
4833 && task.getRootActivity() != null) {
Bryce Lee28d80422017-07-21 13:25:13 -07004834 final ActivityRecord targetActivity = task.getTopActivity();
4835
4836 mService.mActivityStarter.sendPowerHintForLaunchStartIfNeeded(true /* forceSend */,
4837 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004838 mActivityMetricsLogger.notifyActivityLaunching();
Jorim Jaggi42befc62017-06-13 11:54:04 -07004839 mService.moveTaskToFrontLocked(task.taskId, 0, bOptions, true /* fromRecents */);
Matthew Ng606dd802017-06-05 14:06:32 -07004840 mActivityMetricsLogger.notifyActivityLaunched(ActivityManager.START_TASK_TO_FRONT,
Bryce Lee28d80422017-07-21 13:25:13 -07004841 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004842
4843 // If we are launching the task in the docked stack, put it into resizing mode so
4844 // the window renders full-screen with the background filling the void. Also only
4845 // call this at the end to make sure that tasks exists on the window manager side.
4846 if (launchStackId == DOCKED_STACK_ID) {
4847 setResizingDuringAnimation(task);
4848 }
4849
4850 mService.mActivityStarter.postStartActivityProcessing(task.getTopActivity(),
4851 ActivityManager.START_TASK_TO_FRONT,
4852 sourceRecord != null
4853 ? sourceRecord.getTask().getStackId() : INVALID_STACK_ID,
4854 sourceRecord, task.getStack());
4855 return ActivityManager.START_TASK_TO_FRONT;
4856 }
4857 callingUid = task.mCallingUid;
4858 callingPackage = task.mCallingPackage;
4859 intent = task.intent;
4860 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4861 userId = task.userId;
4862 int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004863 null, null, 0, 0, bOptions, userId, task, "startActivityFromRecents");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004864 if (launchStackId == DOCKED_STACK_ID) {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004865 setResizingDuringAnimation(task);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004866 }
Matthew Ng606dd802017-06-05 14:06:32 -07004867 return result;
4868 } finally {
4869 mWindowManager.continueSurfaceLayout();
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004870 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004871 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004872
4873 /**
4874 * @return a list of activities which are the top ones in each visible stack. The first
4875 * entry will be the focused activity.
4876 */
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004877 List<IBinder> getTopVisibleActivities() {
4878 final ArrayList<IBinder> topActivityTokens = new ArrayList<>();
4879 // Traverse all displays.
Robert Carr22374c02017-02-21 13:01:47 -08004880 for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004881 final ActivityDisplay display = mActivityDisplays.valueAt(i);
4882 // Traverse all stacks on a display.
4883 for (int j = display.mStacks.size() - 1; j >= 0; j--) {
4884 final ActivityStack stack = display.mStacks.get(j);
4885 // Get top activity from a visible stack and add it to the list.
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004886 if (stack.shouldBeVisible(null /* starting */)
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004887 == ActivityStack.STACK_VISIBLE) {
4888 final ActivityRecord top = stack.topActivity();
4889 if (top != null) {
4890 if (stack == mFocusedStack) {
4891 topActivityTokens.add(0, top.appToken);
4892 } else {
4893 topActivityTokens.add(top.appToken);
4894 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004895 }
4896 }
4897 }
4898 }
4899 return topActivityTokens;
4900 }
Bryce Lee4a194382017-04-04 14:32:48 -07004901
4902 /**
4903 * Internal container to store a match qualifier alongside a WaitResult.
4904 */
4905 static class WaitInfo {
4906 private final ComponentName mTargetComponent;
4907 private final WaitResult mResult;
4908
4909 public WaitInfo(ComponentName targetComponent, WaitResult result) {
4910 this.mTargetComponent = targetComponent;
4911 this.mResult = result;
4912 }
4913
Wale Ogunwale3270f172017-04-26 07:29:42 -07004914 public boolean matches(ComponentName targetComponent) {
4915 return mTargetComponent == null || mTargetComponent.equals(targetComponent);
Bryce Lee4a194382017-04-04 14:32:48 -07004916 }
4917
4918 public WaitResult getResult() {
4919 return mResult;
4920 }
4921
4922 public ComponentName getComponent() {
4923 return mTargetComponent;
4924 }
4925
4926 public void dump(PrintWriter pw, String prefix) {
4927 pw.println(prefix + "WaitInfo:");
4928 pw.println(prefix + " mTargetComponent=" + mTargetComponent);
4929 pw.println(prefix + " mResult=");
4930 mResult.dump(pw, prefix);
4931 }
4932 }
David Stevensf62360c2017-03-16 19:00:20 -07004933
4934 private final class SleepTokenImpl extends SleepToken {
4935 private final String mTag;
4936 private final long mAcquireTime;
4937 private final int mDisplayId;
4938
4939 public SleepTokenImpl(String tag, int displayId) {
4940 mTag = tag;
4941 mDisplayId = displayId;
4942 mAcquireTime = SystemClock.uptimeMillis();
4943 }
4944
4945 @Override
4946 public void release() {
4947 synchronized (mService) {
4948 removeSleepTokenLocked(this);
4949 }
4950 }
4951
4952 @Override
4953 public String toString() {
4954 return "{\"" + mTag + "\", display " + mDisplayId
4955 + ", acquire at " + TimeUtils.formatUptime(mAcquireTime) + "}";
4956 }
4957 }
4958
Craig Mautner27084302013-03-25 08:05:25 -07004959}