blob: 4005e2ec190214b8b13638b614372e6b2180a93c [file] [log] [blame]
Craig Mautner27084302013-03-25 08:05:25 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Andrii Kulian3c9ad072017-08-01 11:45:22 -070019import static android.Manifest.permission.ACTIVITY_EMBEDDING;
Andrii Kulian3a95edc2017-06-28 16:21:07 -070020import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Jorim Jaggife762342016-10-13 14:33:27 +020021import static android.Manifest.permission.START_ANY_ACTIVITY;
22import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
23import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
24import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
25import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
Jorim Jaggife762342016-10-13 14:33:27 +020026import static android.app.ActivityManager.START_TASK_TO_FRONT;
27import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
28import static android.app.ActivityManager.StackId.FIRST_DYNAMIC_STACK_ID;
29import static android.app.ActivityManager.StackId.FIRST_STATIC_STACK_ID;
30import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
31import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
32import static android.app.ActivityManager.StackId.HOME_STACK_ID;
33import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
34import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
35import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
Matthew Ng330757d2017-02-28 14:19:17 -080036import static android.app.ActivityManager.StackId.RECENTS_STACK_ID;
Andrii Kulian036e3ad2017-04-19 10:55:10 -070037import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY;
38import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Andrii Kulian3c9ad072017-08-01 11:45:22 -070039import static android.content.pm.PackageManager.PERMISSION_DENIED;
Jorim Jaggife762342016-10-13 14:33:27 +020040import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070041import static android.os.Process.SYSTEM_UID;
chaviw59b98852017-06-13 12:05:44 -070042import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
Jorim Jaggife762342016-10-13 14:33:27 +020043import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
44import static android.view.Display.DEFAULT_DISPLAY;
Andrii Kulian16802aa2016-11-02 12:21:33 -070045import static android.view.Display.FLAG_PRIVATE;
46import static android.view.Display.INVALID_DISPLAY;
Andrii Kulian250d6532017-02-08 23:30:45 -080047import static android.view.Display.REMOVE_MODE_DESTROY_CONTENT;
Andrii Kulian1cba31c2017-06-28 09:42:48 -070048import static android.view.Display.TYPE_VIRTUAL;
Jorim Jaggife762342016-10-13 14:33:27 +020049
Winson Chung47900652017-04-06 18:44:25 -070050import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN;
Jorim Jaggife762342016-10-13 14:33:27 +020051import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
Jorim Jaggife762342016-10-13 14:33:27 +020052import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
53import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IDLE;
54import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
55import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
56import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
57import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
58import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
59import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
60import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
61import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020062import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONTAINERS;
63import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
64import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IDLE;
65import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
66import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
67import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
68import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
69import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
70import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
71import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
72import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
Jorim Jaggife762342016-10-13 14:33:27 +020073import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
74import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
75import static com.android.server.am.ActivityManagerService.ANIMATE;
76import static com.android.server.am.ActivityManagerService.FIRST_SUPERVISOR_STACK_MSG;
77import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
78import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
Jorim Jaggife762342016-10-13 14:33:27 +020079import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
80import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
81import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
82import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
83import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
84import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
85import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
86import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
87import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
88import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
89import static com.android.server.am.ActivityStack.STACK_VISIBLE;
90import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
91import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
92import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
93import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
94import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
Winson Chung74666102017-02-22 17:49:24 -080095import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
96import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
97import static com.android.server.am.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
Jorim Jaggife762342016-10-13 14:33:27 +020098import static com.android.server.wm.AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS;
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -080099import static java.lang.Integer.MAX_VALUE;
Jorim Jaggife762342016-10-13 14:33:27 +0200100
Svetoslav7008b512015-06-24 18:47:07 -0700101import android.Manifest;
Winson Chung7900bee2017-03-10 08:59:25 -0800102import android.annotation.IntDef;
Andrii Kulian16802aa2016-11-02 12:21:33 -0700103import android.annotation.NonNull;
Tony Mak853304c2016-04-18 15:17:41 +0100104import android.annotation.UserIdInt;
Craig Mautner2420ead2013-04-01 17:13:20 -0700105import android.app.Activity;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700106import android.app.ActivityManager;
Filip Gruszczynski80e29f12015-12-14 14:58:30 -0800107import android.app.ActivityManager.RunningTaskInfo;
Wale Ogunwale3797c222015-10-27 14:21:58 -0700108import android.app.ActivityManager.StackId;
Craig Mautnered6649f2013-12-02 14:08:25 -0800109import android.app.ActivityManager.StackInfo;
David Stevensf62360c2017-03-16 19:00:20 -0700110import android.app.ActivityManagerInternal.SleepToken;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700111import android.app.ActivityOptions;
Svetoslav7008b512015-06-24 18:47:07 -0700112import android.app.AppOpsManager;
Jeff Hao1b012d32014-08-20 10:35:34 -0700113import android.app.ProfilerInfo;
Craig Mautner2420ead2013-04-01 17:13:20 -0700114import android.app.ResultInfo;
justinzhang5286d3f2014-05-12 17:06:01 -0400115import android.app.StatusBarManager;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700116import android.app.WaitResult;
Jason Monk35c62a42014-06-17 10:24:47 -0400117import android.app.admin.IDevicePolicyManager;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700118import android.content.ComponentName;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700119import android.content.Context;
120import android.content.Intent;
121import android.content.pm.ActivityInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700122import android.content.pm.ApplicationInfo;
Svetoslav7008b512015-06-24 18:47:07 -0700123import android.content.pm.PackageInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700124import android.content.pm.PackageManager;
125import android.content.pm.ResolveInfo;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100126import android.content.pm.UserInfo;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700127import android.content.res.Configuration;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800128import android.graphics.Rect;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800129import android.hardware.display.DisplayManager;
130import android.hardware.display.DisplayManager.DisplayListener;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800131import android.hardware.display.DisplayManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800132import android.hardware.input.InputManagerInternal;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700133import android.os.Binder;
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100134import android.os.Bundle;
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700135import android.os.Debug;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700136import android.os.Handler;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700137import android.os.IBinder;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700138import android.os.Looper;
Craig Mautner2420ead2013-04-01 17:13:20 -0700139import android.os.Message;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700140import android.os.ParcelFileDescriptor;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700141import android.os.PowerManager;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700142import android.os.Process;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700143import android.os.RemoteException;
justinzhang5286d3f2014-05-12 17:06:01 -0400144import android.os.ServiceManager;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700145import android.os.SystemClock;
Wale Ogunwalecad05a02015-09-25 10:41:44 -0700146import android.os.Trace;
Craig Mautner6170f732013-04-02 13:05:23 -0700147import android.os.UserHandle;
Clara Bayarrif7fea162015-10-22 16:09:52 +0100148import android.os.UserManager;
Dianne Hackborn3d07c942015-03-13 18:02:54 -0700149import android.os.WorkSource;
Svetoslav7008b512015-06-24 18:47:07 -0700150import android.provider.MediaStore;
Jason Monk62515be2014-05-21 16:06:19 -0400151import android.provider.Settings;
152import android.provider.Settings.SettingNotFoundException;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700153import android.service.voice.IVoiceInteractionSession;
Svetoslav7008b512015-06-24 18:47:07 -0700154import android.util.ArrayMap;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700155import android.util.ArraySet;
Craig Mautner2420ead2013-04-01 17:13:20 -0700156import android.util.EventLog;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800157import android.util.IntArray;
Wale Ogunwalee610d3d2017-04-25 10:23:48 -0700158import android.util.MergedConfiguration;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700159import android.util.Slog;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800160import android.util.SparseArray;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800161import android.util.SparseIntArray;
David Stevensf62360c2017-03-16 19:00:20 -0700162import android.util.TimeUtils;
Craig Mautnered6649f2013-12-02 14:08:25 -0800163import android.view.Display;
Chong Zhangb15758a2015-11-17 12:12:03 -0800164
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700165import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800166import com.android.internal.content.ReferrerIntent;
Winson Chung14fbe142016-12-19 16:18:24 -0800167import com.android.internal.logging.MetricsLogger;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -0700168import com.android.internal.os.TransferPipe;
justinzhang5286d3f2014-05-12 17:06:01 -0400169import com.android.internal.statusbar.IStatusBarService;
Svetoslav7008b512015-06-24 18:47:07 -0700170import com.android.internal.util.ArrayUtils;
Jason Monke0697792014-08-04 16:28:09 -0400171import com.android.internal.widget.LockPatternUtils;
Jeff Brownca9bc702014-02-11 14:32:56 -0800172import com.android.server.LocalServices;
Craig Mautner2420ead2013-04-01 17:13:20 -0700173import com.android.server.am.ActivityStack.ActivityState;
Winson Chung19953ca2017-04-11 11:19:23 -0700174import com.android.server.wm.PinnedStackWindowController;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700175import com.android.server.wm.WindowManagerService;
Craig Mautner23ac33b2013-04-01 16:26:35 -0700176
Craig Mautner8d341ef2013-03-26 09:03:27 -0700177import java.io.FileDescriptor;
178import java.io.IOException;
Craig Mautner27084302013-03-25 08:05:25 -0700179import java.io.PrintWriter;
Winson Chung7900bee2017-03-10 08:59:25 -0800180import java.lang.annotation.Retention;
181import java.lang.annotation.RetentionPolicy;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700182import java.util.ArrayList;
Craig Mautnere0570202015-05-13 13:06:11 -0700183import java.util.Arrays;
David Stevensf62360c2017-03-16 19:00:20 -0700184import java.util.Iterator;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700185import java.util.List;
Wale Ogunwale540e1232015-05-01 15:35:39 -0700186import java.util.Set;
Craig Mautner27084302013-03-25 08:05:25 -0700187
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -0800188public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener {
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800189 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_AM;
Chong Zhang6cda19c2016-06-14 19:07:56 -0700190 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700191 private static final String TAG_IDLE = TAG + POSTFIX_IDLE;
Craig Mautnere0570202015-05-13 13:06:11 -0700192 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700193 private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700194 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700195 private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700196 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700197 private static final String TAG_STATES = TAG + POSTFIX_STATES;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700198 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800199 static final String TAG_TASKS = TAG + POSTFIX_TASKS;
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800200
Craig Mautnerf3333272013-04-22 10:55:53 -0700201 /** How long we wait until giving up on the last activity telling us it is idle. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700202 static final int IDLE_TIMEOUT = 10 * 1000;
Craig Mautnerf3333272013-04-22 10:55:53 -0700203
Craig Mautner0eea92c2013-05-16 13:35:39 -0700204 /** How long we can hold the sleep wake lock before giving up. */
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700205 static final int SLEEP_TIMEOUT = 5 * 1000;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700206
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700207 // How long we can hold the launch wake lock before giving up.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700208 static final int LAUNCH_TIMEOUT = 10 * 1000;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700209
Craig Mautner05d29032013-05-03 13:40:13 -0700210 static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
211 static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
212 static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700213 static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700214 static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800215 static final int HANDLE_DISPLAY_ADDED = FIRST_SUPERVISOR_STACK_MSG + 5;
216 static final int HANDLE_DISPLAY_CHANGED = FIRST_SUPERVISOR_STACK_MSG + 6;
217 static final int HANDLE_DISPLAY_REMOVED = FIRST_SUPERVISOR_STACK_MSG + 7;
justinzhang5286d3f2014-05-12 17:06:01 -0400218 static final int LOCK_TASK_START_MSG = FIRST_SUPERVISOR_STACK_MSG + 9;
219 static final int LOCK_TASK_END_MSG = FIRST_SUPERVISOR_STACK_MSG + 10;
Wale Ogunwale73eba742015-04-07 14:23:14 -0700220 static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
Craig Mautnerc21ae9e2015-04-15 09:45:42 -0700221 static final int SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG = FIRST_SUPERVISOR_STACK_MSG + 13;
Wale Ogunwale22e25262016-02-01 10:32:02 -0800222 static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
223 static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800224
Wale Ogunwale040b4702015-08-06 18:10:50 -0700225 private static final String VIRTUAL_DISPLAY_BASE_NAME = "ActivityViewVirtualDisplay";
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700226
Jason Monk62515be2014-05-21 16:06:19 -0400227 private static final String LOCK_TASK_TAG = "Lock-to-App";
228
Wale Ogunwale040b4702015-08-06 18:10:50 -0700229 // Used to indicate if an object (e.g. stack) that we are trying to get
230 // should be created if it doesn't exist already.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800231 static final boolean CREATE_IF_NEEDED = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700232
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700233 // Used to indicate that windows of activities should be preserved during the resize.
234 static final boolean PRESERVE_WINDOWS = true;
235
Wale Ogunwale040b4702015-08-06 18:10:50 -0700236 // Used to indicate if an object (e.g. task) should be moved/created
237 // at the top of its container (e.g. stack).
Wale Ogunwaleb30daaa2015-08-07 21:50:49 -0700238 static final boolean ON_TOP = true;
Wale Ogunwale040b4702015-08-06 18:10:50 -0700239
240 // Used to indicate that an objects (e.g. task) removal from its container
241 // (e.g. stack) is due to it moving to another container.
242 static final boolean MOVING = true;
243
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700244 // Force the focus to change to the stack we are moving a task to..
245 static final boolean FORCE_FOCUS = true;
246
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700247 // Don't execute any calls to resume.
248 static final boolean DEFER_RESUME = true;
249
Winson Chung010927a2016-12-15 16:12:35 -0800250 // Used to indicate that a task is removed it should also be removed from recents.
251 static final boolean REMOVE_FROM_RECENTS = true;
252
Winson Chung6954fc92017-03-24 16:22:12 -0700253 // Used to indicate that pausing an activity should occur immediately without waiting for
254 // the activity callback indicating that it has completed pausing
255 static final boolean PAUSE_IMMEDIATELY = true;
256
Winson Chung7900bee2017-03-10 08:59:25 -0800257 /**
258 * The modes which affect which tasks are returned when calling
259 * {@link ActivityStackSupervisor#anyTaskForIdLocked(int)}.
260 */
261 @Retention(RetentionPolicy.SOURCE)
262 @IntDef({
263 MATCH_TASK_IN_STACKS_ONLY,
264 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
265 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
266 })
267 public @interface AnyTaskForIdMatchTaskMode {}
268 // Match only tasks in the current stacks
269 static final int MATCH_TASK_IN_STACKS_ONLY = 0;
270 // Match either tasks in the current stacks, or in the recent tasks if not found in the stacks
271 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS = 1;
272 // Match either tasks in the current stacks, or in the recent tasks, restoring it to the
273 // provided stack id
274 static final int MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE = 2;
275
Svetoslav7008b512015-06-24 18:47:07 -0700276 // Activity actions an app cannot start if it uses a permission which is not granted.
277 private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION =
278 new ArrayMap<>();
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700279
Svetoslav7008b512015-06-24 18:47:07 -0700280 static {
281 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE,
282 Manifest.permission.CAMERA);
283 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE,
284 Manifest.permission.CAMERA);
285 ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL,
286 Manifest.permission.CALL_PHONE);
287 }
288
Svet Ganov99b60432015-06-27 13:15:22 -0700289 /** Action restriction: launching the activity is not restricted. */
290 private static final int ACTIVITY_RESTRICTION_NONE = 0;
291 /** Action restriction: launching the activity is restricted by a permission. */
292 private static final int ACTIVITY_RESTRICTION_PERMISSION = 1;
293 /** Action restriction: launching the activity is restricted by an app op. */
294 private static final int ACTIVITY_RESTRICTION_APPOP = 2;
Svetoslav7008b512015-06-24 18:47:07 -0700295
justinzhang5286d3f2014-05-12 17:06:01 -0400296 /** Status Bar Service **/
297 private IBinder mToken = new Binder();
298 private IStatusBarService mStatusBarService;
Jason Monk35c62a42014-06-17 10:24:47 -0400299 private IDevicePolicyManager mDevicePolicyManager;
justinzhang5286d3f2014-05-12 17:06:01 -0400300
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700301 // For debugging to make sure the caller when acquiring/releasing our
302 // wake lock is the system process.
303 static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800304 /** The number of distinct task ids that can be assigned to the tasks of a single user */
305 private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
Craig Mautnerf3333272013-04-22 10:55:53 -0700306
Craig Mautner27084302013-03-25 08:05:25 -0700307 final ActivityManagerService mService;
308
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800309 private RecentTasks mRecentTasks;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800310
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700311 final ActivityStackSupervisorHandler mHandler;
312
313 /** Short cut */
314 WindowManagerService mWindowManager;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800315 DisplayManager mDisplayManager;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700316
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -0700317 /** Counter for next free stack ID to use for dynamic activity stacks. */
318 private int mNextFreeStackId = FIRST_DYNAMIC_STACK_ID;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700319
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800320 /**
321 * Maps the task identifier that activities are currently being started in to the userId of the
322 * task. Each time a new task is created, the entry for the userId of the task is incremented
323 */
324 private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20);
Craig Mautner8d341ef2013-03-26 09:03:27 -0700325
Craig Mautner2420ead2013-04-01 17:13:20 -0700326 /** The current user */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800327 int mCurrentUser;
Craig Mautner2420ead2013-04-01 17:13:20 -0700328
Craig Mautnere0a38842013-12-16 16:14:02 -0800329 /** The stack containing the launcher app. Assumed to always be attached to
330 * Display.DEFAULT_DISPLAY. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800331 ActivityStack mHomeStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700332
Craig Mautnere0a38842013-12-16 16:14:02 -0800333 /** The stack currently receiving input or launching the next activity. */
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800334 ActivityStack mFocusedStack;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700335
Craig Mautner4a1cb222013-12-04 16:14:06 -0800336 /** If this is the same as mFocusedStack then the activity on the top of the focused stack has
337 * been resumed. If stacks are changing position this will hold the old stack until the new
Craig Mautnere0a38842013-12-16 16:14:02 -0800338 * stack becomes resumed after which it will be set to mFocusedStack. */
Craig Mautner4a1cb222013-12-04 16:14:06 -0800339 private ActivityStack mLastFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -0700340
341 /** List of activities that are waiting for a new activity to become visible before completing
342 * whatever operation they are supposed to do. */
Bryce Lee4a194382017-04-04 14:32:48 -0700343 // TODO: Remove mActivitiesWaitingForVisibleActivity list and just remove activity from
344 // mStoppingActivities when something else comes up.
345 final ArrayList<ActivityRecord> mActivitiesWaitingForVisibleActivity = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700346
Bryce Lee4a194382017-04-04 14:32:48 -0700347 /** List of processes waiting to find out when a specific activity becomes visible. */
348 private final ArrayList<WaitInfo> mWaitingForActivityVisible = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700349
350 /** List of processes waiting to find out about the next launched activity. */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700351 final ArrayList<WaitResult> mWaitingActivityLaunched = new ArrayList<>();
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700352
Craig Mautnerde4ef022013-04-07 19:01:33 -0700353 /** List of activities that are ready to be stopped, but waiting for the next activity to
354 * settle down before doing so. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800355 final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700356
Craig Mautnerf3333272013-04-22 10:55:53 -0700357 /** List of activities that are ready to be finished, but waiting for the previous activity to
358 * settle down before doing so. It contains ActivityRecord objects. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800359 final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700360
Craig Mautner0eea92c2013-05-16 13:35:39 -0700361 /** List of activities that are in the process of going to sleep. */
Craig Mautner8c14c152015-01-15 17:32:07 -0800362 final ArrayList<ActivityRecord> mGoingToSleepActivities = new ArrayList<>();
Craig Mautner0eea92c2013-05-16 13:35:39 -0700363
Wale Ogunwale22e25262016-02-01 10:32:02 -0800364 /** List of activities whose multi-window mode changed that we need to report to the
365 * application */
366 final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
367
368 /** List of activities whose picture-in-picture mode changed that we need to report to the
369 * application */
370 final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
371
Winson Chung5af42fc2017-03-24 17:11:33 -0700372 /** The target stack bounds for the picture-in-picture mode changed that we need to report to
373 * the application */
374 Rect mPipModeChangedTargetStackBounds;
375
Craig Mautnerf3333272013-04-22 10:55:53 -0700376 /** Used on user changes */
Amith Yamasani37a40c22015-06-17 13:25:42 -0700377 final ArrayList<UserState> mStartingUsers = new ArrayList<>();
Craig Mautnerf3333272013-04-22 10:55:53 -0700378
Craig Mautnerde4ef022013-04-07 19:01:33 -0700379 /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity
380 * is being brought in front of us. */
381 boolean mUserLeaving = false;
382
Craig Mautner0eea92c2013-05-16 13:35:39 -0700383 /**
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700384 * We don't want to allow the device to go to sleep while in the process
385 * of launching an activity. This is primarily to allow alarm intent
386 * receivers to launch an activity and get that to run before the device
387 * goes back to sleep.
388 */
Jeff Brown2c43c332014-06-12 22:38:59 -0700389 PowerManager.WakeLock mLaunchingActivity;
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700390
391 /**
Craig Mautner0eea92c2013-05-16 13:35:39 -0700392 * Set when the system is going to sleep, until we have
393 * successfully paused the current activity and released our wake lock.
394 * At that point the system is allowed to actually sleep.
395 */
Jeff Brown2c43c332014-06-12 22:38:59 -0700396 PowerManager.WakeLock mGoingToSleep;
Craig Mautner0eea92c2013-05-16 13:35:39 -0700397
David Stevensf62360c2017-03-16 19:00:20 -0700398 /**
399 * A list of tokens that cause the top activity to be put to sleep.
400 * They are used by components that may hide and block interaction with underlying
401 * activities.
402 */
403 final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>();
404
Craig Mautner4f1df4f2013-10-15 15:44:14 -0700405 /** Stack id of the front stack when user switched, indexed by userId. */
406 SparseIntArray mUserStackInFront = new SparseIntArray(2);
Craig Mautner93529a42013-10-04 15:03:13 -0700407
Craig Mautner4504de52013-12-20 09:06:56 -0800408 // TODO: Add listener for removal of references.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800409 /** Mapping from (ActivityStack/TaskStack).mStackId to their current state */
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700410 SparseArray<ActivityStack> mStacks = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800411
Bryce Leeaf3a4002017-03-20 10:37:12 -0700412 // TODO: There should be an ActivityDisplayController coordinating am/wm interaction.
Craig Mautner4a1cb222013-12-04 16:14:06 -0800413 /** Mapping from displayId to display current state */
Craig Mautner15df08a2015-04-01 12:17:18 -0700414 private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800415
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800416 private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>();
417
418 private DisplayManagerInternal mDisplayManagerInternal;
419 private InputManagerInternal mInputManagerInternal;
Jeff Brownca9bc702014-02-11 14:32:56 -0800420
Craig Mautner15df08a2015-04-01 12:17:18 -0700421 /** The chain of tasks in lockTask mode. The current frontmost task is at the top, and tasks
422 * may be finished until there is only one entry left. If this is empty the system is not
423 * in lockTask mode. */
424 ArrayList<TaskRecord> mLockTaskModeTasks = new ArrayList<>();
Benjamin Franz43261142015-02-11 15:59:44 +0000425 /** Store the current lock task mode. Possible values:
Craig Mautner2568c3a2015-03-26 14:22:34 -0700426 * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
427 * {@link ActivityManager#LOCK_TASK_MODE_PINNED}
Benjamin Franz43261142015-02-11 15:59:44 +0000428 */
429 private int mLockTaskModeState;
Jason Monk62515be2014-05-21 16:06:19 -0400430 /**
431 * Notifies the user when entering/exiting lock-task.
432 */
433 private LockTaskNotify mLockTaskNotify;
Craig Mautneraea74a52014-03-08 14:23:10 -0800434
Wale Ogunwaled046a012015-12-24 13:05:59 -0800435 /** Used to keep resumeTopActivityUncheckedLocked() from being entered recursively */
Craig Mautner42d04db2014-11-06 12:13:23 -0800436 boolean inResumeTopActivity;
437
Andrii Kulian1e32e022016-09-16 15:29:34 -0700438 /**
439 * Temporary rect used during docked stack resize calculation so we don't need to create a new
440 * object each time.
441 */
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -0700442 private final Rect tempRect = new Rect();
Filip Gruszczynskiebcc8752015-08-25 16:51:05 -0700443
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700444 // The default minimal size that will be used if the activity doesn't specify its minimal size.
445 // It will be calculated when the default display gets added.
Andrii Kulianf66a83d2016-05-17 12:17:44 -0700446 int mDefaultMinSizeOfResizeableTask = -1;
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -0700447
Chong Zhangfdcc4d42015-10-14 16:50:12 -0700448 // Whether tasks have moved and we need to rank the tasks before next OOM scoring
449 private boolean mTaskLayersChanged = true;
450
Jorim Jaggi275561a2016-02-23 10:11:02 -0500451 final ActivityMetricsLogger mActivityMetricsLogger;
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800452
Jorim Jaggiea039a82017-08-02 14:37:49 +0200453 private final ArrayList<ActivityRecord> mTmpActivityList = new ArrayList<>();
454
Andrii Kulian1779e612016-10-12 21:58:25 -0700455 @Override
456 protected int getChildCount() {
457 return mActivityDisplays.size();
458 }
459
460 @Override
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700461 protected ActivityDisplay getChildAt(int index) {
Andrii Kulian1779e612016-10-12 21:58:25 -0700462 return mActivityDisplays.valueAt(index);
463 }
464
465 @Override
466 protected ConfigurationContainer getParent() {
467 return null;
468 }
469
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700470 Configuration getDisplayOverrideConfiguration(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700471 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700472 if (activityDisplay == null) {
473 throw new IllegalArgumentException("No display found with id: " + displayId);
474 }
475
476 return activityDisplay.getOverrideConfiguration();
477 }
478
479 void setDisplayOverrideConfiguration(Configuration overrideConfiguration, int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -0700480 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian5406e7a2016-10-21 11:55:23 -0700481 if (activityDisplay == null) {
482 throw new IllegalArgumentException("No display found with id: " + displayId);
483 }
484
485 activityDisplay.onOverrideConfigurationChanged(overrideConfiguration);
486 }
487
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700488 /** Check if placing task or activity on specified display is allowed. */
Andrii Kulian02689a72017-07-06 14:28:59 -0700489 boolean canPlaceEntityOnDisplay(int displayId, boolean resizeable, int callingPid,
490 int callingUid, ActivityInfo activityInfo) {
491 if (displayId == DEFAULT_DISPLAY) {
492 // No restrictions for the default display.
493 return true;
494 }
495 if (!mService.mSupportsMultiDisplay) {
496 // Can't launch on secondary displays if feature is not supported.
497 return false;
498 }
499 if (!resizeable && !displayConfigMatchesGlobal(displayId)) {
500 // Can't apply wrong configuration to non-resizeable activities.
501 return false;
502 }
503 if (!isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, displayId, activityInfo)) {
504 // Can't place activities to a display that has restricted launch rules.
505 // In this case the request should be made by explicitly adding target display id and
506 // by caller with corresponding permissions. See #isCallerAllowedToLaunchOnDisplay().
507 return false;
508 }
509 return true;
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700510 }
511
512 /**
513 * Check if configuration of specified display matches current global config.
514 * Used to check if we can put a non-resizeable activity on a secondary display and it will get
515 * the same config as on the default display.
516 * @param displayId Id of the display to check.
517 * @return {@code true} if configuration matches.
518 */
519 private boolean displayConfigMatchesGlobal(int displayId) {
520 if (displayId == DEFAULT_DISPLAY) {
521 return true;
522 }
523 if (displayId == INVALID_DISPLAY) {
524 return false;
525 }
Andrii Kulian62e6f252017-05-30 22:46:53 -0700526 final ActivityDisplay targetDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian036e3ad2017-04-19 10:55:10 -0700527 if (targetDisplay == null) {
528 throw new IllegalArgumentException("No display found with id: " + displayId);
529 }
530 return getConfiguration().equals(targetDisplay.getConfiguration());
531 }
532
Wale Ogunwale39381972015-12-17 17:15:29 -0800533 static class FindTaskResult {
534 ActivityRecord r;
535 boolean matchedByRootAffinity;
536 }
537 private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
538
Craig Mautneree36c772014-07-16 14:56:05 -0700539 /**
Andrii Kulian7fc22812016-12-28 13:04:11 -0800540 * Temp storage for display ids sorted in focus order.
541 * Maps position to id. Using {@link SparseIntArray} instead of {@link ArrayList} because
542 * it's more efficient, as the number of displays is usually small.
543 */
544 private SparseIntArray mTmpOrderedDisplayIds = new SparseIntArray();
545
546 /**
Jorim Jaggia0fdeec2016-01-07 14:42:28 +0100547 * Used to keep track whether app visibilities got changed since the last pause. Useful to
548 * determine whether to invoke the task stack change listener after pausing.
549 */
550 boolean mAppVisibilitiesChangedSinceLastPause;
551
552 /**
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100553 * Set of tasks that are in resizing mode during an app transition to fill the "void".
554 */
555 private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>();
556
Wale Ogunwalec8da41e2016-04-16 13:27:23 -0700557
558 /**
559 * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked}
560 * will be ignored. Useful for the case where the caller is handling resizing of other stack and
561 * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger
562 * like the docked stack going empty.
563 */
564 private boolean mAllowDockedStackResize = true;
565
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +0100566 /**
Tony Mak853304c2016-04-18 15:17:41 +0100567 * Is dock currently minimized.
568 */
569 boolean mIsDockMinimized;
570
Jorim Jaggife762342016-10-13 14:33:27 +0200571 final KeyguardController mKeyguardController;
572
chaviw59b98852017-06-13 12:05:44 -0700573 private PowerManager mPowerManager;
574 private int mDeferResumeCount;
575
Tony Mak853304c2016-04-18 15:17:41 +0100576 /**
Craig Mautneree36c772014-07-16 14:56:05 -0700577 * Description of a request to start a new activity, which has been held
578 * due to app switches being disabled.
579 */
580 static class PendingActivityLaunch {
581 final ActivityRecord r;
582 final ActivityRecord sourceRecord;
583 final int startFlags;
584 final ActivityStack stack;
Robert Carr13997f52015-10-23 13:13:39 -0700585 final ProcessRecord callerApp;
Craig Mautneree36c772014-07-16 14:56:05 -0700586
587 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord,
Robert Carr13997f52015-10-23 13:13:39 -0700588 int _startFlags, ActivityStack _stack, ProcessRecord _callerApp) {
Craig Mautneree36c772014-07-16 14:56:05 -0700589 r = _r;
590 sourceRecord = _sourceRecord;
591 startFlags = _startFlags;
592 stack = _stack;
Robert Carr13997f52015-10-23 13:13:39 -0700593 callerApp = _callerApp;
594 }
595
596 void sendErrorResult(String message) {
597 try {
598 if (callerApp.thread != null) {
599 callerApp.thread.scheduleCrash(message);
600 }
601 } catch (RemoteException e) {
602 Slog.e(TAG, "Exception scheduling crash of failed "
603 + "activity launcher sourceRecord=" + sourceRecord, e);
604 }
Craig Mautneree36c772014-07-16 14:56:05 -0700605 }
606 }
607
Bryce Leeaf691c02017-03-20 14:20:22 -0700608 public ActivityStackSupervisor(ActivityManagerService service, Looper looper) {
Craig Mautner27084302013-03-25 08:05:25 -0700609 mService = service;
Bryce Leeaf691c02017-03-20 14:20:22 -0700610 mHandler = new ActivityStackSupervisorHandler(looper);
Filip Gruszczynski77d94482015-12-11 13:59:52 -0800611 mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext);
Jorim Jaggife762342016-10-13 14:33:27 +0200612 mKeyguardController = new KeyguardController(service, this);
Jeff Brown2c43c332014-06-12 22:38:59 -0700613 }
614
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800615 void setRecentTasks(RecentTasks recentTasks) {
616 mRecentTasks = recentTasks;
617 }
618
Jeff Brown2c43c332014-06-12 22:38:59 -0700619 /**
620 * At the time when the constructor runs, the power manager has not yet been
621 * initialized. So we initialize our wakelocks afterwards.
622 */
623 void initPowerManagement() {
chaviw59b98852017-06-13 12:05:44 -0700624 mPowerManager = (PowerManager)mService.mContext.getSystemService(Context.POWER_SERVICE);
625 mGoingToSleep = mPowerManager
626 .newWakeLock(PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
627 mLaunchingActivity = mPowerManager.newWakeLock(PARTIAL_WAKE_LOCK, "*launch*");
Craig Mautner7ea5bd42013-07-05 15:27:08 -0700628 mLaunchingActivity.setReferenceCounted(false);
Craig Mautner2219a1b2013-03-25 09:44:30 -0700629 }
630
justinzhang5286d3f2014-05-12 17:06:01 -0400631 // This function returns a IStatusBarService. The value is from ServiceManager.
632 // getService and is cached.
633 private IStatusBarService getStatusBarService() {
634 synchronized (mService) {
635 if (mStatusBarService == null) {
636 mStatusBarService = IStatusBarService.Stub.asInterface(
637 ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
638 if (mStatusBarService == null) {
639 Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
640 }
641 }
642 return mStatusBarService;
643 }
644 }
645
Jason Monk35c62a42014-06-17 10:24:47 -0400646 private IDevicePolicyManager getDevicePolicyManager() {
647 synchronized (mService) {
648 if (mDevicePolicyManager == null) {
649 mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
650 ServiceManager.checkService(Context.DEVICE_POLICY_SERVICE));
651 if (mDevicePolicyManager == null) {
652 Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
653 }
654 }
655 return mDevicePolicyManager;
656 }
657 }
658
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700659 void setWindowManager(WindowManagerService wm) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800660 synchronized (mService) {
661 mWindowManager = wm;
Jorim Jaggife762342016-10-13 14:33:27 +0200662 mKeyguardController.setWindowManager(wm);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800663
664 mDisplayManager =
665 (DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
666 mDisplayManager.registerDisplayListener(this, null);
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800667 mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800668
669 Display[] displays = mDisplayManager.getDisplays();
670 for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
671 final int displayId = displays[displayNdx].getDisplayId();
Craig Mautnere0a38842013-12-16 16:14:02 -0800672 ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
Craig Mautner1a70a162014-09-13 12:09:31 -0700673 if (activityDisplay.mDisplay == null) {
674 throw new IllegalStateException("Default Display does not exist");
675 }
Craig Mautnere0a38842013-12-16 16:14:02 -0800676 mActivityDisplays.put(displayId, activityDisplay);
Filip Gruszczynski7be9a8c2015-10-15 18:20:30 -0700677 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800678 }
679
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800680 mHomeStack = mFocusedStack = mLastFocusedStack =
681 getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Jeff Brownca9bc702014-02-11 14:32:56 -0800682
683 mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800684 }
Craig Mautner27084302013-03-25 08:05:25 -0700685 }
686
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700687 ActivityStack getFocusedStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800688 return mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700689 }
690
Craig Mautnerde4ef022013-04-07 19:01:33 -0700691 ActivityStack getLastStack() {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800692 return mLastFocusedStack;
Craig Mautner2219a1b2013-03-25 09:44:30 -0700693 }
694
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700695 boolean isFocusedStack(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700696 return stack != null && stack == mFocusedStack;
Craig Mautner20e72272013-04-01 13:45:53 -0700697 }
698
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800699 /** The top most stack on its display. */
700 boolean isFrontStackOnDisplay(ActivityStack stack) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700701 return isFrontOfStackList(stack, stack.getDisplay().mStacks);
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800702 }
703
704 private boolean isFrontOfStackList(ActivityStack stack, List<ActivityStack> stackList) {
Andrii Kuliane8d928a2016-11-14 18:38:14 -0800705 return stack == stackList.get((stackList.size() - 1));
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700706 }
707
Wale Ogunwaled046a012015-12-24 13:05:59 -0800708 /** NOTE: Should only be called from {@link ActivityStack#moveToFront} */
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800709 void setFocusStackUnchecked(String reason, ActivityStack focusCandidate) {
710 if (!focusCandidate.isFocusable()) {
711 // The focus candidate isn't focusable. Move focus to the top stack that is focusable.
Andrii Kulian7fc22812016-12-28 13:04:11 -0800712 focusCandidate = getNextFocusableStackLocked(focusCandidate);
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800713 }
714
715 if (focusCandidate != mFocusedStack) {
Wale Ogunwaled046a012015-12-24 13:05:59 -0800716 mLastFocusedStack = mFocusedStack;
Wale Ogunwale4cea0f52015-12-25 06:30:31 -0800717 mFocusedStack = focusCandidate;
Wale Ogunwalecb82f302015-02-25 07:53:40 -0800718
Wale Ogunwaled046a012015-12-24 13:05:59 -0800719 EventLogTags.writeAmFocusedStack(
720 mCurrentUser, mFocusedStack == null ? -1 : mFocusedStack.getStackId(),
721 mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(), reason);
722 }
723
724 final ActivityRecord r = topRunningActivityLocked();
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800725 if (mService.mBooting || !mService.mBooted) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -0800726 if (r != null && r.idle) {
727 checkFinishBootingLocked();
728 }
729 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700730 }
731
Wale Ogunwale925d0d12015-09-23 15:40:07 -0700732 void moveHomeStackToFront(String reason) {
733 mHomeStack.moveToFront(reason);
734 }
735
Matthew Ng330757d2017-02-28 14:19:17 -0800736 void moveRecentsStackToFront(String reason) {
737 final ActivityStack recentsStack = getStack(RECENTS_STACK_ID);
738 if (recentsStack != null) {
739 recentsStack.moveToFront(reason);
740 }
741 }
742
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700743 /** Returns true if the focus activity was adjusted to the home stack top activity. */
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800744 boolean moveHomeStackTaskToTop(String reason) {
745 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700746
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700747 final ActivityRecord top = getHomeActivity();
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700748 if (top == null) {
749 return false;
750 }
Chong Zhang6cda19c2016-06-14 19:07:56 -0700751 moveFocusableActivityStackToFrontLocked(top, reason);
Wale Ogunwaled80c2632015-03-13 10:26:26 -0700752 return true;
Craig Mautner8e569572013-10-11 17:36:59 -0700753 }
754
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800755 boolean resumeHomeStackTask(ActivityRecord prev, String reason) {
Dianne Hackborn7622a0f2014-09-30 14:31:42 -0700756 if (!mService.mBooting && !mService.mBooted) {
757 // Not ready yet!
758 return false;
759 }
760
Craig Mautner84984fa2014-06-19 11:19:20 -0700761 if (prev != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -0700762 prev.getTask().setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
Craig Mautner84984fa2014-06-19 11:19:20 -0700763 }
764
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800765 mHomeStack.moveHomeStackTaskToTop();
Wale Ogunwale2d0f39b2015-04-17 15:35:39 -0700766 ActivityRecord r = getHomeActivity();
Wale Ogunwaled046a012015-12-24 13:05:59 -0800767 final String myReason = reason + " resumeHomeStackTask";
768
Mark Lua56ea122015-10-08 13:31:01 +0800769 // Only resume home activity if isn't finishing.
770 if (r != null && !r.finishing) {
Chong Zhang6cda19c2016-06-14 19:07:56 -0700771 moveFocusableActivityStackToFrontLocked(r, myReason);
Wale Ogunwaled046a012015-12-24 13:05:59 -0800772 return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
Craig Mautner69ada552013-04-18 13:51:51 -0700773 }
Wale Ogunwaled046a012015-12-24 13:05:59 -0800774 return mService.startHomeActivityLocked(mCurrentUser, myReason);
Craig Mautner69ada552013-04-18 13:51:51 -0700775 }
776
Craig Mautner8d341ef2013-03-26 09:03:27 -0700777 TaskRecord anyTaskForIdLocked(int id) {
Winson Chung7900bee2017-03-10 08:59:25 -0800778 return anyTaskForIdLocked(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
779 INVALID_STACK_ID);
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700780 }
781
782 /**
Bryce Lee92b7b652017-04-03 08:33:11 -0700783 * Returns a {@link TaskRecord} for the input id if available. {@code null} otherwise.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700784 * @param id Id of the task we would like returned.
Winson Chung7900bee2017-03-10 08:59:25 -0800785 * @param matchMode The mode to match the given task id in.
Wale Ogunwale3797c222015-10-27 14:21:58 -0700786 * @param stackId The stack to restore the task to (default launch stack will be used if
Winson Chung7900bee2017-03-10 08:59:25 -0800787 * stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}). Only
788 * valid if the matchMode is
789 * {@link #MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE}.
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700790 */
Winson Chung7900bee2017-03-10 08:59:25 -0800791 TaskRecord anyTaskForIdLocked(int id, @AnyTaskForIdMatchTaskMode int matchMode, int stackId) {
792 // If there is a stack id set, ensure that we are attempting to actually restore a task
793 if (matchMode != MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE &&
794 stackId != INVALID_STACK_ID) {
795 throw new IllegalArgumentException("Should not specify stackId for non-restore lookup");
796 }
797
Craig Mautnere0a38842013-12-16 16:14:02 -0800798 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800799 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800800 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800801 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
802 ActivityStack stack = stacks.get(stackNdx);
Bryce Lee92b7b652017-04-03 08:33:11 -0700803 final TaskRecord task = stack.taskForIdLocked(id);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800804 if (task != null) {
805 return task;
806 }
Craig Mautner8d341ef2013-03-26 09:03:27 -0700807 }
808 }
Wale Ogunwale7de05352014-12-12 15:21:33 -0800809
Winson Chung7900bee2017-03-10 08:59:25 -0800810 // If we are matching stack tasks only, return now
811 if (matchMode == MATCH_TASK_IN_STACKS_ONLY) {
Wale Ogunwale7de05352014-12-12 15:21:33 -0800812 return null;
813 }
814
Winson Chung7900bee2017-03-10 08:59:25 -0800815 // Otherwise, check the recent tasks and return if we find it there and we are not restoring
816 // the task from recents
817 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
Bryce Lee92b7b652017-04-03 08:33:11 -0700818 final TaskRecord task = mRecentTasks.taskForIdLocked(id);
819
820 if (task == null) {
821 if (DEBUG_RECENTS) {
Winson Chung7900bee2017-03-10 08:59:25 -0800822 Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents");
823 }
Bryce Lee92b7b652017-04-03 08:33:11 -0700824
825 return null;
826 }
827
828 if (matchMode == MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) {
Wale Ogunwale04f4d6b2015-03-11 09:23:25 -0700829 return task;
830 }
831
Winson Chung7900bee2017-03-10 08:59:25 -0800832 // Implicitly, this case is MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE
Wale Ogunwale7e8184b2015-10-05 14:37:03 -0700833 if (!restoreRecentTaskLocked(task, stackId)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700834 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS,
835 "Couldn't restore task id=" + id + " found in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800836 return null;
837 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700838 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents");
Wale Ogunwale7de05352014-12-12 15:21:33 -0800839 return task;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700840 }
841
Craig Mautner6170f732013-04-02 13:05:23 -0700842 ActivityRecord isInAnyStackLocked(IBinder token) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800843 int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -0800844 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -0800845 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800846 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
847 final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
848 if (r != null) {
849 return r;
850 }
Craig Mautner6170f732013-04-02 13:05:23 -0700851 }
852 }
853 return null;
854 }
855
Tony Mak853304c2016-04-18 15:17:41 +0100856 /**
Robin Lee3fef1f22016-12-20 14:50:13 +0000857 * Detects whether we should show a lock screen in front of this task for a locked user.
858 * <p>
859 * We'll do this if either of the following holds:
860 * <ul>
861 * <li>The top activity explicitly belongs to {@param userId}.</li>
862 * <li>The top activity returns a result to an activity belonging to {@param userId}.</li>
863 * </ul>
864 *
865 * @return {@code true} if the top activity looks like it belongs to {@param userId}.
Tony Mak853304c2016-04-18 15:17:41 +0100866 */
Robin Lee3fef1f22016-12-20 14:50:13 +0000867 private boolean taskTopActivityIsUser(TaskRecord task, @UserIdInt int userId) {
868 // To handle the case that work app is in the task but just is not the top one.
869 final ActivityRecord activityRecord = task.getTopActivity();
870 final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null);
871
872 return (activityRecord != null && activityRecord.userId == userId)
873 || (resultTo != null && resultTo.userId == userId);
874 }
875
876 /**
877 * Find all visible task stacks containing {@param userId} and intercept them with an activity
878 * to block out the contents and possibly start a credential-confirming intent.
879 *
880 * @param userId user handle for the locked managed profile.
881 */
882 void lockAllProfileTasks(@UserIdInt int userId) {
883 mWindowManager.deferSurfaceLayout();
884 try {
885 final List<ActivityStack> stacks = getStacks();
886 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; stackNdx--) {
887 final List<TaskRecord> tasks = stacks.get(stackNdx).getAllTasks();
888 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) {
889 final TaskRecord task = tasks.get(taskNdx);
890
891 // Check the task for a top activity belonging to userId, or returning a result
892 // to an activity belonging to userId. Example case: a document picker for
893 // personal files, opened by a work app, should still get locked.
894 if (taskTopActivityIsUser(task, userId)) {
Robin Leec41f6ec2017-01-10 17:02:34 +0000895 mService.mTaskChangeNotificationController.notifyTaskProfileLocked(
896 task.taskId, userId);
Robin Lee3fef1f22016-12-20 14:50:13 +0000897 }
Tony Mak853304c2016-04-18 15:17:41 +0100898 }
899 }
Robin Lee3fef1f22016-12-20 14:50:13 +0000900 } finally {
901 mWindowManager.continueSurfaceLayout();
Tony Mak853304c2016-04-18 15:17:41 +0100902 }
Clara Bayarrif0649ce2016-01-14 12:30:42 +0000903 }
904
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800905 void setNextTaskIdForUserLocked(int taskId, int userId) {
906 final int currentTaskId = mCurTaskIdForUser.get(userId, -1);
907 if (taskId > currentTaskId) {
908 mCurTaskIdForUser.put(userId, taskId);
Craig Mautneref73ee12014-04-23 11:45:37 -0700909 }
910 }
911
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700912 static int nextTaskIdForUser(int taskId, int userId) {
913 int nextTaskId = taskId + 1;
914 if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) {
915 // Wrap around as there will be smaller task ids that are available now.
916 nextTaskId -= MAX_TASK_IDS_PER_USER;
917 }
918 return nextTaskId;
919 }
920
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800921 int getNextTaskIdForUserLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800922 final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER);
923 // for a userId u, a taskId can only be in the range
924 // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER
925 // 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 -0700926 int candidateTaskId = nextTaskIdForUser(currentTaskId, userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800927 while (mRecentTasks.taskIdTakenForUserLocked(candidateTaskId, userId)
Winson Chung7900bee2017-03-10 08:59:25 -0800928 || anyTaskForIdLocked(candidateTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800929 INVALID_STACK_ID) != null) {
Chong Zhangd9d35bd2016-08-04 17:55:21 -0700930 candidateTaskId = nextTaskIdForUser(candidateTaskId, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800931 if (candidateTaskId == currentTaskId) {
932 // Something wrong!
933 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user
934 throw new IllegalStateException("Cannot get an available task id."
935 + " Reached limit of " + MAX_TASK_IDS_PER_USER
936 + " running tasks per user.");
937 }
938 }
939 mCurTaskIdForUser.put(userId, candidateTaskId);
940 return candidateTaskId;
Craig Mautner8d341ef2013-03-26 09:03:27 -0700941 }
942
Chong Zhang6cda19c2016-06-14 19:07:56 -0700943 ActivityRecord getResumedActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -0800944 ActivityStack stack = mFocusedStack;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -0700945 if (stack == null) {
946 return null;
947 }
Craig Mautnerde4ef022013-04-07 19:01:33 -0700948 ActivityRecord resumedActivity = stack.mResumedActivity;
949 if (resumedActivity == null || resumedActivity.app == null) {
950 resumedActivity = stack.mPausingActivity;
951 if (resumedActivity == null || resumedActivity.app == null) {
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -0700952 resumedActivity = stack.topRunningActivityLocked();
Craig Mautnerde4ef022013-04-07 19:01:33 -0700953 }
954 }
955 return resumedActivity;
956 }
957
Dianne Hackbornff072722014-09-24 10:56:28 -0700958 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
Craig Mautner20e72272013-04-01 13:45:53 -0700959 final String processName = app.processName;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800960 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -0800961 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
962 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800963 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
964 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -0700965 if (!isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800966 continue;
967 }
Jorim Jaggiea039a82017-08-02 14:37:49 +0200968 stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
969 final ActivityRecord top = stack.topRunningActivityLocked();
970 final int size = mTmpActivityList.size();
971 for (int i = 0; i < size; i++) {
972 final ActivityRecord activity = mTmpActivityList.get(i);
973 if (activity.app == null && app.uid == activity.info.applicationInfo.uid
974 && processName.equals(activity.processName)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800975 try {
Jorim Jaggiea039a82017-08-02 14:37:49 +0200976 if (realStartActivityLocked(activity, app,
977 top == activity /* andResume */, true /* checkConfig */)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800978 didSomething = true;
979 }
Dianne Hackbornff072722014-09-24 10:56:28 -0700980 } catch (RemoteException e) {
Craig Mautner4a1cb222013-12-04 16:14:06 -0800981 Slog.w(TAG, "Exception in new application when starting activity "
Jorim Jaggiea039a82017-08-02 14:37:49 +0200982 + top.intent.getComponent().flattenToShortString(), e);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800983 throw e;
Craig Mautner20e72272013-04-01 13:45:53 -0700984 }
Craig Mautner20e72272013-04-01 13:45:53 -0700985 }
Craig Mautner20e72272013-04-01 13:45:53 -0700986 }
987 }
988 }
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700989 if (!didSomething) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -0700990 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerb59dcfd2013-05-06 13:12:58 -0700991 }
Craig Mautner20e72272013-04-01 13:45:53 -0700992 return didSomething;
993 }
994
995 boolean allResumedActivitiesIdle() {
Craig Mautnere0a38842013-12-16 16:14:02 -0800996 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
997 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800998 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
999 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001000 if (!isFocusedStack(stack) || stack.numActivities() == 0) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001001 continue;
1002 }
1003 final ActivityRecord resumedActivity = stack.mResumedActivity;
1004 if (resumedActivity == null || !resumedActivity.idle) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001005 if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
Craig Mautner34b73df2014-01-12 21:11:08 -08001006 + stack.mStackId + " " + resumedActivity + " not idle");
Craig Mautner4a1cb222013-12-04 16:14:06 -08001007 return false;
1008 }
Craig Mautner20e72272013-04-01 13:45:53 -07001009 }
1010 }
Wei Wang65c7a152016-06-02 18:51:22 -07001011 // Send launch end powerhint when idle
1012 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
Craig Mautner20e72272013-04-01 13:45:53 -07001013 return true;
1014 }
1015
Craig Mautnerde4ef022013-04-07 19:01:33 -07001016 boolean allResumedActivitiesComplete() {
Craig Mautnere0a38842013-12-16 16:14:02 -08001017 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1018 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001019 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1020 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001021 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001022 final ActivityRecord r = stack.mResumedActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001023 if (r != null && r.state != RESUMED) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001024 return false;
1025 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001026 }
1027 }
1028 }
1029 // TODO: Not sure if this should check if all Paused are complete too.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001030 if (DEBUG_STACK) Slog.d(TAG_STACK,
Craig Mautner4a1cb222013-12-04 16:14:06 -08001031 "allResumedActivitiesComplete: mLastFocusedStack changing from=" +
1032 mLastFocusedStack + " to=" + mFocusedStack);
1033 mLastFocusedStack = mFocusedStack;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001034 return true;
1035 }
1036
1037 boolean allResumedActivitiesVisible() {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001038 boolean foundResumed = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001039 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1040 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001041 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1042 final ActivityStack stack = stacks.get(stackNdx);
1043 final ActivityRecord r = stack.mResumedActivity;
riddle_hsudb46d6b2015-04-01 18:58:07 +08001044 if (r != null) {
Bryce Lee4a194382017-04-04 14:32:48 -07001045 if (!r.nowVisible || mActivitiesWaitingForVisibleActivity.contains(r)) {
riddle_hsudb46d6b2015-04-01 18:58:07 +08001046 return false;
1047 }
1048 foundResumed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001049 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001050 }
1051 }
riddle_hsudb46d6b2015-04-01 18:58:07 +08001052 return foundResumed;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001053 }
1054
Craig Mautner2acc3892013-09-23 10:28:14 -07001055 /**
1056 * Pause all activities in either all of the stacks or just the back stacks.
1057 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
Wale Ogunwale950faff2016-08-08 09:51:04 -07001058 * @param resuming The resuming activity.
1059 * @param dontWait The resuming activity isn't going to wait for all activities to be paused
1060 * before resuming.
Craig Mautner2acc3892013-09-23 10:28:14 -07001061 * @return true if any activity was paused as a result of this call.
1062 */
Wale Ogunwale950faff2016-08-08 09:51:04 -07001063 boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
Craig Mautnercf910b02013-04-23 11:23:27 -07001064 boolean someActivityPaused = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001065 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1066 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001067 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1068 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001069 if (!isFocusedStack(stack) && stack.mResumedActivity != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001070 if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
Craig Mautner4a1cb222013-12-04 16:14:06 -08001071 " mResumedActivity=" + stack.mResumedActivity);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001072 someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
1073 dontWait);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001074 }
Craig Mautnercf910b02013-04-23 11:23:27 -07001075 }
1076 }
1077 return someActivityPaused;
1078 }
1079
Craig Mautnerde4ef022013-04-07 19:01:33 -07001080 boolean allPausedActivitiesComplete() {
Craig Mautnerac6f8432013-07-17 13:24:59 -07001081 boolean pausing = true;
Craig Mautnere0a38842013-12-16 16:14:02 -08001082 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1083 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001084 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1085 final ActivityStack stack = stacks.get(stackNdx);
1086 final ActivityRecord r = stack.mPausingActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001087 if (r != null && r.state != PAUSED && r.state != STOPPED && r.state != STOPPING) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08001088 if (DEBUG_STATES) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001089 Slog.d(TAG_STATES,
1090 "allPausedActivitiesComplete: r=" + r + " state=" + r.state);
Craig Mautner4a1cb222013-12-04 16:14:06 -08001091 pausing = false;
1092 } else {
1093 return false;
1094 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001095 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001096 }
1097 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07001098 return pausing;
Craig Mautnerde4ef022013-04-07 19:01:33 -07001099 }
1100
Wale Ogunwale2be760d2016-02-17 11:16:10 -08001101 void cancelInitializingActivities() {
1102 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1103 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
1104 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1105 stacks.get(stackNdx).cancelInitializingActivities();
1106 }
1107 }
1108 }
1109
Bryce Lee4a194382017-04-04 14:32:48 -07001110 void waitActivityVisible(ComponentName name, WaitResult result) {
1111 final WaitInfo waitInfo = new WaitInfo(name, result);
1112 mWaitingForActivityVisible.add(waitInfo);
1113 }
1114
1115 void cleanupActivity(ActivityRecord r) {
1116 // Make sure this record is no longer in the pending finishes list.
1117 // This could happen, for example, if we are trimming activities
1118 // down to the max limit while they are still waiting to finish.
1119 mFinishingActivities.remove(r);
1120 mActivitiesWaitingForVisibleActivity.remove(r);
1121
1122 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
Wale Ogunwale3270f172017-04-26 07:29:42 -07001123 if (mWaitingForActivityVisible.get(i).matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001124 mWaitingForActivityVisible.remove(i);
1125 }
1126 }
1127 }
1128
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001129 void reportActivityVisibleLocked(ActivityRecord r) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001130 sendWaitingVisibleReportLocked(r);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001131 }
1132
1133 void sendWaitingVisibleReportLocked(ActivityRecord r) {
1134 boolean changed = false;
Bryce Lee4a194382017-04-04 14:32:48 -07001135 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
1136 final WaitInfo w = mWaitingForActivityVisible.get(i);
Wale Ogunwale3270f172017-04-26 07:29:42 -07001137 if (w.matches(r.realActivity)) {
Bryce Lee4a194382017-04-04 14:32:48 -07001138 final WaitResult result = w.getResult();
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001139 changed = true;
Bryce Lee4a194382017-04-04 14:32:48 -07001140 result.timeout = false;
1141 result.who = w.getComponent();
1142 result.totalTime = SystemClock.uptimeMillis() - result.thisTime;
1143 result.thisTime = result.totalTime;
1144 mWaitingForActivityVisible.remove(w);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001145 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001146 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001147 if (changed) {
1148 mService.notifyAll();
1149 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001150 }
1151
Chong Zhang5022da32016-06-21 16:31:37 -07001152 void reportTaskToFrontNoLaunch(ActivityRecord r) {
1153 boolean changed = false;
1154 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
1155 WaitResult w = mWaitingActivityLaunched.remove(i);
1156 if (w.who == null) {
1157 changed = true;
1158 // Set result to START_TASK_TO_FRONT so that startActivityMayWait() knows that
1159 // the starting activity ends up moving another activity to front, and it should
1160 // wait for this new activity to become visible instead.
1161 // Do not modify other fields.
1162 w.result = START_TASK_TO_FRONT;
1163 }
1164 }
1165 if (changed) {
1166 mService.notifyAll();
1167 }
1168 }
1169
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001170 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
1171 long thisTime, long totalTime) {
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001172 boolean changed = false;
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001173 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) {
Craig Mautnerc64f73e2013-04-24 16:44:56 -07001174 WaitResult w = mWaitingActivityLaunched.remove(i);
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001175 if (w.who == null) {
1176 changed = true;
1177 w.timeout = timeout;
1178 if (r != null) {
1179 w.who = new ComponentName(r.info.packageName, r.info.name);
1180 }
1181 w.thisTime = thisTime;
1182 w.totalTime = totalTime;
Chong Zhang5022da32016-06-21 16:31:37 -07001183 // Do not modify w.result.
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001184 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001185 }
Dianne Hackborn6cfbb712014-09-17 12:47:35 -07001186 if (changed) {
1187 mService.notifyAll();
1188 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07001189 }
1190
Craig Mautner29219d92013-04-16 20:19:12 -07001191 ActivityRecord topRunningActivityLocked() {
Wale Ogunwaled697cea2015-02-20 17:19:49 -08001192 final ActivityStack focusedStack = mFocusedStack;
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07001193 ActivityRecord r = focusedStack.topRunningActivityLocked();
Craig Mautner1602ec22013-05-12 10:24:27 -07001194 if (r != null) {
1195 return r;
Craig Mautner29219d92013-04-16 20:19:12 -07001196 }
Craig Mautner1602ec22013-05-12 10:24:27 -07001197
Andrii Kulian7318d632016-07-20 18:59:28 -07001198 // Look in other non-focused and non-home stacks.
Andrii Kulian7d95df42017-02-15 10:11:48 -08001199 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
1200
1201 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
1202 final int displayId = mTmpOrderedDisplayIds.get(i);
1203 final List<ActivityStack> stacks = mActivityDisplays.get(displayId).mStacks;
1204 if (stacks == null) {
1205 continue;
1206 }
1207 for (int j = stacks.size() - 1; j >= 0; --j) {
1208 final ActivityStack stack = stacks.get(j);
1209 if (stack != focusedStack && isFrontStackOnDisplay(stack) && stack.isFocusable()) {
1210 r = stack.topRunningActivityLocked();
1211 if (r != null) {
1212 return r;
1213 }
Craig Mautner29219d92013-04-16 20:19:12 -07001214 }
1215 }
1216 }
1217 return null;
1218 }
1219
Dianne Hackborn09233282014-04-30 11:33:59 -07001220 void getTasksLocked(int maxNum, List<RunningTaskInfo> list, int callingUid, boolean allowed) {
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001221 // Gather all of the running tasks for each stack into runningTaskLists.
Craig Mautner4a1cb222013-12-04 16:14:06 -08001222 ArrayList<ArrayList<RunningTaskInfo>> runningTaskLists =
1223 new ArrayList<ArrayList<RunningTaskInfo>>();
Craig Mautnere0a38842013-12-16 16:14:02 -08001224 final int numDisplays = mActivityDisplays.size();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001225 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08001226 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001227 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1228 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautner15df08a2015-04-01 12:17:18 -07001229 ArrayList<RunningTaskInfo> stackTaskList = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001230 runningTaskLists.add(stackTaskList);
Dianne Hackborn09233282014-04-30 11:33:59 -07001231 stack.getTasksLocked(stackTaskList, callingUid, allowed);
Craig Mautner20e72272013-04-01 13:45:53 -07001232 }
1233 }
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001234
1235 // The lists are already sorted from most recent to oldest. Just pull the most recent off
1236 // each list and add it to list. Stop when all lists are empty or maxNum reached.
1237 while (maxNum > 0) {
1238 long mostRecentActiveTime = Long.MIN_VALUE;
1239 ArrayList<RunningTaskInfo> selectedStackList = null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001240 final int numTaskLists = runningTaskLists.size();
1241 for (int stackNdx = 0; stackNdx < numTaskLists; ++stackNdx) {
1242 ArrayList<RunningTaskInfo> stackTaskList = runningTaskLists.get(stackNdx);
Craig Mautnerc0fd8052013-09-19 11:20:17 -07001243 if (!stackTaskList.isEmpty()) {
1244 final long lastActiveTime = stackTaskList.get(0).lastActiveTime;
1245 if (lastActiveTime > mostRecentActiveTime) {
1246 mostRecentActiveTime = lastActiveTime;
1247 selectedStackList = stackTaskList;
1248 }
1249 }
1250 }
1251 if (selectedStackList != null) {
1252 list.add(selectedStackList.remove(0));
1253 --maxNum;
1254 } else {
1255 break;
1256 }
1257 }
Craig Mautner20e72272013-04-01 13:45:53 -07001258 }
1259
Todd Kennedy7440f172015-12-09 14:31:22 -08001260 ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
1261 ProfilerInfo profilerInfo) {
1262 final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
Craig Mautner23ac33b2013-04-01 16:26:35 -07001263 if (aInfo != null) {
1264 // Store the found target back into the intent, because now that
1265 // we have it we never want to do this again. For example, if the
1266 // user navigates back to this point in the history, we should
1267 // always restart the exact same activity.
1268 intent.setComponent(new ComponentName(
1269 aInfo.applicationInfo.packageName, aInfo.name));
1270
1271 // Don't debug things in the system process
Man Caocfa78b22015-06-11 20:14:34 -07001272 if (!aInfo.processName.equals("system")) {
1273 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
Chong Zhangd25944e2016-06-09 16:15:27 -07001274 mService.setDebugApp(aInfo.processName, true, false);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001275 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001276
Tamas Berghammerdf6cb282016-01-29 12:07:00 +00001277 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
1278 mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
1279 }
1280
Man Caocfa78b22015-06-11 20:14:34 -07001281 if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
1282 mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
1283 }
1284
1285 if (profilerInfo != null) {
Jeff Hao1b012d32014-08-20 10:35:34 -07001286 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
Craig Mautner23ac33b2013-04-01 16:26:35 -07001287 }
1288 }
Todd Kennedyb3b431302017-03-20 16:05:48 -07001289 final String intentLaunchToken = intent.getLaunchToken();
1290 if (aInfo.launchToken == null && intentLaunchToken != null) {
1291 aInfo.launchToken = intentLaunchToken;
1292 }
Craig Mautner23ac33b2013-04-01 16:26:35 -07001293 }
1294 return aInfo;
1295 }
1296
Todd Kennedy7440f172015-12-09 14:31:22 -08001297 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId) {
Kenny Guyb1b30262016-02-09 16:02:35 +00001298 return resolveIntent(intent, resolvedType, userId, 0);
1299 }
1300
1301 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
Todd Kennedy4d1de7d2017-02-23 10:32:18 -08001302 synchronized (mService) {
1303 return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType,
Todd Kennedybe0b8892017-02-15 14:13:52 -08001304 PackageManager.MATCH_INSTANT | PackageManager.MATCH_DEFAULT_ONLY | flags
Kenny Guyb1b30262016-02-09 16:02:35 +00001305 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Todd Kennedy7440f172015-12-09 14:31:22 -08001306 }
Todd Kennedy7440f172015-12-09 14:31:22 -08001307 }
1308
1309 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
1310 ProfilerInfo profilerInfo, int userId) {
1311 final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
1312 return resolveActivity(intent, rInfo, startFlags, profilerInfo);
1313 }
1314
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001315 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1316 boolean andResume, boolean checkConfig) throws RemoteException {
1317
1318 if (!allPausedActivitiesComplete()) {
1319 // While there are activities pausing we skipping starting any new activities until
1320 // pauses are complete. NOTE: that we also do this for activities that are starting in
1321 // the paused state because they will first be resumed then paused on the client side.
1322 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
1323 "realStartActivityLocked: Skipping start of r=" + r
1324 + " some activities pausing...");
1325 return false;
1326 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001327
Bryce Leeaf691c02017-03-20 14:20:22 -07001328 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07001329 final ActivityStack stack = task.getStack();
chaviw59b98852017-06-13 12:05:44 -07001330
1331 beginDeferResume();
1332
Craig Mautner2420ead2013-04-01 17:13:20 -07001333 try {
chaviw59b98852017-06-13 12:05:44 -07001334 r.startFreezingScreenLocked(app, 0);
1335
1336 // schedule launch ticks to collect information about slow apps.
1337 r.startLaunchTickingLocked();
1338
1339 r.app = app;
1340
1341 // Have the window manager re-evaluate the orientation of the screen based on the new
1342 // activity order. Note that as a result of this, it can call back into the activity
1343 // manager with a new orientation. We don't care about that, because the activity is
1344 // not currently running so we are just restarting it anyway.
1345 if (checkConfig) {
1346 final int displayId = r.getDisplayId();
1347 final Configuration config = mWindowManager.updateOrientationFromAppTokens(
1348 getDisplayOverrideConfiguration(displayId),
1349 r.mayFreezeScreenLocked(app) ? r.appToken : null, displayId);
1350 // Deferring resume here because we're going to launch new activity shortly.
1351 // We don't want to perform a redundant launch of the same record while ensuring
1352 // configurations and trying to resume top activity of focused stack.
1353 mService.updateDisplayOverrideConfigurationLocked(config, r, true /* deferResume */,
1354 displayId);
Craig Mautner2420ead2013-04-01 17:13:20 -07001355 }
chaviw59b98852017-06-13 12:05:44 -07001356
1357 if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */,
1358 true /* isTop */)) {
1359 // We only set the visibility to true if the activity is allowed to be visible
1360 // based on
1361 // keyguard state. This avoids setting this into motion in window manager that is
1362 // later cancelled due to later calls to ensure visible activities that set
1363 // visibility back to false.
1364 r.setVisibility(true);
Craig Mautner2420ead2013-04-01 17:13:20 -07001365 }
chaviw59b98852017-06-13 12:05:44 -07001366
1367 if (mKeyguardController.isKeyguardLocked()) {
1368 r.notifyUnknownVisibilityLaunched();
Craig Mautner2420ead2013-04-01 17:13:20 -07001369 }
chaviw59b98852017-06-13 12:05:44 -07001370 final int applicationInfoUid =
1371 (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
1372 if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
1373 Slog.wtf(TAG,
1374 "User ID for activity changing for " + r
1375 + " appInfo.uid=" + r.appInfo.uid
1376 + " info.ai.uid=" + applicationInfoUid
1377 + " old=" + r.app + " new=" + app);
1378 }
1379
1380 app.waitingToKill = null;
1381 r.launchCount++;
1382 r.lastLaunchTime = SystemClock.uptimeMillis();
1383
1384 if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);
1385
1386 int idx = app.activities.indexOf(r);
1387 if (idx < 0) {
1388 app.activities.add(r);
1389 }
1390 mService.updateLruProcessLocked(app, true, null);
1391 mService.updateOomAdjLocked();
1392
1393 if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
1394 task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
1395 setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE",
1396 false);
1397 }
1398
1399 try {
1400 if (app.thread == null) {
1401 throw new RemoteException();
1402 }
1403 List<ResultInfo> results = null;
1404 List<ReferrerIntent> newIntents = null;
1405 if (andResume) {
1406 // We don't need to deliver new intents and/or set results if activity is going
1407 // to pause immediately after launch.
1408 results = r.results;
1409 newIntents = r.newIntents;
1410 }
1411 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
1412 "Launching: " + r + " icicle=" + r.icicle + " with results=" + results
1413 + " newIntents=" + newIntents + " andResume=" + andResume);
1414 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
1415 System.identityHashCode(r), task.taskId, r.shortComponentName);
1416 if (r.isHomeActivity()) {
1417 // Home process is the root process of the task.
1418 mService.mHomeProcess = task.mActivities.get(0).app;
1419 }
1420 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
1421 PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
1422 r.sleeping = false;
1423 r.forceNewConfig = false;
1424 mService.showUnsupportedZoomDialogIfNeededLocked(r);
1425 mService.showAskCompatModeDialogLocked(r);
1426 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
1427 ProfilerInfo profilerInfo = null;
1428 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
1429 if (mService.mProfileProc == null || mService.mProfileProc == app) {
1430 mService.mProfileProc = app;
Andreas Gampe2b073a02017-06-22 17:28:57 -07001431 ProfilerInfo profilerInfoSvc = mService.mProfilerInfo;
1432 if (profilerInfoSvc != null && profilerInfoSvc.profileFile != null) {
1433 if (profilerInfoSvc.profileFd != null) {
chaviw59b98852017-06-13 12:05:44 -07001434 try {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001435 profilerInfoSvc.profileFd = profilerInfoSvc.profileFd.dup();
chaviw59b98852017-06-13 12:05:44 -07001436 } catch (IOException e) {
Andreas Gampe2b073a02017-06-22 17:28:57 -07001437 profilerInfoSvc.closeFd();
Craig Mautner2568c3a2015-03-26 14:22:34 -07001438 }
1439 }
chaviw59b98852017-06-13 12:05:44 -07001440
Andreas Gampe2b073a02017-06-22 17:28:57 -07001441 profilerInfo = new ProfilerInfo(profilerInfoSvc);
Craig Mautner2420ead2013-04-01 17:13:20 -07001442 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001443 }
1444 }
Adam Powellcfbe9be2013-11-06 14:58:58 -08001445
chaviw59b98852017-06-13 12:05:44 -07001446 app.hasShownUi = true;
1447 app.pendingUiClean = true;
1448 app.forceProcessStateUpTo(mService.mTopProcessState);
1449 // Because we could be starting an Activity in the system process this may not go
1450 // across a Binder interface which would create a new Configuration. Consequently
1451 // we have to always create a new Configuration here.
Bryce Leea163b762017-01-24 11:05:01 -08001452
chaviw59b98852017-06-13 12:05:44 -07001453 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
1454 mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
1455 r.setLastReportedConfiguration(mergedConfiguration);
Bryce Leea163b762017-01-24 11:05:01 -08001456
chaviw59b98852017-06-13 12:05:44 -07001457 logIfTransactionTooLarge(r.intent, r.icicle);
1458 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1459 System.identityHashCode(r), r.info,
1460 // TODO: Have this take the merged configuration instead of separate global
1461 // and override configs.
1462 mergedConfiguration.getGlobalConfiguration(),
1463 mergedConfiguration.getOverrideConfiguration(), r.compat,
1464 r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1465 r.persistentState, results, newIntents, !andResume,
1466 mService.isNextTransitionForward(), profilerInfo);
Craig Mautner2420ead2013-04-01 17:13:20 -07001467
chaviw59b98852017-06-13 12:05:44 -07001468 if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
1469 // This may be a heavy-weight process! Note that the package
1470 // manager will ensure that only activity can run in the main
1471 // process of the .apk, which is the only thing that will be
1472 // considered heavy-weight.
1473 if (app.processName.equals(app.info.packageName)) {
1474 if (mService.mHeavyWeightProcess != null
1475 && mService.mHeavyWeightProcess != app) {
1476 Slog.w(TAG, "Starting new heavy weight process " + app
1477 + " when already running "
1478 + mService.mHeavyWeightProcess);
1479 }
1480 mService.mHeavyWeightProcess = app;
1481 Message msg = mService.mHandler.obtainMessage(
1482 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
1483 msg.obj = r;
1484 mService.mHandler.sendMessage(msg);
Craig Mautner2420ead2013-04-01 17:13:20 -07001485 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001486 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001487
chaviw59b98852017-06-13 12:05:44 -07001488 } catch (RemoteException e) {
1489 if (r.launchFailed) {
1490 // This is the second time we failed -- finish activity
1491 // and give up.
1492 Slog.e(TAG, "Second failure launching "
1493 + r.intent.getComponent().flattenToShortString()
1494 + ", giving up", e);
1495 mService.appDiedLocked(app);
1496 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
1497 "2nd-crash", false);
1498 return false;
1499 }
Craig Mautner2420ead2013-04-01 17:13:20 -07001500
chaviw59b98852017-06-13 12:05:44 -07001501 // This is the first time we failed -- restart process and
1502 // retry.
1503 r.launchFailed = true;
1504 app.activities.remove(r);
1505 throw e;
1506 }
1507 } finally {
1508 endDeferResume();
Craig Mautner2420ead2013-04-01 17:13:20 -07001509 }
1510
1511 r.launchFailed = false;
1512 if (stack.updateLRUListLocked(r)) {
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07001513 Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
Craig Mautner2420ead2013-04-01 17:13:20 -07001514 }
1515
chaviw59b98852017-06-13 12:05:44 -07001516 if (andResume && readyToResume()) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001517 // As part of the process of launching, ActivityThread also performs
1518 // a resume.
1519 stack.minimalResumeActivityLocked(r);
1520 } else {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001521 // This activity is not starting in the resumed state... which should look like we asked
Wale Ogunwale919a05d2017-04-13 00:36:34 +00001522 // it to pause+stop (but remain visible), and it has done so and reported back the
Wale Ogunwaled046a012015-12-24 13:05:59 -08001523 // current icicle and other state.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001524 if (DEBUG_STATES) Slog.v(TAG_STATES,
Wale Ogunwaled046a012015-12-24 13:05:59 -08001525 "Moving to PAUSED: " + r + " (starting in paused state)");
1526 r.state = PAUSED;
Craig Mautner2420ead2013-04-01 17:13:20 -07001527 }
1528
1529 // Launch the new version setup screen if needed. We do this -after-
1530 // launching the initial activity (that is, home), so that it can have
1531 // a chance to initialize itself while in the background, making the
1532 // switch back to it faster and look better.
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001533 if (isFocusedStack(stack)) {
Craig Mautner2420ead2013-04-01 17:13:20 -07001534 mService.startSetupActivityLocked();
1535 }
1536
Dianne Hackborn465fa392014-09-14 14:21:18 -07001537 // Update any services we are bound to that might care about whether
1538 // their client may have activities.
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001539 if (r.app != null) {
1540 mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
1541 }
Dianne Hackborn465fa392014-09-14 14:21:18 -07001542
Craig Mautner2420ead2013-04-01 17:13:20 -07001543 return true;
1544 }
1545
Sudheer Shankafab200f2017-05-17 20:41:53 -07001546 private void logIfTransactionTooLarge(Intent intent, Bundle icicle) {
1547 int extrasSize = 0;
1548 if (intent != null) {
1549 final Bundle extras = intent.getExtras();
1550 if (extras != null) {
1551 extrasSize = extras.getSize();
1552 }
1553 }
1554 int icicleSize = (icicle == null ? 0 : icicle.getSize());
1555 if (extrasSize + icicleSize > 200000) {
1556 Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize
1557 + ", icicle size: " + icicleSize);
1558 }
1559 }
1560
Craig Mautnere79d42682013-04-01 19:01:53 -07001561 void startSpecificActivityLocked(ActivityRecord r,
George Mount2c92c972014-03-20 09:38:23 -07001562 boolean andResume, boolean checkConfig) {
Craig Mautnere79d42682013-04-01 19:01:53 -07001563 // Is this activity's application already running?
1564 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001565 r.info.applicationInfo.uid, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001566
Andrii Kulian02b7a832016-10-06 23:11:56 -07001567 r.getStack().setLaunchTime(r);
Craig Mautnere79d42682013-04-01 19:01:53 -07001568
1569 if (app != null && app.thread != null) {
1570 try {
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001571 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1572 || !"android".equals(r.info.packageName)) {
1573 // Don't add this if it is a platform component that is marked
1574 // to run in multiple processes, because this is actually
1575 // part of the framework so doesn't make sense to track as a
1576 // separate apk in the process.
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001577 app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1578 mService.mProcessStats);
Dianne Hackborn237cefb2013-10-22 18:45:27 -07001579 }
George Mount2c92c972014-03-20 09:38:23 -07001580 realStartActivityLocked(r, app, andResume, checkConfig);
Craig Mautnere79d42682013-04-01 19:01:53 -07001581 return;
1582 } catch (RemoteException e) {
1583 Slog.w(TAG, "Exception when starting activity "
1584 + r.intent.getComponent().flattenToShortString(), e);
1585 }
1586
1587 // If a dead object exception was thrown -- fall through to
1588 // restart the application.
1589 }
1590
1591 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001592 "activity", r.intent.getComponent(), false, false, true);
Craig Mautnere79d42682013-04-01 19:01:53 -07001593 }
1594
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001595 boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo,
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001596 String resultWho, int requestCode, int callingPid, int callingUid,
1597 String callingPackage, boolean ignoreTargetSecurity, ProcessRecord callerApp,
Jorim Jaggi2adba072016-03-03 13:43:39 +01001598 ActivityRecord resultRecord, ActivityStack resultStack, ActivityOptions options) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001599 final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid,
1600 callingUid);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001601 if (startAnyPerm == PERMISSION_GRANTED) {
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001602 return true;
1603 }
1604 final int componentRestriction = getComponentRestrictionForCallingPackage(
1605 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
1606 final int actionRestriction = getActionRestrictionForCallingPackage(
1607 intent.getAction(), callingPackage, callingPid, callingUid);
1608 if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION
1609 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1610 if (resultRecord != null) {
1611 resultStack.sendActivityResultLocked(-1,
1612 resultRecord, resultWho, requestCode,
1613 Activity.RESULT_CANCELED, null);
1614 }
1615 final String msg;
1616 if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) {
1617 msg = "Permission Denial: starting " + intent.toString()
1618 + " from " + callerApp + " (pid=" + callingPid
1619 + ", uid=" + callingUid + ")" + " with revoked permission "
1620 + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction());
1621 } else if (!aInfo.exported) {
1622 msg = "Permission Denial: starting " + intent.toString()
1623 + " from " + callerApp + " (pid=" + callingPid
1624 + ", uid=" + callingUid + ")"
1625 + " not exported from uid " + aInfo.applicationInfo.uid;
1626 } else {
1627 msg = "Permission Denial: starting " + intent.toString()
1628 + " from " + callerApp + " (pid=" + callingPid
1629 + ", uid=" + callingUid + ")"
1630 + " requires " + aInfo.permission;
1631 }
1632 Slog.w(TAG, msg);
1633 throw new SecurityException(msg);
1634 }
1635
1636 if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) {
1637 final String message = "Appop Denial: starting " + intent.toString()
1638 + " from " + callerApp + " (pid=" + callingPid
1639 + ", uid=" + callingUid + ")"
1640 + " requires " + AppOpsManager.permissionToOp(
1641 ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()));
1642 Slog.w(TAG, message);
1643 return false;
1644 } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) {
1645 final String message = "Appop Denial: starting " + intent.toString()
1646 + " from " + callerApp + " (pid=" + callingPid
1647 + ", uid=" + callingUid + ")"
1648 + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission);
1649 Slog.w(TAG, message);
1650 return false;
1651 }
Andrii Kulian16802aa2016-11-02 12:21:33 -07001652 if (options != null) {
1653 if (options.getLaunchTaskId() != INVALID_STACK_ID) {
1654 final int startInTaskPerm = mService.checkPermission(START_TASKS_FROM_RECENTS,
1655 callingPid, callingUid);
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001656 if (startInTaskPerm == PERMISSION_DENIED) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07001657 final String msg = "Permission Denial: starting " + intent.toString()
1658 + " from " + callerApp + " (pid=" + callingPid
1659 + ", uid=" + callingUid + ") with launchTaskId="
1660 + options.getLaunchTaskId();
1661 Slog.w(TAG, msg);
1662 throw new SecurityException(msg);
1663 }
1664 }
1665 // Check if someone tries to launch an activity on a private display with a different
1666 // owner.
1667 final int launchDisplayId = options.getLaunchDisplayId();
Andrii Kulian02689a72017-07-06 14:28:59 -07001668 if (launchDisplayId != INVALID_DISPLAY && !isCallerAllowedToLaunchOnDisplay(callingPid,
1669 callingUid, launchDisplayId, aInfo)) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001670 final String msg = "Permission Denial: starting " + intent.toString()
1671 + " from " + callerApp + " (pid=" + callingPid
1672 + ", uid=" + callingUid + ") with launchDisplayId="
1673 + launchDisplayId;
1674 Slog.w(TAG, msg);
1675 throw new SecurityException(msg);
Jorim Jaggi2adba072016-03-03 13:43:39 +01001676 }
1677 }
1678
Filip Gruszczynskidc394902015-12-14 10:20:22 -08001679 return true;
1680 }
1681
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001682 /** Check if caller is allowed to launch activities on specified display. */
Andrii Kulian02689a72017-07-06 14:28:59 -07001683 boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId,
1684 ActivityInfo aInfo) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001685 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId
1686 + " callingPid=" + callingPid + " callingUid=" + callingUid);
1687
Andrii Kulian02689a72017-07-06 14:28:59 -07001688 if (callingPid == -1 && callingUid == -1) {
1689 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: no caller info, skip check");
1690 return true;
1691 }
1692
Andrii Kulian62e6f252017-05-30 22:46:53 -07001693 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(launchDisplayId);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001694 if (activityDisplay == null) {
1695 Slog.w(TAG, "Launch on display check: display not found");
1696 return false;
1697 }
1698
Andrii Kulian02689a72017-07-06 14:28:59 -07001699 // Check if the caller has enough privileges to embed activities and launch to private
1700 // displays.
Andrii Kulian3a95edc2017-06-28 16:21:07 -07001701 final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid,
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001702 callingUid);
1703 if (startAnyPerm == PERMISSION_GRANTED) {
1704 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1705 + " allow launch any on display");
1706 return true;
1707 }
1708
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001709 final int displayOwnerUid = activityDisplay.mDisplay.getOwnerUid();
1710 if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL && displayOwnerUid != SYSTEM_UID
1711 && displayOwnerUid != aInfo.applicationInfo.uid) {
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001712 // Limit launching on virtual displays, because their contents can be read from Surface
1713 // by apps that created them.
Andrii Kulian02689a72017-07-06 14:28:59 -07001714 if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
1715 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1716 + " disallow launch on virtual display for not-embedded activity.");
1717 return false;
1718 }
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001719 // Check if the caller is allowed to embed activities from other apps.
1720 if (mService.checkPermission(ACTIVITY_EMBEDDING, callingPid, callingUid)
1721 == PERMISSION_DENIED) {
1722 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1723 + " disallow activity embedding without permission.");
1724 return false;
1725 }
Andrii Kulian1cba31c2017-06-28 09:42:48 -07001726 }
1727
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001728 if (!activityDisplay.isPrivate()) {
1729 // Anyone can launch on a public display.
1730 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1731 + " allow launch on public display");
1732 return true;
1733 }
1734
1735 // Check if the caller is the owner of the display.
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001736 if (displayOwnerUid == callingUid) {
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001737 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1738 + " allow launch for owner of the display");
1739 return true;
1740 }
1741
1742 // Check if caller is present on display
1743 if (activityDisplay.isUidPresent(callingUid)) {
1744 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
1745 + " allow launch for caller present on the display");
1746 return true;
1747 }
1748
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001749 Slog.w(TAG, "Launch on display check: denied");
1750 return false;
1751 }
1752
1753 /** Update lists of UIDs that are present on displays and have access to them. */
1754 void updateUIDsPresentOnDisplay() {
1755 mDisplayAccessUIDs.clear();
1756 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1757 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
David Stevens82ea6cb2017-03-03 16:18:50 -08001758 // Only bother calculating the whitelist for private displays
1759 if (activityDisplay.isPrivate()) {
1760 mDisplayAccessUIDs.append(
1761 activityDisplay.mDisplayId, activityDisplay.getPresentUIDs());
1762 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001763 }
1764 // Store updated lists in DisplayManager. Callers from outside of AM should get them there.
1765 mDisplayManagerInternal.setDisplayAccessUIDs(mDisplayAccessUIDs);
1766 }
1767
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001768 UserInfo getUserInfo(int userId) {
Clara Bayarrif7fea162015-10-22 16:09:52 +01001769 final long identity = Binder.clearCallingIdentity();
1770 try {
1771 return UserManager.get(mService.mContext).getUserInfo(userId);
1772 } finally {
1773 Binder.restoreCallingIdentity(identity);
1774 }
1775 }
1776
Svet Ganov99b60432015-06-27 13:15:22 -07001777 private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001778 String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001779 if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
1780 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001781 == PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001782 return ACTIVITY_RESTRICTION_PERMISSION;
1783 }
1784
Christopher Tateff7add02015-08-17 10:23:22 -07001785 if (activityInfo.permission == null) {
1786 return ACTIVITY_RESTRICTION_NONE;
1787 }
1788
Svet Ganov99b60432015-06-27 13:15:22 -07001789 final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission);
1790 if (opCode == AppOpsManager.OP_NONE) {
1791 return ACTIVITY_RESTRICTION_NONE;
1792 }
1793
1794 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1795 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07001796 if (!ignoreTargetSecurity) {
1797 return ACTIVITY_RESTRICTION_APPOP;
1798 }
Svet Ganov99b60432015-06-27 13:15:22 -07001799 }
1800
1801 return ACTIVITY_RESTRICTION_NONE;
1802 }
1803
Svetoslav7008b512015-06-24 18:47:07 -07001804 private int getActionRestrictionForCallingPackage(String action,
1805 String callingPackage, int callingPid, int callingUid) {
1806 if (action == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001807 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001808 }
1809
1810 String permission = ACTION_TO_RUNTIME_PERMISSION.get(action);
1811 if (permission == null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001812 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001813 }
1814
1815 final PackageInfo packageInfo;
1816 try {
1817 packageInfo = mService.mContext.getPackageManager()
1818 .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS);
1819 } catch (PackageManager.NameNotFoundException e) {
1820 Slog.i(TAG, "Cannot find package info for " + callingPackage);
Svet Ganov99b60432015-06-27 13:15:22 -07001821 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001822 }
1823
1824 if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) {
Svet Ganov99b60432015-06-27 13:15:22 -07001825 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001826 }
1827
Andrii Kulian3c9ad072017-08-01 11:45:22 -07001828 if (mService.checkPermission(permission, callingPid, callingUid) == PERMISSION_DENIED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001829 return ACTIVITY_RESTRICTION_PERMISSION;
Svetoslav7008b512015-06-24 18:47:07 -07001830 }
1831
1832 final int opCode = AppOpsManager.permissionToOpCode(permission);
1833 if (opCode == AppOpsManager.OP_NONE) {
Svet Ganov99b60432015-06-27 13:15:22 -07001834 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001835 }
1836
1837 if (mService.mAppOpsService.noteOperation(opCode, callingUid,
1838 callingPackage) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001839 return ACTIVITY_RESTRICTION_APPOP;
Svetoslav7008b512015-06-24 18:47:07 -07001840 }
1841
Svet Ganov99b60432015-06-27 13:15:22 -07001842 return ACTIVITY_RESTRICTION_NONE;
Svetoslav7008b512015-06-24 18:47:07 -07001843 }
1844
Dianne Hackborn3d07c942015-03-13 18:02:54 -07001845 void setLaunchSource(int uid) {
1846 mLaunchingActivity.setWorkSource(new WorkSource(uid));
1847 }
1848
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001849 void acquireLaunchWakelock() {
1850 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
1851 throw new IllegalStateException("Calling must be system uid");
1852 }
1853 mLaunchingActivity.acquire();
1854 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1855 // To be safe, don't allow the wake lock to be held for too long.
1856 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT);
1857 }
1858 }
1859
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001860 /**
1861 * Called when the frontmost task is idle.
1862 * @return the state of mService.mBooting before this was called.
1863 */
1864 private boolean checkFinishBootingLocked() {
1865 final boolean booting = mService.mBooting;
1866 boolean enableScreen = false;
1867 mService.mBooting = false;
1868 if (!mService.mBooted) {
1869 mService.mBooted = true;
1870 enableScreen = true;
1871 }
1872 if (booting || enableScreen) {
1873 mService.postFinishBooting(booting, enableScreen);
1874 }
1875 return booting;
1876 }
1877
Craig Mautnerf3333272013-04-22 10:55:53 -07001878 // Checked.
1879 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
Winson Chung4dabf232017-01-25 13:25:22 -08001880 boolean processPausingActivities, Configuration config) {
Wale Ogunwalee23149f2015-03-06 15:39:44 -08001881 if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001882
Craig Mautnerf3333272013-04-22 10:55:53 -07001883 ArrayList<ActivityRecord> finishes = null;
Amith Yamasani37a40c22015-06-17 13:25:42 -07001884 ArrayList<UserState> startingUsers = null;
Craig Mautnerf3333272013-04-22 10:55:53 -07001885 int NS = 0;
1886 int NF = 0;
Craig Mautnerf3333272013-04-22 10:55:53 -07001887 boolean booting = false;
Craig Mautnerf3333272013-04-22 10:55:53 -07001888 boolean activityRemoved = false;
1889
Wale Ogunwale7d701172015-03-11 15:36:30 -07001890 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Craig Mautnerf3333272013-04-22 10:55:53 -07001891 if (r != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001892 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
1893 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07001894 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
1895 r.finishLaunchTickingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001896 if (fromTimeout) {
1897 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
Craig Mautnerf3333272013-04-22 10:55:53 -07001898 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001899
1900 // This is a hack to semi-deal with a race condition
1901 // in the client where it can be constructed with a
1902 // newer configuration from when we asked it to launch.
1903 // We'll update with whatever configuration it now says
1904 // it used to launch.
1905 if (config != null) {
Bryce Leea163b762017-01-24 11:05:01 -08001906 r.setLastReportedGlobalConfiguration(config);
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001907 }
1908
1909 // We are now idle. If someone is waiting for a thumbnail from
1910 // us, we can now deliver.
1911 r.idle = true;
1912
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001913 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001914 if (isFocusedStack(r.getStack()) || fromTimeout) {
Craig Mautnerf3ea23a2015-01-13 09:37:08 -08001915 booting = checkFinishBootingLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001916 }
1917 }
1918
1919 if (allResumedActivitiesIdle()) {
1920 if (r != null) {
1921 mService.scheduleAppGcsLocked();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001922 }
1923
1924 if (mLaunchingActivity.isHeld()) {
1925 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
1926 if (VALIDATE_WAKE_LOCK_CALLER &&
1927 Binder.getCallingUid() != Process.myUid()) {
1928 throw new IllegalStateException("Calling must be system uid");
1929 }
1930 mLaunchingActivity.release();
1931 }
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07001932 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerf3333272013-04-22 10:55:53 -07001933 }
1934
1935 // Atomically retrieve all of the other things to do.
Winson Chung4dabf232017-01-25 13:25:22 -08001936 final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
1937 true /* remove */, processPausingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001938 NS = stops != null ? stops.size() : 0;
Wale Ogunwale7d701172015-03-11 15:36:30 -07001939 if ((NF = mFinishingActivities.size()) > 0) {
1940 finishes = new ArrayList<>(mFinishingActivities);
Craig Mautnerf3333272013-04-22 10:55:53 -07001941 mFinishingActivities.clear();
1942 }
1943
Craig Mautnerf3333272013-04-22 10:55:53 -07001944 if (mStartingUsers.size() > 0) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07001945 startingUsers = new ArrayList<>(mStartingUsers);
Craig Mautnerf3333272013-04-22 10:55:53 -07001946 mStartingUsers.clear();
1947 }
1948
Craig Mautnerf3333272013-04-22 10:55:53 -07001949 // Stop any activities that are scheduled to do so but have been
1950 // waiting for the next one to start.
1951 for (int i = 0; i < NS; i++) {
1952 r = stops.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001953 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001954 if (stack != null) {
1955 if (r.finishing) {
1956 stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
1957 } else {
1958 stack.stopActivityLocked(r);
1959 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001960 }
1961 }
1962
1963 // Finish any activities that are scheduled to do so but have been
1964 // waiting for the next one to start.
1965 for (int i = 0; i < NF; i++) {
1966 r = finishes.get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -07001967 final ActivityStack stack = r.getStack();
Wale Ogunwale7d701172015-03-11 15:36:30 -07001968 if (stack != null) {
1969 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
1970 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001971 }
1972
Dianne Hackborn7622a0f2014-09-30 14:31:42 -07001973 if (!booting) {
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001974 // Complete user switch
1975 if (startingUsers != null) {
1976 for (int i = 0; i < startingUsers.size(); i++) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001977 mService.mUserController.finishUserSwitch(startingUsers.get(i));
Amith Yamasani1a7eaaa52014-05-07 10:22:15 -07001978 }
1979 }
Craig Mautnerf3333272013-04-22 10:55:53 -07001980 }
1981
1982 mService.trimApplications();
1983 //dump();
1984 //mWindowManager.dump();
1985
Craig Mautnerf3333272013-04-22 10:55:53 -07001986 if (activityRemoved) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001987 resumeFocusedStackTopActivityLocked();
Craig Mautnerf3333272013-04-22 10:55:53 -07001988 }
1989
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001990 return r;
Craig Mautnerf3333272013-04-22 10:55:53 -07001991 }
1992
Craig Mautner8e569572013-10-11 17:36:59 -07001993 boolean handleAppDiedLocked(ProcessRecord app) {
Craig Mautner19091252013-10-05 00:03:53 -07001994 boolean hasVisibleActivities = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08001995 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
1996 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08001997 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1998 hasVisibleActivities |= stacks.get(stackNdx).handleAppDiedLocked(app);
1999 }
Craig Mautner6b74cb52013-09-27 17:02:21 -07002000 }
Craig Mautner19091252013-10-05 00:03:53 -07002001 return hasVisibleActivities;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002002 }
2003
2004 void closeSystemDialogsLocked() {
Craig Mautnere0a38842013-12-16 16:14:02 -08002005 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2006 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002007 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2008 stacks.get(stackNdx).closeSystemDialogsLocked();
2009 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002010 }
2011 }
2012
Craig Mautner93529a42013-10-04 15:03:13 -07002013 void removeUserLocked(int userId) {
Craig Mautner4f1df4f2013-10-15 15:44:14 -07002014 mUserStackInFront.delete(userId);
Craig Mautner93529a42013-10-04 15:03:13 -07002015 }
2016
Craig Mautner8d341ef2013-03-26 09:03:27 -07002017 /**
Chong Zhang45c25ce2015-08-10 22:18:26 -07002018 * Update the last used stack id for non-current user (current user's last
2019 * used stack is the focused stack)
2020 */
2021 void updateUserStackLocked(int userId, ActivityStack stack) {
2022 if (userId != mCurrentUser) {
2023 mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
2024 }
2025 }
2026
2027 /**
Craig Mautner8d341ef2013-03-26 09:03:27 -07002028 * @return true if some activity was finished (or would have finished if doit were true).
2029 */
Wale Ogunwale540e1232015-05-01 15:35:39 -07002030 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
2031 boolean doit, boolean evenPersistent, int userId) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07002032 boolean didSomething = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08002033 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2034 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
louis_chang8f0555a2015-10-27 10:45:53 +08002035 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002036 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002037 if (stack.finishDisabledPackageActivitiesLocked(
2038 packageName, filterByClasses, doit, evenPersistent, userId)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002039 didSomething = true;
2040 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002041 }
2042 }
2043 return didSomething;
2044 }
2045
Dianne Hackborna413dc02013-07-12 12:02:55 -07002046 void updatePreviousProcessLocked(ActivityRecord r) {
2047 // Now that this process has stopped, we may want to consider
2048 // it to be the previous app to try to keep around in case
2049 // the user wants to return to it.
2050
2051 // First, found out what is currently the foreground app, so that
2052 // we don't blow away the previous app if this activity is being
2053 // hosted by the process that is actually still the foreground.
2054 ProcessRecord fgApp = null;
Craig Mautnere0a38842013-12-16 16:14:02 -08002055 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2056 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002057 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2058 final ActivityStack stack = stacks.get(stackNdx);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07002059 if (isFocusedStack(stack)) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002060 if (stack.mResumedActivity != null) {
2061 fgApp = stack.mResumedActivity.app;
2062 } else if (stack.mPausingActivity != null) {
2063 fgApp = stack.mPausingActivity.app;
2064 }
2065 break;
Dianne Hackborna413dc02013-07-12 12:02:55 -07002066 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07002067 }
2068 }
2069
2070 // Now set this one as the previous process, only if that really
2071 // makes sense to.
2072 if (r.app != null && fgApp != null && r.app != fgApp
2073 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
Craig Mautner4ef26932013-09-18 15:15:52 -07002074 && r.app != mService.mHomeProcess) {
Dianne Hackborna413dc02013-07-12 12:02:55 -07002075 mService.mPreviousProcess = r.app;
2076 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
2077 }
2078 }
2079
Wale Ogunwaled046a012015-12-24 13:05:59 -08002080 boolean resumeFocusedStackTopActivityLocked() {
2081 return resumeFocusedStackTopActivityLocked(null, null, null);
Craig Mautner05d29032013-05-03 13:40:13 -07002082 }
2083
Wale Ogunwaled046a012015-12-24 13:05:59 -08002084 boolean resumeFocusedStackTopActivityLocked(
Chong Zhang280d3322015-11-03 17:27:26 -08002085 ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
chaviw59b98852017-06-13 12:05:44 -07002086
2087 if (!readyToResume()) {
2088 return false;
2089 }
2090
Wale Ogunwaled046a012015-12-24 13:05:59 -08002091 if (targetStack != null && isFocusedStack(targetStack)) {
2092 return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
Craig Mautner05d29032013-05-03 13:40:13 -07002093 }
chaviw59b98852017-06-13 12:05:44 -07002094
Wale Ogunwale06579d62016-04-30 15:29:06 -07002095 final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2096 if (r == null || r.state != RESUMED) {
2097 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
skuhne@google.com1b974dc2016-12-09 13:41:29 -08002098 } else if (r.state == RESUMED) {
2099 // Kick off any lingering app transitions form the MoveTaskToFront operation.
2100 mFocusedStack.executeAppTransition(targetOptions);
Wale Ogunwale06579d62016-04-30 15:29:06 -07002101 }
chaviw59b98852017-06-13 12:05:44 -07002102
Wale Ogunwaled046a012015-12-24 13:05:59 -08002103 return false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002104 }
2105
Todd Kennedy39bfee52016-02-24 10:28:21 -08002106 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
2107 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2108 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2109 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2110 stacks.get(stackNdx).updateActivityApplicationInfoLocked(aInfo);
2111 }
2112 }
2113 }
2114
Adrian Roos20d7df32016-01-12 18:59:43 +01002115 TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
2116 TaskRecord finishedTask = null;
2117 ActivityStack focusedStack = getFocusedStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08002118 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2119 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002120 final int numStacks = stacks.size();
2121 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2122 final ActivityStack stack = stacks.get(stackNdx);
Adrian Roos20d7df32016-01-12 18:59:43 +01002123 TaskRecord t = stack.finishTopRunningActivityLocked(app, reason);
2124 if (stack == focusedStack || finishedTask == null) {
2125 finishedTask = t;
2126 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08002127 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002128 }
Adrian Roos20d7df32016-01-12 18:59:43 +01002129 return finishedTask;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002130 }
2131
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07002132 void finishVoiceTask(IVoiceInteractionSession session) {
2133 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2134 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2135 final int numStacks = stacks.size();
2136 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
2137 final ActivityStack stack = stacks.get(stackNdx);
2138 stack.finishVoiceTask(session);
2139 }
2140 }
2141 }
2142
Andrii Kulianc27916642016-04-12 17:59:27 -07002143 void findTaskToMoveToFrontLocked(TaskRecord task, int flags, ActivityOptions options,
2144 String reason, boolean forceNonResizeable) {
Craig Mautneraea74a52014-03-08 14:23:10 -08002145 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
2146 mUserLeaving = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002147 }
Craig Mautneraea74a52014-03-08 14:23:10 -08002148 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
2149 // Caller wants the home activity moved with it. To accomplish this,
2150 // we'll just indicate that this task returns to the home task.
Craig Mautner84984fa2014-06-19 11:19:20 -07002151 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
Craig Mautneraea74a52014-03-08 14:23:10 -08002152 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002153 ActivityStack currentStack = task.getStack();
2154 if (currentStack == null) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07002155 Slog.e(TAG, "findTaskToMoveToFrontLocked: can't move task="
2156 + task + " to front. Stack is null");
2157 return;
2158 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002159
Wale Ogunwaleb1faf602016-01-27 09:12:31 -08002160 if (task.isResizeable() && options != null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002161 int stackId = options.getLaunchStackId();
2162 if (canUseActivityOptionsLaunchBounds(options, stackId)) {
Filip Gruszczynskidce2d162016-01-12 15:40:13 -08002163 final Rect bounds = TaskRecord.validateBounds(options.getLaunchBounds());
Chong Zhang0fa656b2015-08-31 15:17:21 -07002164 task.updateOverrideConfiguration(bounds);
Wale Ogunwale854809c2015-12-27 16:18:19 -08002165 if (stackId == INVALID_STACK_ID) {
2166 stackId = task.getLaunchStackId();
2167 }
Andrii Kulian02b7a832016-10-06 23:11:56 -07002168 if (stackId != currentStack.mStackId) {
Winson Chung74666102017-02-22 17:49:24 -08002169 task.reparent(stackId, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE,
2170 DEFER_RESUME, "findTaskToMoveToFrontLocked");
Andrii Kulian02b7a832016-10-06 23:11:56 -07002171 stackId = currentStack.mStackId;
Chong Zhang112eb8c2015-11-02 11:17:00 -08002172 // moveTaskToStackUncheckedLocked() should already placed the task on top,
2173 // still need moveTaskToFrontLocked() below for any transition settings.
2174 }
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002175 if (StackId.resizeStackWithLaunchBounds(stackId)) {
2176 resizeStackLocked(stackId, bounds,
2177 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002178 !PRESERVE_WINDOWS, true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002179 } else {
2180 // WM resizeTask must be done after the task is moved to the correct stack,
2181 // because Task's setBounds() also updates dim layer's bounds, but that has
2182 // dependency on the stack.
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002183 task.resizeWindowContainer();
Wale Ogunwalecacfaa22016-01-15 11:26:08 -08002184 }
Chong Zhang0fa656b2015-08-31 15:17:21 -07002185 }
2186 }
2187
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002188 final ActivityRecord r = task.getTopActivity();
Andrii Kulian02b7a832016-10-06 23:11:56 -07002189 currentStack.moveTaskToFrontLocked(task, false /* noAnimation */, options,
Chong Zhangdb20b5f2015-10-23 14:01:43 -07002190 r == null ? null : r.appTimeTracker, reason);
2191
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002192 if (DEBUG_STACK) Slog.d(TAG_STACK,
Andrii Kulian02b7a832016-10-06 23:11:56 -07002193 "findTaskToMoveToFront: moved to front of stack=" + currentStack);
Jorim Jaggi2adba072016-03-03 13:43:39 +01002194
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002195 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
2196 currentStack.mStackId, forceNonResizeable);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002197 }
2198
Wale Ogunwale854809c2015-12-27 16:18:19 -08002199 boolean canUseActivityOptionsLaunchBounds(ActivityOptions options, int launchStackId) {
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002200 // We use the launch bounds in the activity options is the device supports freeform
Wale Ogunwale854809c2015-12-27 16:18:19 -08002201 // window management or is launching into the pinned stack.
Wale Ogunwale5122df02016-01-29 22:33:38 -08002202 if (options.getLaunchBounds() == null) {
Wale Ogunwale854809c2015-12-27 16:18:19 -08002203 return false;
2204 }
2205 return (mService.mSupportsPictureInPicture && launchStackId == PINNED_STACK_ID)
2206 || mService.mSupportsFreeformWindowManagement;
Wale Ogunwale7a8fa602015-11-18 15:56:57 -08002207 }
2208
Winson Chung55893332017-02-17 17:13:10 -08002209 protected <T extends ActivityStack> T getStack(int stackId) {
Wale Ogunwale040b4702015-08-06 18:10:50 -07002210 return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002211 }
2212
Winson Chung55893332017-02-17 17:13:10 -08002213 protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
2214 boolean createOnTop) {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002215 final ActivityStack stack = mStacks.get(stackId);
2216 if (stack != null) {
2217 return (T) stack;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002218 }
Wale Ogunwale3797c222015-10-27 14:21:58 -07002219 if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002220 return null;
2221 }
Matthew Ng330757d2017-02-28 14:19:17 -08002222 if (stackId == DOCKED_STACK_ID) {
2223 // Make sure recents stack exist when creating a dock stack as it normally need to be on
2224 // the other side of the docked stack and we make visibility decisions based on that.
2225 getStack(RECENTS_STACK_ID, CREATE_IF_NEEDED, createOnTop);
2226 }
Winson Chung55893332017-02-17 17:13:10 -08002227 return (T) createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
Craig Mautner8d341ef2013-03-26 09:03:27 -07002228 }
2229
Andrii Kulian16802aa2016-11-02 12:21:33 -07002230 /**
2231 * Get a topmost stack on the display, that is a valid launch stack for specified activity.
2232 * If there is no such stack, new dynamic stack can be created.
2233 * @param displayId Target display.
2234 * @param r Activity that should be launched there.
2235 * @return Existing stack if there is a valid one, new dynamic stack if it is valid or null.
2236 */
2237 ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002238 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian16802aa2016-11-02 12:21:33 -07002239 if (activityDisplay == null) {
2240 throw new IllegalArgumentException(
2241 "Display with displayId=" + displayId + " not found.");
2242 }
2243
2244 // Return the topmost valid stack on the display.
2245 for (int i = activityDisplay.mStacks.size() - 1; i >= 0; --i) {
2246 final ActivityStack stack = activityDisplay.mStacks.get(i);
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002247 if (mService.mActivityStarter.isValidLaunchStackId(stack.mStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002248 return stack;
2249 }
2250 }
2251
2252 // If there is no valid stack on the external display - check if new dynamic stack will do.
2253 if (displayId != Display.DEFAULT_DISPLAY) {
2254 final int newDynamicStackId = getNextStackId();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07002255 if (mService.mActivityStarter.isValidLaunchStackId(newDynamicStackId, displayId, r)) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002256 return createStackOnDisplay(newDynamicStackId, displayId, true /*onTop*/);
2257 }
2258 }
2259
2260 Slog.w(TAG, "getValidLaunchStackOnDisplay: can't launch on displayId " + displayId);
2261 return null;
2262 }
2263
Craig Mautner967212c2013-04-13 21:10:58 -07002264 ArrayList<ActivityStack> getStacks() {
Wale Ogunwale3797c222015-10-27 14:21:58 -07002265 ArrayList<ActivityStack> allStacks = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08002266 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2267 allStacks.addAll(mActivityDisplays.valueAt(displayNdx).mStacks);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002268 }
2269 return allStacks;
Craig Mautner967212c2013-04-13 21:10:58 -07002270 }
2271
Jorim Jaggife762342016-10-13 14:33:27 +02002272 ArrayList<ActivityStack> getStacksOnDefaultDisplay() {
2273 return mActivityDisplays.valueAt(DEFAULT_DISPLAY).mStacks;
2274 }
2275
Andrii Kulian7fc22812016-12-28 13:04:11 -08002276 /**
2277 * Get next focusable stack in the system. This will search across displays and stacks
2278 * in last-focused order for a focusable and visible stack, different from the target stack.
2279 *
2280 * @param currentFocus The stack that previously had focus and thus needs to be ignored when
2281 * searching for next candidate.
2282 * @return Next focusable {@link ActivityStack}, null if not found.
2283 */
2284 ActivityStack getNextFocusableStackLocked(ActivityStack currentFocus) {
2285 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2286
2287 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2288 final int displayId = mTmpOrderedDisplayIds.get(i);
Andrii Kulian62e6f252017-05-30 22:46:53 -07002289 // If a display is registered in WM, it must also be available in AM.
2290 @SuppressWarnings("ConstantConditions")
2291 final List<ActivityStack> stacks = getActivityDisplayOrCreateLocked(displayId).mStacks;
Andrii Kulian7fc22812016-12-28 13:04:11 -08002292 for (int j = stacks.size() - 1; j >= 0; --j) {
2293 final ActivityStack stack = stacks.get(j);
2294 if (stack != currentFocus && stack.isFocusable()
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002295 && stack.shouldBeVisible(null) != STACK_INVISIBLE) {
Andrii Kulian7fc22812016-12-28 13:04:11 -08002296 return stack;
2297 }
2298 }
2299 }
2300
2301 return null;
2302 }
2303
Andrii Kuliana8fe3df2017-06-16 15:29:26 -07002304 /**
2305 * Get next valid stack for launching provided activity in the system. This will search across
2306 * displays and stacks in last-focused order for a focusable and visible stack, except those
2307 * that are on a currently focused display.
2308 *
2309 * @param r The activity that is being launched.
2310 * @param currentFocus The display that previously had focus and thus needs to be ignored when
2311 * searching for the next candidate.
2312 * @return Next valid {@link ActivityStack}, null if not found.
2313 */
2314 ActivityStack getNextValidLaunchStackLocked(@NonNull ActivityRecord r, int currentFocus) {
2315 mWindowManager.getDisplaysInFocusOrder(mTmpOrderedDisplayIds);
2316 for (int i = mTmpOrderedDisplayIds.size() - 1; i >= 0; --i) {
2317 final int displayId = mTmpOrderedDisplayIds.get(i);
2318 if (displayId == currentFocus) {
2319 continue;
2320 }
2321 final ActivityStack stack = getValidLaunchStackOnDisplay(displayId, r);
2322 if (stack != null) {
2323 return stack;
2324 }
2325 }
2326 return null;
2327 }
2328
Craig Mautneree2e45a2014-06-27 12:10:03 -07002329 ActivityRecord getHomeActivity() {
Craig Mautnerdb49fec2015-05-21 15:33:30 -07002330 return getHomeActivityForUser(mCurrentUser);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002331 }
2332
2333 ActivityRecord getHomeActivityForUser(int userId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08002334 final ArrayList<TaskRecord> tasks = mHomeStack.getAllTasks();
2335 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
2336 final TaskRecord task = tasks.get(taskNdx);
2337 if (task.isHomeTask()) {
2338 final ArrayList<ActivityRecord> activities = task.mActivities;
2339 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2340 final ActivityRecord r = activities.get(activityNdx);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07002341 if (r.isHomeActivity()
2342 && ((userId == UserHandle.USER_ALL) || (r.userId == userId))) {
Craig Mautneree2e45a2014-06-27 12:10:03 -07002343 return r;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002344 }
2345 }
2346 }
2347 }
2348 return null;
2349 }
2350
Chong Zhangb15758a2015-11-17 12:12:03 -08002351 /**
2352 * Returns if a stack should be treated as if it's docked. Returns true if the stack is
2353 * the docked stack itself, or if it's side-by-side to the docked stack.
2354 */
2355 boolean isStackDockedInEffect(int stackId) {
2356 return stackId == DOCKED_STACK_ID ||
2357 (StackId.isResizeableByDockedStack(stackId) && getStack(DOCKED_STACK_ID) != null);
2358 }
2359
Jorim Jaggidc249c42015-12-15 14:57:31 -08002360 void resizeStackLocked(int stackId, Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002361 boolean preserveWindows, boolean allowResizeInDockedMode, boolean deferResume) {
Jorim Jaggidc249c42015-12-15 14:57:31 -08002362 if (stackId == DOCKED_STACK_ID) {
2363 resizeDockedStackLocked(bounds, tempTaskBounds, tempTaskInsetBounds, null, null,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002364 preserveWindows, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002365 return;
2366 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08002367 final ActivityStack stack = getStack(stackId);
2368 if (stack == null) {
2369 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2370 return;
2371 }
Wale Ogunwale9d3de4c2015-02-01 16:49:44 -08002372
Winson Chunga2249ac2017-03-30 18:15:30 -07002373 if (!allowResizeInDockedMode && !StackId.tasksAreFloating(stackId) &&
2374 getStack(DOCKED_STACK_ID) != null) {
2375 // If the docked stack exists, don't resize non-floating stacks independently of the
2376 // size computed from the docked stack size (otherwise they will be out of sync)
Wale Ogunwaleffc11bb2015-10-10 13:05:45 -07002377 return;
2378 }
2379
Wale Ogunwalecad05a02015-09-25 10:41:44 -07002380 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeStack_" + stackId);
Jorim Jaggic4025202015-10-22 16:43:34 +02002381 mWindowManager.deferSurfaceLayout();
2382 try {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002383 stack.resize(bounds, tempTaskBounds, tempTaskInsetBounds);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002384 if (!deferResume) {
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002385 stack.ensureVisibleActivitiesConfigurationLocked(
2386 stack.topRunningActivityLocked(), preserveWindows);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002387 }
Jorim Jaggic4025202015-10-22 16:43:34 +02002388 } finally {
2389 mWindowManager.continueSurfaceLayout();
2390 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07002391 }
2392 }
2393
Jorim Jaggi192086e2016-03-11 17:17:03 +01002394 void deferUpdateBounds(int stackId) {
2395 final ActivityStack stack = getStack(stackId);
2396 if (stack != null) {
2397 stack.deferUpdateBounds();
2398 }
2399 }
2400
2401 void continueUpdateBounds(int stackId) {
2402 final ActivityStack stack = getStack(stackId);
2403 if (stack != null) {
2404 stack.continueUpdateBounds();
2405 }
2406 }
2407
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002408 void notifyAppTransitionDone() {
Matthew Ng606dd802017-06-05 14:06:32 -07002409 continueUpdateBounds(RECENTS_STACK_ID);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002410 for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) {
2411 final int taskId = mResizingTasksDuringAnimation.valueAt(i);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002412 final TaskRecord task =
Winson Chung7900bee2017-03-10 08:59:25 -08002413 anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_ONLY, INVALID_STACK_ID);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002414 if (task != null) {
2415 task.setTaskDockedResizing(false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01002416 }
2417 }
2418 mResizingTasksDuringAnimation.clear();
2419 }
2420
Robert Carre7cc44d2017-03-20 19:04:30 -07002421 private void moveTasksToFullscreenStackInSurfaceTransaction(int fromStackId,
2422 boolean onTop) {
Robert Carr6914f082017-03-20 19:04:30 -07002423
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002424 final ActivityStack stack = getStack(fromStackId);
2425 if (stack == null) {
2426 return;
2427 }
2428
2429 mWindowManager.deferSurfaceLayout();
2430 try {
2431 if (fromStackId == DOCKED_STACK_ID) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002432 // We are moving all tasks from the docked stack to the fullscreen stack,
2433 // which is dismissing the docked stack, so resize all other stacks to
2434 // fullscreen here already so we don't end up with resize trashing.
2435 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
2436 if (StackId.isResizeableByDockedStack(i)) {
2437 ActivityStack otherStack = getStack(i);
2438 if (otherStack != null) {
2439 resizeStackLocked(i, null, null, null, PRESERVE_WINDOWS,
2440 true /* allowResizeInDockedMode */, DEFER_RESUME);
2441 }
2442 }
2443 }
2444
2445 // Also disable docked stack resizing since we have manually adjusted the
2446 // size of other stacks above and we don't want to trigger a docked stack
2447 // resize when we remove task from it below and it is detached from the
2448 // display because it no longer contains any tasks.
2449 mAllowDockedStackResize = false;
Winson Chung47900652017-04-06 18:44:25 -07002450 } else if (fromStackId == PINNED_STACK_ID) {
2451 if (onTop) {
2452 // Log if we are expanding the PiP to fullscreen
2453 MetricsLogger.action(mService.mContext,
2454 ACTION_PICTURE_IN_PICTURE_EXPANDED_TO_FULLSCREEN);
2455 }
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002456 }
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002457 ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
Winson Chungc85d9ce2017-01-03 11:59:52 -08002458 final boolean isFullscreenStackVisible = fullscreenStack != null &&
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07002459 fullscreenStack.shouldBeVisible(null) == STACK_VISIBLE;
Winson Chung5af42fc2017-03-24 17:11:33 -07002460 // If we are moving from the pinned stack, then the animation takes care of updating
2461 // the picture-in-picture mode.
Winson Chung47900652017-04-06 18:44:25 -07002462 final boolean schedulePictureInPictureModeChange = (fromStackId == PINNED_STACK_ID);
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002463 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2464 final int size = tasks.size();
2465 if (onTop) {
2466 for (int i = 0; i < size; i++) {
Winson Chung0c1ca092016-11-10 17:40:34 -08002467 final TaskRecord task = tasks.get(i);
Winson Chung74666102017-02-22 17:49:24 -08002468 final boolean isTopTask = i == (size - 1);
Winson Chung0c1ca092016-11-10 17:40:34 -08002469 if (fromStackId == PINNED_STACK_ID) {
2470 // Update the return-to to reflect where the pinned stack task was moved
2471 // from so that we retain the stack that was previously visible if the
2472 // pinned stack is recreated. See moveActivityToPinnedStackLocked().
Winson Chungc85d9ce2017-01-03 11:59:52 -08002473 task.setTaskToReturnTo(isFullscreenStackVisible && onTop ?
2474 APPLICATION_ACTIVITY_TYPE : HOME_ACTIVITY_TYPE);
Winson Chung0c1ca092016-11-10 17:40:34 -08002475 }
Winson Chung74666102017-02-22 17:49:24 -08002476 // Defer resume until all the tasks have been moved to the fullscreen stack
2477 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, ON_TOP,
2478 REPARENT_MOVE_STACK_TO_FRONT, isTopTask /* animate */, DEFER_RESUME,
Winson Chung5af42fc2017-03-24 17:11:33 -07002479 schedulePictureInPictureModeChange,
Winson Chung74666102017-02-22 17:49:24 -08002480 "moveTasksToFullscreenStack - onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002481 }
2482 } else {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002483 for (int i = 0; i < size; i++) {
Wale Ogunwalec5cc3012017-01-13 13:26:16 -08002484 final TaskRecord task = tasks.get(i);
Winson Chung3a649982017-04-19 10:16:17 -07002485 // Position the tasks in the fullscreen stack in order at the bottom of the
2486 // stack. Also defer resume until all the tasks have been moved to the
2487 // fullscreen stack.
2488 task.reparent(FULLSCREEN_WORKSPACE_STACK_ID, i /* position */,
Winson Chung5af42fc2017-03-24 17:11:33 -07002489 REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME,
2490 schedulePictureInPictureModeChange,
2491 "moveTasksToFullscreenStack - NOT_onTop");
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002492 }
2493 }
Winson Chung74666102017-02-22 17:49:24 -08002494
2495 ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2496 resumeFocusedStackTopActivityLocked();
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002497 } finally {
2498 mAllowDockedStackResize = true;
2499 mWindowManager.continueSurfaceLayout();
2500 }
2501 }
2502
Robert Carr6914f082017-03-20 19:04:30 -07002503 void moveTasksToFullscreenStackLocked(int fromStackId, boolean onTop) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002504 mWindowManager.inSurfaceTransaction(
2505 () -> moveTasksToFullscreenStackInSurfaceTransaction(fromStackId, onTop));
Robert Carr6914f082017-03-20 19:04:30 -07002506 }
2507
Jorim Jaggidc249c42015-12-15 14:57:31 -08002508 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002509 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2510 boolean preserveWindows) {
2511 resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
2512 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows,
2513 false /* deferResume */);
2514 }
2515
2516 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds,
2517 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds,
2518 boolean preserveWindows, boolean deferResume) {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002519
2520 if (!mAllowDockedStackResize) {
2521 // Docked stack resize currently disabled.
2522 return;
2523 }
2524
Jorim Jaggidc249c42015-12-15 14:57:31 -08002525 final ActivityStack stack = getStack(DOCKED_STACK_ID);
2526 if (stack == null) {
2527 Slog.w(TAG, "resizeDockedStackLocked: docked stack not found");
2528 return;
2529 }
2530
2531 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack");
2532 mWindowManager.deferSurfaceLayout();
2533 try {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002534 // Don't allow re-entry while resizing. E.g. due to docked stack detaching.
2535 mAllowDockedStackResize = false;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002536 ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwale1666e312016-12-16 11:27:18 -08002537 stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002538
Andrii Kulian69fb5e42016-04-05 16:47:29 -07002539 // TODO: Checking for isAttached might not be needed as if the user passes in null
2540 // dockedBounds then they want the docked stack to be dismissed.
2541 if (stack.mFullscreen || (dockedBounds == null && !stack.isAttached())) {
2542 // The dock stack either was dismissed or went fullscreen, which is kinda the same.
Jorim Jaggidc249c42015-12-15 14:57:31 -08002543 // In this case we make all other static stacks fullscreen and move all
2544 // docked stack tasks to the fullscreen stack.
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002545 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, ON_TOP);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002546
2547 // stack shouldn't contain anymore activities, so nothing to resume.
2548 r = null;
2549 } else {
2550 // Docked stacks occupy a dedicated region on screen so the size of all other
2551 // static stacks need to be adjusted so they don't overlap with the docked stack.
2552 // We get the bounds to use from window manager which has been adjusted for any
2553 // screen controls and is also the same for all stacks.
Matthew Ngaa2b6202017-02-10 14:48:21 -08002554 final Rect otherTaskRect = new Rect();
Jorim Jaggidc249c42015-12-15 14:57:31 -08002555 for (int i = FIRST_STATIC_STACK_ID; i <= LAST_STATIC_STACK_ID; i++) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08002556 final ActivityStack current = getStack(i);
2557 if (current != null && StackId.isResizeableByDockedStack(i)) {
Matthew Ngaa2b6202017-02-10 14:48:21 -08002558 current.getStackDockedModeBounds(
2559 tempOtherTaskBounds /* currentTempTaskBounds */,
2560 tempRect /* outStackBounds */,
2561 otherTaskRect /* outTempTaskBounds */, true /* ignoreVisibility */);
2562
Andrii Kuliane48b7d82017-04-28 14:51:05 -07002563 resizeStackLocked(i, !tempRect.isEmpty() ? tempRect : null,
Matthew Ngaa2b6202017-02-10 14:48:21 -08002564 !otherTaskRect.isEmpty() ? otherTaskRect : tempOtherTaskBounds,
2565 tempOtherTaskInsetBounds, preserveWindows,
2566 true /* allowResizeInDockedMode */, deferResume);
Jorim Jaggidc249c42015-12-15 14:57:31 -08002567 }
2568 }
2569 }
Andrii Kuliandb3e4ec2016-07-12 17:11:35 -07002570 if (!deferResume) {
2571 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows);
2572 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002573 } finally {
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002574 mAllowDockedStackResize = true;
Jorim Jaggidc249c42015-12-15 14:57:31 -08002575 mWindowManager.continueSurfaceLayout();
2576 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2577 }
Jorim Jaggidc249c42015-12-15 14:57:31 -08002578 }
2579
Robert Carr0d00c2e2016-02-29 17:45:02 -08002580 void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Winson Chung19953ca2017-04-11 11:19:23 -07002581 final PinnedActivityStack stack = getStack(PINNED_STACK_ID);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002582 if (stack == null) {
2583 Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found");
2584 return;
2585 }
Winson Chung19953ca2017-04-11 11:19:23 -07002586
2587 // It is possible for the bounds animation from the WM to call this but be delayed by
2588 // another AM call that is holding the AMS lock. In such a case, the pinnedBounds may be
2589 // incorrect if AMS.resizeStackWithBoundsFromWindowManager() is already called while waiting
2590 // for the AMS lock to be freed. So check and make sure these bounds are still good.
2591 final PinnedStackWindowController stackController = stack.getWindowContainerController();
Winson Chung8bca9e42017-04-16 15:59:43 -07002592 if (stackController.pinnedStackResizeDisallowed()) {
Winson Chung19953ca2017-04-11 11:19:23 -07002593 return;
2594 }
2595
Robert Carr0d00c2e2016-02-29 17:45:02 -08002596 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack");
2597 mWindowManager.deferSurfaceLayout();
2598 try {
2599 ActivityRecord r = stack.topRunningActivityLocked();
Robert Carr7e4c90e2017-02-15 19:52:38 -08002600 Rect insetBounds = null;
2601 if (tempPinnedTaskBounds != null) {
2602 // We always use 0,0 as the position for the inset rect because
2603 // if we are getting insets at all in the pinned stack it must mean
2604 // we are headed for fullscreen.
2605 insetBounds = tempRect;
2606 insetBounds.top = 0;
2607 insetBounds.left = 0;
2608 insetBounds.right = tempPinnedTaskBounds.width();
2609 insetBounds.bottom = tempPinnedTaskBounds.height();
2610 }
2611 stack.resize(pinnedBounds, tempPinnedTaskBounds, insetBounds);
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07002612 stack.ensureVisibleActivitiesConfigurationLocked(r, false);
Robert Carr0d00c2e2016-02-29 17:45:02 -08002613 } finally {
2614 mWindowManager.continueSurfaceLayout();
2615 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
2616 }
2617 }
2618
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002619 ActivityStack createStackOnDisplay(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002620 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Craig Mautnere0a38842013-12-16 16:14:02 -08002621 if (activityDisplay == null) {
Todd Kennedy4900bf92015-01-16 16:05:14 -08002622 return null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08002623 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002624 return createStack(stackId, activityDisplay, onTop);
Craig Mautner4a1cb222013-12-04 16:14:06 -08002625
Craig Mautner4a1cb222013-12-04 16:14:06 -08002626 }
2627
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002628 ActivityStack createStack(int stackId, ActivityDisplay display, boolean onTop) {
2629 switch (stackId) {
2630 case PINNED_STACK_ID:
2631 return new PinnedActivityStack(display, stackId, this, mRecentTasks, onTop);
2632 default:
2633 return new ActivityStack(display, stackId, this, mRecentTasks, onTop);
2634 }
2635 }
Robert Carr6914f082017-03-20 19:04:30 -07002636
Robert Carre7cc44d2017-03-20 19:04:30 -07002637 void removeStackInSurfaceTransaction(int stackId) {
Winson Chung010927a2016-12-15 16:12:35 -08002638 final ActivityStack stack = getStack(stackId);
2639 if (stack == null) {
2640 return;
2641 }
2642
2643 final ArrayList<TaskRecord> tasks = stack.getAllTasks();
2644 if (stack.getStackId() == PINNED_STACK_ID) {
Winson Chung47900652017-04-06 18:44:25 -07002645 /**
2646 * Workaround: Force-stop all the activities in the pinned stack before we reparent them
2647 * to the fullscreen stack. This is to guarantee that when we are removing a stack,
2648 * that the client receives onStop() before it is reparented. We do this by detaching
2649 * the stack from the display so that it will be considered invisible when
2650 * ensureActivitiesVisibleLocked() is called, and all of its activitys will be marked
2651 * invisible as well and added to the stopping list. After which we process the
2652 * stopping list by handling the idle.
2653 */
2654 final PinnedActivityStack pinnedStack = (PinnedActivityStack) stack;
2655 pinnedStack.mForceHidden = true;
2656 pinnedStack.ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS);
2657 pinnedStack.mForceHidden = false;
2658 activityIdleInternalLocked(null, false /* fromTimeout */,
2659 true /* processPausingActivites */, null /* configuration */);
2660
2661 // Move all the tasks to the bottom of the fullscreen stack
2662 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
Winson Chung010927a2016-12-15 16:12:35 -08002663 } else {
2664 for (int i = tasks.size() - 1; i >= 0; i--) {
2665 removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */,
2666 REMOVE_FROM_RECENTS);
2667 }
2668 }
2669 }
2670
2671 /**
Robert Carr6914f082017-03-20 19:04:30 -07002672 * Removes the stack associated with the given {@param stackId}. If the {@param stackId} is the
2673 * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
2674 * instead moved back onto the fullscreen stack.
2675 */
2676 void removeStackLocked(int stackId) {
Robert Carre7cc44d2017-03-20 19:04:30 -07002677 mWindowManager.inSurfaceTransaction(
2678 () -> removeStackInSurfaceTransaction(stackId));
Robert Carr6914f082017-03-20 19:04:30 -07002679 }
2680
2681 /**
Winson Chung6954fc92017-03-24 16:22:12 -07002682 * See {@link #removeTaskByIdLocked(int, boolean, boolean, boolean)}
2683 */
2684 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents) {
2685 return removeTaskByIdLocked(taskId, killProcess, removeFromRecents, !PAUSE_IMMEDIATELY);
2686 }
2687
2688 /**
Winson Chung010927a2016-12-15 16:12:35 -08002689 * Removes the task with the specified task id.
2690 *
2691 * @param taskId Identifier of the task to be removed.
2692 * @param killProcess Kill any process associated with the task if possible.
2693 * @param removeFromRecents Whether to also remove the task from recents.
Winson Chung6954fc92017-03-24 16:22:12 -07002694 * @param pauseImmediately Pauses all task activities immediately without waiting for the
2695 * pause-complete callback from the activity.
Winson Chung010927a2016-12-15 16:12:35 -08002696 * @return Returns true if the given task was found and removed.
2697 */
Winson Chung6954fc92017-03-24 16:22:12 -07002698 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents,
2699 boolean pauseImmediately) {
Winson Chung7900bee2017-03-10 08:59:25 -08002700 final TaskRecord tr = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS,
2701 INVALID_STACK_ID);
Winson Chung010927a2016-12-15 16:12:35 -08002702 if (tr != null) {
Winson Chung6954fc92017-03-24 16:22:12 -07002703 tr.removeTaskActivitiesLocked(pauseImmediately);
Winson Chung010927a2016-12-15 16:12:35 -08002704 cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents);
2705 if (tr.isPersistable) {
2706 mService.notifyTaskPersisterLocked(null, true);
2707 }
2708 return true;
2709 }
2710 Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
2711 return false;
2712 }
2713
2714 void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) {
2715 if (removeFromRecents) {
2716 mRecentTasks.remove(tr);
2717 tr.removedFromRecents();
2718 }
2719 ComponentName component = tr.getBaseIntent().getComponent();
2720 if (component == null) {
2721 Slog.w(TAG, "No component for base intent of task: " + tr);
2722 return;
2723 }
2724
2725 // Find any running services associated with this app and stop if needed.
2726 mService.mServices.cleanUpRemovedTaskLocked(tr, component, new Intent(tr.getBaseIntent()));
2727
2728 if (!killProcess) {
2729 return;
2730 }
2731
2732 // Determine if the process(es) for this task should be killed.
2733 final String pkg = component.getPackageName();
2734 ArrayList<ProcessRecord> procsToKill = new ArrayList<>();
2735 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mService.mProcessNames.getMap();
2736 for (int i = 0; i < pmap.size(); i++) {
2737
2738 SparseArray<ProcessRecord> uids = pmap.valueAt(i);
2739 for (int j = 0; j < uids.size(); j++) {
2740 ProcessRecord proc = uids.valueAt(j);
2741 if (proc.userId != tr.userId) {
2742 // Don't kill process for a different user.
2743 continue;
2744 }
2745 if (proc == mService.mHomeProcess) {
2746 // Don't kill the home process along with tasks from the same package.
2747 continue;
2748 }
2749 if (!proc.pkgList.containsKey(pkg)) {
2750 // Don't kill process that is not associated with this task.
2751 continue;
2752 }
2753
2754 for (int k = 0; k < proc.activities.size(); k++) {
Bryce Leeaf691c02017-03-20 14:20:22 -07002755 TaskRecord otherTask = proc.activities.get(k).getTask();
Winson Chung010927a2016-12-15 16:12:35 -08002756 if (tr.taskId != otherTask.taskId && otherTask.inRecents) {
2757 // Don't kill process(es) that has an activity in a different task that is
2758 // also in recents.
2759 return;
2760 }
2761 }
2762
2763 if (proc.foregroundServices) {
2764 // Don't kill process(es) with foreground service.
2765 return;
2766 }
2767
2768 // Add process to kill list.
2769 procsToKill.add(proc);
2770 }
2771 }
2772
2773 // Kill the running processes.
2774 for (int i = 0; i < procsToKill.size(); i++) {
2775 ProcessRecord pr = procsToKill.get(i);
2776 if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
2777 && pr.curReceivers.isEmpty()) {
2778 pr.kill("remove task", true);
2779 } else {
2780 // We delay killing processes that are not in the background or running a receiver.
2781 pr.waitingToKill = "remove task";
2782 }
2783 }
2784 }
2785
Craig Mautner4a1cb222013-12-04 16:14:06 -08002786 int getNextStackId() {
Craig Mautner858d8a62013-04-23 17:08:34 -07002787 while (true) {
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002788 if (mNextFreeStackId >= FIRST_DYNAMIC_STACK_ID
2789 && getStack(mNextFreeStackId) == null) {
Craig Mautner858d8a62013-04-23 17:08:34 -07002790 break;
2791 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002792 mNextFreeStackId++;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002793 }
Wale Ogunwaleddc1cb22015-07-25 19:23:04 -07002794 return mNextFreeStackId;
Craig Mautner8d341ef2013-03-26 09:03:27 -07002795 }
2796
Chong Zhang5dcb2752015-08-18 13:50:26 -07002797 /**
2798 * Restores a recent task to a stack
2799 * @param task The recent task to be restored.
2800 * @param stackId The stack to restore the task to (default launch stack will be used
Andrii Kulian16802aa2016-11-02 12:21:33 -07002801 * if stackId is {@link android.app.ActivityManager.StackId#INVALID_STACK_ID}
2802 * or is not a static stack).
Chong Zhang5dcb2752015-08-18 13:50:26 -07002803 * @return true if the task has been restored successfully.
2804 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002805 boolean restoreRecentTaskLocked(TaskRecord task, int stackId) {
Andrii Kulian16802aa2016-11-02 12:21:33 -07002806 if (!StackId.isStaticStack(stackId)) {
2807 // If stack is not static (or stack id is invalid) - use the default one.
2808 // This means that tasks that were on external displays will be restored on the
2809 // primary display.
Wale Ogunwale8b06a582015-10-22 14:38:21 -07002810 stackId = task.getLaunchStackId();
Winson Chungd3395382016-12-13 11:49:09 -08002811 } else if (stackId == DOCKED_STACK_ID && !task.supportsSplitScreen()) {
Wale Ogunwale513346d2016-01-27 10:55:01 -08002812 // Preferred stack is the docked stack, but the task can't go in the docked stack.
2813 // Put it in the fullscreen stack.
2814 stackId = FULLSCREEN_WORKSPACE_STACK_ID;
Chong Zhang5dcb2752015-08-18 13:50:26 -07002815 }
Wale Ogunwale513346d2016-01-27 10:55:01 -08002816
Andrii Kulian02b7a832016-10-06 23:11:56 -07002817 final ActivityStack currentStack = task.getStack();
2818 if (currentStack != null) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002819 // Task has already been restored once. See if we need to do anything more
Andrii Kulian02b7a832016-10-06 23:11:56 -07002820 if (currentStack.mStackId == stackId) {
Wale Ogunwale706ed792015-08-02 10:29:44 -07002821 // Nothing else to do since it is already restored in the right stack.
2822 return true;
2823 }
2824 // Remove current stack association, so we can re-associate the task with the
2825 // right stack below.
Andrii Kulian02b7a832016-10-06 23:11:56 -07002826 currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING);
Wale Ogunwale706ed792015-08-02 10:29:44 -07002827 }
2828
Wale Ogunwale6c5eb1c2015-11-10 07:52:22 -08002829 final ActivityStack stack =
Wale Ogunwale040b4702015-08-06 18:10:50 -07002830 getStack(stackId, CREATE_IF_NEEDED, !ON_TOP);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002831
2832 if (stack == null) {
2833 // What does this mean??? Not sure how we would get here...
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002834 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2835 "Unable to find/create stack to restore recent task=" + task);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002836 return false;
2837 }
2838
Wale Ogunwale72919d22016-12-08 18:58:50 -08002839 stack.addTask(task, false /* toTop */, "restoreRecentTask");
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08002840 // TODO: move call for creation here and other place into Stack.addTask()
2841 task.createWindowContainer(false /* toTop */, true /* showForAllUsers */);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002842 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS,
2843 "Added restored task=" + task + " to stack=" + stack);
Wale Ogunwale7de05352014-12-12 15:21:33 -08002844 final ArrayList<ActivityRecord> activities = task.mActivities;
2845 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002846 activities.get(activityNdx).createWindowContainer();
Wale Ogunwale7de05352014-12-12 15:21:33 -08002847 }
2848 return true;
Craig Mautneref73ee12014-04-23 11:45:37 -07002849 }
2850
Wale Ogunwale040b4702015-08-06 18:10:50 -07002851 /**
Andrii Kulian839def92016-11-02 10:58:58 -07002852 * Move stack with all its existing content to specified display.
2853 * @param stackId Id of stack to move.
2854 * @param displayId Id of display to move stack to.
Andrii Kulian250d6532017-02-08 23:30:45 -08002855 * @param onTop Indicates whether container should be place on top or on bottom.
Andrii Kulian839def92016-11-02 10:58:58 -07002856 */
Andrii Kulian250d6532017-02-08 23:30:45 -08002857 void moveStackToDisplayLocked(int stackId, int displayId, boolean onTop) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07002858 final ActivityDisplay activityDisplay = getActivityDisplayOrCreateLocked(displayId);
Andrii Kulian839def92016-11-02 10:58:58 -07002859 if (activityDisplay == null) {
2860 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown displayId="
2861 + displayId);
2862 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002863 final ActivityStack stack = mStacks.get(stackId);
2864 if (stack == null) {
Andrii Kulian839def92016-11-02 10:58:58 -07002865 throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
2866 + stackId);
2867 }
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002868
2869 final ActivityDisplay currentDisplay = stack.getDisplay();
2870 if (currentDisplay == null) {
2871 throw new IllegalStateException("moveStackToDisplayLocked: Stack with stack=" + stack
2872 + " is not attached to any display.");
2873 }
2874
2875 if (currentDisplay.mDisplayId == displayId) {
2876 throw new IllegalArgumentException("Trying to move stack=" + stack
2877 + " to its current displayId=" + displayId);
2878 }
2879
2880 stack.reparent(activityDisplay, onTop);
Andrii Kulian839def92016-11-02 10:58:58 -07002881 // TODO(multi-display): resize stacks properly if moved from split-screen.
2882 }
2883
2884 /**
Winson Chung74666102017-02-22 17:49:24 -08002885 * Returns the reparent target stack, creating the stack if necessary. This call also enforces
2886 * the various checks on tasks that are going to be reparented from one stack to another.
Wale Ogunwale040b4702015-08-06 18:10:50 -07002887 */
Winson Chung74666102017-02-22 17:49:24 -08002888 ActivityStack getReparentTargetStack(TaskRecord task, int stackId, boolean toTop) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07002889 final ActivityStack prevStack = task.getStack();
Chong Zhang02898352015-08-21 17:27:14 -07002890
Winson Chung74666102017-02-22 17:49:24 -08002891 // Check that we aren't reparenting to the same stack that the task is already in
2892 if (prevStack != null && prevStack.mStackId == stackId) {
2893 Slog.w(TAG, "Can not reparent to same stack, task=" + task
2894 + " already in stackId=" + stackId);
2895 return prevStack;
Wale Ogunwale513346d2016-01-27 10:55:01 -08002896 }
2897
Winson Chung74666102017-02-22 17:49:24 -08002898 // Ensure that we aren't trying to move into a multi-window stack without multi-window
2899 // support
2900 if (StackId.isMultiWindowStack(stackId) && !mService.mSupportsMultiWindow) {
2901 throw new IllegalArgumentException("Device doesn't support multi-window, can not"
2902 + " reparent task=" + task + " to stackId=" + stackId);
Winson Chungc2baac02017-01-11 13:34:47 -08002903 }
2904
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002905 // Ensure that we're not moving a task to a dynamic stack if device doesn't support
2906 // multi-display.
2907 // TODO(multi-display): Support non-dynamic stacks on secondary displays.
Andrii Kulianeafd9db2017-04-05 22:01:35 -07002908 if (StackId.isDynamicStack(stackId) && !mService.mSupportsMultiDisplay) {
2909 throw new IllegalArgumentException("Device doesn't support multi-display, can not"
2910 + " reparent task=" + task + " to stackId=" + stackId);
2911 }
2912
Winson Chung74666102017-02-22 17:49:24 -08002913 // Ensure that we aren't trying to move into a freeform stack without freeform
2914 // support
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002915 if (stackId == FREEFORM_WORKSPACE_STACK_ID && !mService.mSupportsFreeformWindowManagement) {
Winson Chung74666102017-02-22 17:49:24 -08002916 throw new IllegalArgumentException("Device doesn't support freeform, can not reparent"
2917 + " task=" + task);
Wale Ogunwale08559dc2016-02-23 12:20:08 -08002918 }
2919
Winson Chung74666102017-02-22 17:49:24 -08002920 // We don't allow moving a unresizeable task to the docked stack since the docked stack is
2921 // used for split-screen mode and will cause things like the docked divider to show up. We
2922 // instead leave the task in its current stack or move it to the fullscreen stack if it
2923 // isn't currently in a stack.
2924 if (stackId == DOCKED_STACK_ID && !task.isResizeable()) {
2925 stackId = (prevStack != null) ? prevStack.mStackId : FULLSCREEN_WORKSPACE_STACK_ID;
2926 Slog.w(TAG, "Can not move unresizeable task=" + task + " to docked stack."
2927 + " Moving to stackId=" + stackId + " instead.");
Filip Gruszczynski49b80af2015-09-24 09:04:26 -07002928 }
Wale Ogunwale961f4852016-02-01 20:25:54 -08002929
Winson Chung74666102017-02-22 17:49:24 -08002930 // Temporarily disable resizeablility of the task as we don't want it to be resized if, for
2931 // example, a docked stack is created which will lead to the stack we are moving from being
2932 // resized and and its resizeable tasks being resized.
Wale Ogunwale961f4852016-02-01 20:25:54 -08002933 try {
Winson Chung74666102017-02-22 17:49:24 -08002934 task.mTemporarilyUnresizable = true;
2935 return getStack(stackId, CREATE_IF_NEEDED, toTop);
Wale Ogunwale961f4852016-02-01 20:25:54 -08002936 } finally {
Winson Chung74666102017-02-22 17:49:24 -08002937 task.mTemporarilyUnresizable = false;
Chong Zhangf596cd52016-01-05 13:42:44 -08002938 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07002939 }
2940
Winson Chung08f81892017-03-02 15:40:51 -08002941 boolean moveTopStackActivityToPinnedStackLocked(int stackId, Rect destBounds) {
Wale Ogunwale079a0042015-10-24 11:44:07 -07002942 final ActivityStack stack = getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
2943 if (stack == null) {
2944 throw new IllegalArgumentException(
2945 "moveTopStackActivityToPinnedStackLocked: Unknown stackId=" + stackId);
2946 }
2947
2948 final ActivityRecord r = stack.topRunningActivityLocked();
2949 if (r == null) {
2950 Slog.w(TAG, "moveTopStackActivityToPinnedStackLocked: No top running activity"
2951 + " in stack=" + stack);
2952 return false;
2953 }
2954
Wale Ogunwale6cae7652015-12-26 07:36:26 -08002955 if (!mService.mForceResizableActivities && !r.supportsPictureInPicture()) {
Wale Ogunwaleb60692e2015-10-24 12:35:56 -07002956 Slog.w(TAG,
2957 "moveTopStackActivityToPinnedStackLocked: Picture-In-Picture not supported for "
Filip Gruszczynski77d94482015-12-11 13:59:52 -08002958 + " r=" + r);
Wale Ogunwale079a0042015-10-24 11:44:07 -07002959 return false;
2960 }
2961
Winson Chung3a682872017-04-10 14:38:05 -07002962 moveActivityToPinnedStackLocked(r, null /* sourceBounds */, 0f /* aspectRatio */,
Winson Chung08f81892017-03-02 15:40:51 -08002963 true /* moveHomeStackToFront */, "moveTopActivityToPinnedStack");
Wale Ogunwale9c604c72015-12-06 18:42:57 -08002964 return true;
2965 }
2966
Winson Chung8bca9e42017-04-16 15:59:43 -07002967 void moveActivityToPinnedStackLocked(ActivityRecord r, Rect sourceHintBounds, float aspectRatio,
Winson Chung08f81892017-03-02 15:40:51 -08002968 boolean moveHomeStackToFront, String reason) {
2969
Wale Ogunwale480dca02016-02-06 13:58:29 -08002970 mWindowManager.deferSurfaceLayout();
Winson Chung74666102017-02-22 17:49:24 -08002971
Bryce Lee04ab3462017-04-10 15:06:33 -07002972 // This will clear the pinned stack by moving an existing task to the full screen stack,
2973 // ensuring only one task is present.
2974 moveTasksToFullscreenStackLocked(PINNED_STACK_ID, !ON_TOP);
2975
Wale Ogunwale1666e312016-12-16 11:27:18 -08002976 // Need to make sure the pinned stack exist so we can resize it below...
Winson Chung55893332017-02-17 17:13:10 -08002977 final PinnedActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
Wale Ogunwale1666e312016-12-16 11:27:18 -08002978
Wale Ogunwale480dca02016-02-06 13:58:29 -08002979 try {
Bryce Leeaf691c02017-03-20 14:20:22 -07002980 final TaskRecord task = r.getTask();
Wale Ogunwale480dca02016-02-06 13:58:29 -08002981 // Resize the pinned stack to match the current size of the task the activity we are
2982 // going to be moving is currently contained in. We do this to have the right starting
2983 // animation bounds for the pinned stack to the desired bounds the caller wants.
2984 resizeStackLocked(PINNED_STACK_ID, task.mBounds, null /* tempTaskBounds */,
2985 null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS,
Wale Ogunwalec8da41e2016-04-16 13:27:23 -07002986 true /* allowResizeInDockedMode */, !DEFER_RESUME);
Wale Ogunwale480dca02016-02-06 13:58:29 -08002987
2988 if (task.mActivities.size() == 1) {
2989 // There is only one activity in the task. So, we can just move the task over to
Winson Chungc2baac02017-01-11 13:34:47 -08002990 // the stack without re-parenting the activity in a different task. We don't
2991 // move the home stack forward if we are currently entering picture-in-picture
2992 // while pausing because that changes the focused stack and may prevent the new
2993 // starting activity from resuming.
2994 if (moveHomeStackToFront && task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE
Winson Chung105ae5f2017-03-06 15:06:28 -08002995 && (r.state == RESUMED || !r.supportsPictureInPictureWhilePausing)) {
Wale Ogunwaleda4ba962016-03-11 09:33:17 -08002996 // Move the home stack forward if the task we just moved to the pinned stack
2997 // was launched from home so home should be visible behind it.
2998 moveHomeStackToFront(reason);
2999 }
Winson Chung5af42fc2017-03-24 17:11:33 -07003000 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08003001 task.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07003002 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08003003 } else {
Winson Chungb5c41b72016-12-07 15:00:47 -08003004 // There are multiple activities in the task and moving the top activity should
Winson Chung74666102017-02-22 17:49:24 -08003005 // reveal/leave the other activities in their original task.
3006
3007 // Currently, we don't support reparenting activities across tasks in two different
3008 // stacks, so instead, just create a new task in the same stack, reparent the
3009 // activity into that task, and then reparent the whole task to the new stack. This
3010 // ensures that all the necessary work to migrate states in the old and new stacks
3011 // is also done.
3012 final TaskRecord newTask = task.getStack().createTaskRecord(
3013 getNextTaskIdForUserLocked(r.userId), r.info, r.intent, null, null, true,
3014 r.mActivityType);
3015 r.reparent(newTask, MAX_VALUE, "moveActivityToStack");
3016
Winson Chung5af42fc2017-03-24 17:11:33 -07003017 // Defer resume until below, and do not schedule PiP changes until we animate below
Winson Chung74666102017-02-22 17:49:24 -08003018 newTask.reparent(PINNED_STACK_ID, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, !ANIMATE,
Winson Chung5af42fc2017-03-24 17:11:33 -07003019 DEFER_RESUME, false /* schedulePictureInPictureModeChange */, reason);
Wale Ogunwale480dca02016-02-06 13:58:29 -08003020 }
Winson Chungc2baac02017-01-11 13:34:47 -08003021
3022 // Reset the state that indicates it can enter PiP while pausing after we've moved it
3023 // to the pinned stack
3024 r.supportsPictureInPictureWhilePausing = false;
Wale Ogunwale480dca02016-02-06 13:58:29 -08003025 } finally {
3026 mWindowManager.continueSurfaceLayout();
Wale Ogunwale079a0042015-10-24 11:44:07 -07003027 }
3028
Winson Chunge7ba6862017-05-24 12:13:33 -07003029 // Calculate the default bounds (don't use existing stack bounds as we may have just created
3030 // the stack, and schedule the start of the animation into PiP (the bounds animator that
3031 // is triggered by this is posted on another thread)
Winson Chunga71febe2017-05-22 11:14:22 -07003032 final Rect destBounds = stack.getDefaultPictureInPictureBounds(aspectRatio);
3033
Winson Chunge7ba6862017-05-24 12:13:33 -07003034 stack.animateResizePinnedStack(sourceHintBounds, destBounds, -1 /* animationDuration */,
3035 true /* fromFullscreen */);
3036
3037 // Update the visibility of all activities after the they have been reparented to the new
3038 // stack. This MUST run after the animation above is scheduled to ensure that the windows
3039 // drawn signal is scheduled after the bounds animation start call on the bounds animator
3040 // thread.
Wale Ogunwale079a0042015-10-24 11:44:07 -07003041 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwaled046a012015-12-24 13:05:59 -08003042 resumeFocusedStackTopActivityLocked();
Wale Ogunwale03ce8632015-12-29 16:15:22 -08003043
Winson Chungb5026902017-05-03 12:45:13 -07003044 mService.mTaskChangeNotificationController.notifyActivityPinned(r.packageName,
3045 r.getTask().taskId);
Wale Ogunwale079a0042015-10-24 11:44:07 -07003046 }
3047
Andrii Kulian0864bbb2017-02-16 15:45:58 -08003048 /** Move activity with its stack to front and make the stack focused. */
Chong Zhang6cda19c2016-06-14 19:07:56 -07003049 boolean moveFocusableActivityStackToFrontLocked(ActivityRecord r, String reason) {
3050 if (r == null || !r.isFocusable()) {
3051 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3052 "moveActivityStackToFront: unfocusable r=" + r);
3053 return false;
3054 }
3055
Bryce Leeaf691c02017-03-20 14:20:22 -07003056 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003057 final ActivityStack stack = r.getStack();
3058 if (stack == null) {
Chong Zhang6cda19c2016-06-14 19:07:56 -07003059 Slog.w(TAG, "moveActivityStackToFront: invalid task or stack: r="
3060 + r + " task=" + task);
3061 return false;
3062 }
3063
Chong Zhang6cda19c2016-06-14 19:07:56 -07003064 if (stack == mFocusedStack && stack.topRunningActivityLocked() == r) {
3065 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3066 "moveActivityStackToFront: already on top, r=" + r);
3067 return false;
3068 }
3069
3070 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS,
3071 "moveActivityStackToFront: r=" + r);
3072
3073 stack.moveToFront(reason, task);
3074 return true;
3075 }
3076
David Stevensc6b91c62017-02-08 14:23:58 -08003077 ActivityRecord findTaskLocked(ActivityRecord r, int displayId) {
Wale Ogunwale39381972015-12-17 17:15:29 -08003078 mTmpFindTaskResult.r = null;
3079 mTmpFindTaskResult.matchedByRootAffinity = false;
David Stevensc6b91c62017-02-08 14:23:58 -08003080 ActivityRecord affinityMatch = null;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003081 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + r);
Craig Mautnere0a38842013-12-16 16:14:02 -08003082 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3083 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003084 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3085 final ActivityStack stack = stacks.get(stackNdx);
Winson Chung91e5c882017-04-21 14:44:38 -07003086 if (!checkActivityBelongsInStack(r, stack)) {
3087 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) "
3088 + stack);
Craig Mautner1b4bf852014-05-26 15:06:32 -07003089 continue;
3090 }
Wale Ogunwale39381972015-12-17 17:15:29 -08003091 stack.findTaskLocked(r, mTmpFindTaskResult);
David Stevensc6b91c62017-02-08 14:23:58 -08003092 // It is possible to have tasks in multiple stacks with the same root affinity, so
3093 // we should keep looking after finding an affinity match to see if there is a
3094 // better match in another stack. Also, task affinity isn't a good enough reason
3095 // to target a display which isn't the source of the intent, so skip any affinity
3096 // matches not on the specified display.
3097 if (mTmpFindTaskResult.r != null) {
3098 if (!mTmpFindTaskResult.matchedByRootAffinity) {
3099 return mTmpFindTaskResult.r;
3100 } else if (mTmpFindTaskResult.r.getDisplayId() == displayId) {
Winson Chung5b895b72017-05-01 13:46:25 -07003101 // Note: since the traversing through the stacks is top down, the floating
3102 // tasks should always have lower priority than any affinity-matching tasks
3103 // in the fullscreen stacks
David Stevensc6b91c62017-02-08 14:23:58 -08003104 affinityMatch = mTmpFindTaskResult.r;
3105 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003106 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003107 }
3108 }
Winson Chung5b895b72017-05-01 13:46:25 -07003109
David Stevensc6b91c62017-02-08 14:23:58 -08003110 if (DEBUG_TASKS && affinityMatch == null) Slog.d(TAG_TASKS, "No task found");
3111 return affinityMatch;
Craig Mautner8849a5e2013-04-02 16:41:03 -07003112 }
3113
Winson Chung91e5c882017-04-21 14:44:38 -07003114 /**
3115 * Checks that for the given activity {@param r}, its activity type matches the {@param stack}
3116 * type.
3117 */
3118 private boolean checkActivityBelongsInStack(ActivityRecord r, ActivityStack stack) {
3119 if (r.isHomeActivity()) {
3120 return stack.isHomeStack();
3121 } else if (r.isRecentsActivity()) {
3122 return stack.isRecentsStack();
3123 } else if (r.isAssistantActivity()) {
3124 return stack.isAssistantStack();
3125 }
3126 return true;
3127 }
3128
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003129 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
3130 boolean compareIntentFilters) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003131 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3132 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003133 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Andrii Kuliand3bbb132016-06-16 16:00:20 -07003134 final ActivityRecord ar = stacks.get(stackNdx)
3135 .findActivityLocked(intent, info, compareIntentFilters);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003136 if (ar != null) {
3137 return ar;
3138 }
Craig Mautner8849a5e2013-04-02 16:41:03 -07003139 }
3140 }
3141 return null;
3142 }
3143
David Stevensf62360c2017-03-16 19:00:20 -07003144 boolean hasAwakeDisplay() {
3145 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3146 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3147 if (!display.shouldSleep()) {
3148 return true;
3149 }
3150 }
3151 return false;
3152 }
3153
Craig Mautner8d341ef2013-03-26 09:03:27 -07003154 void goingToSleepLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003155 scheduleSleepTimeout();
3156 if (!mGoingToSleep.isHeld()) {
3157 mGoingToSleep.acquire();
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003158 if (mLaunchingActivity.isHeld()) {
3159 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) {
3160 throw new IllegalStateException("Calling must be system uid");
Craig Mautner0eea92c2013-05-16 13:35:39 -07003161 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07003162 mLaunchingActivity.release();
3163 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003164 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003165 }
David Stevensf62360c2017-03-16 19:00:20 -07003166
3167 applySleepTokensLocked(false /* applyToStacks */);
3168
3169 checkReadyForSleepLocked(true /* allowDelay */);
3170 }
3171
3172 void prepareForShutdownLocked() {
3173 for (int i = 0; i < mActivityDisplays.size(); i++) {
3174 createSleepTokenLocked("shutdown", mActivityDisplays.keyAt(i));
3175 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003176 }
3177
3178 boolean shutdownLocked(int timeout) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003179 goingToSleepLocked();
Craig Mautner0eea92c2013-05-16 13:35:39 -07003180
Craig Mautnerf4c909b2014-04-17 18:39:38 -07003181 boolean timedout = false;
Craig Mautner0eea92c2013-05-16 13:35:39 -07003182 final long endTime = System.currentTimeMillis() + timeout;
3183 while (true) {
3184 boolean cantShutdown = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003185 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3186 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003187 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
David Stevensf62360c2017-03-16 19:00:20 -07003188 cantShutdown |=
3189 stacks.get(stackNdx).goToSleepIfPossible(true /* shuttingDown */);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003190 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003191 }
3192 if (cantShutdown) {
3193 long timeRemaining = endTime - System.currentTimeMillis();
3194 if (timeRemaining > 0) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003195 try {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003196 mService.wait(timeRemaining);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003197 } catch (InterruptedException e) {
3198 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003199 } else {
3200 Slog.w(TAG, "Activity manager shutdown timed out");
3201 timedout = true;
3202 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003203 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003204 } else {
3205 break;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003206 }
3207 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003208
3209 // Force checkReadyForSleep to complete.
David Stevensf62360c2017-03-16 19:00:20 -07003210 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07003211
Craig Mautner8d341ef2013-03-26 09:03:27 -07003212 return timedout;
3213 }
3214
3215 void comeOutOfSleepIfNeededLocked() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003216 removeSleepTimeouts();
3217 if (mGoingToSleep.isHeld()) {
3218 mGoingToSleep.release();
3219 }
David Stevensf62360c2017-03-16 19:00:20 -07003220 }
3221
3222 void applySleepTokensLocked(boolean applyToStacks) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003223 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
David Stevensf62360c2017-03-16 19:00:20 -07003224 // Set the sleeping state of the display.
3225 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3226 final boolean displayShouldSleep = display.shouldSleep();
3227 if (displayShouldSleep == display.isSleeping()) {
3228 continue;
3229 }
3230 display.setIsSleeping(displayShouldSleep);
3231
3232 if (!applyToStacks) {
3233 continue;
3234 }
3235
3236 // Set the sleeping state of the stacks on the display.
3237 final ArrayList<ActivityStack> stacks = display.mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003238 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3239 final ActivityStack stack = stacks.get(stackNdx);
David Stevensf62360c2017-03-16 19:00:20 -07003240 if (displayShouldSleep) {
3241 stack.goToSleepIfPossible(false /* shuttingDown */);
3242 } else {
3243 stack.awakeFromSleepingLocked();
3244 if (isFocusedStack(stack)) {
3245 resumeFocusedStackTopActivityLocked();
3246 }
3247 }
3248 }
3249
3250 if (displayShouldSleep || mGoingToSleepActivities.isEmpty()) {
3251 continue;
3252 }
3253 // The display is awake now, so clean up the going to sleep list.
3254 for (Iterator<ActivityRecord> it = mGoingToSleepActivities.iterator(); it.hasNext(); ) {
3255 final ActivityRecord r = it.next();
3256 if (r.getDisplayId() == display.mDisplayId) {
3257 it.remove();
Craig Mautner4a1cb222013-12-04 16:14:06 -08003258 }
Craig Mautner5314a402013-09-26 12:40:16 -07003259 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003260 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003261 }
3262
3263 void activitySleptLocked(ActivityRecord r) {
3264 mGoingToSleepActivities.remove(r);
David Stevensf62360c2017-03-16 19:00:20 -07003265 final ActivityStack s = r.getStack();
3266 if (s != null) {
3267 s.checkReadyForSleep();
3268 } else {
3269 checkReadyForSleepLocked(true);
3270 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003271 }
3272
David Stevensf62360c2017-03-16 19:00:20 -07003273 void checkReadyForSleepLocked(boolean allowDelay) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07003274 if (!mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003275 // Do not care.
3276 return;
3277 }
3278
David Stevensf62360c2017-03-16 19:00:20 -07003279 if (allowDelay) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003280 boolean dontSleep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003281 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
David Stevensf62360c2017-03-16 19:00:20 -07003282 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
3283 final ArrayList<ActivityStack> stacks = display.mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003284 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
David Stevensf62360c2017-03-16 19:00:20 -07003285 dontSleep |= stacks.get(stackNdx).goToSleepIfPossible(false /* shuttingDown */);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003286 }
Craig Mautner0eea92c2013-05-16 13:35:39 -07003287 }
3288
Craig Mautner0eea92c2013-05-16 13:35:39 -07003289 if (dontSleep) {
3290 return;
3291 }
3292 }
3293
Wei Wang65c7a152016-06-02 18:51:22 -07003294 // Send launch end powerhint before going sleep
3295 mService.mActivityStarter.sendPowerHintForLaunchEndIfNeeded();
3296
Craig Mautner0eea92c2013-05-16 13:35:39 -07003297 removeSleepTimeouts();
3298
3299 if (mGoingToSleep.isHeld()) {
3300 mGoingToSleep.release();
3301 }
3302 if (mService.mShuttingDown) {
3303 mService.notifyAll();
3304 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003305 }
3306
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003307 boolean reportResumedActivityLocked(ActivityRecord r) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07003308 final ActivityStack stack = r.getStack();
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003309 if (isFocusedStack(stack)) {
Jeff Sharkey5782da72013-04-25 14:32:30 -07003310 mService.updateUsageStats(r, true);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003311 }
3312 if (allResumedActivitiesComplete()) {
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003313 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003314 mWindowManager.executeAppTransition();
3315 return true;
3316 }
3317 return false;
3318 }
3319
Craig Mautner8d341ef2013-03-26 09:03:27 -07003320 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003321 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3322 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Wale Ogunwale28b23972015-07-29 16:01:50 -07003323 int stackNdx = stacks.size() - 1;
3324 while (stackNdx >= 0) {
3325 stacks.get(stackNdx).handleAppCrashLocked(app);
3326 stackNdx--;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003327 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003328 }
3329 }
3330
Craig Mautnerbb742462014-07-07 15:28:55 -07003331 // Called when WindowManager has finished animating the launchingBehind activity to the back.
Andrii Kulian21713ac2016-10-12 22:05:05 -07003332 private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003333 final TaskRecord task = r.getTask();
Andrii Kulian02b7a832016-10-06 23:11:56 -07003334 final ActivityStack stack = task.getStack();
Winson730bf062016-03-31 18:04:56 -07003335
3336 r.mLaunchTaskBehind = false;
Andrii Kulian21713ac2016-10-12 22:05:05 -07003337 task.setLastThumbnailLocked(r.screenshotActivityLocked());
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08003338 mRecentTasks.addLocked(task);
Yorke Leebd54c2a2016-10-25 13:49:23 -07003339 mService.mTaskChangeNotificationController.notifyTaskStackChanged();
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003340 r.setVisibility(false);
Winson730bf062016-03-31 18:04:56 -07003341
3342 // When launching tasks behind, update the last active time of the top task after the new
3343 // task has been shown briefly
3344 final ActivityRecord top = stack.topActivity();
3345 if (top != null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003346 top.getTask().touchActiveTime();
Winson730bf062016-03-31 18:04:56 -07003347 }
Craig Mautnerbb742462014-07-07 15:28:55 -07003348 }
3349
3350 void scheduleLaunchTaskBehindComplete(IBinder token) {
3351 mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget();
3352 }
3353
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07003354 void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
3355 boolean preserveWindows) {
Jorim Jaggife762342016-10-13 14:33:27 +02003356 mKeyguardController.beginActivityVisibilityUpdate();
3357 try {
3358 // First the front stacks. In case any are not fullscreen and are in front of home.
3359 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3360 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3361 final int topStackNdx = stacks.size() - 1;
3362 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3363 final ActivityStack stack = stacks.get(stackNdx);
3364 stack.ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows);
3365 }
Craig Mautner580ea812013-04-25 12:58:38 -07003366 }
Jorim Jaggife762342016-10-13 14:33:27 +02003367 } finally {
3368 mKeyguardController.endActivityVisibilityUpdate();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003369 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003370 }
3371
Jorim Jaggi8b702ed2017-01-20 16:59:03 +01003372 void addStartingWindowsForVisibleActivities(boolean taskSwitch) {
3373 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3374 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3375 final int topStackNdx = stacks.size() - 1;
3376 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3377 final ActivityStack stack = stacks.get(stackNdx);
3378 stack.addStartingWindowsForVisibleActivities(taskSwitch);
3379 }
3380 }
3381 }
3382
Chong Zhangfdcc4d42015-10-14 16:50:12 -07003383 void invalidateTaskLayers() {
3384 mTaskLayersChanged = true;
3385 }
3386
3387 void rankTaskLayersIfNeeded() {
3388 if (!mTaskLayersChanged) {
3389 return;
3390 }
3391 mTaskLayersChanged = false;
3392 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); displayNdx++) {
3393 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3394 int baseLayer = 0;
3395 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3396 baseLayer += stacks.get(stackNdx).rankTaskLayers(baseLayer);
3397 }
3398 }
3399 }
3400
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07003401 void clearOtherAppTimeTrackers(AppTimeTracker except) {
3402 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3403 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3404 final int topStackNdx = stacks.size() - 1;
3405 for (int stackNdx = topStackNdx; stackNdx >= 0; --stackNdx) {
3406 final ActivityStack stack = stacks.get(stackNdx);
3407 stack.clearOtherAppTimeTrackers(except);
3408 }
3409 }
3410 }
3411
Craig Mautner8d341ef2013-03-26 09:03:27 -07003412 void scheduleDestroyAllActivities(ProcessRecord app, String reason) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003413 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3414 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003415 final int numStacks = stacks.size();
3416 for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
3417 final ActivityStack stack = stacks.get(stackNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003418 stack.scheduleDestroyActivities(app, reason);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003419 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003420 }
3421 }
3422
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003423 void releaseSomeActivitiesLocked(ProcessRecord app, String reason) {
3424 // Examine all activities currently running in the process.
3425 TaskRecord firstTask = null;
3426 // Tasks is non-null only if two or more tasks are found.
3427 ArraySet<TaskRecord> tasks = null;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003428 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
3429 for (int i = 0; i < app.activities.size(); i++) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003430 ActivityRecord r = app.activities.get(i);
3431 // First, if we find an activity that is in the process of being destroyed,
3432 // then we just aren't going to do anything for now; we want things to settle
3433 // down before we try to prune more activities.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003434 if (r.finishing || r.state == DESTROYING || r.state == DESTROYED) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003435 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Abort release; already destroying: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003436 return;
3437 }
3438 // Don't consider any activies that are currently not in a state where they
3439 // can be destroyed.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003440 if (r.visible || !r.stopped || !r.haveState || r.state == RESUMED || r.state == PAUSING
3441 || r.state == PAUSED || r.state == STOPPING) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003442 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003443 continue;
3444 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003445
3446 final TaskRecord task = r.getTask();
3447 if (task != null) {
3448 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Collecting release task " + task
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003449 + " from " + r);
3450 if (firstTask == null) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003451 firstTask = task;
3452 } else if (firstTask != task) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003453 if (tasks == null) {
3454 tasks = new ArraySet<>();
3455 tasks.add(firstTask);
3456 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003457 tasks.add(task);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003458 }
3459 }
3460 }
3461 if (tasks == null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003462 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release");
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003463 return;
3464 }
3465 // If we have activities in multiple tasks that are in a position to be destroyed,
3466 // let's iterate through the tasks and release the oldest one.
3467 final int numDisplays = mActivityDisplays.size();
3468 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3469 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3470 // Step through all stacks starting from behind, to hit the oldest things first.
3471 for (int stackNdx = 0; stackNdx < stacks.size(); stackNdx++) {
3472 final ActivityStack stack = stacks.get(stackNdx);
3473 // Try to release activities in this stack; if we manage to, we are done.
3474 if (stack.releaseSomeActivitiesLocked(app, tasks, reason) > 0) {
3475 return;
3476 }
3477 }
3478 }
3479 }
3480
Amith Yamasani37a40c22015-06-17 13:25:42 -07003481 boolean switchUserLocked(int userId, UserState uss) {
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003482 final int focusStackId = mFocusedStack.getStackId();
3483 // We dismiss the docked stack whenever we switch users.
3484 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, focusStackId == DOCKED_STACK_ID);
Winson Chungc2b23a52017-01-09 15:44:55 -08003485 // Also dismiss the pinned stack whenever we switch users. Removing the pinned stack will
3486 // also cause all tasks to be moved to the fullscreen stack at a position that is
3487 // appropriate.
3488 removeStackLocked(PINNED_STACK_ID);
Wale Ogunwale9a98c522016-04-27 09:23:55 -07003489
3490 mUserStackInFront.put(mCurrentUser, focusStackId);
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003491 final int restoreStackId = mUserStackInFront.get(userId, HOME_STACK_ID);
Craig Mautner2420ead2013-04-01 17:13:20 -07003492 mCurrentUser = userId;
Craig Mautnerac6f8432013-07-17 13:24:59 -07003493
Craig Mautner858d8a62013-04-23 17:08:34 -07003494 mStartingUsers.add(uss);
Craig Mautnere0a38842013-12-16 16:14:02 -08003495 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3496 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003497 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003498 final ActivityStack stack = stacks.get(stackNdx);
3499 stack.switchUserLocked(userId);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003500 TaskRecord task = stack.topTask();
3501 if (task != null) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08003502 stack.positionChildWindowContainerAtTop(task);
Alexandra Gherghinadae57a12014-03-12 19:15:26 +00003503 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003504 }
Craig Mautnerac6f8432013-07-17 13:24:59 -07003505 }
Craig Mautner858d8a62013-04-23 17:08:34 -07003506
Craig Mautner4f1df4f2013-10-15 15:44:14 -07003507 ActivityStack stack = getStack(restoreStackId);
3508 if (stack == null) {
3509 stack = mHomeStack;
3510 }
3511 final boolean homeInFront = stack.isHomeStack();
Craig Mautnere0a38842013-12-16 16:14:02 -08003512 if (stack.isOnHomeDisplay()) {
Wale Ogunwale925d0d12015-09-23 15:40:07 -07003513 stack.moveToFront("switchUserOnHomeDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003514 } else {
3515 // Stack was moved to another display while user was swapped out.
Matthew Ngae1ff4f2016-11-10 15:49:14 -08003516 resumeHomeStackTask(null, "switchUserOnOtherDisplay");
Craig Mautnere0a38842013-12-16 16:14:02 -08003517 }
Craig Mautner93529a42013-10-04 15:03:13 -07003518 return homeInFront;
Craig Mautner2219a1b2013-03-25 09:44:30 -07003519 }
3520
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003521 /** Checks whether the userid is a profile of the current user. */
3522 boolean isCurrentProfileLocked(int userId) {
3523 if (userId == mCurrentUser) return true;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07003524 return mService.mUserController.isCurrentProfileLocked(userId);
Wale Ogunwale0bd2aa72015-04-16 13:50:44 -07003525 }
3526
Bryce Leeb7c9b802017-05-02 14:20:24 -07003527 /**
3528 * Returns whether a stopping activity is present that should be stopped after visible, rather
3529 * than idle.
3530 * @return {@code true} if such activity is present. {@code false} otherwise.
3531 */
3532 boolean isStoppingNoHistoryActivity() {
3533 // Activities that are marked as nohistory should be stopped immediately after the resumed
3534 // activity has become visible.
3535 for (ActivityRecord record : mStoppingActivities) {
3536 if (record.isNoHistory()) {
3537 return true;
3538 }
3539 }
3540
3541 return false;
3542 }
3543
Winson Chung4dabf232017-01-25 13:25:22 -08003544 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
3545 boolean remove, boolean processPausingActivities) {
Craig Mautnerde4ef022013-04-07 19:01:33 -07003546 ArrayList<ActivityRecord> stops = null;
3547
3548 final boolean nowVisible = allResumedActivitiesVisible();
Craig Mautner8c14c152015-01-15 17:32:07 -08003549 for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3550 ActivityRecord s = mStoppingActivities.get(activityNdx);
Bryce Lee4a194382017-04-04 14:32:48 -07003551 boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003552 if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
Craig Mautner8c14c152015-01-15 17:32:07 -08003553 + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
3554 if (waitingVisible && nowVisible) {
Bryce Lee4a194382017-04-04 14:32:48 -07003555 mActivitiesWaitingForVisibleActivity.remove(s);
Andrii Kulianee056812016-09-21 15:34:45 -07003556 waitingVisible = false;
Craig Mautnerde4ef022013-04-07 19:01:33 -07003557 if (s.finishing) {
3558 // If this activity is finishing, it is sitting on top of
3559 // everyone else but we now know it is no longer needed...
3560 // so get rid of it. Otherwise, we need to go through the
3561 // normal flow and hide it once we determine that it is
3562 // hidden by the activities in front of it.
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08003563 if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08003564 s.setVisibility(false);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003565 }
3566 }
David Stevensf62360c2017-03-16 19:00:20 -07003567 if (remove) {
3568 final ActivityStack stack = s.getStack();
3569 final boolean shouldSleepOrShutDown = stack != null
3570 ? stack.shouldSleepOrShutDownActivities()
3571 : mService.isSleepingOrShuttingDownLocked();
3572 if (!waitingVisible || shouldSleepOrShutDown) {
3573 if (!processPausingActivities && s.state == PAUSING) {
3574 // Defer processing pausing activities in this iteration and reschedule
3575 // a delayed idle to reprocess it again
3576 removeTimeoutsForActivityLocked(idleActivity);
3577 scheduleIdleTimeoutLocked(idleActivity);
3578 continue;
3579 }
Winson Chung4dabf232017-01-25 13:25:22 -08003580
David Stevensf62360c2017-03-16 19:00:20 -07003581 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
3582 if (stops == null) {
3583 stops = new ArrayList<>();
3584 }
3585 stops.add(s);
3586 mStoppingActivities.remove(activityNdx);
Craig Mautnerde4ef022013-04-07 19:01:33 -07003587 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07003588 }
3589 }
3590
3591 return stops;
3592 }
3593
Craig Mautnercf910b02013-04-23 11:23:27 -07003594 void validateTopActivitiesLocked() {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003595 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
3596 final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3597 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3598 final ActivityStack stack = stacks.get(stackNdx);
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07003599 final ActivityRecord r = stack.topRunningActivityLocked();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003600 final ActivityState state = r == null ? DESTROYED : r.state;
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07003601 if (isFocusedStack(stack)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003602 if (r == null) Slog.e(TAG,
3603 "validateTop...: null top activity, stack=" + stack);
3604 else {
3605 final ActivityRecord pausing = stack.mPausingActivity;
3606 if (pausing != null && pausing == r) Slog.e(TAG,
3607 "validateTop...: top stack has pausing activity r=" + r
3608 + " state=" + state);
3609 if (state != INITIALIZING && state != RESUMED) Slog.e(TAG,
3610 "validateTop...: activity in front not resumed r=" + r
3611 + " state=" + state);
3612 }
Craig Mautnercf910b02013-04-23 11:23:27 -07003613 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003614 final ActivityRecord resumed = stack.mResumedActivity;
3615 if (resumed != null && resumed == r) Slog.e(TAG,
3616 "validateTop...: back stack has resumed activity r=" + r
3617 + " state=" + state);
3618 if (r != null && (state == INITIALIZING || state == RESUMED)) Slog.e(TAG,
3619 "validateTop...: activity in back resumed r=" + r + " state=" + state);
Craig Mautnercf910b02013-04-23 11:23:27 -07003620 }
3621 }
3622 }
Craig Mautner76ea2242013-05-15 11:40:05 -07003623 }
3624
Craig Mautnere0570202015-05-13 13:06:11 -07003625 private String lockTaskModeToString() {
3626 switch (mLockTaskModeState) {
3627 case LOCK_TASK_MODE_LOCKED:
3628 return "LOCKED";
3629 case LOCK_TASK_MODE_PINNED:
3630 return "PINNED";
3631 case LOCK_TASK_MODE_NONE:
3632 return "NONE";
3633 default: return "unknown=" + mLockTaskModeState;
3634 }
3635 }
3636
Craig Mautner27084302013-03-25 08:05:25 -07003637 public void dump(PrintWriter pw, String prefix) {
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003638 pw.print(prefix); pw.print("mFocusedStack=" + mFocusedStack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003639 pw.print(" mLastFocusedStack="); pw.println(mLastFocusedStack);
Suprabh Shukla09a88f52015-12-02 14:36:31 -08003640 pw.print(prefix);
3641 pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser);
Craig Mautnerd1bbdb4622013-10-22 09:53:20 -07003642 pw.print(prefix); pw.println("mUserStackInFront=" + mUserStackInFront);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003643 pw.print(prefix); pw.println("mStacks=" + mStacks);
Craig Mautnere0570202015-05-13 13:06:11 -07003644 pw.print(prefix); pw.print("mLockTaskModeState=" + lockTaskModeToString());
Jorim Jaggi8d786932016-10-26 19:08:36 -07003645 final SparseArray<String[]> packages = mService.mLockTaskPackages;
3646 if (packages.size() > 0) {
3647 pw.print(prefix); pw.println("mLockTaskPackages (userId:packages)=");
3648 for (int i = 0; i < packages.size(); ++i) {
3649 pw.print(prefix); pw.print(prefix); pw.print(packages.keyAt(i));
3650 pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
3651 }
3652 }
Bryce Lee4a194382017-04-04 14:32:48 -07003653 if (!mWaitingForActivityVisible.isEmpty()) {
3654 pw.print(prefix); pw.println("mWaitingForActivityVisible=");
3655 for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
3656 pw.print(prefix); pw.print(prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
3657 }
3658 }
3659
Jorim Jaggi8d786932016-10-26 19:08:36 -07003660 pw.println(" mLockTaskModeTasks" + mLockTaskModeTasks);
3661 mKeyguardController.dump(pw, prefix);
Craig Mautner27084302013-03-25 08:05:25 -07003662 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07003663
Winson43d1f262016-06-14 16:05:55 -07003664 /**
Andrii Kulian5406e7a2016-10-21 11:55:23 -07003665 * Dump all connected displays' configurations.
3666 * @param prefix Prefix to apply to each line of the dump.
3667 */
3668 void dumpDisplayConfigs(PrintWriter pw, String prefix) {
3669 pw.print(prefix); pw.println("Display override configurations:");
3670 final int displayCount = mActivityDisplays.size();
3671 for (int i = 0; i < displayCount; i++) {
3672 final ActivityDisplay activityDisplay = mActivityDisplays.valueAt(i);
3673 pw.print(prefix); pw.print(" "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
3674 pw.println(activityDisplay.getOverrideConfiguration());
3675 }
3676 }
3677
3678 /**
Winson43d1f262016-06-14 16:05:55 -07003679 * Dumps the activities matching the given {@param name} in the either the focused stack
3680 * or all visible stacks if {@param dumpVisibleStacks} is true.
3681 */
Winson Chung6998bc42017-02-28 17:07:05 -08003682 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name, boolean dumpVisibleStacksOnly,
3683 boolean dumpFocusedStackOnly) {
3684 if (dumpFocusedStackOnly) {
3685 return mFocusedStack.getDumpActivitiesLocked(name);
3686 } else {
Winson43d1f262016-06-14 16:05:55 -07003687 ArrayList<ActivityRecord> activities = new ArrayList<>();
3688 int numDisplays = mActivityDisplays.size();
3689 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
3690 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
3691 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
3692 ActivityStack stack = stacks.get(stackNdx);
Winson Chung6998bc42017-02-28 17:07:05 -08003693 if (!dumpVisibleStacksOnly ||
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07003694 stack.shouldBeVisible(null) == STACK_VISIBLE) {
Winson43d1f262016-06-14 16:05:55 -07003695 activities.addAll(stack.getDumpActivitiesLocked(name));
3696 }
3697 }
3698 }
3699 return activities;
Winson43d1f262016-06-14 16:05:55 -07003700 }
Craig Mautner20e72272013-04-01 13:45:53 -07003701 }
3702
Dianne Hackborn390517b2013-05-30 15:03:32 -07003703 static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage,
3704 boolean needSep, String prefix) {
3705 if (activity != null) {
3706 if (dumpPackage == null || dumpPackage.equals(activity.packageName)) {
3707 if (needSep) {
3708 pw.println();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003709 }
3710 pw.print(prefix);
3711 pw.println(activity);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003712 return true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003713 }
3714 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003715 return false;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003716 }
3717
Craig Mautner8d341ef2013-03-26 09:03:27 -07003718 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3719 boolean dumpClient, String dumpPackage) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003720 boolean printed = false;
3721 boolean needSep = false;
Craig Mautnere0a38842013-12-16 16:14:02 -08003722 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
3723 ActivityDisplay activityDisplay = mActivityDisplays.valueAt(displayNdx);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003724 pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
Craig Mautner737fae22014-10-15 12:52:10 -07003725 pw.println(" (activities from top to bottom):");
Craig Mautnere0a38842013-12-16 16:14:02 -08003726 ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
Craig Mautner737fae22014-10-15 12:52:10 -07003727 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003728 final ActivityStack stack = stacks.get(stackNdx);
3729 StringBuilder stackHeader = new StringBuilder(128);
3730 stackHeader.append(" Stack #");
3731 stackHeader.append(stack.mStackId);
3732 stackHeader.append(":");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003733 stackHeader.append("\n");
3734 stackHeader.append(" mFullscreen=" + stack.mFullscreen);
3735 stackHeader.append("\n");
David Stevensf62360c2017-03-16 19:00:20 -07003736 stackHeader.append(" isSleeping=" + stack.shouldSleepActivities());
3737 stackHeader.append("\n");
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07003738 stackHeader.append(" mBounds=" + stack.mBounds);
Winson Chungabb433b2017-03-24 09:35:42 -07003739
3740 final boolean printedStackHeader = stack.dumpActivitiesLocked(fd, pw, dumpAll,
3741 dumpClient, dumpPackage, needSep, stackHeader.toString());
3742 printed |= printedStackHeader;
3743 if (!printedStackHeader) {
3744 // Ensure we always dump the stack header even if there are no activities
3745 pw.println();
3746 pw.println(stackHeader);
3747 }
3748
Craig Mautner4a1cb222013-12-04 16:14:06 -08003749 printed |= dumpHistoryList(fd, pw, stack.mLRUActivities, " ", "Run", false,
3750 !dumpAll, false, dumpPackage, true,
3751 " Running activities (most recent first):", null);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003752
Craig Mautner4a1cb222013-12-04 16:14:06 -08003753 needSep = printed;
3754 boolean pr = printThisActivity(pw, stack.mPausingActivity, dumpPackage, needSep,
3755 " mPausingActivity: ");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003756 if (pr) {
3757 printed = true;
Craig Mautner4a1cb222013-12-04 16:14:06 -08003758 needSep = false;
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003759 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003760 pr = printThisActivity(pw, stack.mResumedActivity, dumpPackage, needSep,
3761 " mResumedActivity: ");
3762 if (pr) {
3763 printed = true;
3764 needSep = false;
3765 }
3766 if (dumpAll) {
3767 pr = printThisActivity(pw, stack.mLastPausedActivity, dumpPackage, needSep,
3768 " mLastPausedActivity: ");
3769 if (pr) {
3770 printed = true;
3771 needSep = true;
3772 }
3773 printed |= printThisActivity(pw, stack.mLastNoHistoryActivity, dumpPackage,
3774 needSep, " mLastNoHistoryActivity: ");
3775 }
3776 needSep = printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003777 }
3778 }
3779
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003780 printed |= dumpHistoryList(fd, pw, mFinishingActivities, " ", "Fin", false, !dumpAll,
3781 false, dumpPackage, true, " Activities waiting to finish:", null);
3782 printed |= dumpHistoryList(fd, pw, mStoppingActivities, " ", "Stop", false, !dumpAll,
3783 false, dumpPackage, true, " Activities waiting to stop:", null);
Bryce Lee4a194382017-04-04 14:32:48 -07003784 printed |= dumpHistoryList(fd, pw, mActivitiesWaitingForVisibleActivity, " ", "Wait",
3785 false, !dumpAll, false, dumpPackage, true,
3786 " Activities waiting for another to become visible:", null);
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003787 printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, " ", "Sleep", false, !dumpAll,
3788 false, dumpPackage, true, " Activities waiting to sleep:", null);
Craig Mautnerf3333272013-04-22 10:55:53 -07003789
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003790 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003791 }
3792
Dianne Hackborn390517b2013-05-30 15:03:32 -07003793 static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list,
Craig Mautner8d341ef2013-03-26 09:03:27 -07003794 String prefix, String label, boolean complete, boolean brief, boolean client,
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003795 String dumpPackage, boolean needNL, String header1, String header2) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07003796 TaskRecord lastTask = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003797 String innerPrefix = null;
3798 String[] args = null;
3799 boolean printed = false;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003800 for (int i=list.size()-1; i>=0; i--) {
3801 final ActivityRecord r = list.get(i);
3802 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
3803 continue;
3804 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003805 if (innerPrefix == null) {
3806 innerPrefix = prefix + " ";
3807 args = new String[0];
3808 }
3809 printed = true;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003810 final boolean full = !brief && (complete || !r.isInHistory());
3811 if (needNL) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003812 pw.println("");
Craig Mautner8d341ef2013-03-26 09:03:27 -07003813 needNL = false;
3814 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003815 if (header1 != null) {
3816 pw.println(header1);
3817 header1 = null;
3818 }
3819 if (header2 != null) {
3820 pw.println(header2);
3821 header2 = null;
Dianne Hackborn390517b2013-05-30 15:03:32 -07003822 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003823 if (lastTask != r.getTask()) {
3824 lastTask = r.getTask();
Craig Mautner8d341ef2013-03-26 09:03:27 -07003825 pw.print(prefix);
3826 pw.print(full ? "* " : " ");
3827 pw.println(lastTask);
3828 if (full) {
3829 lastTask.dump(pw, prefix + " ");
3830 } else if (complete) {
3831 // Complete + brief == give a summary. Isn't that obvious?!?
3832 if (lastTask.intent != null) {
3833 pw.print(prefix); pw.print(" ");
3834 pw.println(lastTask.intent.toInsecureStringWithClip());
3835 }
3836 }
3837 }
3838 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
3839 pw.print(" #"); pw.print(i); pw.print(": ");
3840 pw.println(r);
3841 if (full) {
3842 r.dump(pw, innerPrefix);
3843 } else if (complete) {
3844 // Complete + brief == give a summary. Isn't that obvious?!?
3845 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
3846 if (r.app != null) {
3847 pw.print(innerPrefix); pw.println(r.app);
3848 }
3849 }
3850 if (client && r.app != null && r.app.thread != null) {
3851 // flush anything that is already in the PrintWriter since the thread is going
3852 // to write to the file descriptor directly
3853 pw.flush();
3854 try {
3855 TransferPipe tp = new TransferPipe();
3856 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003857 r.app.thread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
Craig Mautner8d341ef2013-03-26 09:03:27 -07003858 // Short timeout, since blocking here can
3859 // deadlock with the application.
3860 tp.go(fd, 2000);
3861 } finally {
3862 tp.kill();
3863 }
3864 } catch (IOException e) {
3865 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
3866 } catch (RemoteException e) {
3867 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
3868 }
3869 needNL = true;
3870 }
3871 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003872 return printed;
Craig Mautner8d341ef2013-03-26 09:03:27 -07003873 }
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07003874
Craig Mautnerf3333272013-04-22 10:55:53 -07003875 void scheduleIdleTimeoutLocked(ActivityRecord next) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003876 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
3877 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4));
Craig Mautnerc64f73e2013-04-24 16:44:56 -07003878 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next);
3879 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
Craig Mautnerf3333272013-04-22 10:55:53 -07003880 }
3881
3882 final void scheduleIdleLocked() {
Craig Mautner05d29032013-05-03 13:40:13 -07003883 mHandler.sendEmptyMessage(IDLE_NOW_MSG);
Craig Mautnerf3333272013-04-22 10:55:53 -07003884 }
3885
3886 void removeTimeoutsForActivityLocked(ActivityRecord r) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003887 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers="
3888 + Debug.getCallers(4));
Craig Mautnerf3333272013-04-22 10:55:53 -07003889 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3890 }
3891
Craig Mautner05d29032013-05-03 13:40:13 -07003892 final void scheduleResumeTopActivities() {
Craig Mautner34b73df2014-01-12 21:11:08 -08003893 if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) {
3894 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
3895 }
Craig Mautner05d29032013-05-03 13:40:13 -07003896 }
3897
Craig Mautner0eea92c2013-05-16 13:35:39 -07003898 void removeSleepTimeouts() {
Craig Mautner0eea92c2013-05-16 13:35:39 -07003899 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
3900 }
3901
3902 final void scheduleSleepTimeout() {
3903 removeSleepTimeouts();
3904 mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT);
3905 }
3906
Craig Mautner4a1cb222013-12-04 16:14:06 -08003907 @Override
3908 public void onDisplayAdded(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003909 if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003910 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_ADDED, displayId, 0));
3911 }
3912
3913 @Override
3914 public void onDisplayRemoved(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003915 if (DEBUG_STACK) Slog.v(TAG, "Display removed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003916 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_REMOVED, displayId, 0));
3917 }
3918
3919 @Override
3920 public void onDisplayChanged(int displayId) {
Dianne Hackbornfb81d092015-08-03 17:14:46 -07003921 if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003922 mHandler.sendMessage(mHandler.obtainMessage(HANDLE_DISPLAY_CHANGED, displayId, 0));
3923 }
3924
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003925 private void handleDisplayAdded(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08003926 synchronized (mService) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003927 getActivityDisplayOrCreateLocked(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08003928 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003929 }
3930
Andrii Kulianca007a62016-11-22 16:33:28 -08003931 /** Check if display with specified id is added to the list. */
3932 boolean isDisplayAdded(int displayId) {
Andrii Kulian62e6f252017-05-30 22:46:53 -07003933 return getActivityDisplayOrCreateLocked(displayId) != null;
3934 }
3935
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07003936 ActivityDisplay getActivityDisplay(int displayId) {
3937 return mActivityDisplays.get(displayId);
3938 }
3939
Andrii Kulian62e6f252017-05-30 22:46:53 -07003940 /**
3941 * Get an existing instance of {@link ActivityDisplay} or create new if there is a
3942 * corresponding record in display manager.
3943 */
3944 private ActivityDisplay getActivityDisplayOrCreateLocked(int displayId) {
3945 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3946 if (activityDisplay != null) {
3947 return activityDisplay;
3948 }
3949 if (mDisplayManager == null) {
3950 // The system isn't fully initialized yet.
3951 return null;
3952 }
3953 final Display display = mDisplayManager.getDisplay(displayId);
3954 if (display == null) {
3955 // The display is not registered in DisplayManager.
3956 return null;
3957 }
3958 // The display hasn't been added to ActivityManager yet, create a new record now.
3959 activityDisplay = new ActivityDisplay(displayId);
3960 if (activityDisplay.mDisplay == null) {
3961 Slog.w(TAG, "Display " + displayId + " gone before initialization complete");
3962 return null;
3963 }
3964 mActivityDisplays.put(displayId, activityDisplay);
3965 calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
3966 mWindowManager.onDisplayAdded(displayId);
3967 return activityDisplay;
Andrii Kulianca007a62016-11-22 16:33:28 -08003968 }
3969
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003970 private void calculateDefaultMinimalSizeOfResizeableTasks(ActivityDisplay display) {
Andrii Kulianf66a83d2016-05-17 12:17:44 -07003971 mDefaultMinSizeOfResizeableTask =
Jorim Jaggi19cf2972016-04-07 23:26:10 -07003972 mService.mContext.getResources().getDimensionPixelSize(
3973 com.android.internal.R.dimen.default_minimal_size_resizable_task);
Filip Gruszczynskid2f1d942015-10-14 15:10:12 -07003974 }
3975
Wale Ogunwalef16a2812015-04-01 11:23:15 -07003976 private void handleDisplayRemoved(int displayId) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003977 if (displayId == DEFAULT_DISPLAY) {
3978 throw new IllegalArgumentException("Can't remove the primary display.");
3979 }
3980
Craig Mautner4a1cb222013-12-04 16:14:06 -08003981 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08003982 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
3983 if (activityDisplay != null) {
Andrii Kulian250d6532017-02-08 23:30:45 -08003984 final boolean destroyContentOnRemoval
3985 = activityDisplay.shouldDestroyContentOnRemove();
Andrii Kuliana33818c2017-02-16 16:11:30 -08003986 final ArrayList<ActivityStack> stacks = activityDisplay.mStacks;
3987 while (!stacks.isEmpty()) {
3988 final ActivityStack stack = stacks.get(0);
Andrii Kulian250d6532017-02-08 23:30:45 -08003989 if (destroyContentOnRemoval) {
Andrii Kuliana33818c2017-02-16 16:11:30 -08003990 moveStackToDisplayLocked(stack.mStackId, DEFAULT_DISPLAY,
3991 false /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003992 stack.finishAllActivitiesLocked(true /* immediately */);
Andrii Kuliana33818c2017-02-16 16:11:30 -08003993 } else {
3994 // Moving all tasks to fullscreen stack, because it's guaranteed to be
3995 // a valid launch stack for all activities. This way the task history from
3996 // external display will be preserved on primary after move.
3997 moveTasksToFullscreenStackLocked(stack.getStackId(), true /* onTop */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003998 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08003999 }
David Stevensf62360c2017-03-16 19:00:20 -07004000
4001 releaseSleepTokens(activityDisplay);
4002
Craig Mautnere0a38842013-12-16 16:14:02 -08004003 mActivityDisplays.remove(displayId);
Bryce Leeaf3a4002017-03-20 10:37:12 -07004004 mWindowManager.onDisplayRemoved(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004005 }
4006 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004007 }
4008
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004009 private void handleDisplayChanged(int displayId) {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004010 synchronized (mService) {
Craig Mautnere0a38842013-12-16 16:14:02 -08004011 ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
4012 if (activityDisplay != null) {
David Stevensf62360c2017-03-16 19:00:20 -07004013 // The window policy is responsible for stopping activities on the default display
4014 if (displayId != Display.DEFAULT_DISPLAY) {
4015 int displayState = activityDisplay.mDisplay.getState();
4016 if (displayState == Display.STATE_OFF && activityDisplay.mOffToken == null) {
4017 activityDisplay.mOffToken =
4018 mService.acquireSleepToken("Display-off", displayId);
4019 } else if (displayState == Display.STATE_ON
4020 && activityDisplay.mOffToken != null) {
4021 activityDisplay.mOffToken.release();
4022 activityDisplay.mOffToken = null;
4023 }
4024 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004025 // TODO: Update the bounds.
4026 }
Bryce Leeaf3a4002017-03-20 10:37:12 -07004027 mWindowManager.onDisplayChanged(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004028 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004029 }
4030
David Stevensf62360c2017-03-16 19:00:20 -07004031 SleepToken createSleepTokenLocked(String tag, int displayId) {
4032 ActivityDisplay display = mActivityDisplays.get(displayId);
4033 if (display == null) {
4034 throw new IllegalArgumentException("Invalid display: " + displayId);
4035 }
4036
4037 final SleepTokenImpl token = new SleepTokenImpl(tag, displayId);
4038 mSleepTokens.add(token);
4039 display.mAllSleepTokens.add(token);
4040 return token;
4041 }
4042
4043 private void removeSleepTokenLocked(SleepTokenImpl token) {
4044 mSleepTokens.remove(token);
4045
4046 ActivityDisplay display = mActivityDisplays.get(token.mDisplayId);
4047 if (display != null) {
4048 display.mAllSleepTokens.remove(token);
4049 if (display.mAllSleepTokens.isEmpty()) {
4050 mService.updateSleepIfNeededLocked();
4051 }
4052 }
4053 }
4054
4055 private void releaseSleepTokens(ActivityDisplay display) {
4056 if (display.mAllSleepTokens.isEmpty()) {
4057 return;
4058 }
4059 for (SleepTokenImpl token : display.mAllSleepTokens) {
4060 mSleepTokens.remove(token);
4061 }
4062 display.mAllSleepTokens.clear();
4063
4064 mService.updateSleepIfNeededLocked();
4065 }
4066
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004067 private StackInfo getStackInfoLocked(ActivityStack stack) {
Andrii Kulian7e215d72017-04-26 18:33:28 -07004068 final int displayId = stack.mDisplayId;
4069 final ActivityDisplay display = mActivityDisplays.get(displayId);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004070 StackInfo info = new StackInfo();
Wale Ogunwale1666e312016-12-16 11:27:18 -08004071 stack.getWindowContainerBounds(info.bounds);
Andrii Kulian7e215d72017-04-26 18:33:28 -07004072 info.displayId = displayId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004073 info.stackId = stack.mStackId;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004074 info.userId = stack.mCurrentUser;
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004075 info.visible = stack.shouldBeVisible(null) == STACK_VISIBLE;
Andrii Kulian62e6f252017-05-30 22:46:53 -07004076 // A stack might be not attached to a display.
Winson529c8e42016-05-17 11:08:40 -07004077 info.position = display != null
4078 ? display.mStacks.indexOf(stack)
4079 : 0;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004080
4081 ArrayList<TaskRecord> tasks = stack.getAllTasks();
4082 final int numTasks = tasks.size();
4083 int[] taskIds = new int[numTasks];
4084 String[] taskNames = new String[numTasks];
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004085 Rect[] taskBounds = new Rect[numTasks];
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004086 int[] taskUserIds = new int[numTasks];
Craig Mautner4a1cb222013-12-04 16:14:06 -08004087 for (int i = 0; i < numTasks; ++i) {
4088 final TaskRecord task = tasks.get(i);
4089 taskIds[i] = task.taskId;
4090 taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
4091 : task.realActivity != null ? task.realActivity.flattenToString()
4092 : task.getTopActivity() != null ? task.getTopActivity().packageName
4093 : "unknown";
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004094 taskBounds[i] = new Rect();
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004095 task.getWindowContainerBounds(taskBounds[i]);
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004096 taskUserIds[i] = task.userId;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004097 }
4098 info.taskIds = taskIds;
4099 info.taskNames = taskNames;
Wale Ogunwale868a5e12015-08-02 16:19:20 -07004100 info.taskBounds = taskBounds;
Filip Gruszczynski21199bd2015-12-02 12:49:58 -08004101 info.taskUserIds = taskUserIds;
Winsond46b7272016-04-20 11:54:27 -07004102
4103 final ActivityRecord top = stack.topRunningActivityLocked();
4104 info.topActivity = top != null ? top.intent.getComponent() : null;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004105 return info;
4106 }
4107
4108 StackInfo getStackInfoLocked(int stackId) {
4109 ActivityStack stack = getStack(stackId);
4110 if (stack != null) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004111 return getStackInfoLocked(stack);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004112 }
4113 return null;
4114 }
4115
4116 ArrayList<StackInfo> getAllStackInfosLocked() {
Wale Ogunwalee4a0c572015-06-30 08:40:31 -07004117 ArrayList<StackInfo> list = new ArrayList<>();
Craig Mautnere0a38842013-12-16 16:14:02 -08004118 for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
4119 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004120 for (int ndx = stacks.size() - 1; ndx >= 0; --ndx) {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004121 list.add(getStackInfoLocked(stacks.get(ndx)));
Craig Mautner4a1cb222013-12-04 16:14:06 -08004122 }
4123 }
4124 return list;
4125 }
4126
Craig Mautner15df08a2015-04-01 12:17:18 -07004127 TaskRecord getLockedTaskLocked() {
4128 final int top = mLockTaskModeTasks.size() - 1;
4129 if (top >= 0) {
4130 return mLockTaskModeTasks.get(top);
4131 }
4132 return null;
4133 }
4134
4135 boolean isLockedTask(TaskRecord task) {
4136 return mLockTaskModeTasks.contains(task);
4137 }
4138
4139 boolean isLastLockedTask(TaskRecord task) {
4140 return mLockTaskModeTasks.size() == 1 && mLockTaskModeTasks.contains(task);
4141 }
4142
4143 void removeLockedTaskLocked(final TaskRecord task) {
Craig Mautner432f64e2015-05-20 14:59:57 -07004144 if (!mLockTaskModeTasks.remove(task)) {
4145 return;
4146 }
4147 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "removeLockedTaskLocked: removed " + task);
4148 if (mLockTaskModeTasks.isEmpty()) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004149 // Last one.
Craig Mautnere0570202015-05-13 13:06:11 -07004150 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
4151 " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
Craig Mautner15df08a2015-04-01 12:17:18 -07004152 final Message lockTaskMsg = Message.obtain();
4153 lockTaskMsg.arg1 = task.userId;
4154 lockTaskMsg.what = LOCK_TASK_END_MSG;
4155 mHandler.sendMessage(lockTaskMsg);
4156 }
4157 }
4158
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004159 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4160 int preferredDisplayId, int actualStackId) {
4161 handleNonResizableTaskIfNeeded(task, preferredStackId, preferredDisplayId, actualStackId,
Andrii Kulianc27916642016-04-12 17:59:27 -07004162 false /* forceNonResizable */);
4163 }
4164
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004165 private void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredStackId,
4166 int preferredDisplayId, int actualStackId, boolean forceNonResizable) {
4167 final boolean isSecondaryDisplayPreferred =
4168 (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY)
4169 || StackId.isDynamicStack(preferredStackId);
4170 if (((!isStackDockedInEffect(actualStackId) && preferredStackId != DOCKED_STACK_ID)
4171 && !isSecondaryDisplayPreferred) || task.isHomeTask()) {
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004172 return;
4173 }
4174
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004175 // Handle incorrect launch/move to secondary display if needed.
4176 final boolean launchOnSecondaryDisplayFailed;
4177 if (isSecondaryDisplayPreferred) {
4178 final int actualDisplayId = task.getStack().mDisplayId;
4179 if (!task.canBeLaunchedOnDisplay(actualDisplayId)) {
4180 // The task landed on an inappropriate display somehow, move it to the default
4181 // display.
4182 // TODO(multi-display): Find proper stack for the task on the default display.
4183 mService.moveTaskToStack(task.taskId, FULLSCREEN_WORKSPACE_STACK_ID,
4184 true /* toTop */);
4185 launchOnSecondaryDisplayFailed = true;
4186 } else {
4187 // The task might have landed on a display different from requested.
4188 launchOnSecondaryDisplayFailed = actualDisplayId == DEFAULT_DISPLAY
4189 || (preferredDisplayId != INVALID_DISPLAY
4190 && preferredDisplayId != actualDisplayId);
4191 }
4192 } else {
4193 // The task wasn't requested to be on a secondary display.
4194 launchOnSecondaryDisplayFailed = false;
4195 }
4196
Jorim Jaggicd13d332016-04-27 15:40:20 -07004197 final ActivityRecord topActivity = task.getTopActivity();
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004198 if (launchOnSecondaryDisplayFailed || !task.supportsSplitScreen() || forceNonResizable) {
4199 if (launchOnSecondaryDisplayFailed) {
4200 // Display a warning toast that we tried to put a non-resizeable task on a secondary
4201 // display with config different from global config.
4202 mService.mTaskChangeNotificationController
4203 .notifyActivityLaunchOnSecondaryDisplayFailed();
4204 } else {
4205 // Display a warning toast that we tried to put a non-dockable task in the docked
4206 // stack.
4207 mService.mTaskChangeNotificationController.notifyActivityDismissingDockedStack();
4208 }
Jorim Jaggid53f0922016-04-06 22:16:23 -07004209
Andrii Kulianc27916642016-04-12 17:59:27 -07004210 // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
4211 // we need to move it to top of fullscreen stack, otherwise it will be covered.
Wale Ogunwale9a98c522016-04-27 09:23:55 -07004212 moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
Winson Chungd3395382016-12-13 11:49:09 -08004213 } else if (topActivity != null && topActivity.isNonResizableOrForcedResizable()
Jorim Jaggicd13d332016-04-27 15:40:20 -07004214 && !topActivity.noDisplay) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004215 final String packageName = topActivity.appInfo.packageName;
4216 final int reason = isSecondaryDisplayPreferred
4217 ? FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY
4218 : FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Yorke Leebd54c2a2016-10-25 13:49:23 -07004219 mService.mTaskChangeNotificationController.notifyActivityForcedResizable(
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004220 task.taskId, reason, packageName);
Wale Ogunwaleb9b16a72016-01-27 12:24:44 -08004221 }
Chong Zhangb15758a2015-11-17 12:12:03 -08004222 }
4223
Craig Mautner6cd6cec2015-04-01 00:02:12 -07004224 void showLockTaskToast() {
Hall Liu45784f12016-05-31 15:50:48 -07004225 if (mLockTaskNotify != null) {
4226 mLockTaskNotify.showToast(mLockTaskModeState);
4227 }
Jason Monka8f569c2014-07-07 12:15:21 -04004228 }
4229
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004230 void showLockTaskEscapeMessageLocked(TaskRecord task) {
4231 if (mLockTaskModeTasks.contains(task)) {
4232 mHandler.sendEmptyMessage(SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG);
4233 }
4234 }
4235
Craig Mautner432f64e2015-05-20 14:59:57 -07004236 void setLockTaskModeLocked(TaskRecord task, int lockTaskModeState, String reason,
4237 boolean andResume) {
Craig Mautneraea74a52014-03-08 14:23:10 -08004238 if (task == null) {
Christopher Tate3bd90612014-06-18 16:37:52 -07004239 // Take out of lock task mode if necessary
Craig Mautner15df08a2015-04-01 12:17:18 -07004240 final TaskRecord lockedTask = getLockedTaskLocked();
4241 if (lockedTask != null) {
4242 removeLockedTaskLocked(lockedTask);
4243 if (!mLockTaskModeTasks.isEmpty()) {
4244 // There are locked tasks remaining, can only finish this task, not unlock it.
Craig Mautnere0570202015-05-13 13:06:11 -07004245 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4246 "setLockTaskModeLocked: Tasks remaining, can't unlock");
Craig Mautner15df08a2015-04-01 12:17:18 -07004247 lockedTask.performClearTaskLocked();
Wale Ogunwaled046a012015-12-24 13:05:59 -08004248 resumeFocusedStackTopActivityLocked();
Craig Mautner15df08a2015-04-01 12:17:18 -07004249 return;
4250 }
Christopher Tate3bd90612014-06-18 16:37:52 -07004251 }
Craig Mautnere0570202015-05-13 13:06:11 -07004252 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4253 "setLockTaskModeLocked: No tasks to unlock. Callers=" + Debug.getCallers(4));
Craig Mautneraea74a52014-03-08 14:23:10 -08004254 return;
4255 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004256
4257 // Should have already been checked, but do it again.
4258 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
Craig Mautnere0570202015-05-13 13:06:11 -07004259 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
4260 "setLockTaskModeLocked: Can't lock due to auth");
Craig Mautneraea74a52014-03-08 14:23:10 -08004261 return;
4262 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004263 if (isLockTaskModeViolation(task)) {
Craig Mautnere0570202015-05-13 13:06:11 -07004264 Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
Craig Mautner15df08a2015-04-01 12:17:18 -07004265 return;
4266 }
4267
4268 if (mLockTaskModeTasks.isEmpty()) {
4269 // First locktask.
4270 final Message lockTaskMsg = Message.obtain();
4271 lockTaskMsg.obj = task.intent.getComponent().getPackageName();
4272 lockTaskMsg.arg1 = task.userId;
4273 lockTaskMsg.what = LOCK_TASK_START_MSG;
4274 lockTaskMsg.arg2 = lockTaskModeState;
4275 mHandler.sendMessage(lockTaskMsg);
4276 }
4277 // Add it or move it to the top.
Craig Mautnere0570202015-05-13 13:06:11 -07004278 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskModeLocked: Locking to " + task +
4279 " Callers=" + Debug.getCallers(4));
Craig Mautner15df08a2015-04-01 12:17:18 -07004280 mLockTaskModeTasks.remove(task);
4281 mLockTaskModeTasks.add(task);
4282
4283 if (task.mLockTaskUid == -1) {
Wale Ogunwale5c18d052015-10-12 10:34:14 -07004284 task.mLockTaskUid = task.effectiveUid;
Craig Mautner15df08a2015-04-01 12:17:18 -07004285 }
Craig Mautner432f64e2015-05-20 14:59:57 -07004286
4287 if (andResume) {
Andrii Kulianc27916642016-04-12 17:59:27 -07004288 findTaskToMoveToFrontLocked(task, 0, null, reason,
4289 lockTaskModeState != LOCK_TASK_MODE_NONE);
Wale Ogunwaled046a012015-12-24 13:05:59 -08004290 resumeFocusedStackTopActivityLocked();
Jorim Jaggia42938e2016-11-22 14:31:38 +01004291 mWindowManager.executeAppTransition();
Andrii Kulianc27916642016-04-12 17:59:27 -07004292 } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
Andrii Kulian036e3ad2017-04-19 10:55:10 -07004293 handleNonResizableTaskIfNeeded(task, INVALID_STACK_ID, DEFAULT_DISPLAY,
4294 task.getStackId(), true /* forceNonResizable */);
Craig Mautner432f64e2015-05-20 14:59:57 -07004295 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004296 }
4297
4298 boolean isLockTaskModeViolation(TaskRecord task) {
Jason Monk25d237b2015-06-19 10:39:39 -04004299 return isLockTaskModeViolation(task, false);
4300 }
4301
4302 boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) {
4303 if (getLockedTaskLocked() == task && !isNewClearTask) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004304 return false;
4305 }
4306 final int lockTaskAuth = task.mLockTaskAuth;
4307 switch (lockTaskAuth) {
4308 case LOCK_TASK_AUTH_DONT_LOCK:
4309 return !mLockTaskModeTasks.isEmpty();
Benjamin Franz469dd582015-06-09 14:24:36 +01004310 case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
Craig Mautner15df08a2015-04-01 12:17:18 -07004311 case LOCK_TASK_AUTH_LAUNCHABLE:
4312 case LOCK_TASK_AUTH_WHITELISTED:
4313 return false;
4314 case LOCK_TASK_AUTH_PINNABLE:
4315 // Pinnable tasks can't be launched on top of locktask tasks.
4316 return !mLockTaskModeTasks.isEmpty();
4317 default:
4318 Slog.w(TAG, "isLockTaskModeViolation: invalid lockTaskAuth value=" + lockTaskAuth);
4319 return true;
4320 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004321 }
4322
Craig Mautner15df08a2015-04-01 12:17:18 -07004323 void onLockTaskPackagesUpdatedLocked() {
4324 boolean didSomething = false;
4325 for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
4326 final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx);
Benjamin Franz469dd582015-06-09 14:24:36 +01004327 final boolean wasWhitelisted =
4328 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4329 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
Craig Mautner15df08a2015-04-01 12:17:18 -07004330 lockedTask.setLockTaskAuth();
Benjamin Franz469dd582015-06-09 14:24:36 +01004331 final boolean isWhitelisted =
4332 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) ||
4333 (lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED);
4334 if (wasWhitelisted && !isWhitelisted) {
Craig Mautner15df08a2015-04-01 12:17:18 -07004335 // Lost whitelisting authorization. End it now.
Craig Mautner432f64e2015-05-20 14:59:57 -07004336 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "onLockTaskPackagesUpdated: removing " +
4337 lockedTask + " mLockTaskAuth=" + lockedTask.lockTaskAuthToString());
Craig Mautner15df08a2015-04-01 12:17:18 -07004338 removeLockedTaskLocked(lockedTask);
4339 lockedTask.performClearTaskLocked();
4340 didSomething = true;
4341 }
4342 }
4343 for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
4344 ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
4345 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
4346 final ActivityStack stack = stacks.get(stackNdx);
4347 stack.onLockTaskPackagesUpdatedLocked();
4348 }
4349 }
Craig Mautnere0570202015-05-13 13:06:11 -07004350 final ActivityRecord r = topRunningActivityLocked();
Bryce Leeaf691c02017-03-20 14:20:22 -07004351 final TaskRecord task = r != null ? r.getTask() : null;
Craig Mautnere0570202015-05-13 13:06:11 -07004352 if (mLockTaskModeTasks.isEmpty() && task != null
4353 && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
4354 // This task must have just been authorized.
Craig Mautner432f64e2015-05-20 14:59:57 -07004355 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK,
4356 "onLockTaskPackagesUpdated: starting new locktask task=" + task);
4357 setLockTaskModeLocked(task, ActivityManager.LOCK_TASK_MODE_LOCKED, "package updated",
4358 false);
4359 didSomething = true;
Craig Mautnere0570202015-05-13 13:06:11 -07004360 }
Craig Mautner15df08a2015-04-01 12:17:18 -07004361 if (didSomething) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004362 resumeFocusedStackTopActivityLocked();
Craig Mautneraea74a52014-03-08 14:23:10 -08004363 }
4364 }
4365
Benjamin Franz43261142015-02-11 15:59:44 +00004366 int getLockTaskModeState() {
4367 return mLockTaskModeState;
Craig Mautneraea74a52014-03-08 14:23:10 -08004368 }
4369
Jorim Jaggife89d122015-12-22 16:28:44 +01004370 void activityRelaunchedLocked(IBinder token) {
4371 mWindowManager.notifyAppRelaunchingFinished(token);
David Stevensf62360c2017-03-16 19:00:20 -07004372 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4373 if (r != null) {
4374 if (r.getStack().shouldSleepOrShutDownActivities()) {
Wale Ogunwale3e997362016-09-06 10:37:56 -07004375 r.setSleeping(true, true);
4376 }
4377 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004378 }
4379
4380 void activityRelaunchingLocked(ActivityRecord r) {
4381 mWindowManager.notifyAppRelaunching(r.appToken);
4382 }
4383
Filip Gruszczynski77d94482015-12-11 13:59:52 -08004384 void logStackState() {
4385 mActivityMetricsLogger.logWindowState();
4386 }
4387
Winson Chung5af42fc2017-03-24 17:11:33 -07004388 void scheduleUpdateMultiWindowMode(TaskRecord task) {
Winson Chung8bca9e42017-04-16 15:59:43 -07004389 // If the stack is animating in a way where we will be forcing a multi-mode change at the
4390 // end, then ensure that we defer all in between multi-window mode changes
4391 if (task.getStack().deferScheduleMultiWindowModeChanged()) {
4392 return;
4393 }
4394
Wale Ogunwale22e25262016-02-01 10:32:02 -08004395 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4396 final ActivityRecord r = task.mActivities.get(i);
4397 if (r.app != null && r.app.thread != null) {
4398 mMultiWindowModeChangedActivities.add(r);
4399 }
4400 }
4401
4402 if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) {
4403 mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG);
4404 }
4405 }
4406
Winson Chung5af42fc2017-03-24 17:11:33 -07004407 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07004408 final ActivityStack stack = task.getStack();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004409 if (prevStack == null || prevStack == stack
4410 || (prevStack.mStackId != PINNED_STACK_ID && stack.mStackId != PINNED_STACK_ID)) {
4411 return;
4412 }
4413
Winson Chung5af42fc2017-03-24 17:11:33 -07004414 scheduleUpdatePictureInPictureModeIfNeeded(task, stack.mBounds, false /* immediate */);
4415 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004416
Winson Chung5af42fc2017-03-24 17:11:33 -07004417 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds,
4418 boolean immediate) {
4419
4420 if (immediate) {
4421 mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG);
4422 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4423 final ActivityRecord r = task.mActivities.get(i);
4424 if (r.app != null && r.app.thread != null) {
4425 r.updatePictureInPictureMode(targetStackBounds);
4426 }
4427 }
4428 } else {
4429 for (int i = task.mActivities.size() - 1; i >= 0; i--) {
4430 final ActivityRecord r = task.mActivities.get(i);
4431 if (r.app != null && r.app.thread != null) {
4432 mPipModeChangedActivities.add(r);
4433 }
4434 }
4435 mPipModeChangedTargetStackBounds = targetStackBounds;
4436
4437 if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) {
4438 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG);
4439 }
Wale Ogunwale22e25262016-02-01 10:32:02 -08004440 }
4441 }
4442
Tony Mak853304c2016-04-18 15:17:41 +01004443 void setDockedStackMinimized(boolean minimized) {
4444 mIsDockMinimized = minimized;
Tony Mak853304c2016-04-18 15:17:41 +01004445 }
4446
chaviw59b98852017-06-13 12:05:44 -07004447 void wakeUp(String reason) {
4448 mPowerManager.wakeUp(SystemClock.uptimeMillis(), "android.server.am:TURN_ON:" + reason);
4449 }
4450
4451 /**
4452 * Begin deferring resume to avoid duplicate resumes in one pass.
4453 */
4454 private void beginDeferResume() {
4455 mDeferResumeCount++;
4456 }
4457
4458 /**
4459 * End deferring resume and determine if resume can be called.
4460 */
4461 private void endDeferResume() {
4462 mDeferResumeCount--;
4463 }
4464
4465 /**
4466 * @return True if resume can be called.
4467 */
4468 private boolean readyToResume() {
4469 return mDeferResumeCount == 0;
4470 }
4471
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004472 private final class ActivityStackSupervisorHandler extends Handler {
Craig Mautnerf3333272013-04-22 10:55:53 -07004473
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004474 public ActivityStackSupervisorHandler(Looper looper) {
4475 super(looper);
4476 }
4477
Winson Chung4dabf232017-01-25 13:25:22 -08004478 void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) {
Craig Mautnerf3333272013-04-22 10:55:53 -07004479 synchronized (mService) {
Winson Chung4dabf232017-01-25 13:25:22 -08004480 activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */,
4481 processPausingActivities, null);
Craig Mautnerf3333272013-04-22 10:55:53 -07004482 }
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004483 }
4484
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004485 @Override
4486 public void handleMessage(Message msg) {
4487 switch (msg.what) {
Wale Ogunwale22e25262016-02-01 10:32:02 -08004488 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: {
4489 synchronized (mService) {
4490 for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) {
4491 final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004492 r.updateMultiWindowMode();
Wale Ogunwale22e25262016-02-01 10:32:02 -08004493 }
4494 }
4495 } break;
4496 case REPORT_PIP_MODE_CHANGED_MSG: {
4497 synchronized (mService) {
4498 for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) {
4499 final ActivityRecord r = mPipModeChangedActivities.remove(i);
Winson Chung5af42fc2017-03-24 17:11:33 -07004500 r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds);
Wale Ogunwale22e25262016-02-01 10:32:02 -08004501 }
4502 }
4503 } break;
Craig Mautnerf3333272013-04-22 10:55:53 -07004504 case IDLE_TIMEOUT_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004505 if (DEBUG_IDLE) Slog.d(TAG_IDLE,
4506 "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj);
Craig Mautnerf3333272013-04-22 10:55:53 -07004507 // We don't at this point know if the activity is fullscreen,
4508 // so we need to be conservative and assume it isn't.
Winson Chung4dabf232017-01-25 13:25:22 -08004509 activityIdleInternal((ActivityRecord) msg.obj,
4510 true /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004511 } break;
4512 case IDLE_NOW_MSG: {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07004513 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj);
Winson Chung4dabf232017-01-25 13:25:22 -08004514 activityIdleInternal((ActivityRecord) msg.obj,
4515 false /* processPausingActivities */);
Craig Mautnerf3333272013-04-22 10:55:53 -07004516 } break;
Craig Mautner05d29032013-05-03 13:40:13 -07004517 case RESUME_TOP_ACTIVITY_MSG: {
4518 synchronized (mService) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004519 resumeFocusedStackTopActivityLocked();
Craig Mautner05d29032013-05-03 13:40:13 -07004520 }
4521 } break;
Craig Mautner0eea92c2013-05-16 13:35:39 -07004522 case SLEEP_TIMEOUT_MSG: {
4523 synchronized (mService) {
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07004524 if (mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07004525 Slog.w(TAG, "Sleep timeout! Sleeping now.");
David Stevensf62360c2017-03-16 19:00:20 -07004526 checkReadyForSleepLocked(false /* allowDelay */);
Craig Mautner0eea92c2013-05-16 13:35:39 -07004527 }
4528 }
4529 } break;
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004530 case LAUNCH_TIMEOUT_MSG: {
Craig Mautner7ea5bd42013-07-05 15:27:08 -07004531 synchronized (mService) {
4532 if (mLaunchingActivity.isHeld()) {
4533 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
4534 if (VALIDATE_WAKE_LOCK_CALLER
4535 && Binder.getCallingUid() != Process.myUid()) {
4536 throw new IllegalStateException("Calling must be system uid");
4537 }
4538 mLaunchingActivity.release();
4539 }
4540 }
4541 } break;
Craig Mautner4a1cb222013-12-04 16:14:06 -08004542 case HANDLE_DISPLAY_ADDED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004543 handleDisplayAdded(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004544 } break;
4545 case HANDLE_DISPLAY_CHANGED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004546 handleDisplayChanged(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004547 } break;
4548 case HANDLE_DISPLAY_REMOVED: {
Wale Ogunwalef16a2812015-04-01 11:23:15 -07004549 handleDisplayRemoved(msg.arg1);
Craig Mautner4a1cb222013-12-04 16:14:06 -08004550 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004551 case LOCK_TASK_START_MSG: {
4552 // When lock task starts, we disable the status bars.
4553 try {
Jason Monk62515be2014-05-21 16:06:19 -04004554 if (mLockTaskNotify == null) {
4555 mLockTaskNotify = new LockTaskNotify(mService.mContext);
justinzhang5286d3f2014-05-12 17:06:01 -04004556 }
Jason Monk62515be2014-05-21 16:06:19 -04004557 mLockTaskNotify.show(true);
Benjamin Franz43261142015-02-11 15:59:44 +00004558 mLockTaskModeState = msg.arg2;
Jason Monk62515be2014-05-21 16:06:19 -04004559 if (getStatusBarService() != null) {
Benjamin Franz43261142015-02-11 15:59:44 +00004560 int flags = 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004561 if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004562 flags = StatusBarManager.DISABLE_MASK
4563 & (~StatusBarManager.DISABLE_BACK);
Craig Mautner15df08a2015-04-01 12:17:18 -07004564 } else if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
Benjamin Franz43261142015-02-11 15:59:44 +00004565 flags = StatusBarManager.DISABLE_MASK
4566 & (~StatusBarManager.DISABLE_BACK)
4567 & (~StatusBarManager.DISABLE_HOME)
4568 & (~StatusBarManager.DISABLE_RECENT);
Jason Monk62515be2014-05-21 16:06:19 -04004569 }
4570 getStatusBarService().disable(flags, mToken,
4571 mService.mContext.getPackageName());
4572 }
4573 mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
Jason Monk35c62a42014-06-17 10:24:47 -04004574 if (getDevicePolicyManager() != null) {
4575 getDevicePolicyManager().notifyLockTaskModeChanged(true,
Jason Monk62515be2014-05-21 16:06:19 -04004576 (String)msg.obj, msg.arg1);
Jason Monk35c62a42014-06-17 10:24:47 -04004577 }
justinzhang5286d3f2014-05-12 17:06:01 -04004578 } catch (RemoteException ex) {
4579 throw new RuntimeException(ex);
4580 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004581 } break;
justinzhang5286d3f2014-05-12 17:06:01 -04004582 case LOCK_TASK_END_MSG: {
4583 // When lock task ends, we enable the status bars.
4584 try {
Jason Monk62515be2014-05-21 16:06:19 -04004585 if (getStatusBarService() != null) {
4586 getStatusBarService().disable(StatusBarManager.DISABLE_NONE, mToken,
4587 mService.mContext.getPackageName());
4588 }
4589 mWindowManager.reenableKeyguard(mToken);
Jason Monk35c62a42014-06-17 10:24:47 -04004590 if (getDevicePolicyManager() != null) {
4591 getDevicePolicyManager().notifyLockTaskModeChanged(false, null,
4592 msg.arg1);
4593 }
Jason Monk62515be2014-05-21 16:06:19 -04004594 if (mLockTaskNotify == null) {
4595 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4596 }
4597 mLockTaskNotify.show(false);
4598 try {
Jason Monk94cfd9d2014-10-31 13:18:21 -04004599 boolean shouldLockKeyguard = Settings.Secure.getInt(
Jason Monk62515be2014-05-21 16:06:19 -04004600 mService.mContext.getContentResolver(),
Jason Monk94cfd9d2014-10-31 13:18:21 -04004601 Settings.Secure.LOCK_TO_APP_EXIT_LOCKED) != 0;
Craig Mautner15df08a2015-04-01 12:17:18 -07004602 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED && shouldLockKeyguard) {
Jason Monk62515be2014-05-21 16:06:19 -04004603 mWindowManager.lockNow(null);
Jorim Jaggi241ae102016-11-02 21:57:33 -07004604 mWindowManager.dismissKeyguard(null /* callback */);
Jason Monke0697792014-08-04 16:28:09 -04004605 new LockPatternUtils(mService.mContext)
4606 .requireCredentialEntry(UserHandle.USER_ALL);
Jason Monk62515be2014-05-21 16:06:19 -04004607 }
4608 } catch (SettingNotFoundException e) {
4609 // No setting, don't lock.
4610 }
justinzhang5286d3f2014-05-12 17:06:01 -04004611 } catch (RemoteException ex) {
4612 throw new RuntimeException(ex);
Benjamin Franz43261142015-02-11 15:59:44 +00004613 } finally {
Craig Mautner15df08a2015-04-01 12:17:18 -07004614 mLockTaskModeState = LOCK_TASK_MODE_NONE;
justinzhang5286d3f2014-05-12 17:06:01 -04004615 }
Craig Mautnerb6011c12014-06-04 20:59:13 -07004616 } break;
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07004617 case SHOW_LOCK_TASK_ESCAPE_MESSAGE_MSG: {
4618 if (mLockTaskNotify == null) {
4619 mLockTaskNotify = new LockTaskNotify(mService.mContext);
4620 }
4621 mLockTaskNotify.showToast(LOCK_TASK_MODE_PINNED);
4622 } break;
Craig Mautnerbb742462014-07-07 15:28:55 -07004623 case LAUNCH_TASK_BEHIND_COMPLETE: {
4624 synchronized (mService) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07004625 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
Craig Mautnerbb742462014-07-07 15:28:55 -07004626 if (r != null) {
4627 handleLaunchTaskBehindCompleteLocked(r);
4628 }
4629 }
4630 } break;
Chong Zhangc806d902015-11-30 09:44:27 -08004631
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004632 }
4633 }
4634 }
Craig Mautnered6649f2013-12-02 14:08:25 -08004635
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004636 // TODO: Move to its own file.
Craig Mautner4a1cb222013-12-04 16:14:06 -08004637 /** Exactly one of these classes per Display in the system. Capable of holding zero or more
4638 * attached {@link ActivityStack}s */
Andrii Kulian1779e612016-10-12 21:58:25 -07004639 class ActivityDisplay extends ConfigurationContainer {
Craig Mautner4a1cb222013-12-04 16:14:06 -08004640 /** Actual Display this object tracks. */
Craig Mautner34b73df2014-01-12 21:11:08 -08004641 int mDisplayId;
4642 Display mDisplay;
Craig Mautnered6649f2013-12-02 14:08:25 -08004643
Craig Mautner4a1cb222013-12-04 16:14:06 -08004644 /** All of the stacks on this display. Order matters, topmost stack is in front of all other
4645 * stacks, bottommost behind. Accessed directly by ActivityManager package classes */
Wale Ogunwale1f544be2015-12-17 10:27:23 -08004646 final ArrayList<ActivityStack> mStacks = new ArrayList<>();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004647
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004648 /** Array of all UIDs that are present on the display. */
4649 private IntArray mDisplayAccessUIDs = new IntArray();
4650
David Stevensf62360c2017-03-16 19:00:20 -07004651 /** All tokens used to put activities on this stack to sleep (including mOffToken) */
4652 final ArrayList<SleepTokenImpl> mAllSleepTokens = new ArrayList<>();
4653 /** The token acquired by ActivityStackSupervisor to put stacks on the display to sleep */
4654 SleepToken mOffToken;
4655
4656 private boolean mSleeping;
4657
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004658 @VisibleForTesting
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004659 ActivityDisplay() {
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004660 mActivityDisplays.put(mDisplayId, this);
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004661 }
Craig Mautner4504de52013-12-20 09:06:56 -08004662
Craig Mautner1a70a162014-09-13 12:09:31 -07004663 // After instantiation, check that mDisplay is not null before using this. The alternative
4664 // is for this to throw an exception if mDisplayManager.getDisplay() returns null.
Craig Mautnere0a38842013-12-16 16:14:02 -08004665 ActivityDisplay(int displayId) {
Craig Mautner1a70a162014-09-13 12:09:31 -07004666 final Display display = mDisplayManager.getDisplay(displayId);
4667 if (display == null) {
4668 return;
4669 }
4670 init(display);
Craig Mautner4504de52013-12-20 09:06:56 -08004671 }
4672
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004673 void init(Display display) {
Craig Mautner4504de52013-12-20 09:06:56 -08004674 mDisplay = display;
4675 mDisplayId = display.getDisplayId();
Craig Mautnered6649f2013-12-02 14:08:25 -08004676 }
Craig Mautner4a1cb222013-12-04 16:14:06 -08004677
Winson Chung7c3ede32017-03-14 14:18:34 -07004678 void attachStack(ActivityStack stack, int position) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08004679 if (DEBUG_STACK) Slog.v(TAG_STACK, "attachStack: attaching " + stack
Winson Chung7c3ede32017-03-14 14:18:34 -07004680 + " to displayId=" + mDisplayId + " position=" + position);
4681 mStacks.add(position, stack);
David Stevensf62360c2017-03-16 19:00:20 -07004682 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004683 }
4684
Wale Ogunwale1666e312016-12-16 11:27:18 -08004685 void detachStack(ActivityStack stack) {
4686 if (DEBUG_STACK) Slog.v(TAG_STACK, "detachStack: detaching " + stack
Craig Mautnere0a38842013-12-16 16:14:02 -08004687 + " from displayId=" + mDisplayId);
4688 mStacks.remove(stack);
David Stevensf62360c2017-03-16 19:00:20 -07004689 mService.updateSleepIfNeededLocked();
Craig Mautner4a1cb222013-12-04 16:14:06 -08004690 }
4691
Craig Mautner34b73df2014-01-12 21:11:08 -08004692 @Override
4693 public String toString() {
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004694 return "ActivityDisplay={" + mDisplayId + " numStacks=" + mStacks.size() + "}";
4695 }
Andrii Kulian1779e612016-10-12 21:58:25 -07004696
4697 @Override
4698 protected int getChildCount() {
4699 return mStacks.size();
4700 }
4701
4702 @Override
4703 protected ConfigurationContainer getChildAt(int index) {
4704 return mStacks.get(index);
4705 }
4706
4707 @Override
4708 protected ConfigurationContainer getParent() {
4709 return ActivityStackSupervisor.this;
4710 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08004711
4712 boolean isPrivate() {
4713 return (mDisplay.getFlags() & FLAG_PRIVATE) != 0;
4714 }
4715
4716 boolean isUidPresent(int uid) {
4717 for (ActivityStack stack : mStacks) {
4718 if (stack.isUidPresent(uid)) {
4719 return true;
4720 }
4721 }
4722 return false;
4723 }
4724
4725 /** Update and get all UIDs that are present on the display and have access to it. */
4726 private IntArray getPresentUIDs() {
4727 mDisplayAccessUIDs.clear();
4728 for (ActivityStack stack : mStacks) {
4729 stack.getPresentUIDs(mDisplayAccessUIDs);
4730 }
4731 return mDisplayAccessUIDs;
4732 }
Andrii Kulian250d6532017-02-08 23:30:45 -08004733
4734 boolean shouldDestroyContentOnRemove() {
4735 return mDisplay.getRemoveMode() == REMOVE_MODE_DESTROY_CONTENT;
4736 }
David Stevensf62360c2017-03-16 19:00:20 -07004737
4738 boolean shouldSleep() {
4739 return (mStacks.isEmpty() || !mAllSleepTokens.isEmpty())
4740 && (mService.mRunningVoice == null);
4741 }
4742
4743 boolean isSleeping() {
4744 return mSleeping;
4745 }
4746
4747 void setIsSleeping(boolean asleep) {
4748 mSleeping = asleep;
4749 }
Craig Mautnerf4c909b2014-04-17 18:39:38 -07004750 }
4751
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004752 ActivityStack findStackBehind(ActivityStack stack) {
4753 // TODO(multi-display): We are only looking for stacks on the default display.
Jorim Jaggife762342016-10-13 14:33:27 +02004754 final ActivityDisplay display = mActivityDisplays.get(DEFAULT_DISPLAY);
Filip Gruszczynskicaae14e2015-12-16 14:40:04 -08004755 if (display == null) {
4756 return null;
4757 }
4758 final ArrayList<ActivityStack> stacks = display.mStacks;
4759 for (int i = stacks.size() - 1; i >= 0; i--) {
4760 if (stacks.get(i) == stack && i > 0) {
4761 return stacks.get(i - 1);
4762 }
4763 }
4764 throw new IllegalStateException("Failed to find a stack behind stack=" + stack
4765 + " in=" + stacks);
4766 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004767
Jorim Jaggic69bd222016-03-15 14:38:37 +01004768 /**
4769 * Puts a task into resizing mode during the next app transition.
4770 *
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004771 * @param task The task to put into resizing mode
Jorim Jaggic69bd222016-03-15 14:38:37 +01004772 */
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004773 private void setResizingDuringAnimation(TaskRecord task) {
4774 mResizingTasksDuringAnimation.add(task.taskId);
4775 task.setTaskDockedResizing(true);
Jorim Jaggic69bd222016-03-15 14:38:37 +01004776 }
4777
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004778 final int startActivityFromRecentsInner(int taskId, Bundle bOptions) {
4779 final TaskRecord task;
4780 final int callingUid;
4781 final String callingPackage;
4782 final Intent intent;
4783 final int userId;
4784 final ActivityOptions activityOptions = (bOptions != null)
4785 ? new ActivityOptions(bOptions) : null;
4786 final int launchStackId = (activityOptions != null)
4787 ? activityOptions.getLaunchStackId() : INVALID_STACK_ID;
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004788 if (StackId.isHomeOrRecentsStack(launchStackId)) {
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004789 throw new IllegalArgumentException("startActivityFromRecentsInner: Task "
Matthew Ngae1ff4f2016-11-10 15:49:14 -08004790 + taskId + " can't be launch in the home/recents stack.");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004791 }
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004792
Matthew Ng606dd802017-06-05 14:06:32 -07004793 mWindowManager.deferSurfaceLayout();
4794 try {
4795 if (launchStackId == DOCKED_STACK_ID) {
4796 mWindowManager.setDockedStackCreateState(
4797 activityOptions.getDockCreateMode(), null /* initialBounds */);
Jorim Jaggi3c800a42016-04-15 19:44:50 -07004798
Matthew Ng606dd802017-06-05 14:06:32 -07004799 // Defer updating the stack in which recents is until the app transition is done, to
4800 // not run into issues where we still need to draw the task in recents but the
4801 // docked stack is already created.
4802 deferUpdateBounds(RECENTS_STACK_ID);
4803 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004804 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004805
Matthew Ng606dd802017-06-05 14:06:32 -07004806 task = anyTaskForIdLocked(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE,
4807 launchStackId);
4808 if (task == null) {
4809 continueUpdateBounds(RECENTS_STACK_ID);
4810 mWindowManager.executeAppTransition();
4811 throw new IllegalArgumentException(
4812 "startActivityFromRecentsInner: Task " + taskId + " not found.");
4813 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004814
Matthew Ng606dd802017-06-05 14:06:32 -07004815 // Since we don't have an actual source record here, we assume that the currently
4816 // focused activity was the source.
4817 final ActivityStack focusedStack = getFocusedStack();
4818 final ActivityRecord sourceRecord =
4819 focusedStack != null ? focusedStack.topActivity() : null;
4820
4821 if (launchStackId != INVALID_STACK_ID) {
4822 if (task.getStackId() != launchStackId) {
4823 task.reparent(launchStackId, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE,
4824 DEFER_RESUME, "startActivityFromRecents");
4825 }
4826 }
4827
4828 // If the user must confirm credentials (e.g. when first launching a work app and the
4829 // Work Challenge is present) let startActivityInPackage handle the intercepting.
4830 if (!mService.mUserController.shouldConfirmCredentials(task.userId)
4831 && task.getRootActivity() != null) {
Bryce Lee28d80422017-07-21 13:25:13 -07004832 final ActivityRecord targetActivity = task.getTopActivity();
4833
4834 mService.mActivityStarter.sendPowerHintForLaunchStartIfNeeded(true /* forceSend */,
4835 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004836 mActivityMetricsLogger.notifyActivityLaunching();
Jorim Jaggi42befc62017-06-13 11:54:04 -07004837 mService.moveTaskToFrontLocked(task.taskId, 0, bOptions, true /* fromRecents */);
Matthew Ng606dd802017-06-05 14:06:32 -07004838 mActivityMetricsLogger.notifyActivityLaunched(ActivityManager.START_TASK_TO_FRONT,
Bryce Lee28d80422017-07-21 13:25:13 -07004839 targetActivity);
Matthew Ng606dd802017-06-05 14:06:32 -07004840
4841 // If we are launching the task in the docked stack, put it into resizing mode so
4842 // the window renders full-screen with the background filling the void. Also only
4843 // call this at the end to make sure that tasks exists on the window manager side.
4844 if (launchStackId == DOCKED_STACK_ID) {
4845 setResizingDuringAnimation(task);
4846 }
4847
4848 mService.mActivityStarter.postStartActivityProcessing(task.getTopActivity(),
4849 ActivityManager.START_TASK_TO_FRONT,
4850 sourceRecord != null
4851 ? sourceRecord.getTask().getStackId() : INVALID_STACK_ID,
4852 sourceRecord, task.getStack());
4853 return ActivityManager.START_TASK_TO_FRONT;
4854 }
4855 callingUid = task.mCallingUid;
4856 callingPackage = task.mCallingPackage;
4857 intent = task.intent;
4858 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4859 userId = task.userId;
4860 int result = mService.startActivityInPackage(callingUid, callingPackage, intent, null,
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07004861 null, null, 0, 0, bOptions, userId, task, "startActivityFromRecents");
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004862 if (launchStackId == DOCKED_STACK_ID) {
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004863 setResizingDuringAnimation(task);
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004864 }
Matthew Ng606dd802017-06-05 14:06:32 -07004865 return result;
4866 } finally {
4867 mWindowManager.continueSurfaceLayout();
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004868 }
Jorim Jaggi0b46f3c2016-03-14 12:21:37 +01004869 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004870
4871 /**
4872 * @return a list of activities which are the top ones in each visible stack. The first
4873 * entry will be the focused activity.
4874 */
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004875 List<IBinder> getTopVisibleActivities() {
4876 final ArrayList<IBinder> topActivityTokens = new ArrayList<>();
4877 // Traverse all displays.
Robert Carr22374c02017-02-21 13:01:47 -08004878 for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004879 final ActivityDisplay display = mActivityDisplays.valueAt(i);
4880 // Traverse all stacks on a display.
4881 for (int j = display.mStacks.size() - 1; j >= 0; j--) {
4882 final ActivityStack stack = display.mStacks.get(j);
4883 // Get top activity from a visible stack and add it to the list.
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07004884 if (stack.shouldBeVisible(null /* starting */)
Andrii Kulian0864bbb2017-02-16 15:45:58 -08004885 == ActivityStack.STACK_VISIBLE) {
4886 final ActivityRecord top = stack.topActivity();
4887 if (top != null) {
4888 if (stack == mFocusedStack) {
4889 topActivityTokens.add(0, top.appToken);
4890 } else {
4891 topActivityTokens.add(top.appToken);
4892 }
Amith Yamasanie8222e52016-04-08 15:28:47 -07004893 }
4894 }
4895 }
4896 }
4897 return topActivityTokens;
4898 }
Bryce Lee4a194382017-04-04 14:32:48 -07004899
4900 /**
4901 * Internal container to store a match qualifier alongside a WaitResult.
4902 */
4903 static class WaitInfo {
4904 private final ComponentName mTargetComponent;
4905 private final WaitResult mResult;
4906
4907 public WaitInfo(ComponentName targetComponent, WaitResult result) {
4908 this.mTargetComponent = targetComponent;
4909 this.mResult = result;
4910 }
4911
Wale Ogunwale3270f172017-04-26 07:29:42 -07004912 public boolean matches(ComponentName targetComponent) {
4913 return mTargetComponent == null || mTargetComponent.equals(targetComponent);
Bryce Lee4a194382017-04-04 14:32:48 -07004914 }
4915
4916 public WaitResult getResult() {
4917 return mResult;
4918 }
4919
4920 public ComponentName getComponent() {
4921 return mTargetComponent;
4922 }
4923
4924 public void dump(PrintWriter pw, String prefix) {
4925 pw.println(prefix + "WaitInfo:");
4926 pw.println(prefix + " mTargetComponent=" + mTargetComponent);
4927 pw.println(prefix + " mResult=");
4928 mResult.dump(pw, prefix);
4929 }
4930 }
David Stevensf62360c2017-03-16 19:00:20 -07004931
4932 private final class SleepTokenImpl extends SleepToken {
4933 private final String mTag;
4934 private final long mAcquireTime;
4935 private final int mDisplayId;
4936
4937 public SleepTokenImpl(String tag, int displayId) {
4938 mTag = tag;
4939 mDisplayId = displayId;
4940 mAcquireTime = SystemClock.uptimeMillis();
4941 }
4942
4943 @Override
4944 public void release() {
4945 synchronized (mService) {
4946 removeSleepTokenLocked(this);
4947 }
4948 }
4949
4950 @Override
4951 public String toString() {
4952 return "{\"" + mTag + "\", display " + mDisplayId
4953 + ", acquire at " + TimeUtils.formatUptime(mAcquireTime) + "}";
4954 }
4955 }
4956
Craig Mautner27084302013-03-25 08:05:25 -07004957}