blob: 1b58fc1d2d3e3445629dda9f9041577c51c53b64 [file] [log] [blame]
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001/*
2 * Copyright (C) 2014 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
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080018
Winson Chung1dbc8112017-09-28 18:05:31 -070019import static android.app.ActivityManager.FLAG_AND_UNLOCKED;
Winson Chung1dbc8112017-09-28 18:05:31 -070020import static android.app.ActivityManager.RECENT_IGNORE_UNAVAILABLE;
Winson Chung1dbc8112017-09-28 18:05:31 -070021import static android.app.ActivityManager.RECENT_WITH_EXCLUDED;
Garfield Tan891146c2018-10-09 12:14:00 -070022import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Vadim Trysheveff42d32018-03-05 18:33:48 -080023import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
Galia Peycheva45f48d32020-02-20 15:39:10 +010024import static android.app.WindowConfiguration.ACTIVITY_TYPE_DREAM;
Winson Chungd6aa3db2017-10-05 17:18:43 -070025import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
26import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
Winson Chung27f81882018-04-19 14:45:03 -070027import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Winson Chunge5ab0172020-03-21 23:00:24 -070028import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
Winson Chungd6aa3db2017-10-05 17:18:43 -070029import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
30import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Winson Chung27f81882018-04-19 14:45:03 -070031import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Winson Chungb4132992018-07-03 15:52:38 -070032import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwalee8d5f652016-04-22 16:27:39 -070033import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
34import static android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
35import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Winson Chungb4132992018-07-03 15:52:38 -070036import static android.os.Process.SYSTEM_UID;
Louis Changbd48dca2018-08-29 17:44:34 +080037
Garfield Tan891146c2018-10-09 12:14:00 -070038import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
Wale Ogunwale59507092018-10-29 09:00:30 -070039import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS;
40import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS_TRIM_TASKS;
41import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
42import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS;
43import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
44import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
45import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Wale Ogunwalee23149f2015-03-06 15:39:44 -080046
Philip P. Moltmannee295092020-02-10 08:46:26 -080047import android.annotation.Nullable;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080048import android.app.ActivityManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070049import android.app.ActivityTaskManager;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080050import android.app.AppGlobals;
51import android.content.ComponentName;
52import android.content.Intent;
53import android.content.pm.ActivityInfo;
54import android.content.pm.ApplicationInfo;
55import android.content.pm.IPackageManager;
56import android.content.pm.PackageManager;
Winson Chung1dbc8112017-09-28 18:05:31 -070057import android.content.pm.ParceledListSlice;
Winson Chungd6aa3db2017-10-05 17:18:43 -070058import android.content.pm.UserInfo;
59import android.content.res.Resources;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080060import android.graphics.Bitmap;
61import android.os.Environment;
Winson Chung1dbc8112017-09-28 18:05:31 -070062import android.os.IBinder;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080063import android.os.RemoteException;
Winson Chungd6aa3db2017-10-05 17:18:43 -070064import android.os.SystemProperties;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080065import android.os.UserHandle;
Winson Chung3f0e59a2017-10-25 10:19:05 -070066import android.text.TextUtils;
Daichi Hirono4cb941e2017-03-31 14:30:41 +090067import android.util.ArraySet;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080068import android.util.Slog;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080069import android.util.SparseArray;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080070import android.util.SparseBooleanArray;
Winson Chungc5fe7ff2019-02-19 14:49:25 -080071import android.view.MotionEvent;
72import android.view.WindowManagerPolicyConstants.PointerEventListener;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080073
Winson Chung1dbc8112017-09-28 18:05:31 -070074import com.android.internal.annotations.VisibleForTesting;
Winson Chungc5fe7ff2019-02-19 14:49:25 -080075import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwale59507092018-10-29 09:00:30 -070076import com.android.server.am.ActivityManagerService;
Winson Chung1dbc8112017-09-28 18:05:31 -070077
Winson Chung3f0e59a2017-10-25 10:19:05 -070078import com.google.android.collect.Sets;
79
Suprabh Shukla09a88f52015-12-02 14:36:31 -080080import java.io.File;
Winson Chung1dbc8112017-09-28 18:05:31 -070081import java.io.PrintWriter;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080082import java.util.ArrayList;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080083import java.util.Arrays;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080084import java.util.Collections;
85import java.util.Comparator;
86import java.util.HashMap;
Wale Ogunwale86b74462018-07-02 08:42:43 -070087import java.util.List;
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +000088import java.util.Set;
Winson Chungd6aa3db2017-10-05 17:18:43 -070089import java.util.concurrent.TimeUnit;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080090
91/**
Winson Chung1dbc8112017-09-28 18:05:31 -070092 * Class for managing the recent tasks list. The list is ordered by most recent (index 0) to the
93 * least recent.
Winson Chung0ec2a352017-10-26 11:38:30 -070094 *
95 * The trimming logic can be boiled down to the following. For recent task list with a number of
96 * tasks, the visible tasks are an interleaving subset of tasks that would normally be presented to
97 * the user. Non-visible tasks are not considered for trimming. Of the visible tasks, only a
98 * sub-range are presented to the user, based on the device type, last task active time, or other
99 * task state. Tasks that are not in the visible range and are not returnable from the SystemUI
100 * (considering the back stack) are considered trimmable. If the device does not support recent
101 * tasks, then trimming is completely disabled.
102 *
103 * eg.
104 * L = [TTTTTTTTTTTTTTTTTTTTTTTTTT] // list of tasks
105 * [VVV VV VVVV V V V ] // Visible tasks
106 * [RRR RR XXXX X X X ] // Visible range tasks, eg. if the device only shows 5 tasks,
107 * // 'X' tasks are trimmed.
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800108 */
Winson Chung1dbc8112017-09-28 18:05:31 -0700109class RecentTasks {
Wale Ogunwale98875612018-10-12 07:53:02 -0700110 private static final String TAG = TAG_WITH_CLASS_NAME ? "RecentTasks" : TAG_ATM;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700111 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
112 private static final String TAG_TASKS = TAG + POSTFIX_TASKS;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800113
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800114 private static final int DEFAULT_INITIAL_CAPACITY = 5;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800115
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800116 // The duration of time after freezing the recent tasks list where getRecentTasks() will return
117 // a stable ordering of the tasks. Upon the next call to getRecentTasks() beyond this duration,
118 // the task list will be unfrozen and committed (the current top task will be moved to the
119 // front of the list)
120 private static final long FREEZE_TASK_LIST_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(5);
Winson6976f7b2016-05-03 14:58:12 -0700121
Winson Chung1dbc8112017-09-28 18:05:31 -0700122 // Comparator to sort by taskId
Louis Changcdec0802019-11-11 11:45:07 +0800123 private static final Comparator<Task> TASK_ID_COMPARATOR =
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700124 (lhs, rhs) -> rhs.mTaskId - lhs.mTaskId;
Winson Chung1dbc8112017-09-28 18:05:31 -0700125
126 // Placeholder variables to keep track of activities/apps that are no longer avialble while
127 // iterating through the recents list
128 private static final ActivityInfo NO_ACTIVITY_INFO_TOKEN = new ActivityInfo();
129 private static final ApplicationInfo NO_APPLICATION_INFO_TOKEN = new ApplicationInfo();
Vinit Nayak3e737492019-07-24 13:03:15 -0700130 private TaskChangeNotificationController mTaskNotificationController;
Winson Chung1dbc8112017-09-28 18:05:31 -0700131
132 /**
133 * Callbacks made when manipulating the list.
134 */
135 interface Callbacks {
136 /**
137 * Called when a task is added to the recent tasks list.
138 */
Louis Changcdec0802019-11-11 11:45:07 +0800139 void onRecentTaskAdded(Task task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700140
141 /**
142 * Called when a task is removed from the recent tasks list.
143 */
Louis Changcdec0802019-11-11 11:45:07 +0800144 void onRecentTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess);
Winson Chung1dbc8112017-09-28 18:05:31 -0700145 }
146
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800147 /**
148 * Save recent tasks information across reboots.
149 */
150 private final TaskPersister mTaskPersister;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700151 private final ActivityTaskManagerService mService;
152 private final ActivityStackSupervisor mSupervisor;
Winson Chung1dbc8112017-09-28 18:05:31 -0700153
154 /**
Winson Chung3f0e59a2017-10-25 10:19:05 -0700155 * Keeps track of the static recents package/component which is granted additional permissions
156 * to call recents-related APIs.
157 */
158 private int mRecentsUid = -1;
159 private ComponentName mRecentsComponent = null;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800160 private @Nullable String mFeatureId;
Winson Chung3f0e59a2017-10-25 10:19:05 -0700161
162 /**
Winson Chung1dbc8112017-09-28 18:05:31 -0700163 * Mapping of user id -> whether recent tasks have been loaded for that user.
164 */
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800165 private final SparseBooleanArray mUsersWithRecentsLoaded = new SparseBooleanArray(
166 DEFAULT_INITIAL_CAPACITY);
167
168 /**
169 * Stores for each user task ids that are taken by tasks residing in persistent storage. These
170 * tasks may or may not currently be in memory.
171 */
Winson Chung1dbc8112017-09-28 18:05:31 -0700172 private final SparseArray<SparseBooleanArray> mPersistedTaskIds = new SparseArray<>(
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800173 DEFAULT_INITIAL_CAPACITY);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800174
Winson Chungd6aa3db2017-10-05 17:18:43 -0700175 // List of all active recent tasks
Louis Changcdec0802019-11-11 11:45:07 +0800176 private final ArrayList<Task> mTasks = new ArrayList<>();
Winson Chung1dbc8112017-09-28 18:05:31 -0700177 private final ArrayList<Callbacks> mCallbacks = new ArrayList<>();
178
Riddle Hsu4e361e92019-12-24 16:51:09 +0800179 /** The non-empty tasks that are removed from recent tasks (see {@link #removeForAddTask}). */
180 private final ArrayList<Task> mHiddenTasks = new ArrayList<>();
181
Winson Chungd6aa3db2017-10-05 17:18:43 -0700182 // These values are generally loaded from resources, but can be set dynamically in the tests
183 private boolean mHasVisibleRecentTasks;
184 private int mGlobalMaxNumTasks;
185 private int mMinNumVisibleTasks;
186 private int mMaxNumVisibleTasks;
187 private long mActiveTasksSessionDurationMs;
188
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800189 // When set, the task list will not be reordered as tasks within the list are moved to the
190 // front. Newly created tasks, or tasks that are removed from the list will continue to change
191 // the list. This does not affect affiliated tasks.
192 private boolean mFreezeTaskListReordering;
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800193 private long mFreezeTaskListTimeoutMs = FREEZE_TASK_LIST_TIMEOUT_MS;
194
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800195 // Mainly to avoid object recreation on multiple calls.
Louis Changcdec0802019-11-11 11:45:07 +0800196 private final ArrayList<Task> mTmpRecents = new ArrayList<>();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800197 private final HashMap<ComponentName, ActivityInfo> mTmpAvailActCache = new HashMap<>();
198 private final HashMap<String, ApplicationInfo> mTmpAvailAppCache = new HashMap<>();
Winson Chungd6aa3db2017-10-05 17:18:43 -0700199 private final SparseBooleanArray mTmpQuietProfileUserIds = new SparseBooleanArray();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800200
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800201 // TODO(b/127498985): This is currently a rough heuristic for interaction inside an app
202 private final PointerEventListener mListener = new PointerEventListener() {
203 @Override
204 public void onPointerEvent(MotionEvent ev) {
205 if (!mFreezeTaskListReordering || ev.getAction() != MotionEvent.ACTION_DOWN) {
206 // Skip if we aren't freezing or starting a gesture
207 return;
208 }
209 int displayId = ev.getDisplayId();
210 int x = (int) ev.getX();
211 int y = (int) ev.getY();
212 mService.mH.post(PooledLambda.obtainRunnable((nonArg) -> {
213 synchronized (mService.mGlobalLock) {
214 // Unfreeze the task list once we touch down in a task
Louis Chang149d5c82019-12-30 09:47:39 +0800215 final RootWindowContainer rac = mService.mRootWindowContainer;
Louis Chang677921f2019-12-06 16:44:24 +0800216 final DisplayContent dc = rac.getDisplayContent(displayId).mDisplayContent;
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800217 if (dc.pointWithinAppWindow(x, y)) {
218 final ActivityStack stack = mService.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900219 final Task topTask = stack != null ? stack.getTopMostTask() : null;
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800220 resetFreezeTaskListReordering(topTask);
221 }
222 }
223 }, null).recycleOnUse());
224 }
225 };
226
Winson Chung1fe58e92019-04-10 14:18:06 -0700227 private final Runnable mResetFreezeTaskListOnTimeoutRunnable =
228 this::resetFreezeTaskListReorderingOnTimeout;
229
Winson Chung1dbc8112017-09-28 18:05:31 -0700230 @VisibleForTesting
Wale Ogunwale86b74462018-07-02 08:42:43 -0700231 RecentTasks(ActivityTaskManagerService service, TaskPersister taskPersister) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700232 mService = service;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700233 mSupervisor = mService.mStackSupervisor;
Winson Chung1dbc8112017-09-28 18:05:31 -0700234 mTaskPersister = taskPersister;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700235 mGlobalMaxNumTasks = ActivityTaskManager.getMaxRecentTasksStatic();
Winson Chungd6aa3db2017-10-05 17:18:43 -0700236 mHasVisibleRecentTasks = true;
Vinit Nayak3e737492019-07-24 13:03:15 -0700237 mTaskNotificationController = service.getTaskChangeNotificationController();
Winson Chung1dbc8112017-09-28 18:05:31 -0700238 }
239
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700240 RecentTasks(ActivityTaskManagerService service, ActivityStackSupervisor stackSupervisor) {
Winson Chungd6aa3db2017-10-05 17:18:43 -0700241 final File systemDir = Environment.getDataSystemDirectory();
242 final Resources res = service.mContext.getResources();
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800243 mService = service;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700244 mSupervisor = mService.mStackSupervisor;
Garfield Tan891146c2018-10-09 12:14:00 -0700245 mTaskPersister = new TaskPersister(systemDir, stackSupervisor, service, this,
246 stackSupervisor.mPersisterQueue);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700247 mGlobalMaxNumTasks = ActivityTaskManager.getMaxRecentTasksStatic();
Vinit Nayak3e737492019-07-24 13:03:15 -0700248 mTaskNotificationController = service.getTaskChangeNotificationController();
Winson Chungd6aa3db2017-10-05 17:18:43 -0700249 mHasVisibleRecentTasks = res.getBoolean(com.android.internal.R.bool.config_hasRecents);
Winson Chung3f0e59a2017-10-25 10:19:05 -0700250 loadParametersFromResources(res);
Winson Chungd6aa3db2017-10-05 17:18:43 -0700251 }
252
253 @VisibleForTesting
254 void setParameters(int minNumVisibleTasks, int maxNumVisibleTasks,
255 long activeSessionDurationMs) {
256 mMinNumVisibleTasks = minNumVisibleTasks;
257 mMaxNumVisibleTasks = maxNumVisibleTasks;
258 mActiveTasksSessionDurationMs = activeSessionDurationMs;
259 }
260
261 @VisibleForTesting
262 void setGlobalMaxNumTasks(int globalMaxNumTasks) {
263 mGlobalMaxNumTasks = globalMaxNumTasks;
264 }
265
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800266 @VisibleForTesting
Winson Chung1fe58e92019-04-10 14:18:06 -0700267 void setFreezeTaskListTimeout(long timeoutMs) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800268 mFreezeTaskListTimeoutMs = timeoutMs;
269 }
270
271 PointerEventListener getInputListener() {
272 return mListener;
273 }
274
275 /**
276 * Freezes the current recent task list order until either a user interaction with the current
277 * app, or a timeout occurs.
278 */
279 void setFreezeTaskListReordering() {
Vinit Nayak8e547962019-10-07 10:36:41 -0700280 // Only fire the callback once per quickswitch session, not on every individual switch
281 if (!mFreezeTaskListReordering) {
282 mTaskNotificationController.notifyTaskListFrozen(true);
283 mFreezeTaskListReordering = true;
284 }
285
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800286 // Always update the reordering time when this is called to ensure that the timeout
287 // is reset
Winson Chung1fe58e92019-04-10 14:18:06 -0700288 mService.mH.removeCallbacks(mResetFreezeTaskListOnTimeoutRunnable);
289 mService.mH.postDelayed(mResetFreezeTaskListOnTimeoutRunnable, mFreezeTaskListTimeoutMs);
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800290 }
291
292 /**
293 * Commits the frozen recent task list order, moving the provided {@param topTask} to the
294 * front of the list.
295 */
Louis Changcdec0802019-11-11 11:45:07 +0800296 void resetFreezeTaskListReordering(Task topTask) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800297 if (!mFreezeTaskListReordering) {
298 return;
299 }
300
301 // Once we end freezing the task list, reset the existing task order to the stable state
302 mFreezeTaskListReordering = false;
Winson Chung1fe58e92019-04-10 14:18:06 -0700303 mService.mH.removeCallbacks(mResetFreezeTaskListOnTimeoutRunnable);
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800304
305 // If the top task is provided, then restore the top task to the front of the list
306 if (topTask != null) {
307 mTasks.remove(topTask);
308 mTasks.add(0, topTask);
309 }
310
311 // Resume trimming tasks
312 trimInactiveRecentTasks();
Winson Chung1fe58e92019-04-10 14:18:06 -0700313
Vinit Nayak3e737492019-07-24 13:03:15 -0700314 mTaskNotificationController.notifyTaskStackChanged();
Vinit Nayak8e547962019-10-07 10:36:41 -0700315 mTaskNotificationController.notifyTaskListFrozen(false);
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800316 }
317
318 /**
319 * Resets the frozen recent task list order if the timeout has passed. This should be called
320 * before we need to iterate the task list in order (either for purposes of returning the list
321 * to SystemUI or if we need to trim tasks in order)
322 */
Winson Chung1fe58e92019-04-10 14:18:06 -0700323 @VisibleForTesting
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800324 void resetFreezeTaskListReorderingOnTimeout() {
chaviwa13051f2019-06-14 16:41:17 -0700325 synchronized (mService.mGlobalLock) {
326 final ActivityStack focusedStack = mService.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900327 final Task topTask = focusedStack != null ? focusedStack.getTopMostTask() : null;
chaviwa13051f2019-06-14 16:41:17 -0700328 resetFreezeTaskListReordering(topTask);
329 }
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800330 }
331
332 @VisibleForTesting
333 boolean isFreezeTaskListReorderingSet() {
334 return mFreezeTaskListReordering;
335 }
336
Winson Chungd6aa3db2017-10-05 17:18:43 -0700337 /**
338 * Loads the parameters from the system resources.
339 */
340 @VisibleForTesting
341 void loadParametersFromResources(Resources res) {
342 if (ActivityManager.isLowRamDeviceStatic()) {
343 mMinNumVisibleTasks = res.getInteger(
344 com.android.internal.R.integer.config_minNumVisibleRecentTasks_lowRam);
345 mMaxNumVisibleTasks = res.getInteger(
346 com.android.internal.R.integer.config_maxNumVisibleRecentTasks_lowRam);
347 } else if (SystemProperties.getBoolean("ro.recents.grid", false)) {
348 mMinNumVisibleTasks = res.getInteger(
349 com.android.internal.R.integer.config_minNumVisibleRecentTasks_grid);
350 mMaxNumVisibleTasks = res.getInteger(
351 com.android.internal.R.integer.config_maxNumVisibleRecentTasks_grid);
352 } else {
353 mMinNumVisibleTasks = res.getInteger(
354 com.android.internal.R.integer.config_minNumVisibleRecentTasks);
355 mMaxNumVisibleTasks = res.getInteger(
356 com.android.internal.R.integer.config_maxNumVisibleRecentTasks);
357 }
358 final int sessionDurationHrs = res.getInteger(
359 com.android.internal.R.integer.config_activeTaskDurationHours);
360 mActiveTasksSessionDurationMs = (sessionDurationHrs > 0)
361 ? TimeUnit.HOURS.toMillis(sessionDurationHrs)
362 : -1;
Winson Chung1dbc8112017-09-28 18:05:31 -0700363 }
364
Winson Chung3f0e59a2017-10-25 10:19:05 -0700365 /**
366 * Loads the static recents component. This is called after the system is ready, but before
367 * any dependent services (like SystemUI) is started.
368 */
369 void loadRecentsComponent(Resources res) {
370 final String rawRecentsComponent = res.getString(
371 com.android.internal.R.string.config_recentsComponentName);
372 if (TextUtils.isEmpty(rawRecentsComponent)) {
373 return;
374 }
375
376 final ComponentName cn = ComponentName.unflattenFromString(rawRecentsComponent);
377 if (cn != null) {
378 try {
379 final ApplicationInfo appInfo = AppGlobals.getPackageManager()
380 .getApplicationInfo(cn.getPackageName(), 0, mService.mContext.getUserId());
381 if (appInfo != null) {
382 mRecentsUid = appInfo.uid;
383 mRecentsComponent = cn;
384 }
385 } catch (RemoteException e) {
386 Slog.w(TAG, "Could not load application info for recents component: " + cn);
387 }
388 }
389 }
390
391 /**
392 * @return whether the current caller has the same uid as the recents component.
393 */
394 boolean isCallerRecents(int callingUid) {
395 return UserHandle.isSameApp(callingUid, mRecentsUid);
396 }
397
398 /**
399 * @return whether the given component is the recents component and shares the same uid as the
400 * recents component.
401 */
402 boolean isRecentsComponent(ComponentName cn, int uid) {
403 return cn.equals(mRecentsComponent) && UserHandle.isSameApp(uid, mRecentsUid);
404 }
405
Winson Chungec1ef092017-10-25 16:22:34 -0700406 /**
Winson Chungc1674272018-02-21 10:15:17 -0800407 * @return whether the home app is also the active handler of recent tasks.
408 */
409 boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700410 final ComponentName defaultHomeActivity = mService.getPackageManagerInternalLocked()
Winson Chungc1674272018-02-21 10:15:17 -0800411 .getDefaultHomeActivity(userId);
Alice Sheng1de98fc2018-03-16 09:45:58 -0700412 return defaultHomeActivity != null && mRecentsComponent != null &&
Winson Chungc1674272018-02-21 10:15:17 -0800413 defaultHomeActivity.getPackageName().equals(mRecentsComponent.getPackageName());
414 }
415
416 /**
Winson Chungec1ef092017-10-25 16:22:34 -0700417 * @return the recents component.
418 */
419 ComponentName getRecentsComponent() {
420 return mRecentsComponent;
421 }
422
423 /**
Philip P. Moltmannee295092020-02-10 08:46:26 -0800424 * @return the featureId for the recents component.
425 */
426 @Nullable String getRecentsComponentFeatureId() {
427 return mFeatureId;
428 }
429
430 /**
Winson Chungec1ef092017-10-25 16:22:34 -0700431 * @return the uid for the recents component.
432 */
433 int getRecentsComponentUid() {
434 return mRecentsUid;
435 }
436
Winson Chung1dbc8112017-09-28 18:05:31 -0700437 void registerCallback(Callbacks callback) {
438 mCallbacks.add(callback);
439 }
440
441 void unregisterCallback(Callbacks callback) {
442 mCallbacks.remove(callback);
443 }
444
Louis Changcdec0802019-11-11 11:45:07 +0800445 private void notifyTaskAdded(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700446 for (int i = 0; i < mCallbacks.size(); i++) {
447 mCallbacks.get(i).onRecentTaskAdded(task);
448 }
Vinit Nayak3e737492019-07-24 13:03:15 -0700449 mTaskNotificationController.notifyTaskListUpdated();
Winson Chung1dbc8112017-09-28 18:05:31 -0700450 }
451
Louis Changcdec0802019-11-11 11:45:07 +0800452 private void notifyTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700453 for (int i = 0; i < mCallbacks.size(); i++) {
Winson Chunge6439102018-07-30 15:48:01 -0700454 mCallbacks.get(i).onRecentTaskRemoved(task, wasTrimmed, killProcess);
Winson Chung1dbc8112017-09-28 18:05:31 -0700455 }
Vinit Nayak3e737492019-07-24 13:03:15 -0700456 mTaskNotificationController.notifyTaskListUpdated();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800457 }
458
459 /**
Suprabh Shuklaf5bf0cb2016-01-19 17:42:03 -0800460 * Loads the persistent recentTasks for {@code userId} into this list from persistent storage.
461 * Does nothing if they are already loaded.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800462 *
463 * @param userId the user Id
464 */
465 void loadUserRecentsLocked(int userId) {
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900466 if (mUsersWithRecentsLoaded.get(userId)) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700467 // User already loaded, return early
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900468 return;
469 }
470
471 // Load the task ids if not loaded.
472 loadPersistedTaskIdsForUserLocked(userId);
473
474 // Check if any tasks are added before recents is loaded
475 final SparseBooleanArray preaddedTasks = new SparseBooleanArray();
Louis Changcdec0802019-11-11 11:45:07 +0800476 for (final Task task : mTasks) {
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700477 if (task.mUserId == userId && shouldPersistTaskLocked(task)) {
478 preaddedTasks.put(task.mTaskId, true);
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900479 }
480 }
481
482 Slog.i(TAG, "Loading recents for user " + userId + " into memory.");
Louis Changcdec0802019-11-11 11:45:07 +0800483 List<Task> tasks = mTaskPersister.restoreTasksForUserLocked(userId, preaddedTasks);
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800484 mTasks.addAll(tasks);
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900485 cleanupLocked(userId);
486 mUsersWithRecentsLoaded.put(userId, true);
487
488 // If we have tasks added before loading recents, we need to update persistent task IDs.
489 if (preaddedTasks.size() > 0) {
490 syncPersistentTaskIdsLocked();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800491 }
492 }
493
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800494 private void loadPersistedTaskIdsForUserLocked(int userId) {
495 // An empty instead of a null set here means that no persistent taskIds were present
496 // on file when we loaded them.
497 if (mPersistedTaskIds.get(userId) == null) {
498 mPersistedTaskIds.put(userId, mTaskPersister.loadPersistedTaskIdsForUser(userId));
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700499 Slog.i(TAG, "Loaded persisted task ids for user " + userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800500 }
501 }
502
Winson Chung1dbc8112017-09-28 18:05:31 -0700503 /**
504 * @return whether the {@param taskId} is currently in use for the given user.
505 */
506 boolean containsTaskId(int taskId, int userId) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800507 loadPersistedTaskIdsForUserLocked(userId);
508 return mPersistedTaskIds.get(userId).get(taskId);
509 }
510
Winson Chung1dbc8112017-09-28 18:05:31 -0700511 /**
512 * @return all the task ids for the user with the given {@param userId}.
513 */
514 SparseBooleanArray getTaskIdsForUser(int userId) {
515 loadPersistedTaskIdsForUserLocked(userId);
516 return mPersistedTaskIds.get(userId);
517 }
518
519 /**
520 * Kicks off the task persister to write any pending tasks to disk.
521 */
Louis Changcdec0802019-11-11 11:45:07 +0800522 void notifyTaskPersisterLocked(Task task, boolean flush) {
Andrii Kulian02b7a832016-10-06 23:11:56 -0700523 final ActivityStack stack = task != null ? task.getStack() : null;
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800524 if (stack != null && stack.isHomeOrRecentsStack()) {
525 // Never persist the home or recents stack.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800526 return;
527 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800528 syncPersistentTaskIdsLocked();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800529 mTaskPersister.wakeup(task, flush);
530 }
531
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800532 private void syncPersistentTaskIdsLocked() {
533 for (int i = mPersistedTaskIds.size() - 1; i >= 0; i--) {
534 int userId = mPersistedTaskIds.keyAt(i);
535 if (mUsersWithRecentsLoaded.get(userId)) {
536 // Recents are loaded only after task ids are loaded. Therefore, the set of taskids
537 // referenced here should not be null.
538 mPersistedTaskIds.valueAt(i).clear();
539 }
540 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700541 for (int i = mTasks.size() - 1; i >= 0; i--) {
Louis Changcdec0802019-11-11 11:45:07 +0800542 final Task task = mTasks.get(i);
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900543 if (shouldPersistTaskLocked(task)) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800544 // Set of persisted taskIds for task.userId should not be null here
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700545 // TODO Investigate why it can happen. For now initialize with an empty set
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700546 if (mPersistedTaskIds.get(task.mUserId) == null) {
547 Slog.wtf(TAG, "No task ids found for userId " + task.mUserId + ". task=" + task
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700548 + " mPersistedTaskIds=" + mPersistedTaskIds);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700549 mPersistedTaskIds.put(task.mUserId, new SparseBooleanArray());
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700550 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700551 mPersistedTaskIds.get(task.mUserId).put(task.mTaskId, true);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800552 }
553 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800554 }
555
Louis Changcdec0802019-11-11 11:45:07 +0800556 private static boolean shouldPersistTaskLocked(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700557 final ActivityStack stack = task.getStack();
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900558 return task.isPersistable && (stack == null || !stack.isHomeOrRecentsStack());
559 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800560
561 void onSystemReadyLocked() {
Winson Chung3f0e59a2017-10-25 10:19:05 -0700562 loadRecentsComponent(mService.mContext.getResources());
Winson Chung1dbc8112017-09-28 18:05:31 -0700563 mTasks.clear();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800564 }
565
566 Bitmap getTaskDescriptionIcon(String path) {
567 return mTaskPersister.getTaskDescriptionIcon(path);
568 }
569
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800570 void saveImage(Bitmap image, String path) {
571 mTaskPersister.saveImage(image, path);
572 }
573
574 void flush() {
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700575 synchronized (mService.mGlobalLock) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800576 syncPersistentTaskIdsLocked();
577 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800578 mTaskPersister.flush();
579 }
580
581 /**
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800582 * Returns all userIds for which recents from persistent storage are loaded into this list.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800583 *
584 * @return an array of userIds.
585 */
586 int[] usersWithRecentsLoadedLocked() {
587 int[] usersWithRecentsLoaded = new int[mUsersWithRecentsLoaded.size()];
588 int len = 0;
589 for (int i = 0; i < usersWithRecentsLoaded.length; i++) {
590 int userId = mUsersWithRecentsLoaded.keyAt(i);
591 if (mUsersWithRecentsLoaded.valueAt(i)) {
592 usersWithRecentsLoaded[len++] = userId;
593 }
594 }
595 if (len < usersWithRecentsLoaded.length) {
596 // should never happen.
597 return Arrays.copyOf(usersWithRecentsLoaded, len);
598 }
599 return usersWithRecentsLoaded;
600 }
601
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800602 /**
603 * Removes recent tasks and any other state kept in memory for the passed in user. Does not
604 * touch the information present on persistent storage.
605 *
606 * @param userId the id of the user
607 */
608 void unloadUserDataFromMemoryLocked(int userId) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700609 if (mUsersWithRecentsLoaded.get(userId)) {
610 Slog.i(TAG, "Unloading recents for user " + userId + " from memory.");
611 mUsersWithRecentsLoaded.delete(userId);
612 removeTasksForUserLocked(userId);
613 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800614 mPersistedTaskIds.delete(userId);
615 mTaskPersister.unloadUserDataFromMemory(userId);
616 }
617
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800618 /** Remove recent tasks for a user. */
Winson Chung1dbc8112017-09-28 18:05:31 -0700619 private void removeTasksForUserLocked(int userId) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800620 if(userId <= 0) {
621 Slog.i(TAG, "Can't remove recent task on user " + userId);
622 return;
623 }
624
Winson Chung1dbc8112017-09-28 18:05:31 -0700625 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800626 Task task = mTasks.get(i);
627 if (task.mUserId == userId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700628 if(DEBUG_TASKS) Slog.i(TAG_TASKS,
Louis Changcdec0802019-11-11 11:45:07 +0800629 "remove RecentTask " + task + " when finishing user" + userId);
630 remove(task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800631 }
632 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800633 }
634
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000635 void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
636 final Set<String> packageNames = Sets.newHashSet(packages);
Winson Chung1dbc8112017-09-28 18:05:31 -0700637 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800638 final Task task = mTasks.get(i);
639 if (task.realActivity != null
640 && packageNames.contains(task.realActivity.getPackageName())
641 && task.mUserId == userId
642 && task.realActivitySuspended != suspended) {
643 task.realActivitySuspended = suspended;
Suprabh Shukla021b57a2018-03-08 18:21:50 -0800644 if (suspended) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900645 mSupervisor.removeTask(task, false, REMOVE_FROM_RECENTS, "suspended-package");
Suprabh Shukla021b57a2018-03-08 18:21:50 -0800646 }
Louis Changcdec0802019-11-11 11:45:07 +0800647 notifyTaskPersisterLocked(task, false);
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000648 }
649 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700650 }
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000651
Charles Hed62f9652017-11-01 10:05:51 +0000652 void onLockTaskModeStateChanged(int lockTaskModeState, int userId) {
653 if (lockTaskModeState != ActivityManager.LOCK_TASK_MODE_LOCKED) {
654 return;
655 }
656 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800657 final Task task = mTasks.get(i);
658 if (task.mUserId == userId && !mService.getLockTaskController().isTaskWhitelisted(task)) {
659 remove(task);
Charles Hed62f9652017-11-01 10:05:51 +0000660 }
661 }
662 }
663
Winson Chung1dbc8112017-09-28 18:05:31 -0700664 void removeTasksByPackageName(String packageName, int userId) {
Winson Chung63085842017-10-13 17:18:58 -0700665 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800666 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -0700667 final String taskPackageName =
Louis Changcdec0802019-11-11 11:45:07 +0800668 task.getBaseIntent().getComponent().getPackageName();
669 if (task.mUserId != userId) continue;
Winson Chung99720d42018-04-09 11:28:46 -0700670 if (!taskPackageName.equals(packageName)) continue;
Winson Chung1dbc8112017-09-28 18:05:31 -0700671
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900672 mSupervisor.removeTask(task, true, REMOVE_FROM_RECENTS, "remove-package-task");
Winson Chung1dbc8112017-09-28 18:05:31 -0700673 }
674 }
675
Winson Chung42fa21f2019-04-02 16:23:46 -0700676 void removeAllVisibleTasks(int userId) {
Winson Chungcdd4c3f2019-04-17 15:40:11 -0700677 Set<Integer> profileIds = getProfileIds(userId);
Winson Chunge6439102018-07-30 15:48:01 -0700678 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800679 final Task task = mTasks.get(i);
680 if (!profileIds.contains(task.mUserId)) continue;
681 if (isVisibleRecentTask(task)) {
Winson Chunge6439102018-07-30 15:48:01 -0700682 mTasks.remove(i);
Louis Changcdec0802019-11-11 11:45:07 +0800683 notifyTaskRemoved(task, true /* wasTrimmed */, true /* killProcess */);
Winson Chunge6439102018-07-30 15:48:01 -0700684 }
685 }
686 }
687
Winson Chung1dbc8112017-09-28 18:05:31 -0700688 void cleanupDisabledPackageTasksLocked(String packageName, Set<String> filterByClasses,
689 int userId) {
Winson Chung63085842017-10-13 17:18:58 -0700690 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800691 final Task task = mTasks.get(i);
692 if (userId != UserHandle.USER_ALL && task.mUserId != userId) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700693 continue;
694 }
695
Louis Changcdec0802019-11-11 11:45:07 +0800696 ComponentName cn = task.intent != null ? task.intent.getComponent() : null;
Winson Chung1dbc8112017-09-28 18:05:31 -0700697 final boolean sameComponent = cn != null && cn.getPackageName().equals(packageName)
698 && (filterByClasses == null || filterByClasses.contains(cn.getClassName()));
699 if (sameComponent) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900700 mSupervisor.removeTask(task, false, REMOVE_FROM_RECENTS, "disabled-package");
Winson Chung1dbc8112017-09-28 18:05:31 -0700701 }
702 }
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000703 }
704
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800705 /**
706 * Update the recent tasks lists: make sure tasks should still be here (their
707 * applications / activities still exist), update their availability, fix-up ordering
708 * of affiliations.
709 */
710 void cleanupLocked(int userId) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700711 int recentsCount = mTasks.size();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800712 if (recentsCount == 0) {
713 // Happens when called from the packagemanager broadcast before boot,
714 // or just any empty list.
715 return;
716 }
717
Winson Chung1dbc8112017-09-28 18:05:31 -0700718 // Clear the temp lists
719 mTmpAvailActCache.clear();
720 mTmpAvailAppCache.clear();
721
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800722 final IPackageManager pm = AppGlobals.getPackageManager();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800723 for (int i = recentsCount - 1; i >= 0; i--) {
Louis Changcdec0802019-11-11 11:45:07 +0800724 final Task task = mTasks.get(i);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700725 if (userId != UserHandle.USER_ALL && task.mUserId != userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800726 // Only look at tasks for the user ID of interest.
727 continue;
728 }
Wale Ogunwale21e06482019-11-18 05:14:15 -0800729 if (task.autoRemoveRecents && task.getTopNonFinishingActivity() == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800730 // This situation is broken, and we should just get rid of it now.
Winson Chungb4132992018-07-03 15:52:38 -0700731 remove(task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800732 Slog.w(TAG, "Removing auto-remove without activity: " + task);
733 continue;
734 }
735 // Check whether this activity is currently available.
736 if (task.realActivity != null) {
737 ActivityInfo ai = mTmpAvailActCache.get(task.realActivity);
738 if (ai == null) {
739 try {
740 // At this first cut, we're only interested in
741 // activities that are fully runnable based on
742 // current system state.
743 ai = pm.getActivityInfo(task.realActivity,
Philip P. Moltmanncff8f0f2018-03-27 12:51:51 -0700744 PackageManager.MATCH_DEBUG_TRIAGED_MISSING
745 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800746 } catch (RemoteException e) {
747 // Will never happen.
748 continue;
749 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800750 if (ai == null) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700751 ai = NO_ACTIVITY_INFO_TOKEN;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800752 }
753 mTmpAvailActCache.put(task.realActivity, ai);
754 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700755 if (ai == NO_ACTIVITY_INFO_TOKEN) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800756 // This could be either because the activity no longer exists, or the
757 // app is temporarily gone. For the former we want to remove the recents
758 // entry; for the latter we want to mark it as unavailable.
759 ApplicationInfo app = mTmpAvailAppCache
760 .get(task.realActivity.getPackageName());
761 if (app == null) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800762 try {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800763 app = pm.getApplicationInfo(task.realActivity.getPackageName(),
764 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800765 } catch (RemoteException e) {
766 // Will never happen.
767 continue;
768 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800769 if (app == null) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700770 app = NO_APPLICATION_INFO_TOKEN;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800771 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800772 mTmpAvailAppCache.put(task.realActivity.getPackageName(), app);
773 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700774 if (app == NO_APPLICATION_INFO_TOKEN
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800775 || (app.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
776 // Doesn't exist any more! Good-bye.
Winson Chungb4132992018-07-03 15:52:38 -0700777 remove(task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800778 Slog.w(TAG, "Removing no longer valid recent: " + task);
779 continue;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800780 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800781 // Otherwise just not available for now.
782 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
783 "Making recent unavailable: " + task);
784 task.isAvailable = false;
785 }
786 } else {
787 if (!ai.enabled || !ai.applicationInfo.enabled
788 || (ai.applicationInfo.flags
789 & ApplicationInfo.FLAG_INSTALLED) == 0) {
790 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
791 "Making recent unavailable: " + task
792 + " (enabled=" + ai.enabled + "/"
793 + ai.applicationInfo.enabled
794 + " flags="
795 + Integer.toHexString(ai.applicationInfo.flags)
796 + ")");
797 task.isAvailable = false;
798 } else {
799 if (DEBUG_RECENTS && !task.isAvailable) Slog.d(TAG_RECENTS,
800 "Making recent available: " + task);
801 task.isAvailable = true;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800802 }
803 }
804 }
805 }
806
807 // Verify the affiliate chain for each task.
808 int i = 0;
Winson Chung1dbc8112017-09-28 18:05:31 -0700809 recentsCount = mTasks.size();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800810 while (i < recentsCount) {
811 i = processNextAffiliateChainLocked(i);
812 }
813 // recent tasks are now in sorted, affiliated order.
814 }
815
Winson Chung1dbc8112017-09-28 18:05:31 -0700816 /**
817 * @return whether the given {@param task} can be added to the list without causing another
818 * task to be trimmed as a result of that add.
819 */
Louis Changcdec0802019-11-11 11:45:07 +0800820 private boolean canAddTaskWithoutTrim(Task task) {
Winson Chung079221f2017-12-13 17:43:34 -0800821 return findRemoveIndexForAddTask(task) == -1;
Winson Chung1dbc8112017-09-28 18:05:31 -0700822 }
823
824 /**
825 * Returns the list of {@link ActivityManager.AppTask}s.
826 */
827 ArrayList<IBinder> getAppTasksList(int callingUid, String callingPackage) {
828 final ArrayList<IBinder> list = new ArrayList<>();
829 final int size = mTasks.size();
830 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800831 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -0700832 // Skip tasks that do not match the caller. We don't need to verify
833 // callingPackage, because we are also limiting to callingUid and know
834 // that will limit to the correct security sandbox.
Louis Changcdec0802019-11-11 11:45:07 +0800835 if (task.effectiveUid != callingUid) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700836 continue;
837 }
Louis Changcdec0802019-11-11 11:45:07 +0800838 Intent intent = task.getBaseIntent();
Winson Chung1dbc8112017-09-28 18:05:31 -0700839 if (intent == null || !callingPackage.equals(intent.getComponent().getPackageName())) {
840 continue;
841 }
Louis Changcdec0802019-11-11 11:45:07 +0800842 AppTaskImpl taskImpl = new AppTaskImpl(mService, task.mTaskId, callingUid);
Winson Chung1dbc8112017-09-28 18:05:31 -0700843 list.add(taskImpl.asBinder());
844 }
845 return list;
846 }
847
Wale Ogunwale86b74462018-07-02 08:42:43 -0700848 @VisibleForTesting
849 Set<Integer> getProfileIds(int userId) {
850 Set<Integer> userIds = new ArraySet<>();
Sunny Goyale3de30e2020-03-11 22:42:44 -0700851 int[] profileIds = mService.getUserManager().getProfileIds(userId, false /* enabledOnly */);
852 for (int i = 0; i < profileIds.length; i++) {
853 userIds.add(Integer.valueOf(profileIds[i]));
Wale Ogunwale86b74462018-07-02 08:42:43 -0700854 }
855 return userIds;
856 }
857
858 @VisibleForTesting
859 UserInfo getUserInfo(int userId) {
860 return mService.getUserManager().getUserInfo(userId);
861 }
862
863 @VisibleForTesting
864 int[] getCurrentProfileIds() {
865 return mService.mAmInternal.getCurrentProfileIds();
866 }
867
Winson Chungd2730072019-02-22 14:10:27 -0800868 @VisibleForTesting
869 boolean isUserRunning(int userId, int flags) {
870 return mService.mAmInternal.isUserRunning(userId, flags);
871 }
872
Winson Chung1dbc8112017-09-28 18:05:31 -0700873 /**
874 * @return the list of recent tasks for presentation.
875 */
876 ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
Winson Chung66b08f02020-03-03 14:32:35 -0800877 boolean getTasksAllowed, int userId, int callingUid) {
Winson Chungb4132992018-07-03 15:52:38 -0700878 return new ParceledListSlice<>(getRecentTasksImpl(maxNum, flags, getTasksAllowed,
Winson Chung66b08f02020-03-03 14:32:35 -0800879 userId, callingUid));
Winson Chungb4132992018-07-03 15:52:38 -0700880 }
881
Winson Chungb4132992018-07-03 15:52:38 -0700882 /**
883 * @return the list of recent tasks for presentation.
884 */
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800885 private ArrayList<ActivityManager.RecentTaskInfo> getRecentTasksImpl(int maxNum, int flags,
Winson Chung66b08f02020-03-03 14:32:35 -0800886 boolean getTasksAllowed, int userId, int callingUid) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700887 final boolean withExcluded = (flags & RECENT_WITH_EXCLUDED) != 0;
888
Winson Chungd2730072019-02-22 14:10:27 -0800889 if (!isUserRunning(userId, FLAG_AND_UNLOCKED)) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700890 Slog.i(TAG, "user " + userId + " is still locked. Cannot load recents");
Winson Chungb4132992018-07-03 15:52:38 -0700891 return new ArrayList<>();
Winson Chung1dbc8112017-09-28 18:05:31 -0700892 }
893 loadUserRecentsLocked(userId);
894
Wale Ogunwale86b74462018-07-02 08:42:43 -0700895 final Set<Integer> includedUsers = getProfileIds(userId);
Winson Chung1dbc8112017-09-28 18:05:31 -0700896 includedUsers.add(Integer.valueOf(userId));
897
898 final ArrayList<ActivityManager.RecentTaskInfo> res = new ArrayList<>();
899 final int size = mTasks.size();
Winson Chungfb44d212017-10-04 11:39:10 -0700900 int numVisibleTasks = 0;
Winson Chung1dbc8112017-09-28 18:05:31 -0700901 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800902 final Task task = mTasks.get(i);
Winson Chungfb44d212017-10-04 11:39:10 -0700903
Louis Changcdec0802019-11-11 11:45:07 +0800904 if (isVisibleRecentTask(task)) {
Winson Chungfb44d212017-10-04 11:39:10 -0700905 numVisibleTasks++;
Louis Changcdec0802019-11-11 11:45:07 +0800906 if (isInVisibleRange(task, i, numVisibleTasks, withExcluded)) {
Winson Chungfb44d212017-10-04 11:39:10 -0700907 // Fall through
908 } else {
909 // Not in visible range
910 continue;
911 }
912 } else {
913 // Not visible
914 continue;
915 }
916
Winson Chung1dbc8112017-09-28 18:05:31 -0700917 // Skip remaining tasks once we reach the requested size
918 if (res.size() >= maxNum) {
919 continue;
920 }
921
922 // Only add calling user or related users recent tasks
Louis Changcdec0802019-11-11 11:45:07 +0800923 if (!includedUsers.contains(Integer.valueOf(task.mUserId))) {
924 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700925 continue;
926 }
927
Louis Changcdec0802019-11-11 11:45:07 +0800928 if (task.realActivitySuspended) {
929 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, activity suspended: " + task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700930 continue;
931 }
932
Winson Chungd2730072019-02-22 14:10:27 -0800933 if (!getTasksAllowed) {
934 // If the caller doesn't have the GET_TASKS permission, then only
935 // allow them to see a small subset of tasks -- their own and home.
Louis Changcdec0802019-11-11 11:45:07 +0800936 if (!task.isActivityTypeHome() && task.effectiveUid != callingUid) {
937 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700938 continue;
939 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700940 }
Winson Chungd2730072019-02-22 14:10:27 -0800941
Wale Ogunwale21e06482019-11-18 05:14:15 -0800942 if (task.autoRemoveRecents && task.getTopNonFinishingActivity() == null) {
Winson Chungd2730072019-02-22 14:10:27 -0800943 // Don't include auto remove tasks that are finished or finishing.
944 if (DEBUG_RECENTS) {
Louis Changcdec0802019-11-11 11:45:07 +0800945 Slog.d(TAG_RECENTS, "Skipping, auto-remove without activity: " + task);
Winson Chungd2730072019-02-22 14:10:27 -0800946 }
947 continue;
948 }
Louis Changcdec0802019-11-11 11:45:07 +0800949 if ((flags & RECENT_IGNORE_UNAVAILABLE) != 0 && !task.isAvailable) {
Winson Chungd2730072019-02-22 14:10:27 -0800950 if (DEBUG_RECENTS) {
Louis Changcdec0802019-11-11 11:45:07 +0800951 Slog.d(TAG_RECENTS, "Skipping, unavail real act: " + task);
Winson Chungd2730072019-02-22 14:10:27 -0800952 }
953 continue;
954 }
955
Louis Changcdec0802019-11-11 11:45:07 +0800956 if (!task.mUserSetupComplete) {
Winson Chungd2730072019-02-22 14:10:27 -0800957 // Don't include task launched while user is not done setting-up.
958 if (DEBUG_RECENTS) {
Louis Changcdec0802019-11-11 11:45:07 +0800959 Slog.d(TAG_RECENTS, "Skipping, user setup not complete: " + task);
Winson Chungd2730072019-02-22 14:10:27 -0800960 }
961 continue;
962 }
963
Winson Chung02757712020-06-23 10:41:44 -0700964 res.add(createRecentTaskInfo(task, true /* stripExtras */));
Winson Chung1dbc8112017-09-28 18:05:31 -0700965 }
Winson Chungb4132992018-07-03 15:52:38 -0700966 return res;
Winson Chung1dbc8112017-09-28 18:05:31 -0700967 }
968
969 /**
970 * @return the list of persistable task ids.
971 */
972 void getPersistableTaskIds(ArraySet<Integer> persistentTaskIds) {
973 final int size = mTasks.size();
974 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800975 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -0700976 if (TaskPersister.DEBUG) Slog.d(TAG, "LazyTaskWriter: task=" + task
977 + " persistable=" + task.isPersistable);
978 final ActivityStack stack = task.getStack();
979 if ((task.isPersistable || task.inRecents)
980 && (stack == null || !stack.isHomeOrRecentsStack())) {
981 if (TaskPersister.DEBUG) Slog.d(TAG, "adding to persistentTaskIds task=" + task);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700982 persistentTaskIds.add(task.mTaskId);
Winson Chung1dbc8112017-09-28 18:05:31 -0700983 } else {
984 if (TaskPersister.DEBUG) Slog.d(TAG, "omitting from persistentTaskIds task="
985 + task);
986 }
987 }
988 }
989
Winson Chungd6aa3db2017-10-05 17:18:43 -0700990 @VisibleForTesting
Louis Changcdec0802019-11-11 11:45:07 +0800991 ArrayList<Task> getRawTasks() {
Winson Chungd6aa3db2017-10-05 17:18:43 -0700992 return mTasks;
993 }
994
Winson Chung1dbc8112017-09-28 18:05:31 -0700995 /**
Vadim Tryshev593e9562018-03-08 17:15:45 -0800996 * @return ids of tasks that are presented in Recents UI.
997 */
998 SparseBooleanArray getRecentTaskIds() {
999 final SparseBooleanArray res = new SparseBooleanArray();
1000 final int size = mTasks.size();
1001 int numVisibleTasks = 0;
1002 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001003 final Task task = mTasks.get(i);
1004 if (isVisibleRecentTask(task)) {
Vadim Tryshev593e9562018-03-08 17:15:45 -08001005 numVisibleTasks++;
Louis Changcdec0802019-11-11 11:45:07 +08001006 if (isInVisibleRange(task, i, numVisibleTasks, false /* skipExcludedCheck */)) {
1007 res.put(task.mTaskId, true);
Vadim Tryshev593e9562018-03-08 17:15:45 -08001008 }
1009 }
1010 }
1011 return res;
1012 }
1013
1014 /**
Winson Chung1dbc8112017-09-28 18:05:31 -07001015 * @return the task in the task list with the given {@param id} if one exists.
1016 */
Louis Changcdec0802019-11-11 11:45:07 +08001017 Task getTask(int id) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001018 final int recentsCount = mTasks.size();
1019 for (int i = 0; i < recentsCount; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001020 Task task = mTasks.get(i);
1021 if (task.mTaskId == id) {
1022 return task;
Winson Chung1dbc8112017-09-28 18:05:31 -07001023 }
1024 }
1025 return null;
1026 }
1027
1028 /**
1029 * Add a new task to the recent tasks list.
1030 */
Louis Changcdec0802019-11-11 11:45:07 +08001031 void add(Task task) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001032 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "add: task=" + task);
1033
Riddle Hsuf2ff25f2020-04-29 19:15:33 +08001034 // Only allow trimming task if it is not updating visibility for activities, so the caller
1035 // doesn't need to handle unexpected size and index when looping task containers.
1036 final boolean canTrimTask = !mSupervisor.inActivityVisibilityUpdate();
1037
Riddle Hsu4e361e92019-12-24 16:51:09 +08001038 // Clean up the hidden tasks when going to home because the user may not be unable to return
1039 // to the task from recents.
Riddle Hsuf2ff25f2020-04-29 19:15:33 +08001040 if (canTrimTask && !mHiddenTasks.isEmpty() && task.isActivityTypeHome()) {
Riddle Hsu4e361e92019-12-24 16:51:09 +08001041 removeUnreachableHiddenTasks(task.getWindowingMode());
1042 }
1043
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001044 final boolean isAffiliated = task.mAffiliatedTaskId != task.mTaskId
Winson Chung1dbc8112017-09-28 18:05:31 -07001045 || task.mNextAffiliateTaskId != INVALID_TASK_ID
1046 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
1047
1048 int recentsCount = mTasks.size();
1049 // Quick case: never add voice sessions.
1050 // TODO: VI what about if it's just an activity?
1051 // Probably nothing to do here
1052 if (task.voiceSession != null) {
1053 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1054 "addRecent: not adding voice interaction " + task);
1055 return;
1056 }
1057 // Another quick case: check if the top-most recent task is the same.
1058 if (!isAffiliated && recentsCount > 0 && mTasks.get(0) == task) {
1059 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: already at top: " + task);
1060 return;
1061 }
1062 // Another quick case: check if this is part of a set of affiliated
1063 // tasks that are at the top.
1064 if (isAffiliated && recentsCount > 0 && task.inRecents
1065 && task.mAffiliatedTaskId == mTasks.get(0).mAffiliatedTaskId) {
1066 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: affiliated " + mTasks.get(0)
1067 + " at top when adding " + task);
1068 return;
1069 }
1070
1071 boolean needAffiliationFix = false;
1072
1073 // Slightly less quick case: the task is already in recents, so all we need
1074 // to do is move it.
1075 if (task.inRecents) {
1076 int taskIndex = mTasks.indexOf(task);
1077 if (taskIndex >= 0) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001078 if (!isAffiliated) {
1079 if (!mFreezeTaskListReordering) {
1080 // Simple case: this is not an affiliated task, so we just move it to the
1081 // front unless overridden by the provided activity options
1082 mTasks.remove(taskIndex);
1083 mTasks.add(0, task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001084
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001085 if (DEBUG_RECENTS) {
1086 Slog.d(TAG_RECENTS, "addRecent: moving to top " + task
1087 + " from " + taskIndex);
1088 }
1089 }
1090 notifyTaskPersisterLocked(task, false);
1091 return;
Winson Chung1dbc8112017-09-28 18:05:31 -07001092 }
1093 } else {
1094 Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
1095 needAffiliationFix = true;
1096 }
1097 }
1098
1099 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: trimming tasks for " + task);
Winson Chung079221f2017-12-13 17:43:34 -08001100 removeForAddTask(task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001101
1102 task.inRecents = true;
1103 if (!isAffiliated || needAffiliationFix) {
1104 // If this is a simple non-affiliated task, or we had some failure trying to
1105 // handle it as part of an affilated task, then just place it at the top.
1106 mTasks.add(0, task);
1107 notifyTaskAdded(task);
1108 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding " + task);
1109 } else if (isAffiliated) {
1110 // If this is a new affiliated task, then move all of the affiliated tasks
1111 // to the front and insert this new one.
Louis Changcdec0802019-11-11 11:45:07 +08001112 Task other = task.mNextAffiliate;
Winson Chung1dbc8112017-09-28 18:05:31 -07001113 if (other == null) {
1114 other = task.mPrevAffiliate;
1115 }
1116 if (other != null) {
1117 int otherIndex = mTasks.indexOf(other);
1118 if (otherIndex >= 0) {
1119 // Insert new task at appropriate location.
1120 int taskIndex;
1121 if (other == task.mNextAffiliate) {
1122 // We found the index of our next affiliation, which is who is
1123 // before us in the list, so add after that point.
1124 taskIndex = otherIndex+1;
1125 } else {
1126 // We found the index of our previous affiliation, which is who is
1127 // after us in the list, so add at their position.
1128 taskIndex = otherIndex;
1129 }
1130 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1131 "addRecent: new affiliated task added at " + taskIndex + ": " + task);
1132 mTasks.add(taskIndex, task);
1133 notifyTaskAdded(task);
1134
1135 // Now move everything to the front.
1136 if (moveAffiliatedTasksToFront(task, taskIndex)) {
1137 // All went well.
1138 return;
1139 }
1140
1141 // Uh oh... something bad in the affiliation chain, try to rebuild
1142 // everything and then go through our general path of adding a new task.
1143 needAffiliationFix = true;
1144 } else {
1145 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1146 "addRecent: couldn't find other affiliation " + other);
1147 needAffiliationFix = true;
1148 }
1149 } else {
1150 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1151 "addRecent: adding affiliated task without next/prev:" + task);
1152 needAffiliationFix = true;
1153 }
1154 }
1155
1156 if (needAffiliationFix) {
1157 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: regrouping affiliations");
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001158 cleanupLocked(task.mUserId);
Winson Chung1dbc8112017-09-28 18:05:31 -07001159 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001160
1161 // Trim the set of tasks to the active set
Riddle Hsuf2ff25f2020-04-29 19:15:33 +08001162 if (canTrimTask) {
1163 trimInactiveRecentTasks();
1164 }
Winson Chung081676e2019-12-11 13:55:19 -08001165 notifyTaskPersisterLocked(task, false /* flush */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001166 }
1167
1168 /**
1169 * Add the task to the bottom if possible.
1170 */
Louis Changcdec0802019-11-11 11:45:07 +08001171 boolean addToBottom(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001172 if (!canAddTaskWithoutTrim(task)) {
1173 // Adding this task would cause the task to be removed (since it's appended at
1174 // the bottom and would be trimmed) so just return now
1175 return false;
1176 }
1177
1178 add(task);
1179 return true;
1180 }
1181
1182 /**
1183 * Remove a task from the recent tasks list.
1184 */
Louis Changcdec0802019-11-11 11:45:07 +08001185 void remove(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001186 mTasks.remove(task);
Winson Chunge6439102018-07-30 15:48:01 -07001187 notifyTaskRemoved(task, false /* wasTrimmed */, false /* killProcess */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001188 }
1189
1190 /**
1191 * Trims the recents task list to the global max number of recents.
1192 */
Winson Chungd6aa3db2017-10-05 17:18:43 -07001193 private void trimInactiveRecentTasks() {
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001194 if (mFreezeTaskListReordering) {
1195 // Defer trimming inactive recent tasks until we are unfrozen
1196 return;
1197 }
1198
Winson Chung1dbc8112017-09-28 18:05:31 -07001199 int recentsCount = mTasks.size();
Winson Chungd6aa3db2017-10-05 17:18:43 -07001200
1201 // Remove from the end of the list until we reach the max number of recents
1202 while (recentsCount > mGlobalMaxNumTasks) {
Louis Changcdec0802019-11-11 11:45:07 +08001203 final Task task = mTasks.remove(recentsCount - 1);
1204 notifyTaskRemoved(task, true /* wasTrimmed */, false /* killProcess */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001205 recentsCount--;
Louis Changcdec0802019-11-11 11:45:07 +08001206 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming over max-recents task=" + task
Winson Chungd6aa3db2017-10-05 17:18:43 -07001207 + " max=" + mGlobalMaxNumTasks);
Winson Chung1dbc8112017-09-28 18:05:31 -07001208 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001209
1210 // Remove any tasks that belong to currently quiet profiles
Wale Ogunwale86b74462018-07-02 08:42:43 -07001211 final int[] profileUserIds = getCurrentProfileIds();
Winson Chungd6aa3db2017-10-05 17:18:43 -07001212 mTmpQuietProfileUserIds.clear();
1213 for (int userId : profileUserIds) {
Wale Ogunwale86b74462018-07-02 08:42:43 -07001214 final UserInfo userInfo = getUserInfo(userId);
Winson Chung129771a02017-10-18 13:49:42 -07001215 if (userInfo != null && userInfo.isManagedProfile() && userInfo.isQuietModeEnabled()) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001216 mTmpQuietProfileUserIds.put(userId, true);
1217 }
1218 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "User: " + userInfo
1219 + " quiet=" + mTmpQuietProfileUserIds.get(userId));
1220 }
1221
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001222 // Remove any inactive tasks, calculate the latest set of visible tasks.
Winson Chungd6aa3db2017-10-05 17:18:43 -07001223 int numVisibleTasks = 0;
1224 for (int i = 0; i < mTasks.size();) {
Louis Changcdec0802019-11-11 11:45:07 +08001225 final Task task = mTasks.get(i);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001226
1227 if (isActiveRecentTask(task, mTmpQuietProfileUserIds)) {
1228 if (!mHasVisibleRecentTasks) {
1229 // Keep all active tasks if visible recent tasks is not supported
1230 i++;
1231 continue;
1232 }
1233
1234 if (!isVisibleRecentTask(task)) {
1235 // Keep all active-but-invisible tasks
1236 i++;
1237 continue;
1238 } else {
1239 numVisibleTasks++;
Winson Chung0a10c3a2019-04-23 15:53:08 -07001240 if (isInVisibleRange(task, i, numVisibleTasks, false /* skipExcludedCheck */)
Winson Chungd2730072019-02-22 14:10:27 -08001241 || !isTrimmable(task)) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001242 // Keep visible tasks in range
1243 i++;
1244 continue;
1245 } else {
Winson Chung0ec2a352017-10-26 11:38:30 -07001246 // Fall through to trim visible tasks that are no longer in range and
1247 // trimmable
Winson Chungd6aa3db2017-10-05 17:18:43 -07001248 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG,
1249 "Trimming out-of-range visible task=" + task);
1250 }
1251 }
1252 } else {
1253 // Fall through to trim inactive tasks
1254 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming inactive task=" + task);
1255 }
1256
1257 // Task is no longer active, trim it from the list
1258 mTasks.remove(task);
Winson Chunge6439102018-07-30 15:48:01 -07001259 notifyTaskRemoved(task, true /* wasTrimmed */, false /* killProcess */);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001260 notifyTaskPersisterLocked(task, false /* flush */);
1261 }
1262 }
1263
1264 /**
1265 * @return whether the given task should be considered active.
1266 */
Louis Changcdec0802019-11-11 11:45:07 +08001267 private boolean isActiveRecentTask(Task task, SparseBooleanArray quietProfileUserIds) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001268 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isActiveRecentTask: task=" + task
1269 + " globalMax=" + mGlobalMaxNumTasks);
1270
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001271 if (quietProfileUserIds.get(task.mUserId)) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001272 // Quiet profile user's tasks are never active
1273 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\tisQuietProfileTask=true");
1274 return false;
1275 }
1276
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001277 if (task.mAffiliatedTaskId != INVALID_TASK_ID && task.mAffiliatedTaskId != task.mTaskId) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001278 // Keep the task active if its affiliated task is also active
Louis Changcdec0802019-11-11 11:45:07 +08001279 final Task affiliatedTask = getTask(task.mAffiliatedTaskId);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001280 if (affiliatedTask != null) {
1281 if (!isActiveRecentTask(affiliatedTask, quietProfileUserIds)) {
1282 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG,
1283 "\taffiliatedWithTask=" + affiliatedTask + " is not active");
1284 return false;
1285 }
1286 }
1287 }
1288
1289 // All other tasks are considered active
1290 return true;
1291 }
1292
1293 /**
1294 * @return whether the given active task should be presented to the user through SystemUI.
1295 */
Mark Renouf2aaf4cd2019-02-19 17:24:43 -05001296 @VisibleForTesting
Louis Changcdec0802019-11-11 11:45:07 +08001297 boolean isVisibleRecentTask(Task task) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001298 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isVisibleRecentTask: task=" + task
1299 + " minVis=" + mMinNumVisibleTasks + " maxVis=" + mMaxNumVisibleTasks
1300 + " sessionDuration=" + mActiveTasksSessionDurationMs
1301 + " inactiveDuration=" + task.getInactiveDuration()
1302 + " activityType=" + task.getActivityType()
Vadim Trysheveff42d32018-03-05 18:33:48 -08001303 + " windowingMode=" + task.getWindowingMode()
1304 + " intentFlags=" + task.getBaseIntent().getFlags());
Winson Chungd6aa3db2017-10-05 17:18:43 -07001305
Winson Chungd6aa3db2017-10-05 17:18:43 -07001306 switch (task.getActivityType()) {
1307 case ACTIVITY_TYPE_HOME:
1308 case ACTIVITY_TYPE_RECENTS:
Galia Peycheva45f48d32020-02-20 15:39:10 +01001309 case ACTIVITY_TYPE_DREAM:
Vadim Trysheveff42d32018-03-05 18:33:48 -08001310 // Ignore certain activity types completely
Winson Chungd6aa3db2017-10-05 17:18:43 -07001311 return false;
Vadim Trysheveff42d32018-03-05 18:33:48 -08001312 case ACTIVITY_TYPE_ASSISTANT:
1313 // Ignore assistant that chose to be excluded from Recents, even if it's a top
1314 // task.
Winson Chungb4132992018-07-03 15:52:38 -07001315 if ((task.getBaseIntent().getFlags() & FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
1316 == FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) {
Vadim Trysheveff42d32018-03-05 18:33:48 -08001317 return false;
1318 }
Winson Chunge5ab0172020-03-21 23:00:24 -07001319 break;
Winson Chungd6aa3db2017-10-05 17:18:43 -07001320 }
1321
1322 // Ignore certain windowing modes
1323 switch (task.getWindowingMode()) {
1324 case WINDOWING_MODE_PINNED:
1325 return false;
1326 case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
Winson Chunge5ab0172020-03-21 23:00:24 -07001327 if (DEBUG_RECENTS_TRIM_TASKS) {
1328 Slog.d(TAG, "\ttop=" + task.getStack().getTopMostTask());
1329 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001330 final ActivityStack stack = task.getStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001331 if (stack != null && stack.getTopMostTask() == task) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001332 // Only the non-top task of the primary split screen mode is visible
1333 return false;
1334 }
Winson Chunge5ab0172020-03-21 23:00:24 -07001335 break;
1336 case WINDOWING_MODE_MULTI_WINDOW:
1337 // Ignore tasks that are always on top
1338 if (task.isAlwaysOnTop()) {
1339 return false;
1340 }
1341 break;
Mark Renouf2aaf4cd2019-02-19 17:24:43 -05001342 }
1343
Winson Chung3e405ad2020-06-10 15:25:46 -07001344 // Tasks managed by/associated with an ActivityView should be excluded from recents.
1345 // singleTaskInstance is set on the VirtualDisplay managed by ActivityView
1346 // TODO(b/126185105): Find a different signal to use besides isSingleTaskInstance
1347 final ActivityStack stack = task.getStack();
1348 if (stack != null) {
1349 DisplayContent display = stack.getDisplay();
1350 if (display != null && display.isSingleTaskInstance()) {
1351 return false;
1352 }
1353 }
1354
Benjamin Franz7dcbfb02018-01-16 15:16:16 +00001355 // If we're in lock task mode, ignore the root task
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001356 if (task == mService.getLockTaskController().getRootTask()) {
Benjamin Franz7dcbfb02018-01-16 15:16:16 +00001357 return false;
1358 }
1359
Winson Chungd6aa3db2017-10-05 17:18:43 -07001360 return true;
1361 }
1362
1363 /**
1364 * @return whether the given visible task is within the policy range.
1365 */
Louis Changcdec0802019-11-11 11:45:07 +08001366 private boolean isInVisibleRange(Task task, int taskIndex, int numVisibleTasks,
Winson Chungd2730072019-02-22 14:10:27 -08001367 boolean skipExcludedCheck) {
1368 if (!skipExcludedCheck) {
1369 // Keep the most recent task even if it is excluded from recents
1370 final boolean isExcludeFromRecents =
1371 (task.getBaseIntent().getFlags() & FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
1372 == FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
1373 if (isExcludeFromRecents) {
1374 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\texcludeFromRecents=true");
Winson Chung0a10c3a2019-04-23 15:53:08 -07001375 return taskIndex == 0;
Winson Chungd2730072019-02-22 14:10:27 -08001376 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001377 }
1378
1379 if (mMinNumVisibleTasks >= 0 && numVisibleTasks <= mMinNumVisibleTasks) {
1380 // Always keep up to the min number of recent tasks, after that fall through to the
1381 // checks below
1382 return true;
1383 }
1384
1385 if (mMaxNumVisibleTasks >= 0) {
1386 // Always keep up to the max number of recent tasks, but return false afterwards
1387 return numVisibleTasks <= mMaxNumVisibleTasks;
1388 }
1389
1390 if (mActiveTasksSessionDurationMs > 0) {
1391 // Keep the task if the inactive time is within the session window, this check must come
1392 // after the checks for the min/max visible task range
1393 if (task.getInactiveDuration() <= mActiveTasksSessionDurationMs) {
1394 return true;
1395 }
1396 }
1397
1398 return false;
Winson Chung1dbc8112017-09-28 18:05:31 -07001399 }
1400
Charles Chen7d550c42020-05-15 17:32:03 +08001401 /** @return whether the given task can be trimmed even if it is outside the visible range. */
Louis Changcdec0802019-11-11 11:45:07 +08001402 protected boolean isTrimmable(Task task) {
Winson Chung0ec2a352017-10-26 11:38:30 -07001403 final ActivityStack stack = task.getStack();
Winson Chung0ec2a352017-10-26 11:38:30 -07001404
1405 // No stack for task, just trim it
1406 if (stack == null) {
1407 return true;
1408 }
1409
1410 // Ignore tasks from different displays
Louis Changbd48dca2018-08-29 17:44:34 +08001411 // TODO (b/115289124): No Recents on non-default displays.
Wale Ogunwale8f93b642019-12-26 12:10:52 -08001412 if (!stack.isOnHomeDisplay()) {
Winson Chung0ec2a352017-10-26 11:38:30 -07001413 return false;
1414 }
1415
Charles Chen7d550c42020-05-15 17:32:03 +08001416 final ActivityStack rootHomeTask = stack.getDisplayArea().getRootHomeTask();
1417 // Home stack does not exist. Don't trim the task.
1418 if (rootHomeTask == null) {
1419 return false;
1420 }
Wale Ogunwale0db64ac2020-04-11 10:00:42 -07001421 // Trim tasks that are behind the home task.
Charles Chen7d550c42020-05-15 17:32:03 +08001422 return task.compareTo(rootHomeTask) < 0;
Winson Chung0ec2a352017-10-26 11:38:30 -07001423 }
1424
Riddle Hsu4e361e92019-12-24 16:51:09 +08001425 /** Remove the tasks that user may not be able to return. */
1426 private void removeUnreachableHiddenTasks(int windowingMode) {
1427 for (int i = mHiddenTasks.size() - 1; i >= 0; i--) {
1428 final Task hiddenTask = mHiddenTasks.get(i);
1429 if (!hiddenTask.hasChild()) {
1430 // The task was removed by other path.
1431 mHiddenTasks.remove(i);
1432 continue;
1433 }
1434 if (hiddenTask.getWindowingMode() != windowingMode
1435 || hiddenTask.getTopVisibleActivity() != null) {
1436 // The task may be reachable from the back stack of other windowing mode or it is
1437 // currently in use. Keep the task in the hidden list to avoid losing track, e.g.
1438 // after dismissing primary split screen.
1439 continue;
1440 }
1441 mHiddenTasks.remove(i);
1442 mSupervisor.removeTask(hiddenTask, false /* killProcess */,
1443 !REMOVE_FROM_RECENTS, "remove-hidden-task");
1444 }
1445 }
1446
Winson Chung0ec2a352017-10-26 11:38:30 -07001447 /**
Winson Chung1dbc8112017-09-28 18:05:31 -07001448 * If needed, remove oldest existing entries in recents that are for the same kind
1449 * of task as the given one.
1450 */
Louis Changcdec0802019-11-11 11:45:07 +08001451 private void removeForAddTask(Task task) {
Winson Chung079221f2017-12-13 17:43:34 -08001452 final int removeIndex = findRemoveIndexForAddTask(task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001453 if (removeIndex == -1) {
1454 // Nothing to trim
1455 return;
1456 }
1457
Winson Chungd6aa3db2017-10-05 17:18:43 -07001458 // There is a similar task that will be removed for the addition of {@param task}, but it
1459 // can be the same task, and if so, the task will be re-added in add(), so skip the
1460 // callbacks here.
Louis Changcdec0802019-11-11 11:45:07 +08001461 final Task removedTask = mTasks.remove(removeIndex);
Winson Chung1dbc8112017-09-28 18:05:31 -07001462 if (removedTask != task) {
Riddle Hsu4e361e92019-12-24 16:51:09 +08001463 // The added task is in recents so it is not hidden.
1464 mHiddenTasks.remove(task);
1465 if (removedTask.hasChild()) {
1466 // A non-empty task is replaced by a new task. Because the removed task is no longer
1467 // managed by the recent tasks list, add it to the hidden list to prevent the task
1468 // from becoming dangling.
1469 mHiddenTasks.add(removedTask);
1470 }
Winson Chunge6439102018-07-30 15:48:01 -07001471 notifyTaskRemoved(removedTask, false /* wasTrimmed */, false /* killProcess */);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001472 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming task=" + removedTask
1473 + " for addition of task=" + task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001474 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001475 notifyTaskPersisterLocked(removedTask, false /* flush */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001476 }
1477
1478 /**
1479 * Find the task that would be removed if the given {@param task} is added to the recent tasks
1480 * list (if any).
1481 */
Louis Changcdec0802019-11-11 11:45:07 +08001482 private int findRemoveIndexForAddTask(Task task) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001483 if (mFreezeTaskListReordering) {
1484 // Defer removing tasks due to the addition of new tasks until the task list is unfrozen
1485 return -1;
1486 }
1487
Winson Chung6c9dcad2018-03-13 16:57:55 -07001488 final int recentsCount = mTasks.size();
Winson Chung1dbc8112017-09-28 18:05:31 -07001489 final Intent intent = task.intent;
1490 final boolean document = intent != null && intent.isDocument();
1491 int maxRecents = task.maxRecents - 1;
Winson Chung1dbc8112017-09-28 18:05:31 -07001492 for (int i = 0; i < recentsCount; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001493 final Task t = mTasks.get(i);
1494 if (task != t) {
1495 if (!hasCompatibleActivityTypeAndWindowingMode(task, t)
1496 || task.mUserId != t.mUserId) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001497 continue;
1498 }
Louis Changcdec0802019-11-11 11:45:07 +08001499 final Intent trIntent = t.intent;
Winson Chung1dbc8112017-09-28 18:05:31 -07001500 final boolean sameAffinity =
Louis Changcdec0802019-11-11 11:45:07 +08001501 task.affinity != null && task.affinity.equals(t.affinity);
Winson Chung1dbc8112017-09-28 18:05:31 -07001502 final boolean sameIntent = intent != null && intent.filterEquals(trIntent);
1503 boolean multiTasksAllowed = false;
1504 final int flags = intent.getFlags();
1505 if ((flags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_NEW_DOCUMENT)) != 0
1506 && (flags & FLAG_ACTIVITY_MULTIPLE_TASK) != 0) {
1507 multiTasksAllowed = true;
1508 }
1509 final boolean trIsDocument = trIntent != null && trIntent.isDocument();
1510 final boolean bothDocuments = document && trIsDocument;
1511 if (!sameAffinity && !sameIntent && !bothDocuments) {
1512 continue;
1513 }
1514
1515 if (bothDocuments) {
1516 // Do these documents belong to the same activity?
1517 final boolean sameActivity = task.realActivity != null
Louis Changcdec0802019-11-11 11:45:07 +08001518 && t.realActivity != null
1519 && task.realActivity.equals(t.realActivity);
Winson Chung1dbc8112017-09-28 18:05:31 -07001520 if (!sameActivity) {
1521 // If the document is open in another app or is not the same document, we
1522 // don't need to trim it.
1523 continue;
1524 } else if (maxRecents > 0) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001525 --maxRecents;
1526 if (!sameIntent || multiTasksAllowed) {
1527 // We don't want to trim if we are not over the max allowed entries and
1528 // the tasks are not of the same intent filter, or multiple entries for
1529 // the task is allowed.
1530 continue;
1531 }
1532 }
1533 // Hit the maximum number of documents for this task. Fall through
1534 // and remove this document from recents.
1535 } else if (document || trIsDocument) {
1536 // Only one of these is a document. Not the droid we're looking for.
1537 continue;
1538 }
1539 }
1540 return i;
1541 }
1542 return -1;
1543 }
1544
1545 // Extract the affiliates of the chain containing recent at index start.
1546 private int processNextAffiliateChainLocked(int start) {
Louis Changcdec0802019-11-11 11:45:07 +08001547 final Task startTask = mTasks.get(start);
Winson Chung1dbc8112017-09-28 18:05:31 -07001548 final int affiliateId = startTask.mAffiliatedTaskId;
1549
1550 // Quick identification of isolated tasks. I.e. those not launched behind.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001551 if (startTask.mTaskId == affiliateId && startTask.mPrevAffiliate == null &&
Winson Chung1dbc8112017-09-28 18:05:31 -07001552 startTask.mNextAffiliate == null) {
1553 // There is still a slim chance that there are other tasks that point to this task
1554 // and that the chain is so messed up that this task no longer points to them but
1555 // the gain of this optimization outweighs the risk.
1556 startTask.inRecents = true;
1557 return start + 1;
1558 }
1559
1560 // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
1561 mTmpRecents.clear();
1562 for (int i = mTasks.size() - 1; i >= start; --i) {
Louis Changcdec0802019-11-11 11:45:07 +08001563 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -07001564 if (task.mAffiliatedTaskId == affiliateId) {
1565 mTasks.remove(i);
1566 mTmpRecents.add(task);
1567 }
1568 }
1569
1570 // Sort them all by taskId. That is the order they were create in and that order will
1571 // always be correct.
1572 Collections.sort(mTmpRecents, TASK_ID_COMPARATOR);
1573
1574 // Go through and fix up the linked list.
1575 // The first one is the end of the chain and has no next.
Louis Changcdec0802019-11-11 11:45:07 +08001576 final Task first = mTmpRecents.get(0);
Winson Chung1dbc8112017-09-28 18:05:31 -07001577 first.inRecents = true;
1578 if (first.mNextAffiliate != null) {
1579 Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
1580 first.setNextAffiliate(null);
1581 notifyTaskPersisterLocked(first, false);
1582 }
1583 // Everything in the middle is doubly linked from next to prev.
1584 final int tmpSize = mTmpRecents.size();
1585 for (int i = 0; i < tmpSize - 1; ++i) {
Louis Changcdec0802019-11-11 11:45:07 +08001586 final Task next = mTmpRecents.get(i);
1587 final Task prev = mTmpRecents.get(i + 1);
Winson Chung1dbc8112017-09-28 18:05:31 -07001588 if (next.mPrevAffiliate != prev) {
1589 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
1590 " setting prev=" + prev);
1591 next.setPrevAffiliate(prev);
1592 notifyTaskPersisterLocked(next, false);
1593 }
1594 if (prev.mNextAffiliate != next) {
1595 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
1596 " setting next=" + next);
1597 prev.setNextAffiliate(next);
1598 notifyTaskPersisterLocked(prev, false);
1599 }
1600 prev.inRecents = true;
1601 }
1602 // The last one is the beginning of the list and has no prev.
Louis Changcdec0802019-11-11 11:45:07 +08001603 final Task last = mTmpRecents.get(tmpSize - 1);
Winson Chung1dbc8112017-09-28 18:05:31 -07001604 if (last.mPrevAffiliate != null) {
1605 Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
1606 last.setPrevAffiliate(null);
1607 notifyTaskPersisterLocked(last, false);
1608 }
1609
Winson Chungd6aa3db2017-10-05 17:18:43 -07001610 // Insert the group back into mTmpTasks at start.
Winson Chung1dbc8112017-09-28 18:05:31 -07001611 mTasks.addAll(start, mTmpRecents);
1612 mTmpRecents.clear();
1613
1614 // Let the caller know where we left off.
1615 return start + tmpSize;
1616 }
1617
Louis Changcdec0802019-11-11 11:45:07 +08001618 private boolean moveAffiliatedTasksToFront(Task task, int taskIndex) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001619 int recentsCount = mTasks.size();
Louis Changcdec0802019-11-11 11:45:07 +08001620 Task top = task;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001621 int topIndex = taskIndex;
1622 while (top.mNextAffiliate != null && topIndex > 0) {
1623 top = top.mNextAffiliate;
1624 topIndex--;
1625 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001626 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding affilliates starting at "
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001627 + topIndex + " from intial " + taskIndex);
1628 // Find the end of the chain, doing a sanity check along the way.
1629 boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
1630 int endIndex = topIndex;
Louis Changcdec0802019-11-11 11:45:07 +08001631 Task prev = top;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001632 while (endIndex < recentsCount) {
Louis Changcdec0802019-11-11 11:45:07 +08001633 Task cur = mTasks.get(endIndex);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001634 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: looking at next chain @"
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001635 + endIndex + " " + cur);
1636 if (cur == top) {
1637 // Verify start of the chain.
1638 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != INVALID_TASK_ID) {
1639 Slog.wtf(TAG, "Bad chain @" + endIndex
1640 + ": first task has next affiliate: " + prev);
1641 sane = false;
1642 break;
1643 }
1644 } else {
1645 // Verify middle of the chain's next points back to the one before.
1646 if (cur.mNextAffiliate != prev
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001647 || cur.mNextAffiliateTaskId != prev.mTaskId) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001648 Slog.wtf(TAG, "Bad chain @" + endIndex
1649 + ": middle task " + cur + " @" + endIndex
1650 + " has bad next affiliate "
1651 + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
1652 + ", expected " + prev);
1653 sane = false;
1654 break;
1655 }
1656 }
1657 if (cur.mPrevAffiliateTaskId == INVALID_TASK_ID) {
1658 // Chain ends here.
1659 if (cur.mPrevAffiliate != null) {
1660 Slog.wtf(TAG, "Bad chain @" + endIndex
1661 + ": last task " + cur + " has previous affiliate "
1662 + cur.mPrevAffiliate);
1663 sane = false;
1664 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001665 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: end of chain @" + endIndex);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001666 break;
1667 } else {
1668 // Verify middle of the chain's prev points to a valid item.
1669 if (cur.mPrevAffiliate == null) {
1670 Slog.wtf(TAG, "Bad chain @" + endIndex
1671 + ": task " + cur + " has previous affiliate "
1672 + cur.mPrevAffiliate + " but should be id "
1673 + cur.mPrevAffiliate);
1674 sane = false;
1675 break;
1676 }
1677 }
1678 if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
1679 Slog.wtf(TAG, "Bad chain @" + endIndex
1680 + ": task " + cur + " has affiliated id "
1681 + cur.mAffiliatedTaskId + " but should be "
1682 + task.mAffiliatedTaskId);
1683 sane = false;
1684 break;
1685 }
1686 prev = cur;
1687 endIndex++;
1688 if (endIndex >= recentsCount) {
1689 Slog.wtf(TAG, "Bad chain ran off index " + endIndex
1690 + ": last task " + prev);
1691 sane = false;
1692 break;
1693 }
1694 }
1695 if (sane) {
1696 if (endIndex < taskIndex) {
1697 Slog.wtf(TAG, "Bad chain @" + endIndex
1698 + ": did not extend to task " + task + " @" + taskIndex);
1699 sane = false;
1700 }
1701 }
1702 if (sane) {
1703 // All looks good, we can just move all of the affiliated tasks
1704 // to the top.
1705 for (int i=topIndex; i<=endIndex; i++) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001706 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving affiliated " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001707 + " from " + i + " to " + (i-topIndex));
Louis Changcdec0802019-11-11 11:45:07 +08001708 Task cur = mTasks.remove(i);
Winson Chung1dbc8112017-09-28 18:05:31 -07001709 mTasks.add(i - topIndex, cur);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001710 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001711 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: done moving tasks " + topIndex
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001712 + " to " + endIndex);
1713 return true;
1714 }
1715
1716 // Whoops, couldn't do it.
1717 return false;
1718 }
1719
Winson Chung1dbc8112017-09-28 18:05:31 -07001720 void dump(PrintWriter pw, boolean dumpAll, String dumpPackage) {
1721 pw.println("ACTIVITY MANAGER RECENT TASKS (dumpsys activity recents)");
Winson Chung3f0e59a2017-10-25 10:19:05 -07001722 pw.println("mRecentsUid=" + mRecentsUid);
1723 pw.println("mRecentsComponent=" + mRecentsComponent);
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001724 pw.println("mFreezeTaskListReordering=" + mFreezeTaskListReordering);
Winson Chung1fe58e92019-04-10 14:18:06 -07001725 pw.println("mFreezeTaskListReorderingPendingTimeout="
1726 + mService.mH.hasCallbacks(mResetFreezeTaskListOnTimeoutRunnable));
Riddle Hsu4e361e92019-12-24 16:51:09 +08001727 if (!mHiddenTasks.isEmpty()) {
1728 pw.println("mHiddenTasks=" + mHiddenTasks);
1729 }
Winson Chung1dbc8112017-09-28 18:05:31 -07001730 if (mTasks.isEmpty()) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001731 return;
1732 }
1733
Winson Chungb4132992018-07-03 15:52:38 -07001734 // Dump raw recent task list
Winson Chung3f0e59a2017-10-25 10:19:05 -07001735 boolean printedAnything = false;
1736 boolean printedHeader = false;
Winson Chung1dbc8112017-09-28 18:05:31 -07001737 final int size = mTasks.size();
1738 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001739 final Task task = mTasks.get(i);
Dianne Hackborn9106f2a2020-04-30 16:23:20 -07001740 if (dumpPackage != null) {
1741 boolean match = task.intent != null
1742 && task.intent.getComponent() != null
1743 && dumpPackage.equals(
1744 task.intent.getComponent().getPackageName());
1745 if (!match) {
1746 match |= task.affinityIntent != null
1747 && task.affinityIntent.getComponent() != null
1748 && dumpPackage.equals(
1749 task.affinityIntent.getComponent().getPackageName());
1750 }
1751 if (!match) {
1752 match |= task.origActivity != null
1753 && dumpPackage.equals(task.origActivity.getPackageName());
1754 }
1755 if (!match) {
1756 match |= task.realActivity != null
1757 && dumpPackage.equals(task.realActivity.getPackageName());
1758 }
1759 if (!match) {
1760 match |= dumpPackage.equals(task.mCallingPackage);
1761 }
1762 if (!match) {
1763 continue;
1764 }
Winson Chung1dbc8112017-09-28 18:05:31 -07001765 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001766
Winson Chung3f0e59a2017-10-25 10:19:05 -07001767 if (!printedHeader) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001768 pw.println(" Recent tasks:");
Winson Chung3f0e59a2017-10-25 10:19:05 -07001769 printedHeader = true;
1770 printedAnything = true;
Winson Chung1dbc8112017-09-28 18:05:31 -07001771 }
1772 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
Louis Changcdec0802019-11-11 11:45:07 +08001773 pw.println(task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001774 if (dumpAll) {
Louis Changcdec0802019-11-11 11:45:07 +08001775 task.dump(pw, " ");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001776 }
1777 }
1778
Winson Chungb4132992018-07-03 15:52:38 -07001779 // Dump visible recent task list
1780 if (mHasVisibleRecentTasks) {
1781 // Reset the header flag for the next block
1782 printedHeader = false;
1783 ArrayList<ActivityManager.RecentTaskInfo> tasks = getRecentTasksImpl(Integer.MAX_VALUE,
Winson Chung66b08f02020-03-03 14:32:35 -08001784 0, true /* getTasksAllowed */, mService.getCurrentUserId(), SYSTEM_UID);
Winson Chungb4132992018-07-03 15:52:38 -07001785 for (int i = 0; i < tasks.size(); i++) {
1786 final ActivityManager.RecentTaskInfo taskInfo = tasks.get(i);
Dianne Hackborn9106f2a2020-04-30 16:23:20 -07001787 if (dumpPackage != null) {
1788 boolean match = taskInfo.baseIntent != null
1789 && taskInfo.baseIntent.getComponent() != null
1790 && dumpPackage.equals(
1791 taskInfo.baseIntent.getComponent().getPackageName());
1792 if (!match) {
1793 match |= taskInfo.baseActivity != null
1794 && dumpPackage.equals(taskInfo.baseActivity.getPackageName());
1795 }
1796 if (!match) {
1797 match |= taskInfo.topActivity != null
1798 && dumpPackage.equals(taskInfo.topActivity.getPackageName());
1799 }
1800 if (!match) {
1801 match |= taskInfo.origActivity != null
1802 && dumpPackage.equals(taskInfo.origActivity.getPackageName());
1803 }
1804 if (!match) {
1805 match |= taskInfo.realActivity != null
1806 && dumpPackage.equals(taskInfo.realActivity.getPackageName());
1807 }
1808 if (!match) {
1809 continue;
1810 }
1811 }
Winson Chungb4132992018-07-03 15:52:38 -07001812 if (!printedHeader) {
1813 if (printedAnything) {
1814 // Separate from the last block if it printed
1815 pw.println();
1816 }
1817 pw.println(" Visible recent tasks (most recent first):");
1818 printedHeader = true;
1819 printedAnything = true;
1820 }
1821
1822 pw.print(" * RecentTaskInfo #"); pw.print(i); pw.print(": ");
1823 taskInfo.dump(pw, " ");
1824 }
1825 }
1826
Winson Chung3f0e59a2017-10-25 10:19:05 -07001827 if (!printedAnything) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001828 pw.println(" (nothing)");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001829 }
1830 }
1831
1832 /**
Louis Changcdec0802019-11-11 11:45:07 +08001833 * Creates a new RecentTaskInfo from a Task.
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001834 */
Winson Chung02757712020-06-23 10:41:44 -07001835 ActivityManager.RecentTaskInfo createRecentTaskInfo(Task tr, boolean stripExtras) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001836 ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo();
Winson Chung02757712020-06-23 10:41:44 -07001837 tr.fillTaskInfo(rti, stripExtras);
Winson Chungabfdcce2018-07-02 17:23:33 -07001838 // Fill in some deprecated values
1839 rti.id = rti.isRunning ? rti.taskId : INVALID_TASK_ID;
1840 rti.persistentId = rti.taskId;
Winson Chung1dbc8112017-09-28 18:05:31 -07001841 return rti;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001842 }
Winson Chung27f81882018-04-19 14:45:03 -07001843
1844 /**
1845 * @return Whether the activity types and windowing modes of the two tasks are considered
1846 * compatible. This is necessary because we currently don't persist the activity type
1847 * or the windowing mode with the task, so they can be undefined when restored.
1848 */
Louis Changcdec0802019-11-11 11:45:07 +08001849 private boolean hasCompatibleActivityTypeAndWindowingMode(Task t1, Task t2) {
Winson Chung27f81882018-04-19 14:45:03 -07001850 final int activityType = t1.getActivityType();
1851 final int windowingMode = t1.getWindowingMode();
1852 final boolean isUndefinedType = activityType == ACTIVITY_TYPE_UNDEFINED;
1853 final boolean isUndefinedMode = windowingMode == WINDOWING_MODE_UNDEFINED;
1854 final int otherActivityType = t2.getActivityType();
1855 final int otherWindowingMode = t2.getWindowingMode();
1856 final boolean isOtherUndefinedType = otherActivityType == ACTIVITY_TYPE_UNDEFINED;
1857 final boolean isOtherUndefinedMode = otherWindowingMode == WINDOWING_MODE_UNDEFINED;
1858
1859 // An activity type and windowing mode is compatible if they are the exact same type/mode,
1860 // or if one of the type/modes is undefined
1861 final boolean isCompatibleType = activityType == otherActivityType
1862 || isUndefinedType || isOtherUndefinedType;
1863 final boolean isCompatibleMode = windowingMode == otherWindowingMode
1864 || isUndefinedMode || isOtherUndefinedMode;
1865
1866 return isCompatibleType && isCompatibleMode;
1867 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001868}