blob: 590cc7c10afd3fd981a204b858c248fe0a3ef840 [file] [log] [blame]
Craig Mautner27084302013-03-25 08:05:25 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Andrii Kulian3a95edc2017-06-28 16:21:07 -070019import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Jorim Jaggife762342016-10-13 14:33:27 +020020import static android.Manifest.permission.START_ANY_ACTIVITY;
21import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
22import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
23import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
24import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
Jorim Jaggife762342016-10-13 14:33:27 +020025import static android.app.ActivityManager.START_TASK_TO_FRONT;
26import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
27import static android.app.ActivityManager.StackId.FIRST_DYNAMIC_STACK_ID;
28import static android.app.ActivityManager.StackId.FIRST_STATIC_STACK_ID;
29import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
30import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
31import static android.app.ActivityManager.StackId.HOME_STACK_ID;
32import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
33import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
34import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
Matthew Ng330757d2017-02-28 14:19:17 -080035import static android.app.ActivityManager.StackId.RECENTS_STACK_ID;
Andrii Kulian036e3ad2017-04-19 10:55:10 -070036import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
37import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Jorim Jaggife762342016-10-13 14:33:27 +020038import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070039import static android.os.Process.SYSTEM_UID;
chaviw59b98852017-06-13 12:05:44 -070040import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
Jorim Jaggife762342016-10-13 14:33:27 +020041import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
42import static android.view.Display.DEFAULT_DISPLAY;
Andrii Kulian16802aa2016-11-02 12:21:33 -070043import static android.view.Display.FLAG_PRIVATE;
44import static android.view.Display.INVALID_DISPLAY;
Andrii Kulian250d6532017-02-08 23:30:45 -080045import static android.view.Display.REMOVE_MODE_DESTROY_CONTENT;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070046import static android.view.Display.TYPE_VIRTUAL;
Jorim Jaggife762342016-10-13 14:33:27 +020047
Winson Chung47900652017-04-06 18:44:25 -070048import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN;
Jorim Jaggife762342016-10-13 14:33:27 +020049import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
Jorim Jaggife762342016-10-13 14:33:27 +020050import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
51import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
52import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
53import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
54import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
55import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
56import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
57import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
58import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
59import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020060import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONTAINERS;
61import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
62import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IDLE;
63import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
64import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
65import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
66import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
67import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
68import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
69import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
70import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020071import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
72import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
73import static com.android.server.am.ActivityManagerService.ANIMATE;
74import static com.android.server.am.ActivityManagerService.FIRST_SUPERVISOR_STACK_MSG;
75import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
76import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
Jorim Jaggife762342016-10-13 14:33:27 +020077import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
78import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
79import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
80import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
81import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
82import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
83import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
84import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
85import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
86import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
87import static com.android.server.am.ActivityStack.STACK_VISIBLE;
88import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
89import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
90import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
91import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
92import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
Winson Chung74666102017-02-22 17:49:24 -080093import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
94import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
95import static com.android.server.am.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
Jorim Jaggife762342016-10-13 14:33:27 +020096import static com.android.server.wm.AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS;
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -080097import static java.lang.Integer.MAX_VALUE;
Jorim Jaggife762342016-10-13 14:33:27 +020098
Svetoslav7008b512015-06-24 18:47:07 -070099import android.Manifest;
Winson Chung7900bee2017-03-10 08:59:25 -0800100import android.annotation.IntDef;
Andrii Kulian16802aa2016-11-02 12:21:33 -0700101import android.annotation.NonNull;
Tony Mak853304c2016-04-18 15:17:41 +0100102import android.annotation.UserIdInt;
Craig Mautner2420ead2013-04-01 17:13:20 -0700103import android.app.Activity;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700104import android.app.ActivityManager;
Filip Gruszczynski80e29f12015-12-14 14:58:30 -0800105import android.app.ActivityManager.RunningTaskInfo;
Wale Ogunwale3797c222015-10-27 14:21:58 -0700106import android.app.ActivityManager.StackId;
Craig Mautnered6649f2013-12-02 14:08:25 -0800107import android.app.ActivityManager.StackInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700108import android.app.ActivityOptions;
Svetoslav7008b512015-06-24 18:47:07 -0700109import android.app.AppOpsManager;
Jeff Hao1b012d32014-08-20 10:35:34 -0700110import android.app.ProfilerInfo;
Craig Mautner2420ead2013-04-01 17:13:20 -0700111import android.app.ResultInfo;
justinzhang5286d3f2014-05-12 17:06:01 -0400112import android.app.StatusBarManager;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700113import android.app.WaitResult;
Jason Monk35c62a42014-06-17 10:24:47 -0400114import android.app.admin.IDevicePolicyManager;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700115import android.content.ComponentName;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700116import android.content.Context;
117import android.content.Intent;
118import android.content.pm.ActivityInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700119import android.content.pm.ApplicationInfo;
Svetoslav7008b512015-06-24 18:47:07 -0700120import android.content.pm.PackageInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700121import android.content.pm.PackageManager;
122import android.content.pm.ResolveInfo;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100123import android.content.pm.UserInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700124import android.content.res.Configuration;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800125import android.graphics.Rect;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800126import android.hardware.display.DisplayManager;
127import android.hardware.display.DisplayManager.DisplayListener;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800128import android.hardware.display.DisplayManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800129import android.hardware.input.InputManagerInternal;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700130import android.os.Binder;
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100131import android.os.Bundle;
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700132import android.os.Debug;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700133import android.os.Handler;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700134import android.os.IBinder;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700135import android.os.Looper;
Craig Mautner2420ead2013-04-01 17:13:20 -0700136import android.os.Message;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700137import android.os.PowerManager;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700138import android.os.Process;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700139import android.os.RemoteException;
justinzhang5286d3f2014-05-12 17:06:01 -0400140import android.os.ServiceManager;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700141import android.os.SystemClock;
Wale Ogunwalecad05a02015-09-25 10:41:44 -0700142import android.os.Trace;
Craig Mautner6170f732013-04-02 13:05:23 -0700143import android.os.UserHandle;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100144import android.os.UserManager;
Dianne Hackborn3d07c942015-03-13 18:02:54 -0700145import android.os.WorkSource;
Svetoslav7008b512015-06-24 18:47:07 -0700146import android.provider.MediaStore;
Jason Monk62515be2014-05-21 16:06:19 -0400147import android.provider.Settings;
148import android.provider.Settings.SettingNotFoundException;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700149import android.service.voice.IVoiceInteractionSession;
Svetoslav7008b512015-06-24 18:47:07 -0700150import android.util.ArrayMap;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700151import android.util.ArraySet;
Craig Mautner2420ead2013-04-01 17:13:20 -0700152import android.util.EventLog;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800153import android.util.IntArray;
Wale Ogunwalee610d3d2017-04-25 10:23:48 -0700154import android.util.MergedConfiguration;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700155import android.util.Slog;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800156import android.util.SparseArray;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800157import android.util.SparseIntArray;
Craig Mautnered6649f2013-12-02 14:08:25 -0800158import android.view.Display;
Chong Zhangb15758a2015-11-17 12:12:03 -0800159
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700160import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800161import com.android.internal.content.ReferrerIntent;
Winson Chung14fbe142016-12-19 16:18:24 -0800162import com.android.internal.logging.MetricsLogger;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -0700163import com.android.internal.os.TransferPipe;
justinzhang5286d3f2014-05-12 17:06:01 -0400164import com.android.internal.statusbar.IStatusBarService;
Svetoslav7008b512015-06-24 18:47:07 -0700165import com.android.internal.util.ArrayUtils;
Jason Monke0697792014-08-04 16:28:09 -0400166import com.android.internal.widget.LockPatternUtils;
Jeff Brownca9bc702014-02-11 14:32:56 -0800167import com.android.server.LocalServices;
Craig Mautner2420ead2013-04-01 17:13:20 -0700168import com.android.server.am.ActivityStack.ActivityState;
Wale Ogunwale98d62312017-07-12 09:24:56 -0700169import com.android.server.wm.ConfigurationContainer;
Winson Chung19953ca2017-04-11 11:19:23 -0700170import com.android.server.wm.PinnedStackWindowController;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700171import com.android.server.wm.WindowManagerService;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700172
Craig Mautner8d341ef2013-03-26 09:03:27 -0700173import java.io.FileDescriptor;
174import java.io.IOException;
Craig Mautner27084302013-03-25 08:05:25 -0700175import java.io.PrintWriter;
Winson Chung7900bee2017-03-10 08:59:25 -0800176import java.lang.annotation.Retention;
177import java.lang.annotation.RetentionPolicy;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700178import java.util.ArrayList;
Craig Mautnere0570202015-05-13 13:06:11 -0700179import java.util.Arrays;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700180import java.util.List;
Wale Ogunwale540e1232015-05-01 15:35:39 -0700181import java.util.Set;
Craig Mautner27084302013-03-25 08:05:25 -0700182
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -0800183public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener {
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800184 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_AM;
Chong Zhang6cda19c2016-06-14 19:07:56 -0700185 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700186 private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
Craig Mautnere0570202015-05-13 13:06:11 -0700187 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700188 private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700189 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700190 private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700191 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700192 private static final String TAG_STATES = TAG + POSTFIX_STATES;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700193 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800194 static final String TAG_TASKS = TAG + POSTFIX_TASKS;
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800195
Craig Mautnerf3333272013-04-22 10:55:53 -0700196 /** How long we wait until giving up on the last activity telling us it is idle. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700197 static final int IDLE_TIMEOUT = 10 * 1000;
Craig Mautnerf3333272013-04-22 10:55:53 -0700198
Craig Mautner0eea92c2013-05-16 13:35:39 -0700199 /** How long we can hold the sleep wake lock before giving up. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700200 static final int SLEEP_TIMEOUT = 5 * 1000;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700201
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700202 // How long we can hold the launch wake lock before giving up.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700203 static final int LAUNCH_TIMEOUT = 10 * 1000;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700204
Craig Mautner05d29032013-05-03 13:40:13 -0700205 static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
206 static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
207 static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700208 static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700209 static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800210 static final int HANDLE_DISPLAY_ADDED = FIRST_SUPERVISOR_STACK_MSG + 5;
211 static final int HANDLE_DISPLAY_CHANGED = FIRST_SUPERVISOR_STACK_MSG + 6;
212 static final int HANDLE_DISPLAY_REMOVED = FIRST_SUPERVISOR_STACK_MSG + 7;
justinzhang5286d3f2014-05-12 17:06:01 -0400213 static final int LOCK_TASK_START_MSG = FIRST_SUPERVISOR_STACK_MSG + 9;
214 static final int LOCK_TASK_END_MSG = FIRST_SUPERVISOR_STACK_MSG + 10;
Wale Ogunwale73eba742015-04-07 14:23:14 -0700215 static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
Craig Mautnerc21ae9e2015-04-15 09:45:42 -0700216 static final int SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG = FIRST_SUPERVISOR_STACK_MSG + 13;
Wale Ogunwale22e25262016-02-01 10:32:02 -0800217 static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
218 static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800219
Wale Ogunwale040b4702015-08-06 18:10:50 -0700220 private static final String VIRTUAL_DISPLAY_BASE_NAME = "ActivityViewVirtualDisplay";
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700221
Jason Monk62515be2014-05-21 16:06:19 -0400222 private static final String LOCK_TASK_TAG = "Lock-to-App";
223
Wale Ogunwale040b4702015-08-06 18:10:50 -0700224 // Used to indicate if an object (e.g. stack) that we are trying to get
225 // should be created if it doesn't exist already.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800226 static final boolean CREATE_IF_NEEDED = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700227
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700228 // Used to indicate that windows of activities should be preserved during the resize.
229 static final boolean PRESERVE_WINDOWS = true;
230
Wale Ogunwale040b4702015-08-06 18:10:50 -0700231 // Used to indicate if an object (e.g. task) should be moved/created
232 // at the top of its container (e.g. stack).
Wale Ogunwaleb30daaa2015-08-07 21:50:49 -0700233 static final boolean ON_TOP = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700234
235 // Used to indicate that an objects (e.g. task) removal from its container
236 // (e.g. stack) is due to it moving to another container.
237 static final boolean MOVING = true;
238
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700239 // Force the focus to change to the stack we are moving a task to..
240 static final boolean FORCE_FOCUS = true;
241
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700242 // Don't execute any calls to resume.
243 static final boolean DEFER_RESUME = true;
244
Winson Chung010927a2016-12-15 16:12:35 -0800245 // Used to indicate that a task is removed it should also be removed from recents.
246 static final boolean REMOVE_FROM_RECENTS = true;
247
Winson Chung6954fc92017-03-24 16:22:12 -0700248 // Used to indicate that pausing an activity should occur immediately without waiting for
249 // the activity callback indicating that it has completed pausing
250 static final boolean PAUSE_IMMEDIATELY = true;
251
Winson Chung7900bee2017-03-10 08:59:25 -0800252 /**
253 * The modes which affect which tasks are returned when calling
254 * {@link ActivityStackSupervisor#anyTaskForIdLocked(int)}.
255 */
256 @Retention(RetentionPolicy.SOURCE)
257 @IntDef({
258 MATCH_TASK_IN_STACKS_ONLY,
259 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
260 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
261 })
262 public @interface AnyTaskForIdMatchTaskMode {}
263 // Match only tasks in the current stacks
264 static final int MATCH_TASK_IN_STACKS_ONLY = 0;
265 // Match either tasks in the current stacks, or in the recent tasks if not found in the stacks
266 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS = 1;
267 // Match either tasks in the current stacks, or in the recent tasks, restoring it to the
268 // provided stack id
269 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE = 2;
270
Svetoslav7008b512015-06-24 18:47:07 -0700271 // Activity actions an app cannot start if it uses a permission which is not granted.
272 private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION =
273 new ArrayMap<>();
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700274
Svetoslav7008b512015-06-24 18:47:07 -0700275 static {
276 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE,
277 Manifest.permission.CAMERA);
278 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE,
279 Manifest.permission.CAMERA);
280 ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL,
281 Manifest.permission.CALL_PHONE);
282 }
283
Svet Ganov99b60432015-06-27 13:15:22 -0700284 /** Action restriction: launching the activity is not restricted. */
285 private static final int ACTIVITY_RESTRICTION_NONE = 0;
286 /** Action restriction: launching the activity is restricted by a permission. */
287 private static final int ACTIVITY_RESTRICTION_PERMISSION = 1;
288 /** Action restriction: launching the activity is restricted by an app op. */
289 private static final int ACTIVITY_RESTRICTION_APPOP = 2;
Svetoslav7008b512015-06-24 18:47:07 -0700290
justinzhang5286d3f2014-05-12 17:06:01 -0400291 /** Status Bar Service **/
292 private IBinder mToken = new Binder();
293 private IStatusBarService mStatusBarService;
Jason Monk35c62a42014-06-17 10:24:47 -0400294 private IDevicePolicyManager mDevicePolicyManager;
justinzhang5286d3f2014-05-12 17:06:01 -0400295
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700296 // For debugging to make sure the caller when acquiring/releasing our
297 // wake lock is the system process.
298 static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800299 /** The number of distinct task ids that can be assigned to the tasks of a single user */
300 private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
Craig Mautnerf3333272013-04-22 10:55:53 -0700301
Craig Mautner27084302013-03-25 08:05:25 -0700302 final ActivityManagerService mService;
303
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800304 private RecentTasks mRecentTasks;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800305
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700306 final ActivityStackSupervisorHandler mHandler;
307
308 /** Short cut */
309 WindowManagerService mWindowManager;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800310 DisplayManager mDisplayManager;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700311
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -0700312 /** Counter for next free stack ID to use for dynamic activity stacks. */
313 private int mNextFreeStackId = FIRST_DYNAMIC_STACK_ID;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700314
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800315 /**
316 * Maps the task identifier that activities are currently being started in to the userId of the
317 * task. Each time a new task is created, the entry for the userId of the task is incremented
318 */
319 private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20);
Craig Mautner8d341ef2013-03-26 09:03:27 -0700320
Craig Mautner2420ead2013-04-01 17:13:20 -0700321 /** The current user */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800322 int mCurrentUser;
Craig Mautner2420ead2013-04-01 17:13:20 -0700323
Craig Mautnere0a38842013-12-16 16:14:02 -0800324 /** The stack containing the launcher app. Assumed to always be attached to
325 * Display.DEFAULT_DISPLAY. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800326 ActivityStack mHomeStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700327
Craig Mautnere0a38842013-12-16 16:14:02 -0800328 /** The stack currently receiving input or launching the next activity. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800329 ActivityStack mFocusedStack;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700330
Craig Mautner4a1cb222013-12-04 16:14:06 -0800331 /** If this is the same as mFocusedStack then the activity on the top of the focused stack has
332 * been resumed. If stacks are changing position this will hold the old stack until the new
Craig Mautnere0a38842013-12-16 16:14:02 -0800333 * stack becomes resumed after which it will be set to mFocusedStack. */
Craig Mautner4a1cb222013-12-04 16:14:06 -0800334 private ActivityStack mLastFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -0700335
336 /** List of activities that are waiting for a new activity to become visible before completing
337 * whatever operation they are supposed to do. */
Bryce Lee4a194382017-04-04 14:32:48 -0700338 // TODO: Remove mActivitiesWaitingForVisibleActivity list and just remove activity from
339 // mStoppingActivities when something else comes up.
340 final ArrayList<ActivityRecord> mActivitiesWaitingForVisibleActivity = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700341
Bryce Lee4a194382017-04-04 14:32:48 -0700342 /** List of processes waiting to find out when a specific activity becomes visible. */
343 private final ArrayList<WaitInfo> mWaitingForActivityVisible = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700344
345 /** List of processes waiting to find out about the next launched activity. */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700346 final ArrayList<WaitResult> mWaitingActivityLaunched = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700347
Craig Mautnerde4ef022013-04-07 19:01:33 -0700348 /** List of activities that are ready to be stopped, but waiting for the next activity to
349 * settle down before doing so. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800350 final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700351
Craig Mautnerf3333272013-04-22 10:55:53 -0700352 /** List of activities that are ready to be finished, but waiting for the previous activity to
353 * settle down before doing so. It contains ActivityRecord objects. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800354 final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700355
Craig Mautner0eea92c2013-05-16 13:35:39 -0700356 /** List of activities that are in the process of going to sleep. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800357 final ArrayList<ActivityRecord> mGoingToSleepActivities = new ArrayList<>();
Craig Mautner0eea92c2013-05-16 13:35:39 -0700358
Wale Ogunwale22e25262016-02-01 10:32:02 -0800359 /** List of activities whose multi-window mode changed that we need to report to the
360 * application */
361 final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
362
363 /** List of activities whose picture-in-picture mode changed that we need to report to the
364 * application */
365 final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
366
Winson Chung5af42fc2017-03-24 17:11:33 -0700367 /** The target stack bounds for the picture-in-picture mode changed that we need to report to
368 * the application */
369 Rect mPipModeChangedTargetStackBounds;
370
Craig Mautnerf3333272013-04-22 10:55:53 -0700371 /** Used on user changes */
Amith Yamasani37a40c22015-06-17 13:25:42 -0700372 final ArrayList<UserState> mStartingUsers = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700373
Craig Mautnerde4ef022013-04-07 19:01:33 -0700374 /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity
375 * is being brought in front of us. */
376 boolean mUserLeaving = false;
377
Craig Mautner0eea92c2013-05-16 13:35:39 -0700378 /** Set when we have taken too long waiting to go to sleep. */
379 boolean mSleepTimeout = false;
380
381 /**
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
Craig Mautner4f1df4f2013-10-15 15:44:14 -0700396 /** Stack id of the front stack when user switched, indexed by userId. */
397 SparseIntArray mUserStackInFront = new SparseIntArray(2);
Craig Mautner93529a42013-10-04 15:03:13 -0700398
Craig Mautner4504de52013-12-20 09:06:56 -0800399 // TODO: Add listener for removal of references.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800400 /** Mapping from (ActivityStack/TaskStack).mStackId to their current state */
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700401 SparseArray<ActivityStack> mStacks = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800402
Bryce Leeaf3a4002017-03-20 10:37:12 -0700403 // TODO: There should be an ActivityDisplayController coordinating am/wm interaction.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800404 /** Mapping from displayId to display current state */
Craig Mautner15df08a2015-04-01 12:17:18 -0700405 private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800406
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800407 private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>();
408
409 private DisplayManagerInternal mDisplayManagerInternal;
410 private InputManagerInternal mInputManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800411
Craig Mautner15df08a2015-04-01 12:17:18 -0700412 /** The chain of tasks in lockTask mode. The current frontmost task is at the top, and tasks
413 * may be finished until there is only one entry left. If this is empty the system is not
414 * in lockTask mode. */
415 ArrayList<TaskRecord> mLockTaskModeTasks = new ArrayList<>();
Benjamin Franz43261142015-02-11 15:59:44 +0000416 /** Store the current lock task mode. Possible values:
Craig Mautner2568c3a2015-03-26 14:22:34 -0700417 * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
418 * {@link ActivityManager#LOCK_TASK_MODE_PINNED}
Benjamin Franz43261142015-02-11 15:59:44 +0000419 */
420 private int mLockTaskModeState;
Jason Monk62515be2014-05-21 16:06:19 -0400421 /**
422 * Notifies the user when entering/exiting lock-task.
423 */
424 private LockTaskNotify mLockTaskNotify;
Craig Mautneraea74a52014-03-08 14:23:10 -0800425
Wale Ogunwaled046a012015-12-24 13:05:59 -0800426 /** Used to keep resumeTopActivityUncheckedLocked() from being entered recursively */
Craig Mautner42d04db2014-11-06 12:13:23 -0800427 boolean inResumeTopActivity;
428
Andrii Kulian1e32e022016-09-16 15:29:34 -0700429 /**
430 * Temporary rect used during docked stack resize calculation so we don't need to create a new
431 * object each time.
432 */
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700433 private final Rect tempRect = new Rect();
Filip Gruszczynskiebcc8752015-08-25 16:51:05 -0700434
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700435 // The default minimal size that will be used if the activity doesn't specify its minimal size.
436 // It will be calculated when the default display gets added.
Andrii Kulianf66a83d2016-05-17 12:17:44 -0700437 int mDefaultMinSizeOfResizeableTask = -1;
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700438
Chong Zhangfdcc4d42015-10-14 16:50:12 -0700439 // Whether tasks have moved and we need to rank the tasks before next OOM scoring
440 private boolean mTaskLayersChanged = true;
441
Jorim Jaggi275561a2016-02-23 10:11:02 -0500442 final ActivityMetricsLogger mActivityMetricsLogger;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800443
Andrii Kulian1779e612016-10-12 21:58:25 -0700444 @Override
445 protected int getChildCount() {
446 return mActivityDisplays.size();
447 }
448
449 @Override
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700450 protected ActivityDisplay getChildAt(int index) {
Andrii Kulian1779e612016-10-12 21:58:25 -0700451 return mActivityDisplays.valueAt(index);
452 }
453
454 @Override
455 protected ConfigurationContainer getParent() {
456 return null;
457 }
458
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700459 Configuration getDisplayOverrideConfiguration(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700460 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700461 if (activityDisplay == null) {
462 throw new IllegalArgumentException("No display found with id: " + displayId);
463 }
464
465 return activityDisplay.getOverrideConfiguration();
466 }
467
468 void setDisplayOverrideConfiguration(Configuration overrideConfiguration, 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 activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
475 }
476
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700477 /** Check if placing task or activity on specified display is allowed. */
Andrii Kulian02689a72017-07-06 14:28:59 -0700478 boolean canPlaceEntityOnDisplay(int displayId, boolean resizeable, int callingPid,
479 int callingUid, ActivityInfo activityInfo) {
480 if (displayId == DEFAULT_DISPLAY) {
481 // No restrictions for the default display.
482 return true;
483 }
484 if (!mService.mSupportsMultiDisplay) {
485 // Can't launch on secondary displays if feature is not supported.
486 return false;
487 }
488 if (!resizeable && !displayConfigMatchesGlobal(displayId)) {
489 // Can't apply wrong configuration to non-resizeable activities.
490 return false;
491 }
492 if (!isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, displayId, activityInfo)) {
493 // Can't place activities to a display that has restricted launch rules.
494 // In this case the request should be made by explicitly adding target display id and
495 // by caller with corresponding permissions. See #isCallerAllowedToLaunchOnDisplay().
496 return false;
497 }
498 return true;
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700499 }
500
501 /**
502 * Check if configuration of specified display matches current global config.
503 * Used to check if we can put a non-resizeable activity on a secondary display and it will get
504 * the same config as on the default display.
505 * @param displayId Id of the display to check.
506 * @return {@code true} if configuration matches.
507 */
508 private boolean displayConfigMatchesGlobal(int displayId) {
509 if (displayId == DEFAULT_DISPLAY) {
510 return true;
511 }
512 if (displayId == INVALID_DISPLAY) {
513 return false;
514 }
Andrii Kulian62e6f252017-05-30 22:46:53 -0700515 final ActivityDisplay targetDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700516 if (targetDisplay == null) {
517 throw new IllegalArgumentException("No display found with id: " + displayId);
518 }
519 return getConfiguration().equals(targetDisplay.getConfiguration());
520 }
521
Wale Ogunwale39381972015-12-17 17:15:29 -0800522 static class FindTaskResult {
523 ActivityRecord r;
524 boolean matchedByRootAffinity;
525 }
526 private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
527
Craig Mautneree36c772014-07-16 14:56:05 -0700528 /**
Andrii Kulian7fc22812016-12-28 13:04:11 -0800529 * Temp storage for display ids sorted in focus order.
530 * Maps position to id. Using {@link SparseIntArray} instead of {@link ArrayList} because
531 * it's more efficient, as the number of displays is usually small.
532 */
533 private SparseIntArray mTmpOrderedDisplayIds = new SparseIntArray();
534
535 /**
Jorim Jaggia0fdeec2016-01-07 14:42:28 +0100536 * Used to keep track whether app visibilities got changed since the last pause. Useful to
537 * determine whether to invoke the task stack change listener after pausing.
538 */
539 boolean mAppVisibilitiesChangedSinceLastPause;
540
541 /**
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100542 * Set of tasks that are in resizing mode during an app transition to fill the "void".
543 */
544 private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
545
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700546
547 /**
548 * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked}
549 * will be ignored. Useful for the case where the caller is handling resizing of other stack and
550 * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger
551 * like the docked stack going empty.
552 */
553 private boolean mAllowDockedStackResize = true;
554
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100555 /**
Tony Mak853304c2016-04-18 15:17:41 +0100556 * Is dock currently minimized.
557 */
558 boolean mIsDockMinimized;
559
Jorim Jaggife762342016-10-13 14:33:27 +0200560 final KeyguardController mKeyguardController;
561
chaviw59b98852017-06-13 12:05:44 -0700562 private PowerManager mPowerManager;
563 private int mDeferResumeCount;
564
Tony Mak853304c2016-04-18 15:17:41 +0100565 /**
Craig Mautneree36c772014-07-16 14:56:05 -0700566 * Description of a request to start a new activity, which has been held
567 * due to app switches being disabled.
568 */
569 static class PendingActivityLaunch {
570 final ActivityRecord r;
571 final ActivityRecord sourceRecord;
572 final int startFlags;
573 final ActivityStack stack;
Robert Carr13997f52015-10-23 13:13:39 -0700574 final ProcessRecord callerApp;
Craig Mautneree36c772014-07-16 14:56:05 -0700575
576 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
Robert Carr13997f52015-10-23 13:13:39 -0700577 int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
Craig Mautneree36c772014-07-16 14:56:05 -0700578 r = _r;
579 sourceRecord = _sourceRecord;
580 startFlags = _startFlags;
581 stack = _stack;
Robert Carr13997f52015-10-23 13:13:39 -0700582 callerApp = _callerApp;
583 }
584
585 void sendErrorResult(String message) {
586 try {
587 if (callerApp.thread != null) {
588 callerApp.thread.scheduleCrash(message);
589 }
590 } catch (RemoteException e) {
591 Slog.e(TAG, "Exception scheduling crash of failed "
592 + "activity launcher sourceRecord=" + sourceRecord, e);
593 }
Craig Mautneree36c772014-07-16 14:56:05 -0700594 }
595 }
596
Bryce Leeaf691c02017-03-20 14:20:22 -0700597 public ActivityStackSupervisor(ActivityManagerService service, Looper looper) {
Craig Mautner27084302013-03-25 08:05:25 -0700598 mService = service;
Bryce Leeaf691c02017-03-20 14:20:22 -0700599 mHandler = new ActivityStackSupervisorHandler(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800600 mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
Jorim Jaggife762342016-10-13 14:33:27 +0200601 mKeyguardController = new KeyguardController(service, this);
Jeff Brown2c43c332014-06-12 22:38:59 -0700602 }
603
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800604 void setRecentTasks(RecentTasks recentTasks) {
605 mRecentTasks = recentTasks;
606 }
607
Jeff Brown2c43c332014-06-12 22:38:59 -0700608 /**
609 * At the time when the constructor runs, the power manager has not yet been
610 * initialized. So we initialize our wakelocks afterwards.
611 */
612 void initPowerManagement() {
chaviw59b98852017-06-13 12:05:44 -0700613 mPowerManager = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
614 mGoingToSleep = mPowerManager
615 .newWakeLock(PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
616 mLaunchingActivity = mPowerManager.newWakeLock(PARTIAL_WAKE_LOCK, "*launch*");
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700617 mLaunchingActivity.setReferenceCounted(false);
Craig Mautner2219a1b2013-03-25 09:44:30 -0700618 }
619
justinzhang5286d3f2014-05-12 17:06:01 -0400620 // This function returns a IStatusBarService. The value is from ServiceManager.
621 // getService and is cached.
622 private IStatusBarService getStatusBarService() {
623 synchronized (mService) {
624 if (mStatusBarService == null) {
625 mStatusBarService = IStatusBarService.Stub.asInterface(
626 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
627 if (mStatusBarService == null) {
628 Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
629 }
630 }
631 return mStatusBarService;
632 }
633 }
634
Jason Monk35c62a42014-06-17 10:24:47 -0400635 private IDevicePolicyManager getDevicePolicyManager() {
636 synchronized (mService) {
637 if (mDevicePolicyManager == null) {
638 mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
639 ServiceManager.checkService(Context.DEVICE_POLICY_SERVICE));
640 if (mDevicePolicyManager == null) {
641 Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
642 }
643 }
644 return mDevicePolicyManager;
645 }
646 }
647
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700648 void setWindowManager(WindowManagerService wm) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800649 synchronized (mService) {
650 mWindowManager = wm;
Jorim Jaggife762342016-10-13 14:33:27 +0200651 mKeyguardController.setWindowManager(wm);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800652
653 mDisplayManager =
654 (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
655 mDisplayManager.registerDisplayListener(this, null);
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800656 mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800657
658 Display[] displays = mDisplayManager.getDisplays();
659 for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
660 final int displayId = displays[displayNdx].getDisplayId();
Craig Mautnere0a38842013-12-16 16:14:02 -0800661 ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
Craig Mautner1a70a162014-09-13 12:09:31 -0700662 if (activityDisplay.mDisplay == null) {
663 throw new IllegalStateException("Default Display does not exist");
664 }
Craig Mautnere0a38842013-12-16 16:14:02 -0800665 mActivityDisplays.put(displayId, activityDisplay);
Filip Gruszczynski7be9a8c2015-10-15 18:20:30 -0700666 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800667 }
668
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800669 mHomeStack = mFocusedStack = mLastFocusedStack =
670 getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Jeff Brownca9bc702014-02-11 14:32:56 -0800671
672 mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800673 }
Craig Mautner27084302013-03-25 08:05:25 -0700674 }
675
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700676 ActivityStack getFocusedStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800677 return mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700678 }
679
Craig Mautnerde4ef022013-04-07 19:01:33 -0700680 ActivityStack getLastStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800681 return mLastFocusedStack;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700682 }
683
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700684 boolean isFocusedStack(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700685 return stack != null && stack == mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700686 }
687
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800688 /** The top most stack on its display. */
689 boolean isFrontStackOnDisplay(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700690 return isFrontOfStackList(stack, stack.getDisplay().mStacks);
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800691 }
692
693 private boolean isFrontOfStackList(ActivityStack stack, List<ActivityStack> stackList) {
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800694 return stack == stackList.get((stackList.size() - 1));
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700695 }
696
Wale Ogunwaled046a012015-12-24 13:05:59 -0800697 /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800698 void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
699 if (!focusCandidate.isFocusable()) {
700 // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
Andrii Kulian7fc22812016-12-28 13:04:11 -0800701 focusCandidate = getNextFocusableStackLocked(focusCandidate);
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800702 }
703
704 if (focusCandidate != mFocusedStack) {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800705 mLastFocusedStack = mFocusedStack;
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800706 mFocusedStack = focusCandidate;
Wale Ogunwalecb82f302015-02-25 07:53:40 -0800707
Wale Ogunwaled046a012015-12-24 13:05:59 -0800708 EventLogTags.writeAmFocusedStack(
709 mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
710 mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
711 }
712
713 final ActivityRecord r = topRunningActivityLocked();
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800714 if (mService.mBooting || !mService.mBooted) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800715 if (r != null && r.idle) {
716 checkFinishBootingLocked();
717 }
718 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700719 }
720
Wale Ogunwale925d0d12015-09-23 15:40:07 -0700721 void moveHomeStackToFront(String reason) {
722 mHomeStack.moveToFront(reason);
723 }
724
Matthew Ng330757d2017-02-28 14:19:17 -0800725 void moveRecentsStackToFront(String reason) {
726 final ActivityStack recentsStack = getStack(RECENTS_STACK_ID);
727 if (recentsStack != null) {
728 recentsStack.moveToFront(reason);
729 }
730 }
731
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700732 /** Returns true if the focus activity was adjusted to the home stack top activity. */
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800733 boolean moveHomeStackTaskToTop(String reason) {
734 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700735
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700736 final ActivityRecord top = getHomeActivity();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700737 if (top == null) {
738 return false;
739 }
Chong Zhang6cda19c2016-06-14 19:07:56 -0700740 moveFocusableActivityStackToFrontLocked(top, reason);
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700741 return true;
Craig Mautner8e569572013-10-11 17:36:59 -0700742 }
743
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800744 boolean resumeHomeStackTask(ActivityRecord prev, String reason) {
Dianne Hackborn7622a0f2014-09-30 14:31:42 -0700745 if (!mService.mBooting && !mService.mBooted) {
746 // Not ready yet!
747 return false;
748 }
749
Craig Mautner84984fa2014-06-19 11:19:20 -0700750 if (prev != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -0700751 prev.getTask().setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
Craig Mautner84984fa2014-06-19 11:19:20 -0700752 }
753
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800754 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700755 ActivityRecord r = getHomeActivity();
Wale Ogunwaled046a012015-12-24 13:05:59 -0800756 final String myReason = reason + " resumeHomeStackTask";
757
Mark Lua56ea122015-10-08 13:31:01 +0800758 // Only resume home activity if isn't finishing.
759 if (r != null && !r.finishing) {
Chong Zhang6cda19c2016-06-14 19:07:56 -0700760 moveFocusableActivityStackToFrontLocked(r, myReason);
Wale Ogunwaled046a012015-12-24 13:05:59 -0800761 return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
Craig Mautner69ada552013-04-18 13:51:51 -0700762 }
Wale Ogunwaled046a012015-12-24 13:05:59 -0800763 return mService.startHomeActivityLocked(mCurrentUser, myReason);
Craig Mautner69ada552013-04-18 13:51:51 -0700764 }
765
Craig Mautner8d341ef2013-03-26 09:03:27 -0700766 TaskRecord anyTaskForIdLocked(int id) {
Winson Chung7900bee2017-03-10 08:59:25 -0800767 return anyTaskForIdLocked(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
768 INVALID_STACK_ID);
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700769 }
770
771 /**
Bryce Lee92b7b652017-04-03 08:33:11 -0700772 * Returns a {@link TaskRecord} for the input id if available. {@code null} otherwise.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700773 * @param id Id of the task we would like returned.
Winson Chung7900bee2017-03-10 08:59:25 -0800774 * @param matchMode The mode to match the given task id in.
Wale Ogunwale3797c222015-10-27 14:21:58 -0700775 * @param stackId The stack to restore the task to (default launch stack will be used if
Winson Chung7900bee2017-03-10 08:59:25 -0800776 * stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}). Only
777 * valid if the matchMode is
778 * {@link #MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE}.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700779 */
Winson Chung7900bee2017-03-10 08:59:25 -0800780 TaskRecord anyTaskForIdLocked(int id, @AnyTaskForIdMatchTaskMode int matchMode, int stackId) {
781 // If there is a stack id set, ensure that we are attempting to actually restore a task
782 if (matchMode != MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE &&
783 stackId != INVALID_STACK_ID) {
784 throw new IllegalArgumentException("Should not specify stackId for non-restore lookup");
785 }
786
Craig Mautnere0a38842013-12-16 16:14:02 -0800787 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800788 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800789 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800790 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
791 ActivityStack stack = stacks.get(stackNdx);
Bryce Lee92b7b652017-04-03 08:33:11 -0700792 final TaskRecord task = stack.taskForIdLocked(id);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800793 if (task != null) {
794 return task;
795 }
Craig Mautner8d341ef2013-03-26 09:03:27 -0700796 }
797 }
Wale Ogunwale7de05352014-12-12 15:21:33 -0800798
Winson Chung7900bee2017-03-10 08:59:25 -0800799 // If we are matching stack tasks only, return now
800 if (matchMode == MATCH_TASK_IN_STACKS_ONLY) {
Wale Ogunwale7de05352014-12-12 15:21:33 -0800801 return null;
802 }
803
Winson Chung7900bee2017-03-10 08:59:25 -0800804 // Otherwise, check the recent tasks and return if we find it there and we are not restoring
805 // the task from recents
806 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
Bryce Lee92b7b652017-04-03 08:33:11 -0700807 final TaskRecord task = mRecentTasks.taskForIdLocked(id);
808
809 if (task == null) {
810 if (DEBUG_RECENTS) {
Winson Chung7900bee2017-03-10 08:59:25 -0800811 Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
812 }
Bryce Lee92b7b652017-04-03 08:33:11 -0700813
814 return null;
815 }
816
817 if (matchMode == MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) {
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700818 return task;
819 }
820
Winson Chung7900bee2017-03-10 08:59:25 -0800821 // Implicitly, this case is MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
Wale Ogunwale7e8184b2015-10-05 14:37:03 -0700822 if (!restoreRecentTaskLocked(task, stackId)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700823 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
824 "Couldn't restore task id=" + id + " found in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800825 return null;
826 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700827 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800828 return task;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700829 }
830
Craig Mautner6170f732013-04-02 13:05:23 -0700831 ActivityRecord isInAnyStackLocked(IBinder token) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800832 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800833 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800834 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800835 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
836 final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
837 if (r != null) {
838 return r;
839 }
Craig Mautner6170f732013-04-02 13:05:23 -0700840 }
841 }
842 return null;
843 }
844
Tony Mak853304c2016-04-18 15:17:41 +0100845 /**
Robin Lee3fef1f22016-12-20 14:50:13 +0000846 * Detects whether we should show a lock screen in front of this task for a locked user.
847 * <p>
848 * We'll do this if either of the following holds:
849 * <ul>
850 * <li>The top activity explicitly belongs to {@param userId}.</li>
851 * <li>The top activity returns a result to an activity belonging to {@param userId}.</li>
852 * </ul>
853 *
854 * @return {@code true} if the top activity looks like it belongs to {@param userId}.
Tony Mak853304c2016-04-18 15:17:41 +0100855 */
Robin Lee3fef1f22016-12-20 14:50:13 +0000856 private boolean taskTopActivityIsUser(TaskRecord task, @UserIdInt int userId) {
857 // To handle the case that work app is in the task but just is not the top one.
858 final ActivityRecord activityRecord = task.getTopActivity();
859 final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null);
860
861 return (activityRecord != null && activityRecord.userId == userId)
862 || (resultTo != null && resultTo.userId == userId);
863 }
864
865 /**
866 * Find all visible task stacks containing {@param userId} and intercept them with an activity
867 * to block out the contents and possibly start a credential-confirming intent.
868 *
869 * @param userId user handle for the locked managed profile.
870 */
871 void lockAllProfileTasks(@UserIdInt int userId) {
872 mWindowManager.deferSurfaceLayout();
873 try {
874 final List<ActivityStack> stacks = getStacks();
875 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; stackNdx--) {
876 final List<TaskRecord> tasks = stacks.get(stackNdx).getAllTasks();
877 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) {
878 final TaskRecord task = tasks.get(taskNdx);
879
880 // Check the task for a top activity belonging to userId, or returning a result
881 // to an activity belonging to userId. Example case: a document picker for
882 // personal files, opened by a work app, should still get locked.
883 if (taskTopActivityIsUser(task, userId)) {
Robin Leec41f6ec2017-01-10 17:02:34 +0000884 mService.mTaskChangeNotificationController.notifyTaskProfileLocked(
885 task.taskId, userId);
Robin Lee3fef1f22016-12-20 14:50:13 +0000886 }
Tony Mak853304c2016-04-18 15:17:41 +0100887 }
888 }
Robin Lee3fef1f22016-12-20 14:50:13 +0000889 } finally {
890 mWindowManager.continueSurfaceLayout();
Tony Mak853304c2016-04-18 15:17:41 +0100891 }
Clara Bayarrif0649ce2016-01-14 12:30:42 +0000892 }
893
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800894 void setNextTaskIdForUserLocked(int taskId, int userId) {
895 final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
896 if (taskId > currentTaskId) {
897 mCurTaskIdForUser.put(userId, taskId);
Craig Mautneref73ee12014-04-23 11:45:37 -0700898 }
899 }
900
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700901 static int nextTaskIdForUser(int taskId, int userId) {
902 int nextTaskId = taskId + 1;
903 if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
904 // Wrap around as there will be smaller task ids that are available now.
905 nextTaskId -= MAX_TASK_IDS_PER_USER;
906 }
907 return nextTaskId;
908 }
909
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800910 int getNextTaskIdForUserLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800911 final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
912 // for a userId u, a taskId can only be in the range
913 // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
914 // 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 -0700915 int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800916 while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
Winson Chung7900bee2017-03-10 08:59:25 -0800917 || anyTaskForIdLocked(candidateTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800918 INVALID_STACK_ID) != null) {
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700919 candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800920 if (candidateTaskId == currentTaskId) {
921 // Something wrong!
922 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
923 throw new IllegalStateException("Cannot get an available task id."
924 + " Reached limit of " + MAX_TASK_IDS_PER_USER
925 + " running tasks per user.");
926 }
927 }
928 mCurTaskIdForUser.put(userId, candidateTaskId);
929 return candidateTaskId;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700930 }
931
Chong Zhang6cda19c2016-06-14 19:07:56 -0700932 ActivityRecord getResumedActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -0800933 ActivityStack stack = mFocusedStack;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700934 if (stack == null) {
935 return null;
936 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700937 ActivityRecord resumedActivity = stack.mResumedActivity;
938 if (resumedActivity == null || resumedActivity.app == null) {
939 resumedActivity = stack.mPausingActivity;
940 if (resumedActivity == null || resumedActivity.app == null) {
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -0700941 resumedActivity = stack.topRunningActivityLocked();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700942 }
943 }
944 return resumedActivity;
945 }
946
Dianne Hackbornff072722014-09-24 10:56:28 -0700947 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
Craig Mautner20e72272013-04-01 13:45:53 -0700948 final String processName = app.processName;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800949 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800950 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
951 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800952 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
953 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700954 if (!isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800955 continue;
956 }
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -0700957 ActivityRecord hr = stack.topRunningActivityLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800958 if (hr != null) {
959 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
960 && processName.equals(hr.processName)) {
961 try {
George Mount2c92c972014-03-20 09:38:23 -0700962 if (realStartActivityLocked(hr, app, true, true)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800963 didSomething = true;
964 }
Dianne Hackbornff072722014-09-24 10:56:28 -0700965 } catch (RemoteException e) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800966 Slog.w(TAG, "Exception in new application when starting activity "
967 + hr.intent.getComponent().flattenToShortString(), e);
968 throw e;
Craig Mautner20e72272013-04-01 13:45:53 -0700969 }
Craig Mautner20e72272013-04-01 13:45:53 -0700970 }
Craig Mautner20e72272013-04-01 13:45:53 -0700971 }
972 }
973 }
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700974 if (!didSomething) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700975 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700976 }
Craig Mautner20e72272013-04-01 13:45:53 -0700977 return didSomething;
978 }
979
980 boolean allResumedActivitiesIdle() {
Craig Mautnere0a38842013-12-16 16:14:02 -0800981 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
982 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800983 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
984 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700985 if (!isFocusedStack(stack) || stack.numActivities() == 0) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800986 continue;
987 }
988 final ActivityRecord resumedActivity = stack.mResumedActivity;
989 if (resumedActivity == null || !resumedActivity.idle) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700990 if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
Craig Mautner34b73df2014-01-12 21:11:08 -0800991 + stack.mStackId + " " + resumedActivity + " not idle");
Craig Mautner4a1cb222013-12-04 16:14:06 -0800992 return false;
993 }
Craig Mautner20e72272013-04-01 13:45:53 -0700994 }
995 }
Wei Wang65c7a152016-06-02 18:51:22 -0700996 // Send launch end powerhint when idle
997 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
Craig Mautner20e72272013-04-01 13:45:53 -0700998 return true;
999 }
1000
Craig Mautnerde4ef022013-04-07 19:01:33 -07001001 boolean allResumedActivitiesComplete() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001002 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1003 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001004 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1005 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001006 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001007 final ActivityRecord r = stack.mResumedActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001008 if (r != null && r.state != RESUMED) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001009 return false;
1010 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001011 }
1012 }
1013 }
1014 // TODO: Not sure if this should check if all Paused are complete too.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001015 if (DEBUG_STACK) Slog.d(TAG_STACK,
Craig Mautner4a1cb222013-12-04 16:14:06 -08001016 "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
1017 mLastFocusedStack + " to=" + mFocusedStack);
1018 mLastFocusedStack = mFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001019 return true;
1020 }
1021
1022 boolean allResumedActivitiesVisible() {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001023 boolean foundResumed = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001024 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1025 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001026 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1027 final ActivityStack stack = stacks.get(stackNdx);
1028 final ActivityRecord r = stack.mResumedActivity;
riddle_hsudb46d6b2015-04-01 18:58:07 +08001029 if (r != null) {
Bryce Lee4a194382017-04-04 14:32:48 -07001030 if (!r.nowVisible || mActivitiesWaitingForVisibleActivity.contains(r)) {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001031 return false;
1032 }
1033 foundResumed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001034 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001035 }
1036 }
riddle_hsudb46d6b2015-04-01 18:58:07 +08001037 return foundResumed;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001038 }
1039
Craig Mautner2acc3892013-09-23 10:28:14 -07001040 /**
1041 * Pause all activities in either all of the stacks or just the back stacks.
1042 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
Wale Ogunwale950faff2016-08-08 09:51:04 -07001043 * @param resuming The resuming activity.
1044 * @param dontWait The resuming activity isn't going to wait for all activities to be paused
1045 * before resuming.
Craig Mautner2acc3892013-09-23 10:28:14 -07001046 * @return true if any activity was paused as a result of this call.
1047 */
Wale Ogunwale950faff2016-08-08 09:51:04 -07001048 boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
Craig Mautnercf910b02013-04-23 11:23:27 -07001049 boolean someActivityPaused = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001050 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1051 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001052 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1053 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001054 if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001055 if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
Craig Mautner4a1cb222013-12-04 16:14:06 -08001056 " mResumedActivity=" + stack.mResumedActivity);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001057 someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
1058 dontWait);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001059 }
Craig Mautnercf910b02013-04-23 11:23:27 -07001060 }
1061 }
1062 return someActivityPaused;
1063 }
1064
Craig Mautnerde4ef022013-04-07 19:01:33 -07001065 boolean allPausedActivitiesComplete() {
Craig Mautnerac6f8432013-07-17 13:24:59 -07001066 boolean pausing = true;
Craig Mautnere0a38842013-12-16 16:14:02 -08001067 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1068 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001069 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1070 final ActivityStack stack = stacks.get(stackNdx);
1071 final ActivityRecord r = stack.mPausingActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001072 if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001073 if (DEBUG_STATES) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001074 Slog.d(TAG_STATES,
1075 "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001076 pausing = false;
1077 } else {
1078 return false;
1079 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001080 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001081 }
1082 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001083 return pausing;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001084 }
1085
Wale Ogunwale2be760d2016-02-17 11:16:10 -08001086 void cancelInitializingActivities() {
1087 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1088 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1089 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1090 stacks.get(stackNdx).cancelInitializingActivities();
1091 }
1092 }
1093 }
1094
Bryce Lee4a194382017-04-04 14:32:48 -07001095 void waitActivityVisible(ComponentName name, WaitResult result) {
1096 final WaitInfo waitInfo = new WaitInfo(name, result);
1097 mWaitingForActivityVisible.add(waitInfo);
1098 }
1099
1100 void cleanupActivity(ActivityRecord r) {
1101 // Make sure this record is no longer in the pending finishes list.
1102 // This could happen, for example, if we are trimming activities
1103 // down to the max limit while they are still waiting to finish.
1104 mFinishingActivities.remove(r);
1105 mActivitiesWaitingForVisibleActivity.remove(r);
1106
1107 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
Wale Ogunwale3270f172017-04-26 07:29:42 -07001108 if (mWaitingForActivityVisible.get(i).matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001109 mWaitingForActivityVisible.remove(i);
1110 }
1111 }
1112 }
1113
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001114 void reportActivityVisibleLocked(ActivityRecord r) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001115 sendWaitingVisibleReportLocked(r);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001116 }
1117
1118 void sendWaitingVisibleReportLocked(ActivityRecord r) {
1119 boolean changed = false;
Bryce Lee4a194382017-04-04 14:32:48 -07001120 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
1121 final WaitInfo w = mWaitingForActivityVisible.get(i);
Wale Ogunwale3270f172017-04-26 07:29:42 -07001122 if (w.matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001123 final WaitResult result = w.getResult();
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001124 changed = true;
Bryce Lee4a194382017-04-04 14:32:48 -07001125 result.timeout = false;
1126 result.who = w.getComponent();
1127 result.totalTime = SystemClock.uptimeMillis() - result.thisTime;
1128 result.thisTime = result.totalTime;
1129 mWaitingForActivityVisible.remove(w);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001130 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001131 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001132 if (changed) {
1133 mService.notifyAll();
1134 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001135 }
1136
Chong Zhang5022da32016-06-21 16:31:37 -07001137 void reportTaskToFrontNoLaunch(ActivityRecord r) {
1138 boolean changed = false;
1139 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1140 WaitResult w = mWaitingActivityLaunched.remove(i);
1141 if (w.who == null) {
1142 changed = true;
1143 // Set result to START_TASK_TO_FRONT so that startActivityMayWait() knows that
1144 // the starting activity ends up moving another activity to front, and it should
1145 // wait for this new activity to become visible instead.
1146 // Do not modify other fields.
1147 w.result = START_TASK_TO_FRONT;
1148 }
1149 }
1150 if (changed) {
1151 mService.notifyAll();
1152 }
1153 }
1154
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001155 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
1156 long thisTime, long totalTime) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001157 boolean changed = false;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001158 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
Craig Mautnerc64f73e2013-04-24 16:44:56 -07001159 WaitResult w = mWaitingActivityLaunched.remove(i);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001160 if (w.who == null) {
1161 changed = true;
1162 w.timeout = timeout;
1163 if (r != null) {
1164 w.who = new ComponentName(r.info.packageName, r.info.name);
1165 }
1166 w.thisTime = thisTime;
1167 w.totalTime = totalTime;
Chong Zhang5022da32016-06-21 16:31:37 -07001168 // Do not modify w.result.
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001169 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001170 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001171 if (changed) {
1172 mService.notifyAll();
1173 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001174 }
1175
Craig Mautner29219d92013-04-16 20:19:12 -07001176 ActivityRecord topRunningActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -08001177 final ActivityStack focusedStack = mFocusedStack;
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07001178 ActivityRecord r = focusedStack.topRunningActivityLocked();
Craig Mautner1602ec22013-05-12 10:24:27 -07001179 if (r != null) {
1180 return r;
Craig Mautner29219d92013-04-16 20:19:12 -07001181 }
Craig Mautner1602ec22013-05-12 10:24:27 -07001182
Andrii Kulian7318d632016-07-20 18:59:28 -07001183 // Look in other non-focused and non-home stacks.
Andrii Kulian7d95df42017-02-15 10:11:48 -08001184 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
1185
1186 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
1187 final int displayId = mTmpOrderedDisplayIds.get(i);
1188 final List<ActivityStack> stacks = mActivityDisplays.get(displayId).mStacks;
1189 if (stacks == null) {
1190 continue;
1191 }
1192 for (int j = stacks.size() - 1; j >= 0; --j) {
1193 final ActivityStack stack = stacks.get(j);
1194 if (stack != focusedStack && isFrontStackOnDisplay(stack) && stack.isFocusable()) {
1195 r = stack.topRunningActivityLocked();
1196 if (r != null) {
1197 return r;
1198 }
Craig Mautner29219d92013-04-16 20:19:12 -07001199 }
1200 }
1201 }
1202 return null;
1203 }
1204
Dianne Hackborn09233282014-04-30 11:33:59 -07001205 void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001206 // Gather all of the running tasks for each stack into runningTaskLists.
Craig Mautner4a1cb222013-12-04 16:14:06 -08001207 ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1208 new ArrayList<ArrayList<RunningTaskInfo>>();
Craig Mautnere0a38842013-12-16 16:14:02 -08001209 final int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001210 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08001211 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001212 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1213 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautner15df08a2015-04-01 12:17:18 -07001214 ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001215 runningTaskLists.add(stackTaskList);
Dianne Hackborn09233282014-04-30 11:33:59 -07001216 stack.getTasksLocked(stackTaskList, callingUid, allowed);
Craig Mautner20e72272013-04-01 13:45:53 -07001217 }
1218 }
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001219
1220 // The lists are already sorted from most recent to oldest. Just pull the most recent off
1221 // each list and add it to list. Stop when all lists are empty or maxNum reached.
1222 while (maxNum > 0) {
1223 long mostRecentActiveTime = Long.MIN_VALUE;
1224 ArrayList<RunningTaskInfo> selectedStackList = null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001225 final int numTaskLists = runningTaskLists.size();
1226 for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1227 ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001228 if (!stackTaskList.isEmpty()) {
1229 final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1230 if (lastActiveTime > mostRecentActiveTime) {
1231 mostRecentActiveTime = lastActiveTime;
1232 selectedStackList = stackTaskList;
1233 }
1234 }
1235 }
1236 if (selectedStackList != null) {
1237 list.add(selectedStackList.remove(0));
1238 --maxNum;
1239 } else {
1240 break;
1241 }
1242 }
Craig Mautner20e72272013-04-01 13:45:53 -07001243 }
1244
Todd Kennedy7440f172015-12-09 14:31:22 -08001245 ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1246 ProfilerInfo profilerInfo) {
1247 final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
Craig Mautner23ac33b2013-04-01 16:26:35 -07001248 if (aInfo != null) {
1249 // Store the found target back into the intent, because now that
1250 // we have it we never want to do this again. For example, if the
1251 // user navigates back to this point in the history, we should
1252 // always restart the exact same activity.
1253 intent.setComponent(new ComponentName(
1254 aInfo.applicationInfo.packageName, aInfo.name));
1255
1256 // Don't debug things in the system process
Man Caocfa78b22015-06-11 20:14:34 -07001257 if (!aInfo.processName.equals("system")) {
1258 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
Chong Zhangd25944e2016-06-09 16:15:27 -07001259 mService.setDebugApp(aInfo.processName, true, false);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001260 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001261
Tamas Berghammerdf6cb282016-01-29 12:07:00 +00001262 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1263 mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1264 }
1265
Man Caocfa78b22015-06-11 20:14:34 -07001266 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1267 mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1268 }
1269
1270 if (profilerInfo != null) {
Jeff Hao1b012d32014-08-20 10:35:34 -07001271 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001272 }
1273 }
Todd Kennedyb3b431302017-03-20 16:05:48 -07001274 final String intentLaunchToken = intent.getLaunchToken();
1275 if (aInfo.launchToken == null && intentLaunchToken != null) {
1276 aInfo.launchToken = intentLaunchToken;
1277 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001278 }
1279 return aInfo;
1280 }
1281
Todd Kennedy7440f172015-12-09 14:31:22 -08001282 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
Kenny Guyb1b30262016-02-09 16:02:35 +00001283 return resolveIntent(intent, resolvedType, userId, 0);
1284 }
1285
1286 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
Todd Kennedy4d1de7d2017-02-23 10:32:18 -08001287 synchronized (mService) {
1288 return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001289 PackageManager.MATCH_INSTANT | PackageManager.MATCH_DEFAULT_ONLY | flags
Kenny Guyb1b30262016-02-09 16:02:35 +00001290 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Todd Kennedy7440f172015-12-09 14:31:22 -08001291 }
Todd Kennedy7440f172015-12-09 14:31:22 -08001292 }
1293
1294 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1295 ProfilerInfo profilerInfo, int userId) {
1296 final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1297 return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1298 }
1299
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001300 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1301 boolean andResume, boolean checkConfig) throws RemoteException {
1302
1303 if (!allPausedActivitiesComplete()) {
1304 // While there are activities pausing we skipping starting any new activities until
1305 // pauses are complete. NOTE: that we also do this for activities that are starting in
1306 // the paused state because they will first be resumed then paused on the client side.
1307 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1308 "realStartActivityLocked: Skipping start of r=" + r
1309 + " some activities pausing...");
1310 return false;
1311 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001312
Bryce Leeaf691c02017-03-20 14:20:22 -07001313 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07001314 final ActivityStack stack = task.getStack();
chaviw59b98852017-06-13 12:05:44 -07001315
1316 beginDeferResume();
1317
Craig Mautner2420ead2013-04-01 17:13:20 -07001318 try {
chaviw59b98852017-06-13 12:05:44 -07001319 r.startFreezingScreenLocked(app, 0);
1320
1321 // schedule launch ticks to collect information about slow apps.
1322 r.startLaunchTickingLocked();
1323
1324 r.app = app;
1325
1326 // Have the window manager re-evaluate the orientation of the screen based on the new
1327 // activity order. Note that as a result of this, it can call back into the activity
1328 // manager with a new orientation. We don't care about that, because the activity is
1329 // not currently running so we are just restarting it anyway.
1330 if (checkConfig) {
1331 final int displayId = r.getDisplayId();
1332 final Configuration config = mWindowManager.updateOrientationFromAppTokens(
1333 getDisplayOverrideConfiguration(displayId),
1334 r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
1335 // Deferring resume here because we're going to launch new activity shortly.
1336 // We don't want to perform a redundant launch of the same record while ensuring
1337 // configurations and trying to resume top activity of focused stack.
1338 mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
1339 displayId);
Craig Mautner2420ead2013-04-01 17:13:20 -07001340 }
chaviw59b98852017-06-13 12:05:44 -07001341
1342 if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */,
1343 true /* isTop */)) {
1344 // We only set the visibility to true if the activity is allowed to be visible
1345 // based on
1346 // keyguard state. This avoids setting this into motion in window manager that is
1347 // later cancelled due to later calls to ensure visible activities that set
1348 // visibility back to false.
1349 r.setVisibility(true);
Craig Mautner2420ead2013-04-01 17:13:20 -07001350 }
chaviw59b98852017-06-13 12:05:44 -07001351
1352 if (mKeyguardController.isKeyguardLocked()) {
1353 r.notifyUnknownVisibilityLaunched();
Craig Mautner2420ead2013-04-01 17:13:20 -07001354 }
chaviw59b98852017-06-13 12:05:44 -07001355 final int applicationInfoUid =
1356 (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
1357 if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
1358 Slog.wtf(TAG,
1359 "User ID for activity changing for " + r
1360 + " appInfo.uid=" + r.appInfo.uid
1361 + " info.ai.uid=" + applicationInfoUid
1362 + " old=" + r.app + " new=" + app);
1363 }
1364
1365 app.waitingToKill = null;
1366 r.launchCount++;
1367 r.lastLaunchTime = SystemClock.uptimeMillis();
1368
1369 if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1370
1371 int idx = app.activities.indexOf(r);
1372 if (idx < 0) {
1373 app.activities.add(r);
1374 }
1375 mService.updateLruProcessLocked(app, true, null);
1376 mService.updateOomAdjLocked();
1377
1378 if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1379 task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
1380 setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE",
1381 false);
1382 }
1383
1384 try {
1385 if (app.thread == null) {
1386 throw new RemoteException();
1387 }
1388 List<ResultInfo> results = null;
1389 List<ReferrerIntent> newIntents = null;
1390 if (andResume) {
1391 // We don't need to deliver new intents and/or set results if activity is going
1392 // to pause immediately after launch.
1393 results = r.results;
1394 newIntents = r.newIntents;
1395 }
1396 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1397 "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1398 + " newIntents=" + newIntents + " andResume=" + andResume);
1399 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
1400 System.identityHashCode(r), task.taskId, r.shortComponentName);
1401 if (r.isHomeActivity()) {
1402 // Home process is the root process of the task.
1403 mService.mHomeProcess = task.mActivities.get(0).app;
1404 }
1405 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
1406 PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
1407 r.sleeping = false;
1408 r.forceNewConfig = false;
1409 mService.showUnsupportedZoomDialogIfNeededLocked(r);
1410 mService.showAskCompatModeDialogLocked(r);
1411 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1412 ProfilerInfo profilerInfo = null;
1413 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1414 if (mService.mProfileProc == null || mService.mProfileProc == app) {
1415 mService.mProfileProc = app;
Andreas Gampe2b073a02017-06-22 17:28:57 -07001416 ProfilerInfo profilerInfoSvc = mService.mProfilerInfo;
1417 if (profilerInfoSvc != null && profilerInfoSvc.profileFile != null) {
1418 if (profilerInfoSvc.profileFd != null) {
chaviw59b98852017-06-13 12:05:44 -07001419 try {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001420 profilerInfoSvc.profileFd = profilerInfoSvc.profileFd.dup();
chaviw59b98852017-06-13 12:05:44 -07001421 } catch (IOException e) {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001422 profilerInfoSvc.closeFd();
Craig Mautner2568c3a2015-03-26 14:22:34 -07001423 }
1424 }
chaviw59b98852017-06-13 12:05:44 -07001425
Andreas Gampe2b073a02017-06-22 17:28:57 -07001426 profilerInfo = new ProfilerInfo(profilerInfoSvc);
Craig Mautner2420ead2013-04-01 17:13:20 -07001427 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001428 }
1429 }
Adam Powellcfbe9be2013-11-06 14:58:58 -08001430
chaviw59b98852017-06-13 12:05:44 -07001431 app.hasShownUi = true;
1432 app.pendingUiClean = true;
1433 app.forceProcessStateUpTo(mService.mTopProcessState);
1434 // Because we could be starting an Activity in the system process this may not go
1435 // across a Binder interface which would create a new Configuration. Consequently
1436 // we have to always create a new Configuration here.
Bryce Leea163b762017-01-24 11:05:01 -08001437
chaviw59b98852017-06-13 12:05:44 -07001438 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
1439 mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
1440 r.setLastReportedConfiguration(mergedConfiguration);
Bryce Leea163b762017-01-24 11:05:01 -08001441
chaviw59b98852017-06-13 12:05:44 -07001442 logIfTransactionTooLarge(r.intent, r.icicle);
1443 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1444 System.identityHashCode(r), r.info,
1445 // TODO: Have this take the merged configuration instead of separate global
1446 // and override configs.
1447 mergedConfiguration.getGlobalConfiguration(),
1448 mergedConfiguration.getOverrideConfiguration(), r.compat,
1449 r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1450 r.persistentState, results, newIntents, !andResume,
1451 mService.isNextTransitionForward(), profilerInfo);
Craig Mautner2420ead2013-04-01 17:13:20 -07001452
chaviw59b98852017-06-13 12:05:44 -07001453 if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1454 // This may be a heavy-weight process! Note that the package
1455 // manager will ensure that only activity can run in the main
1456 // process of the .apk, which is the only thing that will be
1457 // considered heavy-weight.
1458 if (app.processName.equals(app.info.packageName)) {
1459 if (mService.mHeavyWeightProcess != null
1460 && mService.mHeavyWeightProcess != app) {
1461 Slog.w(TAG, "Starting new heavy weight process " + app
1462 + " when already running "
1463 + mService.mHeavyWeightProcess);
1464 }
1465 mService.mHeavyWeightProcess = app;
1466 Message msg = mService.mHandler.obtainMessage(
1467 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1468 msg.obj = r;
1469 mService.mHandler.sendMessage(msg);
Craig Mautner2420ead2013-04-01 17:13:20 -07001470 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001471 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001472
chaviw59b98852017-06-13 12:05:44 -07001473 } catch (RemoteException e) {
1474 if (r.launchFailed) {
1475 // This is the second time we failed -- finish activity
1476 // and give up.
1477 Slog.e(TAG, "Second failure launching "
1478 + r.intent.getComponent().flattenToShortString()
1479 + ", giving up", e);
1480 mService.appDiedLocked(app);
1481 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1482 "2nd-crash", false);
1483 return false;
1484 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001485
chaviw59b98852017-06-13 12:05:44 -07001486 // This is the first time we failed -- restart process and
1487 // retry.
1488 r.launchFailed = true;
1489 app.activities.remove(r);
1490 throw e;
1491 }
1492 } finally {
1493 endDeferResume();
Craig Mautner2420ead2013-04-01 17:13:20 -07001494 }
1495
1496 r.launchFailed = false;
1497 if (stack.updateLRUListLocked(r)) {
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07001498 Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
Craig Mautner2420ead2013-04-01 17:13:20 -07001499 }
1500
chaviw59b98852017-06-13 12:05:44 -07001501 if (andResume && readyToResume()) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001502 // As part of the process of launching, ActivityThread also performs
1503 // a resume.
1504 stack.minimalResumeActivityLocked(r);
1505 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001506 // This activity is not starting in the resumed state... which should look like we asked
Wale Ogunwale919a05d2017-04-13 00:36:34 +00001507 // it to pause+stop (but remain visible), and it has done so and reported back the
Wale Ogunwaled046a012015-12-24 13:05:59 -08001508 // current icicle and other state.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001509 if (DEBUG_STATES) Slog.v(TAG_STATES,
Wale Ogunwaled046a012015-12-24 13:05:59 -08001510 "Moving to PAUSED: " + r + " (starting in paused state)");
1511 r.state = PAUSED;
Craig Mautner2420ead2013-04-01 17:13:20 -07001512 }
1513
1514 // Launch the new version setup screen if needed. We do this -after-
1515 // launching the initial activity (that is, home), so that it can have
1516 // a chance to initialize itself while in the background, making the
1517 // switch back to it faster and look better.
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001518 if (isFocusedStack(stack)) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001519 mService.startSetupActivityLocked();
1520 }
1521
Dianne Hackborn465fa392014-09-14 14:21:18 -07001522 // Update any services we are bound to that might care about whether
1523 // their client may have activities.
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001524 if (r.app != null) {
1525 mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1526 }
Dianne Hackborn465fa392014-09-14 14:21:18 -07001527
Craig Mautner2420ead2013-04-01 17:13:20 -07001528 return true;
1529 }
1530
Sudheer Shankafab200f2017-05-17 20:41:53 -07001531 private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
1532 int extrasSize = 0;
1533 if (intent != null) {
1534 final Bundle extras = intent.getExtras();
1535 if (extras != null) {
1536 extrasSize = extras.getSize();
1537 }
1538 }
1539 int icicleSize = (icicle == null ? 0 : icicle.getSize());
1540 if (extrasSize + icicleSize > 200000) {
1541 Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
1542 + ", icicle size: " + icicleSize);
1543 }
1544 }
1545
Craig Mautnere79d42682013-04-01 19:01:53 -07001546 void startSpecificActivityLocked(ActivityRecord r,
George Mount2c92c972014-03-20 09:38:23 -07001547 boolean andResume, boolean checkConfig) {
Craig Mautnere79d42682013-04-01 19:01:53 -07001548 // Is this activity's application already running?
1549 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001550 r.info.applicationInfo.uid, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001551
Andrii Kulian02b7a832016-10-06 23:11:56 -07001552 r.getStack().setLaunchTime(r);
Craig Mautnere79d42682013-04-01 19:01:53 -07001553
1554 if (app != null && app.thread != null) {
1555 try {
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001556 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1557 || !"android".equals(r.info.packageName)) {
1558 // Don't add this if it is a platform component that is marked
1559 // to run in multiple processes, because this is actually
1560 // part of the framework so doesn't make sense to track as a
1561 // separate apk in the process.
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001562 app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1563 mService.mProcessStats);
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001564 }
George Mount2c92c972014-03-20 09:38:23 -07001565 realStartActivityLocked(r, app, andResume, checkConfig);
Craig Mautnere79d42682013-04-01 19:01:53 -07001566 return;
1567 } catch (RemoteException e) {
1568 Slog.w(TAG, "Exception when starting activity "
1569 + r.intent.getComponent().flattenToShortString(), e);
1570 }
1571
1572 // If a dead object exception was thrown -- fall through to
1573 // restart the application.
1574 }
1575
1576 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001577 "activity", r.intent.getComponent(), false, false, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001578 }
1579
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001580 boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001581 String resultWho, int requestCode, int callingPid, int callingUid,
1582 String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
Jorim Jaggi2adba072016-03-03 13:43:39 +01001583 ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001584 final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1585 callingUid);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001586 if (startAnyPerm == PERMISSION_GRANTED) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001587 return true;
1588 }
1589 final int componentRestriction = getComponentRestrictionForCallingPackage(
1590 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1591 final int actionRestriction = getActionRestrictionForCallingPackage(
1592 intent.getAction(), callingPackage, callingPid, callingUid);
1593 if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1594 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1595 if (resultRecord != null) {
1596 resultStack.sendActivityResultLocked(-1,
1597 resultRecord, resultWho, requestCode,
1598 Activity.RESULT_CANCELED, null);
1599 }
1600 final String msg;
1601 if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1602 msg = "Permission Denial: starting " + intent.toString()
1603 + " from " + callerApp + " (pid=" + callingPid
1604 + ", uid=" + callingUid + ")" + " with revoked permission "
1605 + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1606 } else if (!aInfo.exported) {
1607 msg = "Permission Denial: starting " + intent.toString()
1608 + " from " + callerApp + " (pid=" + callingPid
1609 + ", uid=" + callingUid + ")"
1610 + " not exported from uid " + aInfo.applicationInfo.uid;
1611 } else {
1612 msg = "Permission Denial: starting " + intent.toString()
1613 + " from " + callerApp + " (pid=" + callingPid
1614 + ", uid=" + callingUid + ")"
1615 + " requires " + aInfo.permission;
1616 }
1617 Slog.w(TAG, msg);
1618 throw new SecurityException(msg);
1619 }
1620
1621 if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1622 final String message = "Appop Denial: starting " + intent.toString()
1623 + " from " + callerApp + " (pid=" + callingPid
1624 + ", uid=" + callingUid + ")"
1625 + " requires " + AppOpsManager.permissionToOp(
1626 ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1627 Slog.w(TAG, message);
1628 return false;
1629 } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1630 final String message = "Appop Denial: starting " + intent.toString()
1631 + " from " + callerApp + " (pid=" + callingPid
1632 + ", uid=" + callingUid + ")"
1633 + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1634 Slog.w(TAG, message);
1635 return false;
1636 }
Andrii Kulian16802aa2016-11-02 12:21:33 -07001637 if (options != null) {
1638 if (options.getLaunchTaskId() != INVALID_STACK_ID) {
1639 final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1640 callingPid, callingUid);
1641 if (startInTaskPerm != PERMISSION_GRANTED) {
1642 final String msg = "Permission Denial: starting " + intent.toString()
1643 + " from " + callerApp + " (pid=" + callingPid
1644 + ", uid=" + callingUid + ") with launchTaskId="
1645 + options.getLaunchTaskId();
1646 Slog.w(TAG, msg);
1647 throw new SecurityException(msg);
1648 }
1649 }
1650 // Check if someone tries to launch an activity on a private display with a different
1651 // owner.
1652 final int launchDisplayId = options.getLaunchDisplayId();
Andrii Kulian02689a72017-07-06 14:28:59 -07001653 if (launchDisplayId != INVALID_DISPLAY && !isCallerAllowedToLaunchOnDisplay(callingPid,
1654 callingUid, launchDisplayId, aInfo)) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001655 final String msg = "Permission Denial: starting " + intent.toString()
1656 + " from " + callerApp + " (pid=" + callingPid
1657 + ", uid=" + callingUid + ") with launchDisplayId="
1658 + launchDisplayId;
1659 Slog.w(TAG, msg);
1660 throw new SecurityException(msg);
Jorim Jaggi2adba072016-03-03 13:43:39 +01001661 }
1662 }
1663
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001664 return true;
1665 }
1666
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001667 /** Check if caller is allowed to launch activities on specified display. */
Andrii Kulian02689a72017-07-06 14:28:59 -07001668 boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId,
1669 ActivityInfo aInfo) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001670 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId
1671 + " callingPid=" + callingPid + " callingUid=" + callingUid);
1672
Andrii Kulian02689a72017-07-06 14:28:59 -07001673 if (callingPid == -1 && callingUid == -1) {
1674 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: no caller info, skip check");
1675 return true;
1676 }
1677
Andrii Kulian62e6f252017-05-30 22:46:53 -07001678 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(launchDisplayId);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001679 if (activityDisplay == null) {
1680 Slog.w(TAG, "Launch on display check: display not found");
1681 return false;
1682 }
1683
Andrii Kulian02689a72017-07-06 14:28:59 -07001684 // Check if the caller has enough privileges to embed activities and launch to private
1685 // displays.
Andrii Kulian3a95edc2017-06-28 16:21:07 -07001686 final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001687 callingUid);
1688 if (startAnyPerm == PERMISSION_GRANTED) {
1689 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1690 + " allow launch any on display");
1691 return true;
1692 }
1693
1694 if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL
Andrii Kulian02689a72017-07-06 14:28:59 -07001695 && activityDisplay.mDisplay.getOwnerUid() != SYSTEM_UID
1696 && activityDisplay.mDisplay.getOwnerUid() != aInfo.applicationInfo.uid) {
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001697 // Limit launching on virtual displays, because their contents can be read from Surface
1698 // by apps that created them.
Andrii Kulian02689a72017-07-06 14:28:59 -07001699 if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
1700 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1701 + " disallow launch on virtual display for not-embedded activity.");
1702 return false;
1703 }
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001704 }
1705
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001706 if (!activityDisplay.isPrivate()) {
1707 // Anyone can launch on a public display.
1708 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1709 + " allow launch on public display");
1710 return true;
1711 }
1712
1713 // Check if the caller is the owner of the display.
1714 if (activityDisplay.mDisplay.getOwnerUid() == callingUid) {
1715 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1716 + " allow launch for owner of the display");
1717 return true;
1718 }
1719
1720 // Check if caller is present on display
1721 if (activityDisplay.isUidPresent(callingUid)) {
1722 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1723 + " allow launch for caller present on the display");
1724 return true;
1725 }
1726
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001727 Slog.w(TAG, "Launch on display check: denied");
1728 return false;
1729 }
1730
1731 /** Update lists of UIDs that are present on displays and have access to them. */
1732 void updateUIDsPresentOnDisplay() {
1733 mDisplayAccessUIDs.clear();
1734 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1735 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
David Stevens82ea6cb2017-03-03 16:18:50 -08001736 // Only bother calculating the whitelist for private displays
1737 if (activityDisplay.isPrivate()) {
1738 mDisplayAccessUIDs.append(
1739 activityDisplay.mDisplayId, activityDisplay.getPresentUIDs());
1740 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001741 }
1742 // Store updated lists in DisplayManager. Callers from outside of AM should get them there.
1743 mDisplayManagerInternal.setDisplayAccessUIDs(mDisplayAccessUIDs);
1744 }
1745
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001746 UserInfo getUserInfo(int userId) {
Clara Bayarrif7fea162015-10-22 16:09:52 +01001747 final long identity = Binder.clearCallingIdentity();
1748 try {
1749 return UserManager.get(mService.mContext).getUserInfo(userId);
1750 } finally {
1751 Binder.restoreCallingIdentity(identity);
1752 }
1753 }
1754
Svet Ganov99b60432015-06-27 13:15:22 -07001755 private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001756 String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001757 if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1758 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
Svet Ganov99b60432015-06-27 13:15:22 -07001759 == PackageManager.PERMISSION_DENIED) {
1760 return ACTIVITY_RESTRICTION_PERMISSION;
1761 }
1762
Christopher Tateff7add02015-08-17 10:23:22 -07001763 if (activityInfo.permission == null) {
1764 return ACTIVITY_RESTRICTION_NONE;
1765 }
1766
Svet Ganov99b60432015-06-27 13:15:22 -07001767 final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1768 if (opCode == AppOpsManager.OP_NONE) {
1769 return ACTIVITY_RESTRICTION_NONE;
1770 }
1771
1772 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1773 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001774 if (!ignoreTargetSecurity) {
1775 return ACTIVITY_RESTRICTION_APPOP;
1776 }
Svet Ganov99b60432015-06-27 13:15:22 -07001777 }
1778
1779 return ACTIVITY_RESTRICTION_NONE;
1780 }
1781
Svetoslav7008b512015-06-24 18:47:07 -07001782 private int getActionRestrictionForCallingPackage(String action,
1783 String callingPackage, int callingPid, int callingUid) {
1784 if (action == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001785 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001786 }
1787
1788 String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1789 if (permission == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001790 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001791 }
1792
1793 final PackageInfo packageInfo;
1794 try {
1795 packageInfo = mService.mContext.getPackageManager()
1796 .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1797 } catch (PackageManager.NameNotFoundException e) {
1798 Slog.i(TAG, "Cannot find package info for " + callingPackage);
Svet Ganov99b60432015-06-27 13:15:22 -07001799 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001800 }
1801
1802 if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
Svet Ganov99b60432015-06-27 13:15:22 -07001803 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001804 }
1805
1806 if (mService.checkPermission(permission, callingPid, callingUid) ==
1807 PackageManager.PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001808 return ACTIVITY_RESTRICTION_PERMISSION;
Svetoslav7008b512015-06-24 18:47:07 -07001809 }
1810
1811 final int opCode = AppOpsManager.permissionToOpCode(permission);
1812 if (opCode == AppOpsManager.OP_NONE) {
Svet Ganov99b60432015-06-27 13:15:22 -07001813 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001814 }
1815
1816 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1817 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001818 return ACTIVITY_RESTRICTION_APPOP;
Svetoslav7008b512015-06-24 18:47:07 -07001819 }
1820
Svet Ganov99b60432015-06-27 13:15:22 -07001821 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001822 }
1823
Dianne Hackborn3d07c942015-03-13 18:02:54 -07001824 void setLaunchSource(int uid) {
1825 mLaunchingActivity.setWorkSource(new WorkSource(uid));
1826 }
1827
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001828 void acquireLaunchWakelock() {
1829 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1830 throw new IllegalStateException("Calling must be system uid");
1831 }
1832 mLaunchingActivity.acquire();
1833 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1834 // To be safe, don't allow the wake lock to be held for too long.
1835 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1836 }
1837 }
1838
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001839 /**
1840 * Called when the frontmost task is idle.
1841 * @return the state of mService.mBooting before this was called.
1842 */
1843 private boolean checkFinishBootingLocked() {
1844 final boolean booting = mService.mBooting;
1845 boolean enableScreen = false;
1846 mService.mBooting = false;
1847 if (!mService.mBooted) {
1848 mService.mBooted = true;
1849 enableScreen = true;
1850 }
1851 if (booting || enableScreen) {
1852 mService.postFinishBooting(booting, enableScreen);
1853 }
1854 return booting;
1855 }
1856
Craig Mautnerf3333272013-04-22 10:55:53 -07001857 // Checked.
1858 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
Winson Chung4dabf232017-01-25 13:25:22 -08001859 boolean processPausingActivities, Configuration config) {
Wale Ogunwalee23149f2015-03-06 15:39:44 -08001860 if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001861
Craig Mautnerf3333272013-04-22 10:55:53 -07001862 ArrayList<ActivityRecord> finishes = null;
Amith Yamasani37a40c22015-06-17 13:25:42 -07001863 ArrayList<UserState> startingUsers = null;
Craig Mautnerf3333272013-04-22 10:55:53 -07001864 int NS = 0;
1865 int NF = 0;
Craig Mautnerf3333272013-04-22 10:55:53 -07001866 boolean booting = false;
Craig Mautnerf3333272013-04-22 10:55:53 -07001867 boolean activityRemoved = false;
1868
Wale Ogunwale7d701172015-03-11 15:36:30 -07001869 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001870 if (r != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001871 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1872 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07001873 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1874 r.finishLaunchTickingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001875 if (fromTimeout) {
1876 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
Craig Mautnerf3333272013-04-22 10:55:53 -07001877 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001878
1879 // This is a hack to semi-deal with a race condition
1880 // in the client where it can be constructed with a
1881 // newer configuration from when we asked it to launch.
1882 // We'll update with whatever configuration it now says
1883 // it used to launch.
1884 if (config != null) {
Bryce Leea163b762017-01-24 11:05:01 -08001885 r.setLastReportedGlobalConfiguration(config);
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001886 }
1887
1888 // We are now idle. If someone is waiting for a thumbnail from
1889 // us, we can now deliver.
1890 r.idle = true;
1891
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001892 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001893 if (isFocusedStack(r.getStack()) || fromTimeout) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001894 booting = checkFinishBootingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001895 }
1896 }
1897
1898 if (allResumedActivitiesIdle()) {
1899 if (r != null) {
1900 mService.scheduleAppGcsLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001901 }
1902
1903 if (mLaunchingActivity.isHeld()) {
1904 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1905 if (VALIDATE_WAKE_LOCK_CALLER &&
1906 Binder.getCallingUid() != Process.myUid()) {
1907 throw new IllegalStateException("Calling must be system uid");
1908 }
1909 mLaunchingActivity.release();
1910 }
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07001911 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerf3333272013-04-22 10:55:53 -07001912 }
1913
1914 // Atomically retrieve all of the other things to do.
Winson Chung4dabf232017-01-25 13:25:22 -08001915 final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
1916 true /* remove */, processPausingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001917 NS = stops != null ? stops.size() : 0;
Wale Ogunwale7d701172015-03-11 15:36:30 -07001918 if ((NF = mFinishingActivities.size()) > 0) {
1919 finishes = new ArrayList<>(mFinishingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001920 mFinishingActivities.clear();
1921 }
1922
Craig Mautnerf3333272013-04-22 10:55:53 -07001923 if (mStartingUsers.size() > 0) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07001924 startingUsers = new ArrayList<>(mStartingUsers);
Craig Mautnerf3333272013-04-22 10:55:53 -07001925 mStartingUsers.clear();
1926 }
1927
Craig Mautnerf3333272013-04-22 10:55:53 -07001928 // Stop any activities that are scheduled to do so but have been
1929 // waiting for the next one to start.
1930 for (int i = 0; i < NS; i++) {
1931 r = stops.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001932 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001933 if (stack != null) {
1934 if (r.finishing) {
1935 stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1936 } else {
1937 stack.stopActivityLocked(r);
1938 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001939 }
1940 }
1941
1942 // Finish any activities that are scheduled to do so but have been
1943 // waiting for the next one to start.
1944 for (int i = 0; i < NF; i++) {
1945 r = finishes.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001946 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001947 if (stack != null) {
1948 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1949 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001950 }
1951
Dianne Hackborn7622a0f2014-09-30 14:31:42 -07001952 if (!booting) {
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001953 // Complete user switch
1954 if (startingUsers != null) {
1955 for (int i = 0; i < startingUsers.size(); i++) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001956 mService.mUserController.finishUserSwitch(startingUsers.get(i));
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001957 }
1958 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001959 }
1960
1961 mService.trimApplications();
1962 //dump();
1963 //mWindowManager.dump();
1964
Craig Mautnerf3333272013-04-22 10:55:53 -07001965 if (activityRemoved) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001966 resumeFocusedStackTopActivityLocked();
Craig Mautnerf3333272013-04-22 10:55:53 -07001967 }
1968
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001969 return r;
Craig Mautnerf3333272013-04-22 10:55:53 -07001970 }
1971
Craig Mautner8e569572013-10-11 17:36:59 -07001972 boolean handleAppDiedLocked(ProcessRecord app) {
Craig Mautner19091252013-10-05 00:03:53 -07001973 boolean hasVisibleActivities = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001974 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1975 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001976 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1977 hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
1978 }
Craig Mautner6b74cb52013-09-27 17:02:21 -07001979 }
Craig Mautner19091252013-10-05 00:03:53 -07001980 return hasVisibleActivities;
Craig Mautner8d341ef2013-03-26 09:03:27 -07001981 }
1982
1983 void closeSystemDialogsLocked() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001984 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1985 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001986 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1987 stacks.get(stackNdx).closeSystemDialogsLocked();
1988 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07001989 }
1990 }
1991
Craig Mautner93529a42013-10-04 15:03:13 -07001992 void removeUserLocked(int userId) {
Craig Mautner4f1df4f2013-10-15 15:44:14 -07001993 mUserStackInFront.delete(userId);
Craig Mautner93529a42013-10-04 15:03:13 -07001994 }
1995
Craig Mautner8d341ef2013-03-26 09:03:27 -07001996 /**
Chong Zhang45c25ce2015-08-10 22:18:26 -07001997 * Update the last used stack id for non-current user (current user's last
1998 * used stack is the focused stack)
1999 */
2000 void updateUserStackLocked(int userId, ActivityStack stack) {
2001 if (userId != mCurrentUser) {
2002 mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
2003 }
2004 }
2005
2006 /**
Craig Mautner8d341ef2013-03-26 09:03:27 -07002007 * @return true if some activity was finished (or would have finished if doit were true).
2008 */
Wale Ogunwale540e1232015-05-01 15:35:39 -07002009 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
2010 boolean doit, boolean evenPersistent, int userId) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07002011 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08002012 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2013 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
louis_chang8f0555a2015-10-27 10:45:53 +08002014 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002015 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002016 if (stack.finishDisabledPackageActivitiesLocked(
2017 packageName, filterByClasses, doit, evenPersistent, userId)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002018 didSomething = true;
2019 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002020 }
2021 }
2022 return didSomething;
2023 }
2024
Dianne Hackborna413dc02013-07-12 12:02:55 -07002025 void updatePreviousProcessLocked(ActivityRecord r) {
2026 // Now that this process has stopped, we may want to consider
2027 // it to be the previous app to try to keep around in case
2028 // the user wants to return to it.
2029
2030 // First, found out what is currently the foreground app, so that
2031 // we don't blow away the previous app if this activity is being
2032 // hosted by the process that is actually still the foreground.
2033 ProcessRecord fgApp = null;
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;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002036 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2037 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07002038 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002039 if (stack.mResumedActivity != null) {
2040 fgApp = stack.mResumedActivity.app;
2041 } else if (stack.mPausingActivity != null) {
2042 fgApp = stack.mPausingActivity.app;
2043 }
2044 break;
Dianne Hackborna413dc02013-07-12 12:02:55 -07002045 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07002046 }
2047 }
2048
2049 // Now set this one as the previous process, only if that really
2050 // makes sense to.
2051 if (r.app != null && fgApp != null && r.app != fgApp
2052 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
Craig Mautner4ef26932013-09-18 15:15:52 -07002053 && r.app != mService.mHomeProcess) {
Dianne Hackborna413dc02013-07-12 12:02:55 -07002054 mService.mPreviousProcess = r.app;
2055 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
2056 }
2057 }
2058
Wale Ogunwaled046a012015-12-24 13:05:59 -08002059 boolean resumeFocusedStackTopActivityLocked() {
2060 return resumeFocusedStackTopActivityLocked(null, null, null);
Craig Mautner05d29032013-05-03 13:40:13 -07002061 }
2062
Wale Ogunwaled046a012015-12-24 13:05:59 -08002063 boolean resumeFocusedStackTopActivityLocked(
Chong Zhang280d3322015-11-03 17:27:26 -08002064 ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
chaviw59b98852017-06-13 12:05:44 -07002065
2066 if (!readyToResume()) {
2067 return false;
2068 }
2069
Wale Ogunwaled046a012015-12-24 13:05:59 -08002070 if (targetStack != null && isFocusedStack(targetStack)) {
2071 return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
Craig Mautner05d29032013-05-03 13:40:13 -07002072 }
chaviw59b98852017-06-13 12:05:44 -07002073
Wale Ogunwale06579d62016-04-30 15:29:06 -07002074 final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2075 if (r == null || r.state != RESUMED) {
2076 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
skuhne@google.com1b974dc2016-12-09 13:41:29 -08002077 } else if (r.state == RESUMED) {
2078 // Kick off any lingering app transitions form the MoveTaskToFront operation.
2079 mFocusedStack.executeAppTransition(targetOptions);
Wale Ogunwale06579d62016-04-30 15:29:06 -07002080 }
chaviw59b98852017-06-13 12:05:44 -07002081
Wale Ogunwaled046a012015-12-24 13:05:59 -08002082 return false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002083 }
2084
Todd Kennedy39bfee52016-02-24 10:28:21 -08002085 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
2086 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2087 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2088 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2089 stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
2090 }
2091 }
2092 }
2093
Adrian Roos20d7df32016-01-12 18:59:43 +01002094 TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
2095 TaskRecord finishedTask = null;
2096 ActivityStack focusedStack = getFocusedStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08002097 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2098 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002099 final int numStacks = stacks.size();
2100 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2101 final ActivityStack stack = stacks.get(stackNdx);
Adrian Roos20d7df32016-01-12 18:59:43 +01002102 TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
2103 if (stack == focusedStack || finishedTask == null) {
2104 finishedTask = t;
2105 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08002106 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002107 }
Adrian Roos20d7df32016-01-12 18:59:43 +01002108 return finishedTask;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002109 }
2110
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07002111 void finishVoiceTask(IVoiceInteractionSession session) {
2112 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2113 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2114 final int numStacks = stacks.size();
2115 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2116 final ActivityStack stack = stacks.get(stackNdx);
2117 stack.finishVoiceTask(session);
2118 }
2119 }
2120 }
2121
Andrii Kulianc27916642016-04-12 17:59:27 -07002122 void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
2123 String reason, boolean forceNonResizeable) {
Craig Mautneraea74a52014-03-08 14:23:10 -08002124 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
2125 mUserLeaving = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002126 }
Craig Mautneraea74a52014-03-08 14:23:10 -08002127 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
2128 // Caller wants the home activity moved with it. To accomplish this,
2129 // we'll just indicate that this task returns to the home task.
Craig Mautner84984fa2014-06-19 11:19:20 -07002130 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
Craig Mautneraea74a52014-03-08 14:23:10 -08002131 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002132 ActivityStack currentStack = task.getStack();
2133 if (currentStack == null) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07002134 Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
2135 + task + " to front. Stack is null");
2136 return;
2137 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002138
Wale Ogunwaleb1faf602016-01-27 09:12:31 -08002139 if (task.isResizeable() && options != null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002140 int stackId = options.getLaunchStackId();
2141 if (canUseActivityOptionsLaunchBounds(options, stackId)) {
Filip Gruszczynskidce2d162016-01-12 15:40:13 -08002142 final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
Chong Zhang0fa656b2015-08-31 15:17:21 -07002143 task.updateOverrideConfiguration(bounds);
Wale Ogunwale854809c2015-12-27 16:18:19 -08002144 if (stackId == INVALID_STACK_ID) {
2145 stackId = task.getLaunchStackId();
2146 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002147 if (stackId != currentStack.mStackId) {
Winson Chung74666102017-02-22 17:49:24 -08002148 task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE,
2149 DEFER_RESUME, "findTaskToMoveToFrontLocked");
Andrii Kulian02b7a832016-10-06 23:11:56 -07002150 stackId = currentStack.mStackId;
Chong Zhang112eb8c2015-11-02 11:17:00 -08002151 // moveTaskToStackUncheckedLocked() should already placed the task on top,
2152 // still need moveTaskToFrontLocked() below for any transition settings.
2153 }
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002154 if (StackId.resizeStackWithLaunchBounds(stackId)) {
2155 resizeStackLocked(stackId, bounds,
2156 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002157 !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002158 } else {
2159 // WM resizeTask must be done after the task is moved to the correct stack,
2160 // because Task's setBounds() also updates dim layer's bounds, but that has
2161 // dependency on the stack.
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002162 task.resizeWindowContainer();
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002163 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002164 }
2165 }
2166
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002167 final ActivityRecord r = task.getTopActivity();
Andrii Kulian02b7a832016-10-06 23:11:56 -07002168 currentStack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002169 r == null ? null : r.appTimeTracker, reason);
2170
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002171 if (DEBUG_STACK) Slog.d(TAG_STACK,
Andrii Kulian02b7a832016-10-06 23:11:56 -07002172 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
Jorim Jaggi2adba072016-03-03 13:43:39 +01002173
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002174 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
2175 currentStack.mStackId, forceNonResizeable);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002176 }
2177
Wale Ogunwale854809c2015-12-27 16:18:19 -08002178 boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002179 // We use the launch bounds in the activity options is the device supports freeform
Wale Ogunwale854809c2015-12-27 16:18:19 -08002180 // window management or is launching into the pinned stack.
Wale Ogunwale5122df02016-01-29 22:33:38 -08002181 if (options.getLaunchBounds() == null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002182 return false;
2183 }
2184 return (mService.mSupportsPictureInPicture && launchStackId == PINNED_STACK_ID)
2185 || mService.mSupportsFreeformWindowManagement;
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002186 }
2187
Winson Chung55893332017-02-17 17:13:10 -08002188 protected <T extends ActivityStack> T getStack(int stackId) {
Wale Ogunwale040b4702015-08-06 18:10:50 -07002189 return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002190 }
2191
Winson Chung55893332017-02-17 17:13:10 -08002192 protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
2193 boolean createOnTop) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002194 final ActivityStack stack = mStacks.get(stackId);
2195 if (stack != null) {
2196 return (T) stack;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002197 }
Wale Ogunwale3797c222015-10-27 14:21:58 -07002198 if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002199 return null;
2200 }
Matthew Ng330757d2017-02-28 14:19:17 -08002201 if (stackId == DOCKED_STACK_ID) {
2202 // Make sure recents stack exist when creating a dock stack as it normally need to be on
2203 // the other side of the docked stack and we make visibility decisions based on that.
2204 getStack(RECENTS_STACK_ID, CREATE_IF_NEEDED, createOnTop);
2205 }
Winson Chung55893332017-02-17 17:13:10 -08002206 return (T) createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002207 }
2208
Andrii Kulian16802aa2016-11-02 12:21:33 -07002209 /**
2210 * Get a topmost stack on the display, that is a valid launch stack for specified activity.
2211 * If there is no such stack, new dynamic stack can be created.
2212 * @param displayId Target display.
2213 * @param r Activity that should be launched there.
2214 * @return Existing stack if there is a valid one, new dynamic stack if it is valid or null.
2215 */
2216 ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002217 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian16802aa2016-11-02 12:21:33 -07002218 if (activityDisplay == null) {
2219 throw new IllegalArgumentException(
2220 "Display with displayId=" + displayId + " not found.");
2221 }
2222
2223 // Return the topmost valid stack on the display.
2224 for (int i = activityDisplay.mStacks.size() - 1; i >= 0; --i) {
2225 final ActivityStack stack = activityDisplay.mStacks.get(i);
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002226 if (mService.mActivityStarter.isValidLaunchStackId(stack.mStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002227 return stack;
2228 }
2229 }
2230
2231 // If there is no valid stack on the external display - check if new dynamic stack will do.
2232 if (displayId != Display.DEFAULT_DISPLAY) {
2233 final int newDynamicStackId = getNextStackId();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002234 if (mService.mActivityStarter.isValidLaunchStackId(newDynamicStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002235 return createStackOnDisplay(newDynamicStackId, displayId, true /*onTop*/);
2236 }
2237 }
2238
2239 Slog.w(TAG, "getValidLaunchStackOnDisplay: can't launch on displayId " + displayId);
2240 return null;
2241 }
2242
Craig Mautner967212c2013-04-13 21:10:58 -07002243 ArrayList<ActivityStack> getStacks() {
Wale Ogunwale3797c222015-10-27 14:21:58 -07002244 ArrayList<ActivityStack> allStacks = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08002245 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2246 allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002247 }
2248 return allStacks;
Craig Mautner967212c2013-04-13 21:10:58 -07002249 }
2250
Jorim Jaggife762342016-10-13 14:33:27 +02002251 ArrayList<ActivityStack> getStacksOnDefaultDisplay() {
2252 return mActivityDisplays.valueAt(DEFAULT_DISPLAY).mStacks;
2253 }
2254
Andrii Kulian7fc22812016-12-28 13:04:11 -08002255 /**
2256 * Get next focusable stack in the system. This will search across displays and stacks
2257 * in last-focused order for a focusable and visible stack, different from the target stack.
2258 *
2259 * @param currentFocus The stack that previously had focus and thus needs to be ignored when
2260 * searching for next candidate.
2261 * @return Next focusable {@link ActivityStack}, null if not found.
2262 */
2263 ActivityStack getNextFocusableStackLocked(ActivityStack currentFocus) {
2264 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2265
2266 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2267 final int displayId = mTmpOrderedDisplayIds.get(i);
Andrii Kulian62e6f252017-05-30 22:46:53 -07002268 // If a display is registered in WM, it must also be available in AM.
2269 @SuppressWarnings("ConstantConditions")
2270 final List<ActivityStack> stacks = getActivityDisplayOrCreateLocked(displayId).mStacks;
Andrii Kulian7fc22812016-12-28 13:04:11 -08002271 for (int j = stacks.size() - 1; j >= 0; --j) {
2272 final ActivityStack stack = stacks.get(j);
2273 if (stack != currentFocus && stack.isFocusable()
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002274 && stack.shouldBeVisible(null) != STACK_INVISIBLE) {
Andrii Kulian7fc22812016-12-28 13:04:11 -08002275 return stack;
2276 }
2277 }
2278 }
2279
2280 return null;
2281 }
2282
Andrii Kuliana8fe3df2017-06-16 15:29:26 -07002283 /**
2284 * Get next valid stack for launching provided activity in the system. This will search across
2285 * displays and stacks in last-focused order for a focusable and visible stack, except those
2286 * that are on a currently focused display.
2287 *
2288 * @param r The activity that is being launched.
2289 * @param currentFocus The display that previously had focus and thus needs to be ignored when
2290 * searching for the next candidate.
2291 * @return Next valid {@link ActivityStack}, null if not found.
2292 */
2293 ActivityStack getNextValidLaunchStackLocked(@NonNull ActivityRecord r, int currentFocus) {
2294 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2295 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2296 final int displayId = mTmpOrderedDisplayIds.get(i);
2297 if (displayId == currentFocus) {
2298 continue;
2299 }
2300 final ActivityStack stack = getValidLaunchStackOnDisplay(displayId, r);
2301 if (stack != null) {
2302 return stack;
2303 }
2304 }
2305 return null;
2306 }
2307
Craig Mautneree2e45a2014-06-27 12:10:03 -07002308 ActivityRecord getHomeActivity() {
Craig Mautnerdb49fec2015-05-21 15:33:30 -07002309 return getHomeActivityForUser(mCurrentUser);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002310 }
2311
2312 ActivityRecord getHomeActivityForUser(int userId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002313 final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
2314 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
2315 final TaskRecord task = tasks.get(taskNdx);
2316 if (task.isHomeTask()) {
2317 final ArrayList<ActivityRecord> activities = task.mActivities;
2318 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2319 final ActivityRecord r = activities.get(activityNdx);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002320 if (r.isHomeActivity()
2321 && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
Craig Mautneree2e45a2014-06-27 12:10:03 -07002322 return r;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002323 }
2324 }
2325 }
2326 }
2327 return null;
2328 }
2329
Chong Zhangb15758a2015-11-17 12:12:03 -08002330 /**
2331 * Returns if a stack should be treated as if it's docked. Returns true if the stack is
2332 * the docked stack itself, or if it's side-by-side to the docked stack.
2333 */
2334 boolean isStackDockedInEffect(int stackId) {
2335 return stackId == DOCKED_STACK_ID ||
2336 (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
2337 }
2338
Jorim Jaggidc249c42015-12-15 14:57:31 -08002339 void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002340 boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
Jorim Jaggidc249c42015-12-15 14:57:31 -08002341 if (stackId == DOCKED_STACK_ID) {
2342 resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002343 preserveWindows, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002344 return;
2345 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08002346 final ActivityStack stack = getStack(stackId);
2347 if (stack == null) {
2348 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2349 return;
2350 }
Wale Ogunwale9d3de4c2015-02-01 16:49:44 -08002351
Winson Chunga2249ac2017-03-30 18:15:30 -07002352 if (!allowResizeInDockedMode && !StackId.tasksAreFloating(stackId) &&
2353 getStack(DOCKED_STACK_ID) != null) {
2354 // If the docked stack exists, don't resize non-floating stacks independently of the
2355 // size computed from the docked stack size (otherwise they will be out of sync)
Wale Ogunwaleffc11bb2015-10-10 13:05:45 -07002356 return;
2357 }
2358
Wale Ogunwalecad05a02015-09-25 10:41:44 -07002359 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
Jorim Jaggic4025202015-10-22 16:43:34 +02002360 mWindowManager.deferSurfaceLayout();
2361 try {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002362 stack.resize(bounds, tempTaskBounds, tempTaskInsetBounds);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002363 if (!deferResume) {
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002364 stack.ensureVisibleActivitiesConfigurationLocked(
2365 stack.topRunningActivityLocked(), preserveWindows);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002366 }
Jorim Jaggic4025202015-10-22 16:43:34 +02002367 } finally {
2368 mWindowManager.continueSurfaceLayout();
2369 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07002370 }
2371 }
2372
Jorim Jaggi192086e2016-03-11 17:17:03 +01002373 void deferUpdateBounds(int stackId) {
2374 final ActivityStack stack = getStack(stackId);
2375 if (stack != null) {
2376 stack.deferUpdateBounds();
2377 }
2378 }
2379
2380 void continueUpdateBounds(int stackId) {
2381 final ActivityStack stack = getStack(stackId);
2382 if (stack != null) {
2383 stack.continueUpdateBounds();
2384 }
2385 }
2386
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002387 void notifyAppTransitionDone() {
Matthew Ng606dd802017-06-05 14:06:32 -07002388 continueUpdateBounds(RECENTS_STACK_ID);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002389 for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2390 final int taskId = mResizingTasksDuringAnimation.valueAt(i);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002391 final TaskRecord task =
Winson Chung7900bee2017-03-10 08:59:25 -08002392 anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002393 if (task != null) {
2394 task.setTaskDockedResizing(false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002395 }
2396 }
2397 mResizingTasksDuringAnimation.clear();
2398 }
2399
Robert Carre7cc44d2017-03-20 19:04:30 -07002400 private void moveTasksToFullscreenStackInSurfaceTransaction(int fromStackId,
2401 boolean onTop) {
Robert Carr6914f082017-03-20 19:04:30 -07002402
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002403 final ActivityStack stack = getStack(fromStackId);
2404 if (stack == null) {
2405 return;
2406 }
2407
2408 mWindowManager.deferSurfaceLayout();
2409 try {
2410 if (fromStackId == DOCKED_STACK_ID) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002411 // We are moving all tasks from the docked stack to the fullscreen stack,
2412 // which is dismissing the docked stack, so resize all other stacks to
2413 // fullscreen here already so we don't end up with resize trashing.
2414 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2415 if (StackId.isResizeableByDockedStack(i)) {
2416 ActivityStack otherStack = getStack(i);
2417 if (otherStack != null) {
2418 resizeStackLocked(i, null, null, null, PRESERVE_WINDOWS,
2419 true /* allowResizeInDockedMode */, DEFER_RESUME);
2420 }
2421 }
2422 }
2423
2424 // Also disable docked stack resizing since we have manually adjusted the
2425 // size of other stacks above and we don't want to trigger a docked stack
2426 // resize when we remove task from it below and it is detached from the
2427 // display because it no longer contains any tasks.
2428 mAllowDockedStackResize = false;
Winson Chung47900652017-04-06 18:44:25 -07002429 } else if (fromStackId == PINNED_STACK_ID) {
2430 if (onTop) {
2431 // Log if we are expanding the PiP to fullscreen
2432 MetricsLogger.action(mService.mContext,
2433 ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN);
2434 }
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002435 }
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002436 ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
Winson Chungc85d9ce2017-01-03 11:59:52 -08002437 final boolean isFullscreenStackVisible = fullscreenStack != null &&
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002438 fullscreenStack.shouldBeVisible(null) == STACK_VISIBLE;
Winson Chung5af42fc2017-03-24 17:11:33 -07002439 // If we are moving from the pinned stack, then the animation takes care of updating
2440 // the picture-in-picture mode.
Winson Chung47900652017-04-06 18:44:25 -07002441 final boolean schedulePictureInPictureModeChange = (fromStackId == PINNED_STACK_ID);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002442 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2443 final int size = tasks.size();
2444 if (onTop) {
2445 for (int i = 0; i < size; i++) {
Winson Chung0c1ca092016-11-10 17:40:34 -08002446 final TaskRecord task = tasks.get(i);
Winson Chung74666102017-02-22 17:49:24 -08002447 final boolean isTopTask = i == (size - 1);
Winson Chung0c1ca092016-11-10 17:40:34 -08002448 if (fromStackId == PINNED_STACK_ID) {
2449 // Update the return-to to reflect where the pinned stack task was moved
2450 // from so that we retain the stack that was previously visible if the
2451 // pinned stack is recreated. See moveActivityToPinnedStackLocked().
Winson Chungc85d9ce2017-01-03 11:59:52 -08002452 task.setTaskToReturnTo(isFullscreenStackVisible && onTop ?
2453 APPLICATION_ACTIVITY_TYPE : HOME_ACTIVITY_TYPE);
Winson Chung0c1ca092016-11-10 17:40:34 -08002454 }
Winson Chung74666102017-02-22 17:49:24 -08002455 // Defer resume until all the tasks have been moved to the fullscreen stack
2456 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
2457 REPARENT_MOVE_STACK_TO_FRONT, isTopTask /* animate */, DEFER_RESUME,
Winson Chung5af42fc2017-03-24 17:11:33 -07002458 schedulePictureInPictureModeChange,
Winson Chung74666102017-02-22 17:49:24 -08002459 "moveTasksToFullscreenStack - onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002460 }
2461 } else {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002462 for (int i = 0; i < size; i++) {
Wale Ogunwalec5cc3012017-01-13 13:26:16 -08002463 final TaskRecord task = tasks.get(i);
Winson Chung3a649982017-04-19 10:16:17 -07002464 // Position the tasks in the fullscreen stack in order at the bottom of the
2465 // stack. Also defer resume until all the tasks have been moved to the
2466 // fullscreen stack.
2467 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, i /* position */,
Winson Chung5af42fc2017-03-24 17:11:33 -07002468 REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME,
2469 schedulePictureInPictureModeChange,
2470 "moveTasksToFullscreenStack - NOT_onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002471 }
2472 }
Winson Chung74666102017-02-22 17:49:24 -08002473
2474 ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2475 resumeFocusedStackTopActivityLocked();
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002476 } finally {
2477 mAllowDockedStackResize = true;
2478 mWindowManager.continueSurfaceLayout();
2479 }
2480 }
2481
Robert Carr6914f082017-03-20 19:04:30 -07002482 void moveTasksToFullscreenStackLocked(int fromStackId, boolean onTop) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002483 mWindowManager.inSurfaceTransaction(
2484 () -> moveTasksToFullscreenStackInSurfaceTransaction(fromStackId, onTop));
Robert Carr6914f082017-03-20 19:04:30 -07002485 }
2486
Jorim Jaggidc249c42015-12-15 14:57:31 -08002487 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002488 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2489 boolean preserveWindows) {
2490 resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
2491 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows,
2492 false /* deferResume */);
2493 }
2494
2495 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2496 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2497 boolean preserveWindows, boolean deferResume) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002498
2499 if (!mAllowDockedStackResize) {
2500 // Docked stack resize currently disabled.
2501 return;
2502 }
2503
Jorim Jaggidc249c42015-12-15 14:57:31 -08002504 final ActivityStack stack = getStack(DOCKED_STACK_ID);
2505 if (stack == null) {
2506 Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2507 return;
2508 }
2509
2510 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2511 mWindowManager.deferSurfaceLayout();
2512 try {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002513 // Don't allow re-entry while resizing. E.g. due to docked stack detaching.
2514 mAllowDockedStackResize = false;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002515 ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwale1666e312016-12-16 11:27:18 -08002516 stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002517
Andrii Kulian69fb5e42016-04-05 16:47:29 -07002518 // TODO: Checking for isAttached might not be needed as if the user passes in null
2519 // dockedBounds then they want the docked stack to be dismissed.
2520 if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2521 // The dock stack either was dismissed or went fullscreen, which is kinda the same.
Jorim Jaggidc249c42015-12-15 14:57:31 -08002522 // In this case we make all other static stacks fullscreen and move all
2523 // docked stack tasks to the fullscreen stack.
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002524 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, ON_TOP);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002525
2526 // stack shouldn't contain anymore activities, so nothing to resume.
2527 r = null;
2528 } else {
2529 // Docked stacks occupy a dedicated region on screen so the size of all other
2530 // static stacks need to be adjusted so they don't overlap with the docked stack.
2531 // We get the bounds to use from window manager which has been adjusted for any
2532 // screen controls and is also the same for all stacks.
Matthew Ngaa2b6202017-02-10 14:48:21 -08002533 final Rect otherTaskRect = new Rect();
Jorim Jaggidc249c42015-12-15 14:57:31 -08002534 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002535 final ActivityStack current = getStack(i);
2536 if (current != null && StackId.isResizeableByDockedStack(i)) {
Matthew Ngaa2b6202017-02-10 14:48:21 -08002537 current.getStackDockedModeBounds(
2538 tempOtherTaskBounds /* currentTempTaskBounds */,
2539 tempRect /* outStackBounds */,
2540 otherTaskRect /* outTempTaskBounds */, true /* ignoreVisibility */);
2541
Andrii Kuliane48b7d82017-04-28 14:51:05 -07002542 resizeStackLocked(i, !tempRect.isEmpty() ? tempRect : null,
Matthew Ngaa2b6202017-02-10 14:48:21 -08002543 !otherTaskRect.isEmpty() ? otherTaskRect : tempOtherTaskBounds,
2544 tempOtherTaskInsetBounds, preserveWindows,
2545 true /* allowResizeInDockedMode */, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002546 }
2547 }
2548 }
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002549 if (!deferResume) {
2550 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows);
2551 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002552 } finally {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002553 mAllowDockedStackResize = true;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002554 mWindowManager.continueSurfaceLayout();
2555 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2556 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002557 }
2558
Robert Carr0d00c2e2016-02-29 17:45:02 -08002559 void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Winson Chung19953ca2017-04-11 11:19:23 -07002560 final PinnedActivityStack stack = getStack(PINNED_STACK_ID);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002561 if (stack == null) {
2562 Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2563 return;
2564 }
Winson Chung19953ca2017-04-11 11:19:23 -07002565
2566 // It is possible for the bounds animation from the WM to call this but be delayed by
2567 // another AM call that is holding the AMS lock. In such a case, the pinnedBounds may be
2568 // incorrect if AMS.resizeStackWithBoundsFromWindowManager() is already called while waiting
2569 // for the AMS lock to be freed. So check and make sure these bounds are still good.
2570 final PinnedStackWindowController stackController = stack.getWindowContainerController();
Winson Chung8bca9e42017-04-16 15:59:43 -07002571 if (stackController.pinnedStackResizeDisallowed()) {
Winson Chung19953ca2017-04-11 11:19:23 -07002572 return;
2573 }
2574
Robert Carr0d00c2e2016-02-29 17:45:02 -08002575 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2576 mWindowManager.deferSurfaceLayout();
2577 try {
2578 ActivityRecord r = stack.topRunningActivityLocked();
Robert Carr7e4c90e2017-02-15 19:52:38 -08002579 Rect insetBounds = null;
2580 if (tempPinnedTaskBounds != null) {
2581 // We always use 0,0 as the position for the inset rect because
2582 // if we are getting insets at all in the pinned stack it must mean
2583 // we are headed for fullscreen.
2584 insetBounds = tempRect;
2585 insetBounds.top = 0;
2586 insetBounds.left = 0;
2587 insetBounds.right = tempPinnedTaskBounds.width();
2588 insetBounds.bottom = tempPinnedTaskBounds.height();
2589 }
2590 stack.resize(pinnedBounds, tempPinnedTaskBounds, insetBounds);
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002591 stack.ensureVisibleActivitiesConfigurationLocked(r, false);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002592 } finally {
2593 mWindowManager.continueSurfaceLayout();
2594 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2595 }
2596 }
2597
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002598 ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002599 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Craig Mautnere0a38842013-12-16 16:14:02 -08002600 if (activityDisplay == null) {
Todd Kennedy4900bf92015-01-16 16:05:14 -08002601 return null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002602 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002603 return createStack(stackId, activityDisplay, onTop);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002604
Craig Mautner4a1cb222013-12-04 16:14:06 -08002605 }
2606
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002607 ActivityStack createStack(int stackId, ActivityDisplay display, boolean onTop) {
2608 switch (stackId) {
2609 case PINNED_STACK_ID:
2610 return new PinnedActivityStack(display, stackId, this, mRecentTasks, onTop);
2611 default:
2612 return new ActivityStack(display, stackId, this, mRecentTasks, onTop);
2613 }
2614 }
Robert Carr6914f082017-03-20 19:04:30 -07002615
Robert Carre7cc44d2017-03-20 19:04:30 -07002616 void removeStackInSurfaceTransaction(int stackId) {
Winson Chung010927a2016-12-15 16:12:35 -08002617 final ActivityStack stack = getStack(stackId);
2618 if (stack == null) {
2619 return;
2620 }
2621
2622 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2623 if (stack.getStackId() == PINNED_STACK_ID) {
Winson Chung47900652017-04-06 18:44:25 -07002624 /**
2625 * Workaround: Force-stop all the activities in the pinned stack before we reparent them
2626 * to the fullscreen stack. This is to guarantee that when we are removing a stack,
2627 * that the client receives onStop() before it is reparented. We do this by detaching
2628 * the stack from the display so that it will be considered invisible when
2629 * ensureActivitiesVisibleLocked() is called, and all of its activitys will be marked
2630 * invisible as well and added to the stopping list. After which we process the
2631 * stopping list by handling the idle.
2632 */
2633 final PinnedActivityStack pinnedStack = (PinnedActivityStack) stack;
2634 pinnedStack.mForceHidden = true;
2635 pinnedStack.ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2636 pinnedStack.mForceHidden = false;
2637 activityIdleInternalLocked(null, false /* fromTimeout */,
2638 true /* processPausingActivites */, null /* configuration */);
2639
2640 // Move all the tasks to the bottom of the fullscreen stack
2641 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
Winson Chung010927a2016-12-15 16:12:35 -08002642 } else {
2643 for (int i = tasks.size() - 1; i >= 0; i--) {
2644 removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */,
2645 REMOVE_FROM_RECENTS);
2646 }
2647 }
2648 }
2649
2650 /**
Robert Carr6914f082017-03-20 19:04:30 -07002651 * Removes the stack associated with the given {@param stackId}. If the {@param stackId} is the
2652 * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
2653 * instead moved back onto the fullscreen stack.
2654 */
2655 void removeStackLocked(int stackId) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002656 mWindowManager.inSurfaceTransaction(
2657 () -> removeStackInSurfaceTransaction(stackId));
Robert Carr6914f082017-03-20 19:04:30 -07002658 }
2659
2660 /**
Winson Chung6954fc92017-03-24 16:22:12 -07002661 * See {@link #removeTaskByIdLocked(int, boolean, boolean, boolean)}
2662 */
2663 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents) {
2664 return removeTaskByIdLocked(taskId, killProcess, removeFromRecents, !PAUSE_IMMEDIATELY);
2665 }
2666
2667 /**
Winson Chung010927a2016-12-15 16:12:35 -08002668 * Removes the task with the specified task id.
2669 *
2670 * @param taskId Identifier of the task to be removed.
2671 * @param killProcess Kill any process associated with the task if possible.
2672 * @param removeFromRecents Whether to also remove the task from recents.
Winson Chung6954fc92017-03-24 16:22:12 -07002673 * @param pauseImmediately Pauses all task activities immediately without waiting for the
2674 * pause-complete callback from the activity.
Winson Chung010927a2016-12-15 16:12:35 -08002675 * @return Returns true if the given task was found and removed.
2676 */
Winson Chung6954fc92017-03-24 16:22:12 -07002677 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents,
2678 boolean pauseImmediately) {
Winson Chung7900bee2017-03-10 08:59:25 -08002679 final TaskRecord tr = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
2680 INVALID_STACK_ID);
Winson Chung010927a2016-12-15 16:12:35 -08002681 if (tr != null) {
Winson Chung6954fc92017-03-24 16:22:12 -07002682 tr.removeTaskActivitiesLocked(pauseImmediately);
Winson Chung010927a2016-12-15 16:12:35 -08002683 cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents);
2684 if (tr.isPersistable) {
2685 mService.notifyTaskPersisterLocked(null, true);
2686 }
2687 return true;
2688 }
2689 Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
2690 return false;
2691 }
2692
2693 void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) {
2694 if (removeFromRecents) {
2695 mRecentTasks.remove(tr);
2696 tr.removedFromRecents();
2697 }
2698 ComponentName component = tr.getBaseIntent().getComponent();
2699 if (component == null) {
2700 Slog.w(TAG, "No component for base intent of task: " + tr);
2701 return;
2702 }
2703
2704 // Find any running services associated with this app and stop if needed.
2705 mService.mServices.cleanUpRemovedTaskLocked(tr, component, new Intent(tr.getBaseIntent()));
2706
2707 if (!killProcess) {
2708 return;
2709 }
2710
2711 // Determine if the process(es) for this task should be killed.
2712 final String pkg = component.getPackageName();
2713 ArrayList<ProcessRecord> procsToKill = new ArrayList<>();
2714 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mService.mProcessNames.getMap();
2715 for (int i = 0; i < pmap.size(); i++) {
2716
2717 SparseArray<ProcessRecord> uids = pmap.valueAt(i);
2718 for (int j = 0; j < uids.size(); j++) {
2719 ProcessRecord proc = uids.valueAt(j);
2720 if (proc.userId != tr.userId) {
2721 // Don't kill process for a different user.
2722 continue;
2723 }
2724 if (proc == mService.mHomeProcess) {
2725 // Don't kill the home process along with tasks from the same package.
2726 continue;
2727 }
2728 if (!proc.pkgList.containsKey(pkg)) {
2729 // Don't kill process that is not associated with this task.
2730 continue;
2731 }
2732
2733 for (int k = 0; k < proc.activities.size(); k++) {
Bryce Leeaf691c02017-03-20 14:20:22 -07002734 TaskRecord otherTask = proc.activities.get(k).getTask();
Winson Chung010927a2016-12-15 16:12:35 -08002735 if (tr.taskId != otherTask.taskId && otherTask.inRecents) {
2736 // Don't kill process(es) that has an activity in a different task that is
2737 // also in recents.
2738 return;
2739 }
2740 }
2741
2742 if (proc.foregroundServices) {
2743 // Don't kill process(es) with foreground service.
2744 return;
2745 }
2746
2747 // Add process to kill list.
2748 procsToKill.add(proc);
2749 }
2750 }
2751
2752 // Kill the running processes.
2753 for (int i = 0; i < procsToKill.size(); i++) {
2754 ProcessRecord pr = procsToKill.get(i);
2755 if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
2756 && pr.curReceivers.isEmpty()) {
2757 pr.kill("remove task", true);
2758 } else {
2759 // We delay killing processes that are not in the background or running a receiver.
2760 pr.waitingToKill = "remove task";
2761 }
2762 }
2763 }
2764
Craig Mautner4a1cb222013-12-04 16:14:06 -08002765 int getNextStackId() {
Craig Mautner858d8a62013-04-23 17:08:34 -07002766 while (true) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002767 if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2768 && getStack(mNextFreeStackId) == null) {
Craig Mautner858d8a62013-04-23 17:08:34 -07002769 break;
2770 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002771 mNextFreeStackId++;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002772 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002773 return mNextFreeStackId;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002774 }
2775
Chong Zhang5dcb2752015-08-18 13:50:26 -07002776 /**
2777 * Restores a recent task to a stack
2778 * @param task The recent task to be restored.
2779 * @param stackId The stack to restore the task to (default launch stack will be used
Andrii Kulian16802aa2016-11-02 12:21:33 -07002780 * if stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}
2781 * or is not a static stack).
Chong Zhang5dcb2752015-08-18 13:50:26 -07002782 * @return true if the task has been restored successfully.
2783 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002784 boolean restoreRecentTaskLocked(TaskRecord task, int stackId) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002785 if (!StackId.isStaticStack(stackId)) {
2786 // If stack is not static (or stack id is invalid) - use the default one.
2787 // This means that tasks that were on external displays will be restored on the
2788 // primary display.
Wale Ogunwale8b06a582015-10-22 14:38:21 -07002789 stackId = task.getLaunchStackId();
Winson Chungd3395382016-12-13 11:49:09 -08002790 } else if (stackId == DOCKED_STACK_ID && !task.supportsSplitScreen()) {
Wale Ogunwale513346d2016-01-27 10:55:01 -08002791 // Preferred stack is the docked stack, but the task can't go in the docked stack.
2792 // Put it in the fullscreen stack.
2793 stackId = FULLSCREEN_WORKSPACE_STACK_ID;
Chong Zhang5dcb2752015-08-18 13:50:26 -07002794 }
Wale Ogunwale513346d2016-01-27 10:55:01 -08002795
Andrii Kulian02b7a832016-10-06 23:11:56 -07002796 final ActivityStack currentStack = task.getStack();
2797 if (currentStack != null) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002798 // Task has already been restored once. See if we need to do anything more
Andrii Kulian02b7a832016-10-06 23:11:56 -07002799 if (currentStack.mStackId == stackId) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002800 // Nothing else to do since it is already restored in the right stack.
2801 return true;
2802 }
2803 // Remove current stack association, so we can re-associate the task with the
2804 // right stack below.
Andrii Kulian02b7a832016-10-06 23:11:56 -07002805 currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING);
Wale Ogunwale706ed792015-08-02 10:29:44 -07002806 }
2807
Wale Ogunwale6c5eb1c2015-11-10 07:52:22 -08002808 final ActivityStack stack =
Wale Ogunwale040b4702015-08-06 18:10:50 -07002809 getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002810
2811 if (stack == null) {
2812 // What does this mean??? Not sure how we would get here...
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002813 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2814 "Unable to find/create stack to restore recent task=" + task);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002815 return false;
2816 }
2817
Wale Ogunwale72919d22016-12-08 18:58:50 -08002818 stack.addTask(task, false /* toTop */, "restoreRecentTask");
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002819 // TODO: move call for creation here and other place into Stack.addTask()
2820 task.createWindowContainer(false /* toTop */, true /* showForAllUsers */);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002821 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2822 "Added restored task=" + task + " to stack=" + stack);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002823 final ArrayList<ActivityRecord> activities = task.mActivities;
2824 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002825 activities.get(activityNdx).createWindowContainer();
Wale Ogunwale7de05352014-12-12 15:21:33 -08002826 }
2827 return true;
Craig Mautneref73ee12014-04-23 11:45:37 -07002828 }
2829
Wale Ogunwale040b4702015-08-06 18:10:50 -07002830 /**
Andrii Kulian839def92016-11-02 10:58:58 -07002831 * Move stack with all its existing content to specified display.
2832 * @param stackId Id of stack to move.
2833 * @param displayId Id of display to move stack to.
Andrii Kulian250d6532017-02-08 23:30:45 -08002834 * @param onTop Indicates whether container should be place on top or on bottom.
Andrii Kulian839def92016-11-02 10:58:58 -07002835 */
Andrii Kulian250d6532017-02-08 23:30:45 -08002836 void moveStackToDisplayLocked(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002837 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian839def92016-11-02 10:58:58 -07002838 if (activityDisplay == null) {
2839 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown displayId="
2840 + displayId);
2841 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002842 final ActivityStack stack = mStacks.get(stackId);
2843 if (stack == null) {
Andrii Kulian839def92016-11-02 10:58:58 -07002844 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
2845 + stackId);
2846 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002847
2848 final ActivityDisplay currentDisplay = stack.getDisplay();
2849 if (currentDisplay == null) {
2850 throw new IllegalStateException("moveStackToDisplayLocked: Stack with stack=" + stack
2851 + " is not attached to any display.");
2852 }
2853
2854 if (currentDisplay.mDisplayId == displayId) {
2855 throw new IllegalArgumentException("Trying to move stack=" + stack
2856 + " to its current displayId=" + displayId);
2857 }
2858
2859 stack.reparent(activityDisplay, onTop);
Andrii Kulian839def92016-11-02 10:58:58 -07002860 // TODO(multi-display): resize stacks properly if moved from split-screen.
2861 }
2862
2863 /**
Winson Chung74666102017-02-22 17:49:24 -08002864 * Returns the reparent target stack, creating the stack if necessary. This call also enforces
2865 * the various checks on tasks that are going to be reparented from one stack to another.
Wale Ogunwale040b4702015-08-06 18:10:50 -07002866 */
Winson Chung74666102017-02-22 17:49:24 -08002867 ActivityStack getReparentTargetStack(TaskRecord task, int stackId, boolean toTop) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07002868 final ActivityStack prevStack = task.getStack();
Chong Zhang02898352015-08-21 17:27:14 -07002869
Winson Chung74666102017-02-22 17:49:24 -08002870 // Check that we aren't reparenting to the same stack that the task is already in
2871 if (prevStack != null && prevStack.mStackId == stackId) {
2872 Slog.w(TAG, "Can not reparent to same stack, task=" + task
2873 + " already in stackId=" + stackId);
2874 return prevStack;
Wale Ogunwale513346d2016-01-27 10:55:01 -08002875 }
2876
Winson Chung74666102017-02-22 17:49:24 -08002877 // Ensure that we aren't trying to move into a multi-window stack without multi-window
2878 // support
2879 if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
2880 throw new IllegalArgumentException("Device doesn't support multi-window, can not"
2881 + " reparent task=" + task + " to stackId=" + stackId);
Winson Chungc2baac02017-01-11 13:34:47 -08002882 }
2883
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002884 // Ensure that we're not moving a task to a dynamic stack if device doesn't support
2885 // multi-display.
2886 // TODO(multi-display): Support non-dynamic stacks on secondary displays.
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002887 if (StackId.isDynamicStack(stackId) && !mService.mSupportsMultiDisplay) {
2888 throw new IllegalArgumentException("Device doesn't support multi-display, can not"
2889 + " reparent task=" + task + " to stackId=" + stackId);
2890 }
2891
Winson Chung74666102017-02-22 17:49:24 -08002892 // Ensure that we aren't trying to move into a freeform stack without freeform
2893 // support
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002894 if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
Winson Chung74666102017-02-22 17:49:24 -08002895 throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
2896 + " task=" + task);
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002897 }
2898
Winson Chung74666102017-02-22 17:49:24 -08002899 // We don't allow moving a unresizeable task to the docked stack since the docked stack is
2900 // used for split-screen mode and will cause things like the docked divider to show up. We
2901 // instead leave the task in its current stack or move it to the fullscreen stack if it
2902 // isn't currently in a stack.
2903 if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
2904 stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
2905 Slog.w(TAG, "Can not move unresizeable task=" + task + " to docked stack."
2906 + " Moving to stackId=" + stackId + " instead.");
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07002907 }
Wale Ogunwale961f4852016-02-01 20:25:54 -08002908
Winson Chung74666102017-02-22 17:49:24 -08002909 // Temporarily disable resizeablility of the task as we don't want it to be resized if, for
2910 // example, a docked stack is created which will lead to the stack we are moving from being
2911 // resized and and its resizeable tasks being resized.
Wale Ogunwale961f4852016-02-01 20:25:54 -08002912 try {
Winson Chung74666102017-02-22 17:49:24 -08002913 task.mTemporarilyUnresizable = true;
2914 return getStack(stackId, CREATE_IF_NEEDED, toTop);
Wale Ogunwale961f4852016-02-01 20:25:54 -08002915 } finally {
Winson Chung74666102017-02-22 17:49:24 -08002916 task.mTemporarilyUnresizable = false;
Chong Zhangf596cd52016-01-05 13:42:44 -08002917 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002918 }
2919
Winson Chung08f81892017-03-02 15:40:51 -08002920 boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect destBounds) {
Wale Ogunwale079a0042015-10-24 11:44:07 -07002921 final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2922 if (stack == null) {
2923 throw new IllegalArgumentException(
2924 "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
2925 }
2926
2927 final ActivityRecord r = stack.topRunningActivityLocked();
2928 if (r == null) {
2929 Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
2930 + " in stack=" + stack);
2931 return false;
2932 }
2933
Wale Ogunwale6cae7652015-12-26 07:36:26 -08002934 if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
Wale Ogunwaleb60692e2015-10-24 12:35:56 -07002935 Slog.w(TAG,
2936 "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
Filip Gruszczynski77d94482015-12-11 13:59:52 -08002937 + " r=" + r);
Wale Ogunwale079a0042015-10-24 11:44:07 -07002938 return false;
2939 }
2940
Winson Chung3a682872017-04-10 14:38:05 -07002941 moveActivityToPinnedStackLocked(r, null /* sourceBounds */, 0f /* aspectRatio */,
Winson Chung08f81892017-03-02 15:40:51 -08002942 true /* moveHomeStackToFront */, "moveTopActivityToPinnedStack");
Wale Ogunwale9c604c72015-12-06 18:42:57 -08002943 return true;
2944 }
2945
Winson Chung8bca9e42017-04-16 15:59:43 -07002946 void moveActivityToPinnedStackLocked(ActivityRecord r, Rect sourceHintBounds, float aspectRatio,
Winson Chung08f81892017-03-02 15:40:51 -08002947 boolean moveHomeStackToFront, String reason) {
2948
Wale Ogunwale480dca02016-02-06 13:58:29 -08002949 mWindowManager.deferSurfaceLayout();
Winson Chung74666102017-02-22 17:49:24 -08002950
Bryce Lee04ab3462017-04-10 15:06:33 -07002951 // This will clear the pinned stack by moving an existing task to the full screen stack,
2952 // ensuring only one task is present.
2953 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
2954
Wale Ogunwale1666e312016-12-16 11:27:18 -08002955 // Need to make sure the pinned stack exist so we can resize it below...
Winson Chung55893332017-02-17 17:13:10 -08002956 final PinnedActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Wale Ogunwale1666e312016-12-16 11:27:18 -08002957
Wale Ogunwale480dca02016-02-06 13:58:29 -08002958 try {
Bryce Leeaf691c02017-03-20 14:20:22 -07002959 final TaskRecord task = r.getTask();
Wale Ogunwale480dca02016-02-06 13:58:29 -08002960 // Resize the pinned stack to match the current size of the task the activity we are
2961 // going to be moving is currently contained in. We do this to have the right starting
2962 // animation bounds for the pinned stack to the desired bounds the caller wants.
2963 resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
2964 null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002965 true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002966
2967 if (task.mActivities.size() == 1) {
2968 // There is only one activity in the task. So, we can just move the task over to
Winson Chungc2baac02017-01-11 13:34:47 -08002969 // the stack without re-parenting the activity in a different task. We don't
2970 // move the home stack forward if we are currently entering picture-in-picture
2971 // while pausing because that changes the focused stack and may prevent the new
2972 // starting activity from resuming.
2973 if (moveHomeStackToFront && task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE
Winson Chung105ae5f2017-03-06 15:06:28 -08002974 && (r.state == RESUMED || !r.supportsPictureInPictureWhilePausing)) {
Wale Ogunwaleda4ba962016-03-11 09:33:17 -08002975 // Move the home stack forward if the task we just moved to the pinned stack
2976 // was launched from home so home should be visible behind it.
2977 moveHomeStackToFront(reason);
2978 }
Winson Chung5af42fc2017-03-24 17:11:33 -07002979 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08002980 task.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07002981 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002982 } else {
Winson Chungb5c41b72016-12-07 15:00:47 -08002983 // There are multiple activities in the task and moving the top activity should
Winson Chung74666102017-02-22 17:49:24 -08002984 // reveal/leave the other activities in their original task.
2985
2986 // Currently, we don't support reparenting activities across tasks in two different
2987 // stacks, so instead, just create a new task in the same stack, reparent the
2988 // activity into that task, and then reparent the whole task to the new stack. This
2989 // ensures that all the necessary work to migrate states in the old and new stacks
2990 // is also done.
2991 final TaskRecord newTask = task.getStack().createTaskRecord(
2992 getNextTaskIdForUserLocked(r.userId), r.info, r.intent, null, null, true,
2993 r.mActivityType);
2994 r.reparent(newTask, MAX_VALUE, "moveActivityToStack");
2995
Winson Chung5af42fc2017-03-24 17:11:33 -07002996 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08002997 newTask.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07002998 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002999 }
Winson Chungc2baac02017-01-11 13:34:47 -08003000
3001 // Reset the state that indicates it can enter PiP while pausing after we've moved it
3002 // to the pinned stack
3003 r.supportsPictureInPictureWhilePausing = false;
Wale Ogunwale480dca02016-02-06 13:58:29 -08003004 } finally {
3005 mWindowManager.continueSurfaceLayout();
Wale Ogunwale079a0042015-10-24 11:44:07 -07003006 }
3007
Winson Chunge7ba6862017-05-24 12:13:33 -07003008 // Calculate the default bounds (don't use existing stack bounds as we may have just created
3009 // the stack, and schedule the start of the animation into PiP (the bounds animator that
3010 // is triggered by this is posted on another thread)
Winson Chunga71febe2017-05-22 11:14:22 -07003011 final Rect destBounds = stack.getDefaultPictureInPictureBounds(aspectRatio);
3012
Winson Chunge7ba6862017-05-24 12:13:33 -07003013 stack.animateResizePinnedStack(sourceHintBounds, destBounds, -1 /* animationDuration */,
3014 true /* fromFullscreen */);
3015
3016 // Update the visibility of all activities after the they have been reparented to the new
3017 // stack. This MUST run after the animation above is scheduled to ensure that the windows
3018 // drawn signal is scheduled after the bounds animation start call on the bounds animator
3019 // thread.
Wale Ogunwale079a0042015-10-24 11:44:07 -07003020 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwaled046a012015-12-24 13:05:59 -08003021 resumeFocusedStackTopActivityLocked();
Wale Ogunwale03ce8632015-12-29 16:15:22 -08003022
Winson Chungb5026902017-05-03 12:45:13 -07003023 mService.mTaskChangeNotificationController.notifyActivityPinned(r.packageName,
3024 r.getTask().taskId);
Wale Ogunwale079a0042015-10-24 11:44:07 -07003025 }
3026
Andrii Kulian0864bbb2017-02-16 15:45:58 -08003027 /** Move activity with its stack to front and make the stack focused. */
Chong Zhang6cda19c2016-06-14 19:07:56 -07003028 boolean moveFocusableActivityStackToFrontLocked(ActivityRecord r, String reason) {
3029 if (r == null || !r.isFocusable()) {
3030 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3031 "moveActivityStackToFront: unfocusable r=" + r);
3032 return false;
3033 }
3034
Bryce Leeaf691c02017-03-20 14:20:22 -07003035 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003036 final ActivityStack stack = r.getStack();
3037 if (stack == null) {
Chong Zhang6cda19c2016-06-14 19:07:56 -07003038 Slog.w(TAG, "moveActivityStackToFront: invalid task or stack: r="
3039 + r + " task=" + task);
3040 return false;
3041 }
3042
Chong Zhang6cda19c2016-06-14 19:07:56 -07003043 if (stack == mFocusedStack && stack.topRunningActivityLocked() == r) {
3044 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3045 "moveActivityStackToFront: already on top, r=" + r);
3046 return false;
3047 }
3048
3049 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3050 "moveActivityStackToFront: r=" + r);
3051
3052 stack.moveToFront(reason, task);
3053 return true;
3054 }
3055
David Stevensc6b91c62017-02-08 14:23:58 -08003056 ActivityRecord findTaskLocked(ActivityRecord r, int displayId) {
Wale Ogunwale39381972015-12-17 17:15:29 -08003057 mTmpFindTaskResult.r = null;
3058 mTmpFindTaskResult.matchedByRootAffinity = false;
David Stevensc6b91c62017-02-08 14:23:58 -08003059 ActivityRecord affinityMatch = null;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003060 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
Craig Mautnere0a38842013-12-16 16:14:02 -08003061 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3062 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003063 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3064 final ActivityStack stack = stacks.get(stackNdx);
Winson Chung91e5c882017-04-21 14:44:38 -07003065 if (!checkActivityBelongsInStack(r, stack)) {
3066 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) "
3067 + stack);
Craig Mautner1b4bf852014-05-26 15:06:32 -07003068 continue;
3069 }
Wale Ogunwale39381972015-12-17 17:15:29 -08003070 stack.findTaskLocked(r, mTmpFindTaskResult);
David Stevensc6b91c62017-02-08 14:23:58 -08003071 // It is possible to have tasks in multiple stacks with the same root affinity, so
3072 // we should keep looking after finding an affinity match to see if there is a
3073 // better match in another stack. Also, task affinity isn't a good enough reason
3074 // to target a display which isn't the source of the intent, so skip any affinity
3075 // matches not on the specified display.
3076 if (mTmpFindTaskResult.r != null) {
3077 if (!mTmpFindTaskResult.matchedByRootAffinity) {
3078 return mTmpFindTaskResult.r;
3079 } else if (mTmpFindTaskResult.r.getDisplayId() == displayId) {
Winson Chung5b895b72017-05-01 13:46:25 -07003080 // Note: since the traversing through the stacks is top down, the floating
3081 // tasks should always have lower priority than any affinity-matching tasks
3082 // in the fullscreen stacks
David Stevensc6b91c62017-02-08 14:23:58 -08003083 affinityMatch = mTmpFindTaskResult.r;
3084 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003085 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003086 }
3087 }
Winson Chung5b895b72017-05-01 13:46:25 -07003088
David Stevensc6b91c62017-02-08 14:23:58 -08003089 if (DEBUG_TASKS && affinityMatch == null) Slog.d(TAG_TASKS, "No task found");
3090 return affinityMatch;
Craig Mautner8849a5e2013-04-02 16:41:03 -07003091 }
3092
Winson Chung91e5c882017-04-21 14:44:38 -07003093 /**
3094 * Checks that for the given activity {@param r}, its activity type matches the {@param stack}
3095 * type.
3096 */
3097 private boolean checkActivityBelongsInStack(ActivityRecord r, ActivityStack stack) {
3098 if (r.isHomeActivity()) {
3099 return stack.isHomeStack();
3100 } else if (r.isRecentsActivity()) {
3101 return stack.isRecentsStack();
3102 } else if (r.isAssistantActivity()) {
3103 return stack.isAssistantStack();
3104 }
3105 return true;
3106 }
3107
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003108 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
3109 boolean compareIntentFilters) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003110 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3111 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003112 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003113 final ActivityRecord ar = stacks.get(stackNdx)
3114 .findActivityLocked(intent, info, compareIntentFilters);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003115 if (ar != null) {
3116 return ar;
3117 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003118 }
3119 }
3120 return null;
3121 }
3122
Craig Mautner8d341ef2013-03-26 09:03:27 -07003123 void goingToSleepLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003124 scheduleSleepTimeout();
3125 if (!mGoingToSleep.isHeld()) {
3126 mGoingToSleep.acquire();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003127 if (mLaunchingActivity.isHeld()) {
3128 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
3129 throw new IllegalStateException("Calling must be system uid");
Craig Mautner0eea92c2013-05-16 13:35:39 -07003130 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003131 mLaunchingActivity.release();
3132 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003133 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003134 }
Amith Yamasanice15e152013-09-19 12:30:32 -07003135 checkReadyForSleepLocked();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003136 }
3137
3138 boolean shutdownLocked(int timeout) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003139 goingToSleepLocked();
Craig Mautner0eea92c2013-05-16 13:35:39 -07003140
Craig Mautnerf4c909b2014-04-17 18:39:38 -07003141 boolean timedout = false;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003142 final long endTime = System.currentTimeMillis() + timeout;
3143 while (true) {
3144 boolean cantShutdown = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003145 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3146 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003147 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3148 cantShutdown |= stacks.get(stackNdx).checkReadyForSleepLocked();
3149 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003150 }
3151 if (cantShutdown) {
3152 long timeRemaining = endTime - System.currentTimeMillis();
3153 if (timeRemaining > 0) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003154 try {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003155 mService.wait(timeRemaining);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003156 } catch (InterruptedException e) {
3157 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003158 } else {
3159 Slog.w(TAG, "Activity manager shutdown timed out");
3160 timedout = true;
3161 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003162 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003163 } else {
3164 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003165 }
3166 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003167
3168 // Force checkReadyForSleep to complete.
3169 mSleepTimeout = true;
3170 checkReadyForSleepLocked();
3171
Craig Mautner8d341ef2013-03-26 09:03:27 -07003172 return timedout;
3173 }
3174
3175 void comeOutOfSleepIfNeededLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003176 removeSleepTimeouts();
3177 if (mGoingToSleep.isHeld()) {
3178 mGoingToSleep.release();
3179 }
Craig Mautnere0a38842013-12-16 16:14:02 -08003180 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3181 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003182 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3183 final ActivityStack stack = stacks.get(stackNdx);
3184 stack.awakeFromSleepingLocked();
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003185 if (isFocusedStack(stack)) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08003186 resumeFocusedStackTopActivityLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08003187 }
Craig Mautner5314a402013-09-26 12:40:16 -07003188 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003189 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003190 mGoingToSleepActivities.clear();
3191 }
3192
3193 void activitySleptLocked(ActivityRecord r) {
3194 mGoingToSleepActivities.remove(r);
3195 checkReadyForSleepLocked();
3196 }
3197
3198 void checkReadyForSleepLocked() {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07003199 if (!mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003200 // Do not care.
3201 return;
3202 }
3203
3204 if (!mSleepTimeout) {
3205 boolean dontSleep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003206 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3207 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003208 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3209 dontSleep |= stacks.get(stackNdx).checkReadyForSleepLocked();
3210 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003211 }
3212
3213 if (mStoppingActivities.size() > 0) {
3214 // Still need to tell some activities to stop; can't sleep yet.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003215 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to stop "
Craig Mautner0eea92c2013-05-16 13:35:39 -07003216 + mStoppingActivities.size() + " activities");
3217 scheduleIdleLocked();
3218 dontSleep = true;
3219 }
3220
3221 if (mGoingToSleepActivities.size() > 0) {
3222 // Still need to tell some activities to sleep; can't sleep yet.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003223 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to sleep "
Craig Mautner0eea92c2013-05-16 13:35:39 -07003224 + mGoingToSleepActivities.size() + " activities");
3225 dontSleep = true;
3226 }
3227
3228 if (dontSleep) {
3229 return;
3230 }
3231 }
3232
Wei Wang65c7a152016-06-02 18:51:22 -07003233 // Send launch end powerhint before going sleep
3234 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
3235
Craig Mautnere0a38842013-12-16 16:14:02 -08003236 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3237 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003238 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3239 stacks.get(stackNdx).goToSleep();
3240 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003241 }
3242
3243 removeSleepTimeouts();
3244
3245 if (mGoingToSleep.isHeld()) {
3246 mGoingToSleep.release();
3247 }
3248 if (mService.mShuttingDown) {
3249 mService.notifyAll();
3250 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003251 }
3252
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003253 boolean reportResumedActivityLocked(ActivityRecord r) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07003254 final ActivityStack stack = r.getStack();
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003255 if (isFocusedStack(stack)) {
Jeff Sharkey5782da72013-04-25 14:32:30 -07003256 mService.updateUsageStats(r, true);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003257 }
3258 if (allResumedActivitiesComplete()) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003259 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003260 mWindowManager.executeAppTransition();
3261 return true;
3262 }
3263 return false;
3264 }
3265
Craig Mautner8d341ef2013-03-26 09:03:27 -07003266 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003267 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3268 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Wale Ogunwale28b23972015-07-29 16:01:50 -07003269 int stackNdx = stacks.size() - 1;
3270 while (stackNdx >= 0) {
3271 stacks.get(stackNdx).handleAppCrashLocked(app);
3272 stackNdx--;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003273 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003274 }
3275 }
3276
Craig Mautnerbb742462014-07-07 15:28:55 -07003277 // Called when WindowManager has finished animating the launchingBehind activity to the back.
Andrii Kulian21713ac2016-10-12 22:05:05 -07003278 private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003279 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003280 final ActivityStack stack = task.getStack();
Winson730bf062016-03-31 18:04:56 -07003281
3282 r.mLaunchTaskBehind = false;
Andrii Kulian21713ac2016-10-12 22:05:05 -07003283 task.setLastThumbnailLocked(r.screenshotActivityLocked());
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08003284 mRecentTasks.addLocked(task);
Yorke Leebd54c2a2016-10-25 13:49:23 -07003285 mService.mTaskChangeNotificationController.notifyTaskStackChanged();
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003286 r.setVisibility(false);
Winson730bf062016-03-31 18:04:56 -07003287
3288 // When launching tasks behind, update the last active time of the top task after the new
3289 // task has been shown briefly
3290 final ActivityRecord top = stack.topActivity();
3291 if (top != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003292 top.getTask().touchActiveTime();
Winson730bf062016-03-31 18:04:56 -07003293 }
Craig Mautnerbb742462014-07-07 15:28:55 -07003294 }
3295
3296 void scheduleLaunchTaskBehindComplete(IBinder token) {
3297 mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
3298 }
3299
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003300 void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
3301 boolean preserveWindows) {
Jorim Jaggife762342016-10-13 14:33:27 +02003302 mKeyguardController.beginActivityVisibilityUpdate();
3303 try {
3304 // First the front stacks. In case any are not fullscreen and are in front of home.
3305 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3306 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3307 final int topStackNdx = stacks.size() - 1;
3308 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3309 final ActivityStack stack = stacks.get(stackNdx);
3310 stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
3311 }
Craig Mautner580ea812013-04-25 12:58:38 -07003312 }
Jorim Jaggife762342016-10-13 14:33:27 +02003313 } finally {
3314 mKeyguardController.endActivityVisibilityUpdate();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003315 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003316 }
3317
Jorim Jaggi8b702ed2017-01-20 16:59:03 +01003318 void addStartingWindowsForVisibleActivities(boolean taskSwitch) {
3319 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3320 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3321 final int topStackNdx = stacks.size() - 1;
3322 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3323 final ActivityStack stack = stacks.get(stackNdx);
3324 stack.addStartingWindowsForVisibleActivities(taskSwitch);
3325 }
3326 }
3327 }
3328
Chong Zhangfdcc4d42015-10-14 16:50:12 -07003329 void invalidateTaskLayers() {
3330 mTaskLayersChanged = true;
3331 }
3332
3333 void rankTaskLayersIfNeeded() {
3334 if (!mTaskLayersChanged) {
3335 return;
3336 }
3337 mTaskLayersChanged = false;
3338 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
3339 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3340 int baseLayer = 0;
3341 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3342 baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
3343 }
3344 }
3345 }
3346
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07003347 void clearOtherAppTimeTrackers(AppTimeTracker except) {
3348 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3349 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3350 final int topStackNdx = stacks.size() - 1;
3351 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3352 final ActivityStack stack = stacks.get(stackNdx);
3353 stack.clearOtherAppTimeTrackers(except);
3354 }
3355 }
3356 }
3357
Craig Mautner8d341ef2013-03-26 09:03:27 -07003358 void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003359 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3360 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003361 final int numStacks = stacks.size();
3362 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
3363 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003364 stack.scheduleDestroyActivities(app, reason);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003365 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003366 }
3367 }
3368
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003369 void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
3370 // Examine all activities currently running in the process.
3371 TaskRecord firstTask = null;
3372 // Tasks is non-null only if two or more tasks are found.
3373 ArraySet<TaskRecord> tasks = null;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003374 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
3375 for (int i = 0; i < app.activities.size(); i++) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003376 ActivityRecord r = app.activities.get(i);
3377 // First, if we find an activity that is in the process of being destroyed,
3378 // then we just aren't going to do anything for now; we want things to settle
3379 // down before we try to prune more activities.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003380 if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003381 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003382 return;
3383 }
3384 // Don't consider any activies that are currently not in a state where they
3385 // can be destroyed.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003386 if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
3387 || r.state == PAUSED || r.state == STOPPING) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003388 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003389 continue;
3390 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003391
3392 final TaskRecord task = r.getTask();
3393 if (task != null) {
3394 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + task
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003395 + " from " + r);
3396 if (firstTask == null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003397 firstTask = task;
3398 } else if (firstTask != task) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003399 if (tasks == null) {
3400 tasks = new ArraySet<>();
3401 tasks.add(firstTask);
3402 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003403 tasks.add(task);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003404 }
3405 }
3406 }
3407 if (tasks == null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003408 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003409 return;
3410 }
3411 // If we have activities in multiple tasks that are in a position to be destroyed,
3412 // let's iterate through the tasks and release the oldest one.
3413 final int numDisplays = mActivityDisplays.size();
3414 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3415 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3416 // Step through all stacks starting from behind, to hit the oldest things first.
3417 for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
3418 final ActivityStack stack = stacks.get(stackNdx);
3419 // Try to release activities in this stack; if we manage to, we are done.
3420 if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
3421 return;
3422 }
3423 }
3424 }
3425 }
3426
Amith Yamasani37a40c22015-06-17 13:25:42 -07003427 boolean switchUserLocked(int userId, UserState uss) {
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003428 final int focusStackId = mFocusedStack.getStackId();
3429 // We dismiss the docked stack whenever we switch users.
3430 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, focusStackId == DOCKED_STACK_ID);
Winson Chungc2b23a52017-01-09 15:44:55 -08003431 // Also dismiss the pinned stack whenever we switch users. Removing the pinned stack will
3432 // also cause all tasks to be moved to the fullscreen stack at a position that is
3433 // appropriate.
3434 removeStackLocked(PINNED_STACK_ID);
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003435
3436 mUserStackInFront.put(mCurrentUser, focusStackId);
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003437 final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
Craig Mautner2420ead2013-04-01 17:13:20 -07003438 mCurrentUser = userId;
Craig Mautnerac6f8432013-07-17 13:24:59 -07003439
Craig Mautner858d8a62013-04-23 17:08:34 -07003440 mStartingUsers.add(uss);
Craig Mautnere0a38842013-12-16 16:14:02 -08003441 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3442 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003443 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003444 final ActivityStack stack = stacks.get(stackNdx);
3445 stack.switchUserLocked(userId);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003446 TaskRecord task = stack.topTask();
3447 if (task != null) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08003448 stack.positionChildWindowContainerAtTop(task);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003449 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003450 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07003451 }
Craig Mautner858d8a62013-04-23 17:08:34 -07003452
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003453 ActivityStack stack = getStack(restoreStackId);
3454 if (stack == null) {
3455 stack = mHomeStack;
3456 }
3457 final boolean homeInFront = stack.isHomeStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08003458 if (stack.isOnHomeDisplay()) {
Wale Ogunwale925d0d12015-09-23 15:40:07 -07003459 stack.moveToFront("switchUserOnHomeDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003460 } else {
3461 // Stack was moved to another display while user was swapped out.
Matthew Ngae1ff4f2016-11-10 15:49:14 -08003462 resumeHomeStackTask(null, "switchUserOnOtherDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003463 }
Craig Mautner93529a42013-10-04 15:03:13 -07003464 return homeInFront;
Craig Mautner2219a1b2013-03-25 09:44:30 -07003465 }
3466
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003467 /** Checks whether the userid is a profile of the current user. */
3468 boolean isCurrentProfileLocked(int userId) {
3469 if (userId == mCurrentUser) return true;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07003470 return mService.mUserController.isCurrentProfileLocked(userId);
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003471 }
3472
Bryce Leeb7c9b802017-05-02 14:20:24 -07003473 /**
3474 * Returns whether a stopping activity is present that should be stopped after visible, rather
3475 * than idle.
3476 * @return {@code true} if such activity is present. {@code false} otherwise.
3477 */
3478 boolean isStoppingNoHistoryActivity() {
3479 // Activities that are marked as nohistory should be stopped immediately after the resumed
3480 // activity has become visible.
3481 for (ActivityRecord record : mStoppingActivities) {
3482 if (record.isNoHistory()) {
3483 return true;
3484 }
3485 }
3486
3487 return false;
3488 }
3489
Winson Chung4dabf232017-01-25 13:25:22 -08003490 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
3491 boolean remove, boolean processPausingActivities) {
Craig Mautnerde4ef022013-04-07 19:01:33 -07003492 ArrayList<ActivityRecord> stops = null;
3493
3494 final boolean nowVisible = allResumedActivitiesVisible();
Craig Mautner8c14c152015-01-15 17:32:07 -08003495 for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3496 ActivityRecord s = mStoppingActivities.get(activityNdx);
Bryce Lee4a194382017-04-04 14:32:48 -07003497 boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003498 if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
Craig Mautner8c14c152015-01-15 17:32:07 -08003499 + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
3500 if (waitingVisible && nowVisible) {
Bryce Lee4a194382017-04-04 14:32:48 -07003501 mActivitiesWaitingForVisibleActivity.remove(s);
Andrii Kulianee056812016-09-21 15:34:45 -07003502 waitingVisible = false;
Craig Mautnerde4ef022013-04-07 19:01:33 -07003503 if (s.finishing) {
3504 // If this activity is finishing, it is sitting on top of
3505 // everyone else but we now know it is no longer needed...
3506 // so get rid of it. Otherwise, we need to go through the
3507 // normal flow and hide it once we determine that it is
3508 // hidden by the activities in front of it.
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003509 if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003510 s.setVisibility(false);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003511 }
3512 }
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07003513 if ((!waitingVisible || mService.isSleepingOrShuttingDownLocked()) && remove) {
Winson Chung4dabf232017-01-25 13:25:22 -08003514 if (!processPausingActivities && s.state == PAUSING) {
3515 // Defer processing pausing activities in this iteration and reschedule
3516 // a delayed idle to reprocess it again
3517 removeTimeoutsForActivityLocked(idleActivity);
3518 scheduleIdleTimeoutLocked(idleActivity);
3519 continue;
3520 }
3521
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003522 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003523 if (stops == null) {
Craig Mautner8c14c152015-01-15 17:32:07 -08003524 stops = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -07003525 }
3526 stops.add(s);
Craig Mautner8c14c152015-01-15 17:32:07 -08003527 mStoppingActivities.remove(activityNdx);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003528 }
3529 }
3530
3531 return stops;
3532 }
3533
Craig Mautnercf910b02013-04-23 11:23:27 -07003534 void validateTopActivitiesLocked() {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003535 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3536 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3537 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3538 final ActivityStack stack = stacks.get(stackNdx);
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07003539 final ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003540 final ActivityState state = r == null ? DESTROYED : r.state;
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003541 if (isFocusedStack(stack)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003542 if (r == null) Slog.e(TAG,
3543 "validateTop...: null top activity, stack=" + stack);
3544 else {
3545 final ActivityRecord pausing = stack.mPausingActivity;
3546 if (pausing != null && pausing == r) Slog.e(TAG,
3547 "validateTop...: top stack has pausing activity r=" + r
3548 + " state=" + state);
3549 if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3550 "validateTop...: activity in front not resumed r=" + r
3551 + " state=" + state);
3552 }
Craig Mautnercf910b02013-04-23 11:23:27 -07003553 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003554 final ActivityRecord resumed = stack.mResumedActivity;
3555 if (resumed != null && resumed == r) Slog.e(TAG,
3556 "validateTop...: back stack has resumed activity r=" + r
3557 + " state=" + state);
3558 if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3559 "validateTop...: activity in back resumed r=" + r + " state=" + state);
Craig Mautnercf910b02013-04-23 11:23:27 -07003560 }
3561 }
3562 }
Craig Mautner76ea2242013-05-15 11:40:05 -07003563 }
3564
Craig Mautnere0570202015-05-13 13:06:11 -07003565 private String lockTaskModeToString() {
3566 switch (mLockTaskModeState) {
3567 case LOCK_TASK_MODE_LOCKED:
3568 return "LOCKED";
3569 case LOCK_TASK_MODE_PINNED:
3570 return "PINNED";
3571 case LOCK_TASK_MODE_NONE:
3572 return "NONE";
3573 default: return "unknown=" + mLockTaskModeState;
3574 }
3575 }
3576
Craig Mautner27084302013-03-25 08:05:25 -07003577 public void dump(PrintWriter pw, String prefix) {
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003578 pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003579 pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003580 pw.print(prefix); pw.println("mSleepTimeout=" + mSleepTimeout);
Suprabh Shukla09a88f52015-12-02 14:36:31 -08003581 pw.print(prefix);
3582 pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003583 pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003584 pw.print(prefix); pw.println("mStacks=" + mStacks);
Craig Mautnere0570202015-05-13 13:06:11 -07003585 pw.print(prefix); pw.print("mLockTaskModeState=" + lockTaskModeToString());
Jorim Jaggi8d786932016-10-26 19:08:36 -07003586 final SparseArray<String[]> packages = mService.mLockTaskPackages;
3587 if (packages.size() > 0) {
3588 pw.print(prefix); pw.println("mLockTaskPackages (userId:packages)=");
3589 for (int i = 0; i < packages.size(); ++i) {
3590 pw.print(prefix); pw.print(prefix); pw.print(packages.keyAt(i));
3591 pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
3592 }
3593 }
Bryce Lee4a194382017-04-04 14:32:48 -07003594 if (!mWaitingForActivityVisible.isEmpty()) {
3595 pw.print(prefix); pw.println("mWaitingForActivityVisible=");
3596 for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
3597 pw.print(prefix); pw.print(prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
3598 }
3599 }
3600
Jorim Jaggi8d786932016-10-26 19:08:36 -07003601 pw.println(" mLockTaskModeTasks" + mLockTaskModeTasks);
3602 mKeyguardController.dump(pw, prefix);
Craig Mautner27084302013-03-25 08:05:25 -07003603 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003604
Winson43d1f262016-06-14 16:05:55 -07003605 /**
Andrii Kulian5406e7a2016-10-21 11:55:23 -07003606 * Dump all connected displays' configurations.
3607 * @param prefix Prefix to apply to each line of the dump.
3608 */
3609 void dumpDisplayConfigs(PrintWriter pw, String prefix) {
3610 pw.print(prefix); pw.println("Display override configurations:");
3611 final int displayCount = mActivityDisplays.size();
3612 for (int i = 0; i < displayCount; i++) {
3613 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(i);
3614 pw.print(prefix); pw.print(" "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
3615 pw.println(activityDisplay.getOverrideConfiguration());
3616 }
3617 }
3618
3619 /**
Winson43d1f262016-06-14 16:05:55 -07003620 * Dumps the activities matching the given {@param name} in the either the focused stack
3621 * or all visible stacks if {@param dumpVisibleStacks} is true.
3622 */
Winson Chung6998bc42017-02-28 17:07:05 -08003623 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name, boolean dumpVisibleStacksOnly,
3624 boolean dumpFocusedStackOnly) {
3625 if (dumpFocusedStackOnly) {
3626 return mFocusedStack.getDumpActivitiesLocked(name);
3627 } else {
Winson43d1f262016-06-14 16:05:55 -07003628 ArrayList<ActivityRecord> activities = new ArrayList<>();
3629 int numDisplays = mActivityDisplays.size();
3630 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3631 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3632 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3633 ActivityStack stack = stacks.get(stackNdx);
Winson Chung6998bc42017-02-28 17:07:05 -08003634 if (!dumpVisibleStacksOnly ||
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07003635 stack.shouldBeVisible(null) == STACK_VISIBLE) {
Winson43d1f262016-06-14 16:05:55 -07003636 activities.addAll(stack.getDumpActivitiesLocked(name));
3637 }
3638 }
3639 }
3640 return activities;
Winson43d1f262016-06-14 16:05:55 -07003641 }
Craig Mautner20e72272013-04-01 13:45:53 -07003642 }
3643
Dianne Hackborn390517b2013-05-30 15:03:32 -07003644 static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3645 boolean needSep, String prefix) {
3646 if (activity != null) {
3647 if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3648 if (needSep) {
3649 pw.println();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003650 }
3651 pw.print(prefix);
3652 pw.println(activity);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003653 return true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003654 }
3655 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003656 return false;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003657 }
3658
Craig Mautner8d341ef2013-03-26 09:03:27 -07003659 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3660 boolean dumpClient, String dumpPackage) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003661 boolean printed = false;
3662 boolean needSep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003663 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3664 ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003665 pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
Craig Mautner737fae22014-10-15 12:52:10 -07003666 pw.println(" (activities from top to bottom):");
Craig Mautnere0a38842013-12-16 16:14:02 -08003667 ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
Craig Mautner737fae22014-10-15 12:52:10 -07003668 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003669 final ActivityStack stack = stacks.get(stackNdx);
3670 StringBuilder stackHeader = new StringBuilder(128);
3671 stackHeader.append(" Stack #");
3672 stackHeader.append(stack.mStackId);
3673 stackHeader.append(":");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003674 stackHeader.append("\n");
3675 stackHeader.append(" mFullscreen=" + stack.mFullscreen);
3676 stackHeader.append("\n");
3677 stackHeader.append(" mBounds=" + stack.mBounds);
Winson Chungabb433b2017-03-24 09:35:42 -07003678
3679 final boolean printedStackHeader = stack.dumpActivitiesLocked(fd, pw, dumpAll,
3680 dumpClient, dumpPackage, needSep, stackHeader.toString());
3681 printed |= printedStackHeader;
3682 if (!printedStackHeader) {
3683 // Ensure we always dump the stack header even if there are no activities
3684 pw.println();
3685 pw.println(stackHeader);
3686 }
3687
Craig Mautner4a1cb222013-12-04 16:14:06 -08003688 printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, " ", "Run", false,
3689 !dumpAll, false, dumpPackage, true,
3690 " Running activities (most recent first):", null);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003691
Craig Mautner4a1cb222013-12-04 16:14:06 -08003692 needSep = printed;
3693 boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3694 " mPausingActivity: ");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003695 if (pr) {
3696 printed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003697 needSep = false;
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003698 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003699 pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3700 " mResumedActivity: ");
3701 if (pr) {
3702 printed = true;
3703 needSep = false;
3704 }
3705 if (dumpAll) {
3706 pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3707 " mLastPausedActivity: ");
3708 if (pr) {
3709 printed = true;
3710 needSep = true;
3711 }
3712 printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3713 needSep, " mLastNoHistoryActivity: ");
3714 }
3715 needSep = printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003716 }
3717 }
3718
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003719 printed |= dumpHistoryList(fd, pw, mFinishingActivities, " ", "Fin", false, !dumpAll,
3720 false, dumpPackage, true, " Activities waiting to finish:", null);
3721 printed |= dumpHistoryList(fd, pw, mStoppingActivities, " ", "Stop", false, !dumpAll,
3722 false, dumpPackage, true, " Activities waiting to stop:", null);
Bryce Lee4a194382017-04-04 14:32:48 -07003723 printed |= dumpHistoryList(fd, pw, mActivitiesWaitingForVisibleActivity, " ", "Wait",
3724 false, !dumpAll, false, dumpPackage, true,
3725 " Activities waiting for another to become visible:", null);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003726 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3727 false, dumpPackage, true, " Activities waiting to sleep:", null);
3728 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3729 false, dumpPackage, true, " Activities waiting to sleep:", null);
Craig Mautnerf3333272013-04-22 10:55:53 -07003730
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003731 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003732 }
3733
Dianne Hackborn390517b2013-05-30 15:03:32 -07003734 static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
Craig Mautner8d341ef2013-03-26 09:03:27 -07003735 String prefix, String label, boolean complete, boolean brief, boolean client,
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003736 String dumpPackage, boolean needNL, String header1, String header2) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003737 TaskRecord lastTask = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003738 String innerPrefix = null;
3739 String[] args = null;
3740 boolean printed = false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003741 for (int i=list.size()-1; i>=0; i--) {
3742 final ActivityRecord r = list.get(i);
3743 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3744 continue;
3745 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003746 if (innerPrefix == null) {
3747 innerPrefix = prefix + " ";
3748 args = new String[0];
3749 }
3750 printed = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003751 final boolean full = !brief && (complete || !r.isInHistory());
3752 if (needNL) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003753 pw.println("");
Craig Mautner8d341ef2013-03-26 09:03:27 -07003754 needNL = false;
3755 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003756 if (header1 != null) {
3757 pw.println(header1);
3758 header1 = null;
3759 }
3760 if (header2 != null) {
3761 pw.println(header2);
3762 header2 = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003763 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003764 if (lastTask != r.getTask()) {
3765 lastTask = r.getTask();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003766 pw.print(prefix);
3767 pw.print(full ? "* " : " ");
3768 pw.println(lastTask);
3769 if (full) {
3770 lastTask.dump(pw, prefix + " ");
3771 } else if (complete) {
3772 // Complete + brief == give a summary. Isn't that obvious?!?
3773 if (lastTask.intent != null) {
3774 pw.print(prefix); pw.print(" ");
3775 pw.println(lastTask.intent.toInsecureStringWithClip());
3776 }
3777 }
3778 }
3779 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
3780 pw.print(" #"); pw.print(i); pw.print(": ");
3781 pw.println(r);
3782 if (full) {
3783 r.dump(pw, innerPrefix);
3784 } else if (complete) {
3785 // Complete + brief == give a summary. Isn't that obvious?!?
3786 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3787 if (r.app != null) {
3788 pw.print(innerPrefix); pw.println(r.app);
3789 }
3790 }
3791 if (client && r.app != null && r.app.thread != null) {
3792 // flush anything that is already in the PrintWriter since the thread is going
3793 // to write to the file descriptor directly
3794 pw.flush();
3795 try {
3796 TransferPipe tp = new TransferPipe();
3797 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003798 r.app.thread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003799 // Short timeout, since blocking here can
3800 // deadlock with the application.
3801 tp.go(fd, 2000);
3802 } finally {
3803 tp.kill();
3804 }
3805 } catch (IOException e) {
3806 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3807 } catch (RemoteException e) {
3808 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3809 }
3810 needNL = true;
3811 }
3812 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003813 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003814 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003815
Craig Mautnerf3333272013-04-22 10:55:53 -07003816 void scheduleIdleTimeoutLocked(ActivityRecord next) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003817 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3818 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
Craig Mautnerc64f73e2013-04-24 16:44:56 -07003819 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
3820 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
Craig Mautnerf3333272013-04-22 10:55:53 -07003821 }
3822
3823 final void scheduleIdleLocked() {
Craig Mautner05d29032013-05-03 13:40:13 -07003824 mHandler.sendEmptyMessage(IDLE_NOW_MSG);
Craig Mautnerf3333272013-04-22 10:55:53 -07003825 }
3826
3827 void removeTimeoutsForActivityLocked(ActivityRecord r) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003828 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
3829 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07003830 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3831 }
3832
Craig Mautner05d29032013-05-03 13:40:13 -07003833 final void scheduleResumeTopActivities() {
Craig Mautner34b73df2014-01-12 21:11:08 -08003834 if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
3835 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
3836 }
Craig Mautner05d29032013-05-03 13:40:13 -07003837 }
3838
Craig Mautner0eea92c2013-05-16 13:35:39 -07003839 void removeSleepTimeouts() {
3840 mSleepTimeout = false;
3841 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
3842 }
3843
3844 final void scheduleSleepTimeout() {
3845 removeSleepTimeouts();
3846 mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
3847 }
3848
Craig Mautner4a1cb222013-12-04 16:14:06 -08003849 @Override
3850 public void onDisplayAdded(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003851 if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003852 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
3853 }
3854
3855 @Override
3856 public void onDisplayRemoved(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003857 if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003858 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
3859 }
3860
3861 @Override
3862 public void onDisplayChanged(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003863 if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003864 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
3865 }
3866
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003867 private void handleDisplayAdded(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003868 synchronized (mService) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003869 getActivityDisplayOrCreateLocked(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003870 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003871 }
3872
Andrii Kulianca007a62016-11-22 16:33:28 -08003873 /** Check if display with specified id is added to the list. */
3874 boolean isDisplayAdded(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003875 return getActivityDisplayOrCreateLocked(displayId) != null;
3876 }
3877
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003878 ActivityDisplay getActivityDisplay(int displayId) {
3879 return mActivityDisplays.get(displayId);
3880 }
3881
Andrii Kulian62e6f252017-05-30 22:46:53 -07003882 /**
3883 * Get an existing instance of {@link ActivityDisplay} or create new if there is a
3884 * corresponding record in display manager.
3885 */
3886 private ActivityDisplay getActivityDisplayOrCreateLocked(int displayId) {
3887 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3888 if (activityDisplay != null) {
3889 return activityDisplay;
3890 }
3891 if (mDisplayManager == null) {
3892 // The system isn't fully initialized yet.
3893 return null;
3894 }
3895 final Display display = mDisplayManager.getDisplay(displayId);
3896 if (display == null) {
3897 // The display is not registered in DisplayManager.
3898 return null;
3899 }
3900 // The display hasn't been added to ActivityManager yet, create a new record now.
3901 activityDisplay = new ActivityDisplay(displayId);
3902 if (activityDisplay.mDisplay == null) {
3903 Slog.w(TAG, "Display " + displayId + " gone before initialization complete");
3904 return null;
3905 }
3906 mActivityDisplays.put(displayId, activityDisplay);
3907 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
3908 mWindowManager.onDisplayAdded(displayId);
3909 return activityDisplay;
Andrii Kulianca007a62016-11-22 16:33:28 -08003910 }
3911
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003912 private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
Andrii Kulianf66a83d2016-05-17 12:17:44 -07003913 mDefaultMinSizeOfResizeableTask =
Jorim Jaggi19cf2972016-04-07 23:26:10 -07003914 mService.mContext.getResources().getDimensionPixelSize(
3915 com.android.internal.R.dimen.default_minimal_size_resizable_task);
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003916 }
3917
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003918 private void handleDisplayRemoved(int displayId) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003919 if (displayId == DEFAULT_DISPLAY) {
3920 throw new IllegalArgumentException("Can't remove the primary display.");
3921 }
3922
Craig Mautner4a1cb222013-12-04 16:14:06 -08003923 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003924 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3925 if (activityDisplay != null) {
Andrii Kulian250d6532017-02-08 23:30:45 -08003926 final boolean destroyContentOnRemoval
3927 = activityDisplay.shouldDestroyContentOnRemove();
Andrii Kuliana33818c2017-02-16 16:11:30 -08003928 final ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3929 while (!stacks.isEmpty()) {
3930 final ActivityStack stack = stacks.get(0);
Andrii Kulian250d6532017-02-08 23:30:45 -08003931 if (destroyContentOnRemoval) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003932 moveStackToDisplayLocked(stack.mStackId, DEFAULT_DISPLAY,
3933 false /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003934 stack.finishAllActivitiesLocked(true /* immediately */);
Andrii Kuliana33818c2017-02-16 16:11:30 -08003935 } else {
3936 // Moving all tasks to fullscreen stack, because it's guaranteed to be
3937 // a valid launch stack for all activities. This way the task history from
3938 // external display will be preserved on primary after move.
3939 moveTasksToFullscreenStackLocked(stack.getStackId(), true /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003940 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003941 }
Craig Mautnere0a38842013-12-16 16:14:02 -08003942 mActivityDisplays.remove(displayId);
Bryce Leeaf3a4002017-03-20 10:37:12 -07003943 mWindowManager.onDisplayRemoved(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003944 }
3945 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003946 }
3947
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003948 private void handleDisplayChanged(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003949 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003950 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3951 if (activityDisplay != null) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003952 // TODO: Update the bounds.
3953 }
Bryce Leeaf3a4002017-03-20 10:37:12 -07003954 mWindowManager.onDisplayChanged(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003955 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003956 }
3957
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003958 private StackInfo getStackInfoLocked(ActivityStack stack) {
Andrii Kulian7e215d72017-04-26 18:33:28 -07003959 final int displayId = stack.mDisplayId;
3960 final ActivityDisplay display = mActivityDisplays.get(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003961 StackInfo info = new StackInfo();
Wale Ogunwale1666e312016-12-16 11:27:18 -08003962 stack.getWindowContainerBounds(info.bounds);
Andrii Kulian7e215d72017-04-26 18:33:28 -07003963 info.displayId = displayId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003964 info.stackId = stack.mStackId;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08003965 info.userId = stack.mCurrentUser;
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07003966 info.visible = stack.shouldBeVisible(null) == STACK_VISIBLE;
Andrii Kulian62e6f252017-05-30 22:46:53 -07003967 // A stack might be not attached to a display.
Winson529c8e42016-05-17 11:08:40 -07003968 info.position = display != null
3969 ? display.mStacks.indexOf(stack)
3970 : 0;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003971
3972 ArrayList<TaskRecord> tasks = stack.getAllTasks();
3973 final int numTasks = tasks.size();
3974 int[] taskIds = new int[numTasks];
3975 String[] taskNames = new String[numTasks];
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07003976 Rect[] taskBounds = new Rect[numTasks];
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08003977 int[] taskUserIds = new int[numTasks];
Craig Mautner4a1cb222013-12-04 16:14:06 -08003978 for (int i = 0; i < numTasks; ++i) {
3979 final TaskRecord task = tasks.get(i);
3980 taskIds[i] = task.taskId;
3981 taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
3982 : task.realActivity != null ? task.realActivity.flattenToString()
3983 : task.getTopActivity() != null ? task.getTopActivity().packageName
3984 : "unknown";
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07003985 taskBounds[i] = new Rect();
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08003986 task.getWindowContainerBounds(taskBounds[i]);
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08003987 taskUserIds[i] = task.userId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003988 }
3989 info.taskIds = taskIds;
3990 info.taskNames = taskNames;
Wale Ogunwale868a5e12015-08-02 16:19:20 -07003991 info.taskBounds = taskBounds;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08003992 info.taskUserIds = taskUserIds;
Winsond46b7272016-04-20 11:54:27 -07003993
3994 final ActivityRecord top = stack.topRunningActivityLocked();
3995 info.topActivity = top != null ? top.intent.getComponent() : null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003996 return info;
3997 }
3998
3999 StackInfo getStackInfoLocked(int stackId) {
4000 ActivityStack stack = getStack(stackId);
4001 if (stack != null) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004002 return getStackInfoLocked(stack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004003 }
4004 return null;
4005 }
4006
4007 ArrayList<StackInfo> getAllStackInfosLocked() {
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004008 ArrayList<StackInfo> list = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08004009 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
4010 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004011 for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004012 list.add(getStackInfoLocked(stacks.get(ndx)));
Craig Mautner4a1cb222013-12-04 16:14:06 -08004013 }
4014 }
4015 return list;
4016 }
4017
Craig Mautner15df08a2015-04-01 12:17:18 -07004018 TaskRecord getLockedTaskLocked() {
4019 final int top = mLockTaskModeTasks.size() - 1;
4020 if (top >= 0) {
4021 return mLockTaskModeTasks.get(top);
4022 }
4023 return null;
4024 }
4025
4026 boolean isLockedTask(TaskRecord task) {
4027 return mLockTaskModeTasks.contains(task);
4028 }
4029
4030 boolean isLastLockedTask(TaskRecord task) {
4031 return mLockTaskModeTasks.size() == 1 && mLockTaskModeTasks.contains(task);
4032 }
4033
4034 void removeLockedTaskLocked(final TaskRecord task) {
Craig Mautner432f64e2015-05-20 14:59:57 -07004035 if (!mLockTaskModeTasks.remove(task)) {
4036 return;
4037 }
4038 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "removeLockedTaskLocked: removed " + task);
4039 if (mLockTaskModeTasks.isEmpty()) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004040 // Last one.
Craig Mautnere0570202015-05-13 13:06:11 -07004041 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
4042 " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
Craig Mautner15df08a2015-04-01 12:17:18 -07004043 final Message lockTaskMsg = Message.obtain();
4044 lockTaskMsg.arg1 = task.userId;
4045 lockTaskMsg.what = LOCK_TASK_END_MSG;
4046 mHandler.sendMessage(lockTaskMsg);
4047 }
4048 }
4049
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004050 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4051 int preferredDisplayId, int actualStackId) {
4052 handleNonResizableTaskIfNeeded(task, preferredStackId, preferredDisplayId, actualStackId,
Andrii Kulianc27916642016-04-12 17:59:27 -07004053 false /* forceNonResizable */);
4054 }
4055
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004056 private void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4057 int preferredDisplayId, int actualStackId, boolean forceNonResizable) {
4058 final boolean isSecondaryDisplayPreferred =
4059 (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY)
4060 || StackId.isDynamicStack(preferredStackId);
4061 if (((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
4062 && !isSecondaryDisplayPreferred) || task.isHomeTask()) {
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004063 return;
4064 }
4065
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004066 // Handle incorrect launch/move to secondary display if needed.
4067 final boolean launchOnSecondaryDisplayFailed;
4068 if (isSecondaryDisplayPreferred) {
4069 final int actualDisplayId = task.getStack().mDisplayId;
4070 if (!task.canBeLaunchedOnDisplay(actualDisplayId)) {
4071 // The task landed on an inappropriate display somehow, move it to the default
4072 // display.
4073 // TODO(multi-display): Find proper stack for the task on the default display.
4074 mService.moveTaskToStack(task.taskId, FULLSCREEN_WORKSPACE_STACK_ID,
4075 true /* toTop */);
4076 launchOnSecondaryDisplayFailed = true;
4077 } else {
4078 // The task might have landed on a display different from requested.
4079 launchOnSecondaryDisplayFailed = actualDisplayId == DEFAULT_DISPLAY
4080 || (preferredDisplayId != INVALID_DISPLAY
4081 && preferredDisplayId != actualDisplayId);
4082 }
4083 } else {
4084 // The task wasn't requested to be on a secondary display.
4085 launchOnSecondaryDisplayFailed = false;
4086 }
4087
Jorim Jaggicd13d332016-04-27 15:40:20 -07004088 final ActivityRecord topActivity = task.getTopActivity();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004089 if (launchOnSecondaryDisplayFailed || !task.supportsSplitScreen() || forceNonResizable) {
4090 if (launchOnSecondaryDisplayFailed) {
4091 // Display a warning toast that we tried to put a non-resizeable task on a secondary
4092 // display with config different from global config.
4093 mService.mTaskChangeNotificationController
4094 .notifyActivityLaunchOnSecondaryDisplayFailed();
4095 } else {
4096 // Display a warning toast that we tried to put a non-dockable task in the docked
4097 // stack.
4098 mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
4099 }
Jorim Jaggid53f0922016-04-06 22:16:23 -07004100
Andrii Kulianc27916642016-04-12 17:59:27 -07004101 // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
4102 // we need to move it to top of fullscreen stack, otherwise it will be covered.
Wale Ogunwale9a98c522016-04-27 09:23:55 -07004103 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
Winson Chungd3395382016-12-13 11:49:09 -08004104 } else if (topActivity != null && topActivity.isNonResizableOrForcedResizable()
Jorim Jaggicd13d332016-04-27 15:40:20 -07004105 && !topActivity.noDisplay) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004106 final String packageName = topActivity.appInfo.packageName;
4107 final int reason = isSecondaryDisplayPreferred
4108 ? FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY
4109 : FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Yorke Leebd54c2a2016-10-25 13:49:23 -07004110 mService.mTaskChangeNotificationController.notifyActivityForcedResizable(
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004111 task.taskId, reason, packageName);
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004112 }
Chong Zhangb15758a2015-11-17 12:12:03 -08004113 }
4114
Craig Mautner6cd6cec2015-04-01 00:02:12 -07004115 void showLockTaskToast() {
Hall Liu45784f12016-05-31 15:50:48 -07004116 if (mLockTaskNotify != null) {
4117 mLockTaskNotify.showToast(mLockTaskModeState);
4118 }
Jason Monka8f569c2014-07-07 12:15:21 -04004119 }
4120
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004121 void showLockTaskEscapeMessageLocked(TaskRecord task) {
4122 if (mLockTaskModeTasks.contains(task)) {
4123 mHandler.sendEmptyMessage(SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG);
4124 }
4125 }
4126
Craig Mautner432f64e2015-05-20 14:59:57 -07004127 void setLockTaskModeLocked(TaskRecord task, int lockTaskModeState, String reason,
4128 boolean andResume) {
Craig Mautneraea74a52014-03-08 14:23:10 -08004129 if (task == null) {
Christopher Tate3bd90612014-06-18 16:37:52 -07004130 // Take out of lock task mode if necessary
Craig Mautner15df08a2015-04-01 12:17:18 -07004131 final TaskRecord lockedTask = getLockedTaskLocked();
4132 if (lockedTask != null) {
4133 removeLockedTaskLocked(lockedTask);
4134 if (!mLockTaskModeTasks.isEmpty()) {
4135 // There are locked tasks remaining, can only finish this task, not unlock it.
Craig Mautnere0570202015-05-13 13:06:11 -07004136 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4137 "setLockTaskModeLocked: Tasks remaining, can't unlock");
Craig Mautner15df08a2015-04-01 12:17:18 -07004138 lockedTask.performClearTaskLocked();
Wale Ogunwaled046a012015-12-24 13:05:59 -08004139 resumeFocusedStackTopActivityLocked();
Craig Mautner15df08a2015-04-01 12:17:18 -07004140 return;
4141 }
Christopher Tate3bd90612014-06-18 16:37:52 -07004142 }
Craig Mautnere0570202015-05-13 13:06:11 -07004143 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4144 "setLockTaskModeLocked: No tasks to unlock. Callers=" + Debug.getCallers(4));
Craig Mautneraea74a52014-03-08 14:23:10 -08004145 return;
4146 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004147
4148 // Should have already been checked, but do it again.
4149 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
Craig Mautnere0570202015-05-13 13:06:11 -07004150 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4151 "setLockTaskModeLocked: Can't lock due to auth");
Craig Mautneraea74a52014-03-08 14:23:10 -08004152 return;
4153 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004154 if (isLockTaskModeViolation(task)) {
Craig Mautnere0570202015-05-13 13:06:11 -07004155 Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
Craig Mautner15df08a2015-04-01 12:17:18 -07004156 return;
4157 }
4158
4159 if (mLockTaskModeTasks.isEmpty()) {
4160 // First locktask.
4161 final Message lockTaskMsg = Message.obtain();
4162 lockTaskMsg.obj = task.intent.getComponent().getPackageName();
4163 lockTaskMsg.arg1 = task.userId;
4164 lockTaskMsg.what = LOCK_TASK_START_MSG;
4165 lockTaskMsg.arg2 = lockTaskModeState;
4166 mHandler.sendMessage(lockTaskMsg);
4167 }
4168 // Add it or move it to the top.
Craig Mautnere0570202015-05-13 13:06:11 -07004169 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskModeLocked: Locking to " + task +
4170 " Callers=" + Debug.getCallers(4));
Craig Mautner15df08a2015-04-01 12:17:18 -07004171 mLockTaskModeTasks.remove(task);
4172 mLockTaskModeTasks.add(task);
4173
4174 if (task.mLockTaskUid == -1) {
Wale Ogunwale5c18d052015-10-12 10:34:14 -07004175 task.mLockTaskUid = task.effectiveUid;
Craig Mautner15df08a2015-04-01 12:17:18 -07004176 }
Craig Mautner432f64e2015-05-20 14:59:57 -07004177
4178 if (andResume) {
Andrii Kulianc27916642016-04-12 17:59:27 -07004179 findTaskToMoveToFrontLocked(task, 0, null, reason,
4180 lockTaskModeState != LOCK_TASK_MODE_NONE);
Wale Ogunwaled046a012015-12-24 13:05:59 -08004181 resumeFocusedStackTopActivityLocked();
Jorim Jaggia42938e2016-11-22 14:31:38 +01004182 mWindowManager.executeAppTransition();
Andrii Kulianc27916642016-04-12 17:59:27 -07004183 } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004184 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
4185 task.getStackId(), true /* forceNonResizable */);
Craig Mautner432f64e2015-05-20 14:59:57 -07004186 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004187 }
4188
4189 boolean isLockTaskModeViolation(TaskRecord task) {
Jason Monk25d237b2015-06-19 10:39:39 -04004190 return isLockTaskModeViolation(task, false);
4191 }
4192
4193 boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) {
4194 if (getLockedTaskLocked() == task && !isNewClearTask) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004195 return false;
4196 }
4197 final int lockTaskAuth = task.mLockTaskAuth;
4198 switch (lockTaskAuth) {
4199 case LOCK_TASK_AUTH_DONT_LOCK:
4200 return !mLockTaskModeTasks.isEmpty();
Benjamin Franz469dd582015-06-09 14:24:36 +01004201 case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
Craig Mautner15df08a2015-04-01 12:17:18 -07004202 case LOCK_TASK_AUTH_LAUNCHABLE:
4203 case LOCK_TASK_AUTH_WHITELISTED:
4204 return false;
4205 case LOCK_TASK_AUTH_PINNABLE:
4206 // Pinnable tasks can't be launched on top of locktask tasks.
4207 return !mLockTaskModeTasks.isEmpty();
4208 default:
4209 Slog.w(TAG, "isLockTaskModeViolation: invalid lockTaskAuth value=" + lockTaskAuth);
4210 return true;
4211 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004212 }
4213
Craig Mautner15df08a2015-04-01 12:17:18 -07004214 void onLockTaskPackagesUpdatedLocked() {
4215 boolean didSomething = false;
4216 for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
4217 final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx);
Benjamin Franz469dd582015-06-09 14:24:36 +01004218 final boolean wasWhitelisted =
4219 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4220 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
Craig Mautner15df08a2015-04-01 12:17:18 -07004221 lockedTask.setLockTaskAuth();
Benjamin Franz469dd582015-06-09 14:24:36 +01004222 final boolean isWhitelisted =
4223 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4224 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
4225 if (wasWhitelisted && !isWhitelisted) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004226 // Lost whitelisting authorization. End it now.
Craig Mautner432f64e2015-05-20 14:59:57 -07004227 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "onLockTaskPackagesUpdated: removing " +
4228 lockedTask + " mLockTaskAuth=" + lockedTask.lockTaskAuthToString());
Craig Mautner15df08a2015-04-01 12:17:18 -07004229 removeLockedTaskLocked(lockedTask);
4230 lockedTask.performClearTaskLocked();
4231 didSomething = true;
4232 }
4233 }
4234 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
4235 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
4236 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
4237 final ActivityStack stack = stacks.get(stackNdx);
4238 stack.onLockTaskPackagesUpdatedLocked();
4239 }
4240 }
Craig Mautnere0570202015-05-13 13:06:11 -07004241 final ActivityRecord r = topRunningActivityLocked();
Bryce Leeaf691c02017-03-20 14:20:22 -07004242 final TaskRecord task = r != null ? r.getTask() : null;
Craig Mautnere0570202015-05-13 13:06:11 -07004243 if (mLockTaskModeTasks.isEmpty() && task != null
4244 && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
4245 // This task must have just been authorized.
Craig Mautner432f64e2015-05-20 14:59:57 -07004246 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK,
4247 "onLockTaskPackagesUpdated: starting new locktask task=" + task);
4248 setLockTaskModeLocked(task, ActivityManager.LOCK_TASK_MODE_LOCKED, "package updated",
4249 false);
4250 didSomething = true;
Craig Mautnere0570202015-05-13 13:06:11 -07004251 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004252 if (didSomething) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004253 resumeFocusedStackTopActivityLocked();
Craig Mautneraea74a52014-03-08 14:23:10 -08004254 }
4255 }
4256
Benjamin Franz43261142015-02-11 15:59:44 +00004257 int getLockTaskModeState() {
4258 return mLockTaskModeState;
Craig Mautneraea74a52014-03-08 14:23:10 -08004259 }
4260
Jorim Jaggife89d122015-12-22 16:28:44 +01004261 void activityRelaunchedLocked(IBinder token) {
4262 mWindowManager.notifyAppRelaunchingFinished(token);
Wale Ogunwale3e997362016-09-06 10:37:56 -07004263 if (mService.isSleepingOrShuttingDownLocked()) {
4264 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4265 if (r != null) {
4266 r.setSleeping(true, true);
4267 }
4268 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004269 }
4270
4271 void activityRelaunchingLocked(ActivityRecord r) {
4272 mWindowManager.notifyAppRelaunching(r.appToken);
4273 }
4274
Filip Gruszczynski77d94482015-12-11 13:59:52 -08004275 void logStackState() {
4276 mActivityMetricsLogger.logWindowState();
4277 }
4278
Winson Chung5af42fc2017-03-24 17:11:33 -07004279 void scheduleUpdateMultiWindowMode(TaskRecord task) {
Winson Chung8bca9e42017-04-16 15:59:43 -07004280 // If the stack is animating in a way where we will be forcing a multi-mode change at the
4281 // end, then ensure that we defer all in between multi-window mode changes
4282 if (task.getStack().deferScheduleMultiWindowModeChanged()) {
4283 return;
4284 }
4285
Wale Ogunwale22e25262016-02-01 10:32:02 -08004286 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4287 final ActivityRecord r = task.mActivities.get(i);
4288 if (r.app != null && r.app.thread != null) {
4289 mMultiWindowModeChangedActivities.add(r);
4290 }
4291 }
4292
4293 if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
4294 mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
4295 }
4296 }
4297
Winson Chung5af42fc2017-03-24 17:11:33 -07004298 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07004299 final ActivityStack stack = task.getStack();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004300 if (prevStack == null || prevStack == stack
4301 || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
4302 return;
4303 }
4304
Winson Chung5af42fc2017-03-24 17:11:33 -07004305 scheduleUpdatePictureInPictureModeIfNeeded(task, stack.mBounds, false /* immediate */);
4306 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004307
Winson Chung5af42fc2017-03-24 17:11:33 -07004308 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds,
4309 boolean immediate) {
4310
4311 if (immediate) {
4312 mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG);
4313 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4314 final ActivityRecord r = task.mActivities.get(i);
4315 if (r.app != null && r.app.thread != null) {
4316 r.updatePictureInPictureMode(targetStackBounds);
4317 }
4318 }
4319 } else {
4320 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4321 final ActivityRecord r = task.mActivities.get(i);
4322 if (r.app != null && r.app.thread != null) {
4323 mPipModeChangedActivities.add(r);
4324 }
4325 }
4326 mPipModeChangedTargetStackBounds = targetStackBounds;
4327
4328 if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
4329 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
4330 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004331 }
4332 }
4333
Tony Mak853304c2016-04-18 15:17:41 +01004334 void setDockedStackMinimized(boolean minimized) {
4335 mIsDockMinimized = minimized;
Tony Mak853304c2016-04-18 15:17:41 +01004336 }
4337
chaviw59b98852017-06-13 12:05:44 -07004338 void wakeUp(String reason) {
4339 mPowerManager.wakeUp(SystemClock.uptimeMillis(), "android.server.am:TURN_ON:" + reason);
4340 }
4341
4342 /**
4343 * Begin deferring resume to avoid duplicate resumes in one pass.
4344 */
4345 private void beginDeferResume() {
4346 mDeferResumeCount++;
4347 }
4348
4349 /**
4350 * End deferring resume and determine if resume can be called.
4351 */
4352 private void endDeferResume() {
4353 mDeferResumeCount--;
4354 }
4355
4356 /**
4357 * @return True if resume can be called.
4358 */
4359 private boolean readyToResume() {
4360 return mDeferResumeCount == 0;
4361 }
4362
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004363 private final class ActivityStackSupervisorHandler extends Handler {
Craig Mautnerf3333272013-04-22 10:55:53 -07004364
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004365 public ActivityStackSupervisorHandler(Looper looper) {
4366 super(looper);
4367 }
4368
Winson Chung4dabf232017-01-25 13:25:22 -08004369 void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) {
Craig Mautnerf3333272013-04-22 10:55:53 -07004370 synchronized (mService) {
Winson Chung4dabf232017-01-25 13:25:22 -08004371 activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */,
4372 processPausingActivities, null);
Craig Mautnerf3333272013-04-22 10:55:53 -07004373 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004374 }
4375
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004376 @Override
4377 public void handleMessage(Message msg) {
4378 switch (msg.what) {
Wale Ogunwale22e25262016-02-01 10:32:02 -08004379 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
4380 synchronized (mService) {
4381 for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
4382 final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004383 r.updateMultiWindowMode();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004384 }
4385 }
4386 } break;
4387 case REPORT_PIP_MODE_CHANGED_MSG: {
4388 synchronized (mService) {
4389 for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
4390 final ActivityRecord r = mPipModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004391 r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds);
Wale Ogunwale22e25262016-02-01 10:32:02 -08004392 }
4393 }
4394 } break;
Craig Mautnerf3333272013-04-22 10:55:53 -07004395 case IDLE_TIMEOUT_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004396 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
4397 "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
Craig Mautnerf3333272013-04-22 10:55:53 -07004398 // We don't at this point know if the activity is fullscreen,
4399 // so we need to be conservative and assume it isn't.
Winson Chung4dabf232017-01-25 13:25:22 -08004400 activityIdleInternal((ActivityRecord) msg.obj,
4401 true /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004402 } break;
4403 case IDLE_NOW_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004404 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
Winson Chung4dabf232017-01-25 13:25:22 -08004405 activityIdleInternal((ActivityRecord) msg.obj,
4406 false /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004407 } break;
Craig Mautner05d29032013-05-03 13:40:13 -07004408 case RESUME_TOP_ACTIVITY_MSG: {
4409 synchronized (mService) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004410 resumeFocusedStackTopActivityLocked();
Craig Mautner05d29032013-05-03 13:40:13 -07004411 }
4412 } break;
Craig Mautner0eea92c2013-05-16 13:35:39 -07004413 case SLEEP_TIMEOUT_MSG: {
4414 synchronized (mService) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07004415 if (mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07004416 Slog.w(TAG, "Sleep timeout! Sleeping now.");
4417 mSleepTimeout = true;
4418 checkReadyForSleepLocked();
4419 }
4420 }
4421 } break;
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004422 case LAUNCH_TIMEOUT_MSG: {
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004423 synchronized (mService) {
4424 if (mLaunchingActivity.isHeld()) {
4425 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
4426 if (VALIDATE_WAKE_LOCK_CALLER
4427 && Binder.getCallingUid() != Process.myUid()) {
4428 throw new IllegalStateException("Calling must be system uid");
4429 }
4430 mLaunchingActivity.release();
4431 }
4432 }
4433 } break;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004434 case HANDLE_DISPLAY_ADDED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004435 handleDisplayAdded(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004436 } break;
4437 case HANDLE_DISPLAY_CHANGED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004438 handleDisplayChanged(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004439 } break;
4440 case HANDLE_DISPLAY_REMOVED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004441 handleDisplayRemoved(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004442 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004443 case LOCK_TASK_START_MSG: {
4444 // When lock task starts, we disable the status bars.
4445 try {
Jason Monk62515be2014-05-21 16:06:19 -04004446 if (mLockTaskNotify == null) {
4447 mLockTaskNotify = new LockTaskNotify(mService.mContext);
justinzhang5286d3f2014-05-12 17:06:01 -04004448 }
Jason Monk62515be2014-05-21 16:06:19 -04004449 mLockTaskNotify.show(true);
Benjamin Franz43261142015-02-11 15:59:44 +00004450 mLockTaskModeState = msg.arg2;
Jason Monk62515be2014-05-21 16:06:19 -04004451 if (getStatusBarService() != null) {
Benjamin Franz43261142015-02-11 15:59:44 +00004452 int flags = 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004453 if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004454 flags = StatusBarManager.DISABLE_MASK
4455 & (~StatusBarManager.DISABLE_BACK);
Craig Mautner15df08a2015-04-01 12:17:18 -07004456 } else if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004457 flags = StatusBarManager.DISABLE_MASK
4458 & (~StatusBarManager.DISABLE_BACK)
4459 & (~StatusBarManager.DISABLE_HOME)
4460 & (~StatusBarManager.DISABLE_RECENT);
Jason Monk62515be2014-05-21 16:06:19 -04004461 }
4462 getStatusBarService().disable(flags, mToken,
4463 mService.mContext.getPackageName());
4464 }
4465 mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
Jason Monk35c62a42014-06-17 10:24:47 -04004466 if (getDevicePolicyManager() != null) {
4467 getDevicePolicyManager().notifyLockTaskModeChanged(true,
Jason Monk62515be2014-05-21 16:06:19 -04004468 (String)msg.obj, msg.arg1);
Jason Monk35c62a42014-06-17 10:24:47 -04004469 }
justinzhang5286d3f2014-05-12 17:06:01 -04004470 } catch (RemoteException ex) {
4471 throw new RuntimeException(ex);
4472 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004473 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004474 case LOCK_TASK_END_MSG: {
4475 // When lock task ends, we enable the status bars.
4476 try {
Jason Monk62515be2014-05-21 16:06:19 -04004477 if (getStatusBarService() != null) {
4478 getStatusBarService().disable(StatusBarManager.DISABLE_NONE, mToken,
4479 mService.mContext.getPackageName());
4480 }
4481 mWindowManager.reenableKeyguard(mToken);
Jason Monk35c62a42014-06-17 10:24:47 -04004482 if (getDevicePolicyManager() != null) {
4483 getDevicePolicyManager().notifyLockTaskModeChanged(false, null,
4484 msg.arg1);
4485 }
Jason Monk62515be2014-05-21 16:06:19 -04004486 if (mLockTaskNotify == null) {
4487 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4488 }
4489 mLockTaskNotify.show(false);
4490 try {
Jason Monk94cfd9d2014-10-31 13:18:21 -04004491 boolean shouldLockKeyguard = Settings.Secure.getInt(
Jason Monk62515be2014-05-21 16:06:19 -04004492 mService.mContext.getContentResolver(),
Jason Monk94cfd9d2014-10-31 13:18:21 -04004493 Settings.Secure.LOCK_TO_APP_EXIT_LOCKED) != 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004494 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED && shouldLockKeyguard) {
Jason Monk62515be2014-05-21 16:06:19 -04004495 mWindowManager.lockNow(null);
Jorim Jaggi241ae102016-11-02 21:57:33 -07004496 mWindowManager.dismissKeyguard(null /* callback */);
Jason Monke0697792014-08-04 16:28:09 -04004497 new LockPatternUtils(mService.mContext)
4498 .requireCredentialEntry(UserHandle.USER_ALL);
Jason Monk62515be2014-05-21 16:06:19 -04004499 }
4500 } catch (SettingNotFoundException e) {
4501 // No setting, don't lock.
4502 }
justinzhang5286d3f2014-05-12 17:06:01 -04004503 } catch (RemoteException ex) {
4504 throw new RuntimeException(ex);
Benjamin Franz43261142015-02-11 15:59:44 +00004505 } finally {
Craig Mautner15df08a2015-04-01 12:17:18 -07004506 mLockTaskModeState = LOCK_TASK_MODE_NONE;
justinzhang5286d3f2014-05-12 17:06:01 -04004507 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004508 } break;
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004509 case SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG: {
4510 if (mLockTaskNotify == null) {
4511 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4512 }
4513 mLockTaskNotify.showToast(LOCK_TASK_MODE_PINNED);
4514 } break;
Craig Mautnerbb742462014-07-07 15:28:55 -07004515 case LAUNCH_TASK_BEHIND_COMPLETE: {
4516 synchronized (mService) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07004517 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
Craig Mautnerbb742462014-07-07 15:28:55 -07004518 if (r != null) {
4519 handleLaunchTaskBehindCompleteLocked(r);
4520 }
4521 }
4522 } break;
Chong Zhangc806d902015-11-30 09:44:27 -08004523
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004524 }
4525 }
4526 }
Craig Mautnered6649f2013-12-02 14:08:25 -08004527
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004528 // TODO: Move to its own file.
Craig Mautner4a1cb222013-12-04 16:14:06 -08004529 /** Exactly one of these classes per Display in the system. Capable of holding zero or more
4530 * attached {@link ActivityStack}s */
Andrii Kulian1779e612016-10-12 21:58:25 -07004531 class ActivityDisplay extends ConfigurationContainer {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004532 /** Actual Display this object tracks. */
Craig Mautner34b73df2014-01-12 21:11:08 -08004533 int mDisplayId;
4534 Display mDisplay;
Craig Mautnered6649f2013-12-02 14:08:25 -08004535
Craig Mautner4a1cb222013-12-04 16:14:06 -08004536 /** All of the stacks on this display. Order matters, topmost stack is in front of all other
4537 * stacks, bottommost behind. Accessed directly by ActivityManager package classes */
Wale Ogunwale1f544be2015-12-17 10:27:23 -08004538 final ArrayList<ActivityStack> mStacks = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004539
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004540 /** Array of all UIDs that are present on the display. */
4541 private IntArray mDisplayAccessUIDs = new IntArray();
4542
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004543 @VisibleForTesting
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004544 ActivityDisplay() {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004545 mActivityDisplays.put(mDisplayId, this);
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004546 }
Craig Mautner4504de52013-12-20 09:06:56 -08004547
Craig Mautner1a70a162014-09-13 12:09:31 -07004548 // After instantiation, check that mDisplay is not null before using this. The alternative
4549 // is for this to throw an exception if mDisplayManager.getDisplay() returns null.
Craig Mautnere0a38842013-12-16 16:14:02 -08004550 ActivityDisplay(int displayId) {
Craig Mautner1a70a162014-09-13 12:09:31 -07004551 final Display display = mDisplayManager.getDisplay(displayId);
4552 if (display == null) {
4553 return;
4554 }
4555 init(display);
Craig Mautner4504de52013-12-20 09:06:56 -08004556 }
4557
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004558 void init(Display display) {
Craig Mautner4504de52013-12-20 09:06:56 -08004559 mDisplay = display;
4560 mDisplayId = display.getDisplayId();
Craig Mautnered6649f2013-12-02 14:08:25 -08004561 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004562
Winson Chung7c3ede32017-03-14 14:18:34 -07004563 void attachStack(ActivityStack stack, int position) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08004564 if (DEBUG_STACK) Slog.v(TAG_STACK, "attachStack: attaching " + stack
Winson Chung7c3ede32017-03-14 14:18:34 -07004565 + " to displayId=" + mDisplayId + " position=" + position);
4566 mStacks.add(position, stack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004567 }
4568
Wale Ogunwale1666e312016-12-16 11:27:18 -08004569 void detachStack(ActivityStack stack) {
4570 if (DEBUG_STACK) Slog.v(TAG_STACK, "detachStack: detaching " + stack
Craig Mautnere0a38842013-12-16 16:14:02 -08004571 + " from displayId=" + mDisplayId);
4572 mStacks.remove(stack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004573 }
4574
Craig Mautner34b73df2014-01-12 21:11:08 -08004575 @Override
4576 public String toString() {
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004577 return "ActivityDisplay={" + mDisplayId + " numStacks=" + mStacks.size() + "}";
4578 }
Andrii Kulian1779e612016-10-12 21:58:25 -07004579
4580 @Override
4581 protected int getChildCount() {
4582 return mStacks.size();
4583 }
4584
4585 @Override
4586 protected ConfigurationContainer getChildAt(int index) {
4587 return mStacks.get(index);
4588 }
4589
4590 @Override
4591 protected ConfigurationContainer getParent() {
4592 return ActivityStackSupervisor.this;
4593 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004594
4595 boolean isPrivate() {
4596 return (mDisplay.getFlags() & FLAG_PRIVATE) != 0;
4597 }
4598
4599 boolean isUidPresent(int uid) {
4600 for (ActivityStack stack : mStacks) {
4601 if (stack.isUidPresent(uid)) {
4602 return true;
4603 }
4604 }
4605 return false;
4606 }
4607
4608 /** Update and get all UIDs that are present on the display and have access to it. */
4609 private IntArray getPresentUIDs() {
4610 mDisplayAccessUIDs.clear();
4611 for (ActivityStack stack : mStacks) {
4612 stack.getPresentUIDs(mDisplayAccessUIDs);
4613 }
4614 return mDisplayAccessUIDs;
4615 }
Andrii Kulian250d6532017-02-08 23:30:45 -08004616
4617 boolean shouldDestroyContentOnRemove() {
4618 return mDisplay.getRemoveMode() == REMOVE_MODE_DESTROY_CONTENT;
4619 }
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004620 }
4621
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004622 ActivityStack findStackBehind(ActivityStack stack) {
4623 // TODO(multi-display): We are only looking for stacks on the default display.
Jorim Jaggife762342016-10-13 14:33:27 +02004624 final ActivityDisplay display = mActivityDisplays.get(DEFAULT_DISPLAY);
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004625 if (display == null) {
4626 return null;
4627 }
4628 final ArrayList<ActivityStack> stacks = display.mStacks;
4629 for (int i = stacks.size() - 1; i >= 0; i--) {
4630 if (stacks.get(i) == stack && i > 0) {
4631 return stacks.get(i - 1);
4632 }
4633 }
4634 throw new IllegalStateException("Failed to find a stack behind stack=" + stack
4635 + " in=" + stacks);
4636 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004637
Jorim Jaggic69bd222016-03-15 14:38:37 +01004638 /**
4639 * Puts a task into resizing mode during the next app transition.
4640 *
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004641 * @param task The task to put into resizing mode
Jorim Jaggic69bd222016-03-15 14:38:37 +01004642 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004643 private void setResizingDuringAnimation(TaskRecord task) {
4644 mResizingTasksDuringAnimation.add(task.taskId);
4645 task.setTaskDockedResizing(true);
Jorim Jaggic69bd222016-03-15 14:38:37 +01004646 }
4647
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004648 final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
4649 final TaskRecord task;
4650 final int callingUid;
4651 final String callingPackage;
4652 final Intent intent;
4653 final int userId;
4654 final ActivityOptions activityOptions = (bOptions != null)
4655 ? new ActivityOptions(bOptions) : null;
4656 final int launchStackId = (activityOptions != null)
4657 ? activityOptions.getLaunchStackId() : INVALID_STACK_ID;
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004658 if (StackId.isHomeOrRecentsStack(launchStackId)) {
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004659 throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004660 + taskId + " can't be launch in the home/recents stack.");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004661 }
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004662
Matthew Ng606dd802017-06-05 14:06:32 -07004663 mWindowManager.deferSurfaceLayout();
4664 try {
4665 if (launchStackId == DOCKED_STACK_ID) {
4666 mWindowManager.setDockedStackCreateState(
4667 activityOptions.getDockCreateMode(), null /* initialBounds */);
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004668
Matthew Ng606dd802017-06-05 14:06:32 -07004669 // Defer updating the stack in which recents is until the app transition is done, to
4670 // not run into issues where we still need to draw the task in recents but the
4671 // docked stack is already created.
4672 deferUpdateBounds(RECENTS_STACK_ID);
4673 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004674 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004675
Matthew Ng606dd802017-06-05 14:06:32 -07004676 task = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
4677 launchStackId);
4678 if (task == null) {
4679 continueUpdateBounds(RECENTS_STACK_ID);
4680 mWindowManager.executeAppTransition();
4681 throw new IllegalArgumentException(
4682 "startActivityFromRecentsInner: Task " + taskId + " not found.");
4683 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004684
Matthew Ng606dd802017-06-05 14:06:32 -07004685 // Since we don't have an actual source record here, we assume that the currently
4686 // focused activity was the source.
4687 final ActivityStack focusedStack = getFocusedStack();
4688 final ActivityRecord sourceRecord =
4689 focusedStack != null ? focusedStack.topActivity() : null;
4690
4691 if (launchStackId != INVALID_STACK_ID) {
4692 if (task.getStackId() != launchStackId) {
4693 task.reparent(launchStackId, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE,
4694 DEFER_RESUME, "startActivityFromRecents");
4695 }
4696 }
4697
4698 // If the user must confirm credentials (e.g. when first launching a work app and the
4699 // Work Challenge is present) let startActivityInPackage handle the intercepting.
4700 if (!mService.mUserController.shouldConfirmCredentials(task.userId)
4701 && task.getRootActivity() != null) {
Bryce Lee28d80422017-07-21 13:25:13 -07004702 final ActivityRecord targetActivity = task.getTopActivity();
4703
4704 mService.mActivityStarter.sendPowerHintForLaunchStartIfNeeded(true /* forceSend */,
4705 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004706 mActivityMetricsLogger.notifyActivityLaunching();
Jorim Jaggi42befc62017-06-13 11:54:04 -07004707 mService.moveTaskToFrontLocked(task.taskId, 0, bOptions, true /* fromRecents */);
Matthew Ng606dd802017-06-05 14:06:32 -07004708 mActivityMetricsLogger.notifyActivityLaunched(ActivityManager.START_TASK_TO_FRONT,
Bryce Lee28d80422017-07-21 13:25:13 -07004709 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004710
4711 // If we are launching the task in the docked stack, put it into resizing mode so
4712 // the window renders full-screen with the background filling the void. Also only
4713 // call this at the end to make sure that tasks exists on the window manager side.
4714 if (launchStackId == DOCKED_STACK_ID) {
4715 setResizingDuringAnimation(task);
4716 }
4717
4718 mService.mActivityStarter.postStartActivityProcessing(task.getTopActivity(),
4719 ActivityManager.START_TASK_TO_FRONT,
4720 sourceRecord != null
4721 ? sourceRecord.getTask().getStackId() : INVALID_STACK_ID,
4722 sourceRecord, task.getStack());
4723 return ActivityManager.START_TASK_TO_FRONT;
4724 }
4725 callingUid = task.mCallingUid;
4726 callingPackage = task.mCallingPackage;
4727 intent = task.intent;
4728 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4729 userId = task.userId;
4730 int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004731 null, null, 0, 0, bOptions, userId, task, "startActivityFromRecents");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004732 if (launchStackId == DOCKED_STACK_ID) {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004733 setResizingDuringAnimation(task);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004734 }
Matthew Ng606dd802017-06-05 14:06:32 -07004735 return result;
4736 } finally {
4737 mWindowManager.continueSurfaceLayout();
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004738 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004739 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004740
4741 /**
4742 * @return a list of activities which are the top ones in each visible stack. The first
4743 * entry will be the focused activity.
4744 */
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004745 List<IBinder> getTopVisibleActivities() {
4746 final ArrayList<IBinder> topActivityTokens = new ArrayList<>();
4747 // Traverse all displays.
Robert Carr22374c02017-02-21 13:01:47 -08004748 for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004749 final ActivityDisplay display = mActivityDisplays.valueAt(i);
4750 // Traverse all stacks on a display.
4751 for (int j = display.mStacks.size() - 1; j >= 0; j--) {
4752 final ActivityStack stack = display.mStacks.get(j);
4753 // Get top activity from a visible stack and add it to the list.
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004754 if (stack.shouldBeVisible(null /* starting */)
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004755 == ActivityStack.STACK_VISIBLE) {
4756 final ActivityRecord top = stack.topActivity();
4757 if (top != null) {
4758 if (stack == mFocusedStack) {
4759 topActivityTokens.add(0, top.appToken);
4760 } else {
4761 topActivityTokens.add(top.appToken);
4762 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004763 }
4764 }
4765 }
4766 }
4767 return topActivityTokens;
4768 }
Bryce Lee4a194382017-04-04 14:32:48 -07004769
4770 /**
4771 * Internal container to store a match qualifier alongside a WaitResult.
4772 */
4773 static class WaitInfo {
4774 private final ComponentName mTargetComponent;
4775 private final WaitResult mResult;
4776
4777 public WaitInfo(ComponentName targetComponent, WaitResult result) {
4778 this.mTargetComponent = targetComponent;
4779 this.mResult = result;
4780 }
4781
Wale Ogunwale3270f172017-04-26 07:29:42 -07004782 public boolean matches(ComponentName targetComponent) {
4783 return mTargetComponent == null || mTargetComponent.equals(targetComponent);
Bryce Lee4a194382017-04-04 14:32:48 -07004784 }
4785
4786 public WaitResult getResult() {
4787 return mResult;
4788 }
4789
4790 public ComponentName getComponent() {
4791 return mTargetComponent;
4792 }
4793
4794 public void dump(PrintWriter pw, String prefix) {
4795 pw.println(prefix + "WaitInfo:");
4796 pw.println(prefix + " mTargetComponent=" + mTargetComponent);
4797 pw.println(prefix + " mResult=");
4798 mResult.dump(pw, prefix);
4799 }
4800 }
Craig Mautner27084302013-03-25 08:05:25 -07004801}