blob: f0e441fe77b11075ea7b9e54202d9ed133ef079d [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;
Winson Chungd6aa3db2017-10-05 17:18:43 -070024import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
25import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
Winson Chung27f81882018-04-19 14:45:03 -070026import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Winson Chungd6aa3db2017-10-05 17:18:43 -070027import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
28import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Winson Chung27f81882018-04-19 14:45:03 -070029import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Winson Chungb4132992018-07-03 15:52:38 -070030import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwalee8d5f652016-04-22 16:27:39 -070031import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
32import static android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
33import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Winson Chungb4132992018-07-03 15:52:38 -070034import static android.os.Process.SYSTEM_UID;
Louis Changbd48dca2018-08-29 17:44:34 +080035import static android.view.Display.DEFAULT_DISPLAY;
36
Garfield Tan891146c2018-10-09 12:14:00 -070037import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
Wale Ogunwale59507092018-10-29 09:00:30 -070038import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS;
39import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS_TRIM_TASKS;
40import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
41import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS;
42import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
43import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
44import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Wale Ogunwalee23149f2015-03-06 15:39:44 -080045
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080046import android.app.ActivityManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070047import android.app.ActivityTaskManager;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080048import android.app.AppGlobals;
49import android.content.ComponentName;
50import android.content.Intent;
51import android.content.pm.ActivityInfo;
52import android.content.pm.ApplicationInfo;
53import android.content.pm.IPackageManager;
54import android.content.pm.PackageManager;
Winson Chung1dbc8112017-09-28 18:05:31 -070055import android.content.pm.ParceledListSlice;
Winson Chungd6aa3db2017-10-05 17:18:43 -070056import android.content.pm.UserInfo;
57import android.content.res.Resources;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080058import android.graphics.Bitmap;
Winson Chung1dbc8112017-09-28 18:05:31 -070059import android.os.Bundle;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080060import android.os.Environment;
Winson Chung1dbc8112017-09-28 18:05:31 -070061import android.os.IBinder;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080062import android.os.RemoteException;
Winson Chungd6aa3db2017-10-05 17:18:43 -070063import android.os.SystemProperties;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080064import android.os.UserHandle;
Winson Chung3f0e59a2017-10-25 10:19:05 -070065import android.text.TextUtils;
Daichi Hirono4cb941e2017-03-31 14:30:41 +090066import android.util.ArraySet;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080067import android.util.Slog;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080068import android.util.SparseArray;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080069import android.util.SparseBooleanArray;
Winson Chungc5fe7ff2019-02-19 14:49:25 -080070import android.view.MotionEvent;
71import android.view.WindowManagerPolicyConstants.PointerEventListener;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080072
Winson Chung1dbc8112017-09-28 18:05:31 -070073import com.android.internal.annotations.VisibleForTesting;
Winson Chungc5fe7ff2019-02-19 14:49:25 -080074import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwale59507092018-10-29 09:00:30 -070075import com.android.server.am.ActivityManagerService;
Winson Chung1dbc8112017-09-28 18:05:31 -070076
Winson Chung3f0e59a2017-10-25 10:19:05 -070077import com.google.android.collect.Sets;
78
Suprabh Shukla09a88f52015-12-02 14:36:31 -080079import java.io.File;
Winson Chung1dbc8112017-09-28 18:05:31 -070080import java.io.PrintWriter;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080081import java.util.ArrayList;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080082import java.util.Arrays;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080083import java.util.Collections;
84import java.util.Comparator;
85import java.util.HashMap;
Wale Ogunwale86b74462018-07-02 08:42:43 -070086import java.util.List;
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +000087import java.util.Set;
Winson Chungd6aa3db2017-10-05 17:18:43 -070088import java.util.concurrent.TimeUnit;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080089
90/**
Winson Chung1dbc8112017-09-28 18:05:31 -070091 * Class for managing the recent tasks list. The list is ordered by most recent (index 0) to the
92 * least recent.
Winson Chung0ec2a352017-10-26 11:38:30 -070093 *
94 * The trimming logic can be boiled down to the following. For recent task list with a number of
95 * tasks, the visible tasks are an interleaving subset of tasks that would normally be presented to
96 * the user. Non-visible tasks are not considered for trimming. Of the visible tasks, only a
97 * sub-range are presented to the user, based on the device type, last task active time, or other
98 * task state. Tasks that are not in the visible range and are not returnable from the SystemUI
99 * (considering the back stack) are considered trimmable. If the device does not support recent
100 * tasks, then trimming is completely disabled.
101 *
102 * eg.
103 * L = [TTTTTTTTTTTTTTTTTTTTTTTTTT] // list of tasks
104 * [VVV VV VVVV V V V ] // Visible tasks
105 * [RRR RR XXXX X X X ] // Visible range tasks, eg. if the device only shows 5 tasks,
106 * // 'X' tasks are trimmed.
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800107 */
Winson Chung1dbc8112017-09-28 18:05:31 -0700108class RecentTasks {
Wale Ogunwale98875612018-10-12 07:53:02 -0700109 private static final String TAG = TAG_WITH_CLASS_NAME ? "RecentTasks" : TAG_ATM;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700110 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
111 private static final String TAG_TASKS = TAG + POSTFIX_TASKS;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800112
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800113 private static final int DEFAULT_INITIAL_CAPACITY = 5;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800114
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800115 // The duration of time after freezing the recent tasks list where getRecentTasks() will return
116 // a stable ordering of the tasks. Upon the next call to getRecentTasks() beyond this duration,
117 // the task list will be unfrozen and committed (the current top task will be moved to the
118 // front of the list)
119 private static final long FREEZE_TASK_LIST_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(5);
Winson6976f7b2016-05-03 14:58:12 -0700120
Winson Chung1dbc8112017-09-28 18:05:31 -0700121 // Comparator to sort by taskId
Louis Changcdec0802019-11-11 11:45:07 +0800122 private static final Comparator<Task> TASK_ID_COMPARATOR =
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700123 (lhs, rhs) -> rhs.mTaskId - lhs.mTaskId;
Winson Chung1dbc8112017-09-28 18:05:31 -0700124
125 // Placeholder variables to keep track of activities/apps that are no longer avialble while
126 // iterating through the recents list
127 private static final ActivityInfo NO_ACTIVITY_INFO_TOKEN = new ActivityInfo();
128 private static final ApplicationInfo NO_APPLICATION_INFO_TOKEN = new ApplicationInfo();
Vinit Nayak3e737492019-07-24 13:03:15 -0700129 private TaskChangeNotificationController mTaskNotificationController;
Winson Chung1dbc8112017-09-28 18:05:31 -0700130
131 /**
132 * Callbacks made when manipulating the list.
133 */
134 interface Callbacks {
135 /**
136 * Called when a task is added to the recent tasks list.
137 */
Louis Changcdec0802019-11-11 11:45:07 +0800138 void onRecentTaskAdded(Task task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700139
140 /**
141 * Called when a task is removed from the recent tasks list.
142 */
Louis Changcdec0802019-11-11 11:45:07 +0800143 void onRecentTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess);
Winson Chung1dbc8112017-09-28 18:05:31 -0700144 }
145
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800146 /**
147 * Save recent tasks information across reboots.
148 */
149 private final TaskPersister mTaskPersister;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700150 private final ActivityTaskManagerService mService;
151 private final ActivityStackSupervisor mSupervisor;
Winson Chung1dbc8112017-09-28 18:05:31 -0700152
153 /**
Winson Chung3f0e59a2017-10-25 10:19:05 -0700154 * Keeps track of the static recents package/component which is granted additional permissions
155 * to call recents-related APIs.
156 */
157 private int mRecentsUid = -1;
158 private ComponentName mRecentsComponent = null;
159
160 /**
Winson Chung1dbc8112017-09-28 18:05:31 -0700161 * Mapping of user id -> whether recent tasks have been loaded for that user.
162 */
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800163 private final SparseBooleanArray mUsersWithRecentsLoaded = new SparseBooleanArray(
164 DEFAULT_INITIAL_CAPACITY);
165
166 /**
167 * Stores for each user task ids that are taken by tasks residing in persistent storage. These
168 * tasks may or may not currently be in memory.
169 */
Winson Chung1dbc8112017-09-28 18:05:31 -0700170 private final SparseArray<SparseBooleanArray> mPersistedTaskIds = new SparseArray<>(
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800171 DEFAULT_INITIAL_CAPACITY);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800172
Winson Chungd6aa3db2017-10-05 17:18:43 -0700173 // List of all active recent tasks
Louis Changcdec0802019-11-11 11:45:07 +0800174 private final ArrayList<Task> mTasks = new ArrayList<>();
Winson Chung1dbc8112017-09-28 18:05:31 -0700175 private final ArrayList<Callbacks> mCallbacks = new ArrayList<>();
176
Winson Chungd6aa3db2017-10-05 17:18:43 -0700177 // These values are generally loaded from resources, but can be set dynamically in the tests
178 private boolean mHasVisibleRecentTasks;
179 private int mGlobalMaxNumTasks;
180 private int mMinNumVisibleTasks;
181 private int mMaxNumVisibleTasks;
182 private long mActiveTasksSessionDurationMs;
183
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800184 // When set, the task list will not be reordered as tasks within the list are moved to the
185 // front. Newly created tasks, or tasks that are removed from the list will continue to change
186 // the list. This does not affect affiliated tasks.
187 private boolean mFreezeTaskListReordering;
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800188 private long mFreezeTaskListTimeoutMs = FREEZE_TASK_LIST_TIMEOUT_MS;
189
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800190 // Mainly to avoid object recreation on multiple calls.
Louis Changcdec0802019-11-11 11:45:07 +0800191 private final ArrayList<Task> mTmpRecents = new ArrayList<>();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800192 private final HashMap<ComponentName, ActivityInfo> mTmpAvailActCache = new HashMap<>();
193 private final HashMap<String, ApplicationInfo> mTmpAvailAppCache = new HashMap<>();
Winson Chungd6aa3db2017-10-05 17:18:43 -0700194 private final SparseBooleanArray mTmpQuietProfileUserIds = new SparseBooleanArray();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800195
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800196 // TODO(b/127498985): This is currently a rough heuristic for interaction inside an app
197 private final PointerEventListener mListener = new PointerEventListener() {
198 @Override
199 public void onPointerEvent(MotionEvent ev) {
200 if (!mFreezeTaskListReordering || ev.getAction() != MotionEvent.ACTION_DOWN) {
201 // Skip if we aren't freezing or starting a gesture
202 return;
203 }
204 int displayId = ev.getDisplayId();
205 int x = (int) ev.getX();
206 int y = (int) ev.getY();
207 mService.mH.post(PooledLambda.obtainRunnable((nonArg) -> {
208 synchronized (mService.mGlobalLock) {
209 // Unfreeze the task list once we touch down in a task
210 final RootActivityContainer rac = mService.mRootActivityContainer;
211 final DisplayContent dc = rac.getActivityDisplay(displayId).mDisplayContent;
212 if (dc.pointWithinAppWindow(x, y)) {
213 final ActivityStack stack = mService.getTopDisplayFocusedStack();
Louis Changcdec0802019-11-11 11:45:07 +0800214 final Task topTask = stack != null ? stack.topTask() : null;
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800215 resetFreezeTaskListReordering(topTask);
216 }
217 }
218 }, null).recycleOnUse());
219 }
220 };
221
Winson Chung1fe58e92019-04-10 14:18:06 -0700222 private final Runnable mResetFreezeTaskListOnTimeoutRunnable =
223 this::resetFreezeTaskListReorderingOnTimeout;
224
Winson Chung1dbc8112017-09-28 18:05:31 -0700225 @VisibleForTesting
Wale Ogunwale86b74462018-07-02 08:42:43 -0700226 RecentTasks(ActivityTaskManagerService service, TaskPersister taskPersister) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700227 mService = service;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700228 mSupervisor = mService.mStackSupervisor;
Winson Chung1dbc8112017-09-28 18:05:31 -0700229 mTaskPersister = taskPersister;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700230 mGlobalMaxNumTasks = ActivityTaskManager.getMaxRecentTasksStatic();
Winson Chungd6aa3db2017-10-05 17:18:43 -0700231 mHasVisibleRecentTasks = true;
Vinit Nayak3e737492019-07-24 13:03:15 -0700232 mTaskNotificationController = service.getTaskChangeNotificationController();
Winson Chung1dbc8112017-09-28 18:05:31 -0700233 }
234
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700235 RecentTasks(ActivityTaskManagerService service, ActivityStackSupervisor stackSupervisor) {
Winson Chungd6aa3db2017-10-05 17:18:43 -0700236 final File systemDir = Environment.getDataSystemDirectory();
237 final Resources res = service.mContext.getResources();
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800238 mService = service;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700239 mSupervisor = mService.mStackSupervisor;
Garfield Tan891146c2018-10-09 12:14:00 -0700240 mTaskPersister = new TaskPersister(systemDir, stackSupervisor, service, this,
241 stackSupervisor.mPersisterQueue);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700242 mGlobalMaxNumTasks = ActivityTaskManager.getMaxRecentTasksStatic();
Vinit Nayak3e737492019-07-24 13:03:15 -0700243 mTaskNotificationController = service.getTaskChangeNotificationController();
Winson Chungd6aa3db2017-10-05 17:18:43 -0700244 mHasVisibleRecentTasks = res.getBoolean(com.android.internal.R.bool.config_hasRecents);
Winson Chung3f0e59a2017-10-25 10:19:05 -0700245 loadParametersFromResources(res);
Winson Chungd6aa3db2017-10-05 17:18:43 -0700246 }
247
248 @VisibleForTesting
249 void setParameters(int minNumVisibleTasks, int maxNumVisibleTasks,
250 long activeSessionDurationMs) {
251 mMinNumVisibleTasks = minNumVisibleTasks;
252 mMaxNumVisibleTasks = maxNumVisibleTasks;
253 mActiveTasksSessionDurationMs = activeSessionDurationMs;
254 }
255
256 @VisibleForTesting
257 void setGlobalMaxNumTasks(int globalMaxNumTasks) {
258 mGlobalMaxNumTasks = globalMaxNumTasks;
259 }
260
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800261 @VisibleForTesting
Winson Chung1fe58e92019-04-10 14:18:06 -0700262 void setFreezeTaskListTimeout(long timeoutMs) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800263 mFreezeTaskListTimeoutMs = timeoutMs;
264 }
265
266 PointerEventListener getInputListener() {
267 return mListener;
268 }
269
270 /**
271 * Freezes the current recent task list order until either a user interaction with the current
272 * app, or a timeout occurs.
273 */
274 void setFreezeTaskListReordering() {
Vinit Nayak8e547962019-10-07 10:36:41 -0700275 // Only fire the callback once per quickswitch session, not on every individual switch
276 if (!mFreezeTaskListReordering) {
277 mTaskNotificationController.notifyTaskListFrozen(true);
278 mFreezeTaskListReordering = true;
279 }
280
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800281 // Always update the reordering time when this is called to ensure that the timeout
282 // is reset
Winson Chung1fe58e92019-04-10 14:18:06 -0700283 mService.mH.removeCallbacks(mResetFreezeTaskListOnTimeoutRunnable);
284 mService.mH.postDelayed(mResetFreezeTaskListOnTimeoutRunnable, mFreezeTaskListTimeoutMs);
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800285 }
286
287 /**
288 * Commits the frozen recent task list order, moving the provided {@param topTask} to the
289 * front of the list.
290 */
Louis Changcdec0802019-11-11 11:45:07 +0800291 void resetFreezeTaskListReordering(Task topTask) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800292 if (!mFreezeTaskListReordering) {
293 return;
294 }
295
296 // Once we end freezing the task list, reset the existing task order to the stable state
297 mFreezeTaskListReordering = false;
Winson Chung1fe58e92019-04-10 14:18:06 -0700298 mService.mH.removeCallbacks(mResetFreezeTaskListOnTimeoutRunnable);
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800299
300 // If the top task is provided, then restore the top task to the front of the list
301 if (topTask != null) {
302 mTasks.remove(topTask);
303 mTasks.add(0, topTask);
304 }
305
306 // Resume trimming tasks
307 trimInactiveRecentTasks();
Winson Chung1fe58e92019-04-10 14:18:06 -0700308
Vinit Nayak3e737492019-07-24 13:03:15 -0700309 mTaskNotificationController.notifyTaskStackChanged();
Vinit Nayak8e547962019-10-07 10:36:41 -0700310 mTaskNotificationController.notifyTaskListFrozen(false);
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800311 }
312
313 /**
314 * Resets the frozen recent task list order if the timeout has passed. This should be called
315 * before we need to iterate the task list in order (either for purposes of returning the list
316 * to SystemUI or if we need to trim tasks in order)
317 */
Winson Chung1fe58e92019-04-10 14:18:06 -0700318 @VisibleForTesting
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800319 void resetFreezeTaskListReorderingOnTimeout() {
chaviwa13051f2019-06-14 16:41:17 -0700320 synchronized (mService.mGlobalLock) {
321 final ActivityStack focusedStack = mService.getTopDisplayFocusedStack();
Louis Changcdec0802019-11-11 11:45:07 +0800322 final Task topTask = focusedStack != null ? focusedStack.topTask() : null;
chaviwa13051f2019-06-14 16:41:17 -0700323 resetFreezeTaskListReordering(topTask);
324 }
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800325 }
326
327 @VisibleForTesting
328 boolean isFreezeTaskListReorderingSet() {
329 return mFreezeTaskListReordering;
330 }
331
Winson Chungd6aa3db2017-10-05 17:18:43 -0700332 /**
333 * Loads the parameters from the system resources.
334 */
335 @VisibleForTesting
336 void loadParametersFromResources(Resources res) {
337 if (ActivityManager.isLowRamDeviceStatic()) {
338 mMinNumVisibleTasks = res.getInteger(
339 com.android.internal.R.integer.config_minNumVisibleRecentTasks_lowRam);
340 mMaxNumVisibleTasks = res.getInteger(
341 com.android.internal.R.integer.config_maxNumVisibleRecentTasks_lowRam);
342 } else if (SystemProperties.getBoolean("ro.recents.grid", false)) {
343 mMinNumVisibleTasks = res.getInteger(
344 com.android.internal.R.integer.config_minNumVisibleRecentTasks_grid);
345 mMaxNumVisibleTasks = res.getInteger(
346 com.android.internal.R.integer.config_maxNumVisibleRecentTasks_grid);
347 } else {
348 mMinNumVisibleTasks = res.getInteger(
349 com.android.internal.R.integer.config_minNumVisibleRecentTasks);
350 mMaxNumVisibleTasks = res.getInteger(
351 com.android.internal.R.integer.config_maxNumVisibleRecentTasks);
352 }
353 final int sessionDurationHrs = res.getInteger(
354 com.android.internal.R.integer.config_activeTaskDurationHours);
355 mActiveTasksSessionDurationMs = (sessionDurationHrs > 0)
356 ? TimeUnit.HOURS.toMillis(sessionDurationHrs)
357 : -1;
Winson Chung1dbc8112017-09-28 18:05:31 -0700358 }
359
Winson Chung3f0e59a2017-10-25 10:19:05 -0700360 /**
361 * Loads the static recents component. This is called after the system is ready, but before
362 * any dependent services (like SystemUI) is started.
363 */
364 void loadRecentsComponent(Resources res) {
365 final String rawRecentsComponent = res.getString(
366 com.android.internal.R.string.config_recentsComponentName);
367 if (TextUtils.isEmpty(rawRecentsComponent)) {
368 return;
369 }
370
371 final ComponentName cn = ComponentName.unflattenFromString(rawRecentsComponent);
372 if (cn != null) {
373 try {
374 final ApplicationInfo appInfo = AppGlobals.getPackageManager()
375 .getApplicationInfo(cn.getPackageName(), 0, mService.mContext.getUserId());
376 if (appInfo != null) {
377 mRecentsUid = appInfo.uid;
378 mRecentsComponent = cn;
379 }
380 } catch (RemoteException e) {
381 Slog.w(TAG, "Could not load application info for recents component: " + cn);
382 }
383 }
384 }
385
386 /**
387 * @return whether the current caller has the same uid as the recents component.
388 */
389 boolean isCallerRecents(int callingUid) {
390 return UserHandle.isSameApp(callingUid, mRecentsUid);
391 }
392
393 /**
394 * @return whether the given component is the recents component and shares the same uid as the
395 * recents component.
396 */
397 boolean isRecentsComponent(ComponentName cn, int uid) {
398 return cn.equals(mRecentsComponent) && UserHandle.isSameApp(uid, mRecentsUid);
399 }
400
Winson Chungec1ef092017-10-25 16:22:34 -0700401 /**
Winson Chungc1674272018-02-21 10:15:17 -0800402 * @return whether the home app is also the active handler of recent tasks.
403 */
404 boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700405 final ComponentName defaultHomeActivity = mService.getPackageManagerInternalLocked()
Winson Chungc1674272018-02-21 10:15:17 -0800406 .getDefaultHomeActivity(userId);
Alice Sheng1de98fc2018-03-16 09:45:58 -0700407 return defaultHomeActivity != null && mRecentsComponent != null &&
Winson Chungc1674272018-02-21 10:15:17 -0800408 defaultHomeActivity.getPackageName().equals(mRecentsComponent.getPackageName());
409 }
410
411 /**
Winson Chungec1ef092017-10-25 16:22:34 -0700412 * @return the recents component.
413 */
414 ComponentName getRecentsComponent() {
415 return mRecentsComponent;
416 }
417
418 /**
419 * @return the uid for the recents component.
420 */
421 int getRecentsComponentUid() {
422 return mRecentsUid;
423 }
424
Winson Chung1dbc8112017-09-28 18:05:31 -0700425 void registerCallback(Callbacks callback) {
426 mCallbacks.add(callback);
427 }
428
429 void unregisterCallback(Callbacks callback) {
430 mCallbacks.remove(callback);
431 }
432
Louis Changcdec0802019-11-11 11:45:07 +0800433 private void notifyTaskAdded(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700434 for (int i = 0; i < mCallbacks.size(); i++) {
435 mCallbacks.get(i).onRecentTaskAdded(task);
436 }
Vinit Nayak3e737492019-07-24 13:03:15 -0700437 mTaskNotificationController.notifyTaskListUpdated();
Winson Chung1dbc8112017-09-28 18:05:31 -0700438 }
439
Louis Changcdec0802019-11-11 11:45:07 +0800440 private void notifyTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700441 for (int i = 0; i < mCallbacks.size(); i++) {
Winson Chunge6439102018-07-30 15:48:01 -0700442 mCallbacks.get(i).onRecentTaskRemoved(task, wasTrimmed, killProcess);
Winson Chung1dbc8112017-09-28 18:05:31 -0700443 }
Vinit Nayak3e737492019-07-24 13:03:15 -0700444 mTaskNotificationController.notifyTaskListUpdated();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800445 }
446
447 /**
Suprabh Shuklaf5bf0cb2016-01-19 17:42:03 -0800448 * Loads the persistent recentTasks for {@code userId} into this list from persistent storage.
449 * Does nothing if they are already loaded.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800450 *
451 * @param userId the user Id
452 */
453 void loadUserRecentsLocked(int userId) {
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900454 if (mUsersWithRecentsLoaded.get(userId)) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700455 // User already loaded, return early
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900456 return;
457 }
458
459 // Load the task ids if not loaded.
460 loadPersistedTaskIdsForUserLocked(userId);
461
462 // Check if any tasks are added before recents is loaded
463 final SparseBooleanArray preaddedTasks = new SparseBooleanArray();
Louis Changcdec0802019-11-11 11:45:07 +0800464 for (final Task task : mTasks) {
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700465 if (task.mUserId == userId && shouldPersistTaskLocked(task)) {
466 preaddedTasks.put(task.mTaskId, true);
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900467 }
468 }
469
470 Slog.i(TAG, "Loading recents for user " + userId + " into memory.");
Louis Changcdec0802019-11-11 11:45:07 +0800471 List<Task> tasks = mTaskPersister.restoreTasksForUserLocked(userId, preaddedTasks);
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800472 mTasks.addAll(tasks);
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900473 cleanupLocked(userId);
474 mUsersWithRecentsLoaded.put(userId, true);
475
476 // If we have tasks added before loading recents, we need to update persistent task IDs.
477 if (preaddedTasks.size() > 0) {
478 syncPersistentTaskIdsLocked();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800479 }
480 }
481
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800482 private void loadPersistedTaskIdsForUserLocked(int userId) {
483 // An empty instead of a null set here means that no persistent taskIds were present
484 // on file when we loaded them.
485 if (mPersistedTaskIds.get(userId) == null) {
486 mPersistedTaskIds.put(userId, mTaskPersister.loadPersistedTaskIdsForUser(userId));
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700487 Slog.i(TAG, "Loaded persisted task ids for user " + userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800488 }
489 }
490
Winson Chung1dbc8112017-09-28 18:05:31 -0700491 /**
492 * @return whether the {@param taskId} is currently in use for the given user.
493 */
494 boolean containsTaskId(int taskId, int userId) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800495 loadPersistedTaskIdsForUserLocked(userId);
496 return mPersistedTaskIds.get(userId).get(taskId);
497 }
498
Winson Chung1dbc8112017-09-28 18:05:31 -0700499 /**
500 * @return all the task ids for the user with the given {@param userId}.
501 */
502 SparseBooleanArray getTaskIdsForUser(int userId) {
503 loadPersistedTaskIdsForUserLocked(userId);
504 return mPersistedTaskIds.get(userId);
505 }
506
507 /**
508 * Kicks off the task persister to write any pending tasks to disk.
509 */
Louis Changcdec0802019-11-11 11:45:07 +0800510 void notifyTaskPersisterLocked(Task task, boolean flush) {
Andrii Kulian02b7a832016-10-06 23:11:56 -0700511 final ActivityStack stack = task != null ? task.getStack() : null;
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800512 if (stack != null && stack.isHomeOrRecentsStack()) {
513 // Never persist the home or recents stack.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800514 return;
515 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800516 syncPersistentTaskIdsLocked();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800517 mTaskPersister.wakeup(task, flush);
518 }
519
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800520 private void syncPersistentTaskIdsLocked() {
521 for (int i = mPersistedTaskIds.size() - 1; i >= 0; i--) {
522 int userId = mPersistedTaskIds.keyAt(i);
523 if (mUsersWithRecentsLoaded.get(userId)) {
524 // Recents are loaded only after task ids are loaded. Therefore, the set of taskids
525 // referenced here should not be null.
526 mPersistedTaskIds.valueAt(i).clear();
527 }
528 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700529 for (int i = mTasks.size() - 1; i >= 0; i--) {
Louis Changcdec0802019-11-11 11:45:07 +0800530 final Task task = mTasks.get(i);
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900531 if (shouldPersistTaskLocked(task)) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800532 // Set of persisted taskIds for task.userId should not be null here
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700533 // TODO Investigate why it can happen. For now initialize with an empty set
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700534 if (mPersistedTaskIds.get(task.mUserId) == null) {
535 Slog.wtf(TAG, "No task ids found for userId " + task.mUserId + ". task=" + task
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700536 + " mPersistedTaskIds=" + mPersistedTaskIds);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700537 mPersistedTaskIds.put(task.mUserId, new SparseBooleanArray());
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700538 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700539 mPersistedTaskIds.get(task.mUserId).put(task.mTaskId, true);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800540 }
541 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800542 }
543
Louis Changcdec0802019-11-11 11:45:07 +0800544 private static boolean shouldPersistTaskLocked(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700545 final ActivityStack stack = task.getStack();
Daichi Hirono4cb941e2017-03-31 14:30:41 +0900546 return task.isPersistable && (stack == null || !stack.isHomeOrRecentsStack());
547 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800548
549 void onSystemReadyLocked() {
Winson Chung3f0e59a2017-10-25 10:19:05 -0700550 loadRecentsComponent(mService.mContext.getResources());
Winson Chung1dbc8112017-09-28 18:05:31 -0700551 mTasks.clear();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800552 }
553
554 Bitmap getTaskDescriptionIcon(String path) {
555 return mTaskPersister.getTaskDescriptionIcon(path);
556 }
557
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800558 void saveImage(Bitmap image, String path) {
559 mTaskPersister.saveImage(image, path);
560 }
561
562 void flush() {
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700563 synchronized (mService.mGlobalLock) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800564 syncPersistentTaskIdsLocked();
565 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800566 mTaskPersister.flush();
567 }
568
569 /**
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800570 * Returns all userIds for which recents from persistent storage are loaded into this list.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800571 *
572 * @return an array of userIds.
573 */
574 int[] usersWithRecentsLoadedLocked() {
575 int[] usersWithRecentsLoaded = new int[mUsersWithRecentsLoaded.size()];
576 int len = 0;
577 for (int i = 0; i < usersWithRecentsLoaded.length; i++) {
578 int userId = mUsersWithRecentsLoaded.keyAt(i);
579 if (mUsersWithRecentsLoaded.valueAt(i)) {
580 usersWithRecentsLoaded[len++] = userId;
581 }
582 }
583 if (len < usersWithRecentsLoaded.length) {
584 // should never happen.
585 return Arrays.copyOf(usersWithRecentsLoaded, len);
586 }
587 return usersWithRecentsLoaded;
588 }
589
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800590 /**
591 * Removes recent tasks and any other state kept in memory for the passed in user. Does not
592 * touch the information present on persistent storage.
593 *
594 * @param userId the id of the user
595 */
596 void unloadUserDataFromMemoryLocked(int userId) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700597 if (mUsersWithRecentsLoaded.get(userId)) {
598 Slog.i(TAG, "Unloading recents for user " + userId + " from memory.");
599 mUsersWithRecentsLoaded.delete(userId);
600 removeTasksForUserLocked(userId);
601 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800602 mPersistedTaskIds.delete(userId);
603 mTaskPersister.unloadUserDataFromMemory(userId);
604 }
605
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800606 /** Remove recent tasks for a user. */
Winson Chung1dbc8112017-09-28 18:05:31 -0700607 private void removeTasksForUserLocked(int userId) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800608 if(userId <= 0) {
609 Slog.i(TAG, "Can't remove recent task on user " + userId);
610 return;
611 }
612
Winson Chung1dbc8112017-09-28 18:05:31 -0700613 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800614 Task task = mTasks.get(i);
615 if (task.mUserId == userId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700616 if(DEBUG_TASKS) Slog.i(TAG_TASKS,
Louis Changcdec0802019-11-11 11:45:07 +0800617 "remove RecentTask " + task + " when finishing user" + userId);
618 remove(task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800619 }
620 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800621 }
622
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000623 void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
624 final Set<String> packageNames = Sets.newHashSet(packages);
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 final Task task = mTasks.get(i);
627 if (task.realActivity != null
628 && packageNames.contains(task.realActivity.getPackageName())
629 && task.mUserId == userId
630 && task.realActivitySuspended != suspended) {
631 task.realActivitySuspended = suspended;
Suprabh Shukla021b57a2018-03-08 18:21:50 -0800632 if (suspended) {
Louis Changcdec0802019-11-11 11:45:07 +0800633 mSupervisor.removeTaskByIdLocked(task.mTaskId, false,
Suprabh Shukla021b57a2018-03-08 18:21:50 -0800634 REMOVE_FROM_RECENTS, "suspended-package");
635 }
Louis Changcdec0802019-11-11 11:45:07 +0800636 notifyTaskPersisterLocked(task, false);
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000637 }
638 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700639 }
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000640
Charles Hed62f9652017-11-01 10:05:51 +0000641 void onLockTaskModeStateChanged(int lockTaskModeState, int userId) {
642 if (lockTaskModeState != ActivityManager.LOCK_TASK_MODE_LOCKED) {
643 return;
644 }
645 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800646 final Task task = mTasks.get(i);
647 if (task.mUserId == userId && !mService.getLockTaskController().isTaskWhitelisted(task)) {
648 remove(task);
Charles Hed62f9652017-11-01 10:05:51 +0000649 }
650 }
651 }
652
Winson Chung1dbc8112017-09-28 18:05:31 -0700653 void removeTasksByPackageName(String packageName, int userId) {
Winson Chung63085842017-10-13 17:18:58 -0700654 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800655 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -0700656 final String taskPackageName =
Louis Changcdec0802019-11-11 11:45:07 +0800657 task.getBaseIntent().getComponent().getPackageName();
658 if (task.mUserId != userId) continue;
Winson Chung99720d42018-04-09 11:28:46 -0700659 if (!taskPackageName.equals(packageName)) continue;
Winson Chung1dbc8112017-09-28 18:05:31 -0700660
Louis Changcdec0802019-11-11 11:45:07 +0800661 mSupervisor.removeTaskByIdLocked(task.mTaskId, true, REMOVE_FROM_RECENTS,
Winson Chung0ec2a352017-10-26 11:38:30 -0700662 "remove-package-task");
Winson Chung1dbc8112017-09-28 18:05:31 -0700663 }
664 }
665
Winson Chung42fa21f2019-04-02 16:23:46 -0700666 void removeAllVisibleTasks(int userId) {
Winson Chungcdd4c3f2019-04-17 15:40:11 -0700667 Set<Integer> profileIds = getProfileIds(userId);
Winson Chunge6439102018-07-30 15:48:01 -0700668 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800669 final Task task = mTasks.get(i);
670 if (!profileIds.contains(task.mUserId)) continue;
671 if (isVisibleRecentTask(task)) {
Winson Chunge6439102018-07-30 15:48:01 -0700672 mTasks.remove(i);
Louis Changcdec0802019-11-11 11:45:07 +0800673 notifyTaskRemoved(task, true /* wasTrimmed */, true /* killProcess */);
Winson Chunge6439102018-07-30 15:48:01 -0700674 }
675 }
676 }
677
Winson Chung1dbc8112017-09-28 18:05:31 -0700678 void cleanupDisabledPackageTasksLocked(String packageName, Set<String> filterByClasses,
679 int userId) {
Winson Chung63085842017-10-13 17:18:58 -0700680 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800681 final Task task = mTasks.get(i);
682 if (userId != UserHandle.USER_ALL && task.mUserId != userId) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700683 continue;
684 }
685
Louis Changcdec0802019-11-11 11:45:07 +0800686 ComponentName cn = task.intent != null ? task.intent.getComponent() : null;
Winson Chung1dbc8112017-09-28 18:05:31 -0700687 final boolean sameComponent = cn != null && cn.getPackageName().equals(packageName)
688 && (filterByClasses == null || filterByClasses.contains(cn.getClassName()));
689 if (sameComponent) {
Louis Changcdec0802019-11-11 11:45:07 +0800690 mSupervisor.removeTaskByIdLocked(task.mTaskId, false,
Winson Chung0ec2a352017-10-26 11:38:30 -0700691 REMOVE_FROM_RECENTS, "disabled-package");
Winson Chung1dbc8112017-09-28 18:05:31 -0700692 }
693 }
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000694 }
695
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800696 /**
697 * Update the recent tasks lists: make sure tasks should still be here (their
698 * applications / activities still exist), update their availability, fix-up ordering
699 * of affiliations.
700 */
701 void cleanupLocked(int userId) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700702 int recentsCount = mTasks.size();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800703 if (recentsCount == 0) {
704 // Happens when called from the packagemanager broadcast before boot,
705 // or just any empty list.
706 return;
707 }
708
Winson Chung1dbc8112017-09-28 18:05:31 -0700709 // Clear the temp lists
710 mTmpAvailActCache.clear();
711 mTmpAvailAppCache.clear();
712
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800713 final IPackageManager pm = AppGlobals.getPackageManager();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800714 for (int i = recentsCount - 1; i >= 0; i--) {
Louis Changcdec0802019-11-11 11:45:07 +0800715 final Task task = mTasks.get(i);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700716 if (userId != UserHandle.USER_ALL && task.mUserId != userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800717 // Only look at tasks for the user ID of interest.
718 continue;
719 }
Wale Ogunwale21e06482019-11-18 05:14:15 -0800720 if (task.autoRemoveRecents && task.getTopNonFinishingActivity() == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800721 // This situation is broken, and we should just get rid of it now.
Winson Chungb4132992018-07-03 15:52:38 -0700722 remove(task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800723 Slog.w(TAG, "Removing auto-remove without activity: " + task);
724 continue;
725 }
726 // Check whether this activity is currently available.
727 if (task.realActivity != null) {
728 ActivityInfo ai = mTmpAvailActCache.get(task.realActivity);
729 if (ai == null) {
730 try {
731 // At this first cut, we're only interested in
732 // activities that are fully runnable based on
733 // current system state.
734 ai = pm.getActivityInfo(task.realActivity,
Philip P. Moltmanncff8f0f2018-03-27 12:51:51 -0700735 PackageManager.MATCH_DEBUG_TRIAGED_MISSING
736 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800737 } catch (RemoteException e) {
738 // Will never happen.
739 continue;
740 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800741 if (ai == null) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700742 ai = NO_ACTIVITY_INFO_TOKEN;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800743 }
744 mTmpAvailActCache.put(task.realActivity, ai);
745 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700746 if (ai == NO_ACTIVITY_INFO_TOKEN) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800747 // This could be either because the activity no longer exists, or the
748 // app is temporarily gone. For the former we want to remove the recents
749 // entry; for the latter we want to mark it as unavailable.
750 ApplicationInfo app = mTmpAvailAppCache
751 .get(task.realActivity.getPackageName());
752 if (app == null) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800753 try {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800754 app = pm.getApplicationInfo(task.realActivity.getPackageName(),
755 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800756 } catch (RemoteException e) {
757 // Will never happen.
758 continue;
759 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800760 if (app == null) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700761 app = NO_APPLICATION_INFO_TOKEN;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800762 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800763 mTmpAvailAppCache.put(task.realActivity.getPackageName(), app);
764 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700765 if (app == NO_APPLICATION_INFO_TOKEN
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800766 || (app.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
767 // Doesn't exist any more! Good-bye.
Winson Chungb4132992018-07-03 15:52:38 -0700768 remove(task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800769 Slog.w(TAG, "Removing no longer valid recent: " + task);
770 continue;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800771 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800772 // Otherwise just not available for now.
773 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
774 "Making recent unavailable: " + task);
775 task.isAvailable = false;
776 }
777 } else {
778 if (!ai.enabled || !ai.applicationInfo.enabled
779 || (ai.applicationInfo.flags
780 & ApplicationInfo.FLAG_INSTALLED) == 0) {
781 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
782 "Making recent unavailable: " + task
783 + " (enabled=" + ai.enabled + "/"
784 + ai.applicationInfo.enabled
785 + " flags="
786 + Integer.toHexString(ai.applicationInfo.flags)
787 + ")");
788 task.isAvailable = false;
789 } else {
790 if (DEBUG_RECENTS && !task.isAvailable) Slog.d(TAG_RECENTS,
791 "Making recent available: " + task);
792 task.isAvailable = true;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800793 }
794 }
795 }
796 }
797
798 // Verify the affiliate chain for each task.
799 int i = 0;
Winson Chung1dbc8112017-09-28 18:05:31 -0700800 recentsCount = mTasks.size();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800801 while (i < recentsCount) {
802 i = processNextAffiliateChainLocked(i);
803 }
804 // recent tasks are now in sorted, affiliated order.
805 }
806
Winson Chung1dbc8112017-09-28 18:05:31 -0700807 /**
808 * @return whether the given {@param task} can be added to the list without causing another
809 * task to be trimmed as a result of that add.
810 */
Louis Changcdec0802019-11-11 11:45:07 +0800811 private boolean canAddTaskWithoutTrim(Task task) {
Winson Chung079221f2017-12-13 17:43:34 -0800812 return findRemoveIndexForAddTask(task) == -1;
Winson Chung1dbc8112017-09-28 18:05:31 -0700813 }
814
815 /**
816 * Returns the list of {@link ActivityManager.AppTask}s.
817 */
818 ArrayList<IBinder> getAppTasksList(int callingUid, String callingPackage) {
819 final ArrayList<IBinder> list = new ArrayList<>();
820 final int size = mTasks.size();
821 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800822 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -0700823 // Skip tasks that do not match the caller. We don't need to verify
824 // callingPackage, because we are also limiting to callingUid and know
825 // that will limit to the correct security sandbox.
Louis Changcdec0802019-11-11 11:45:07 +0800826 if (task.effectiveUid != callingUid) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700827 continue;
828 }
Louis Changcdec0802019-11-11 11:45:07 +0800829 Intent intent = task.getBaseIntent();
Winson Chung1dbc8112017-09-28 18:05:31 -0700830 if (intent == null || !callingPackage.equals(intent.getComponent().getPackageName())) {
831 continue;
832 }
Louis Changcdec0802019-11-11 11:45:07 +0800833 AppTaskImpl taskImpl = new AppTaskImpl(mService, task.mTaskId, callingUid);
Winson Chung1dbc8112017-09-28 18:05:31 -0700834 list.add(taskImpl.asBinder());
835 }
836 return list;
837 }
838
Wale Ogunwale86b74462018-07-02 08:42:43 -0700839 @VisibleForTesting
840 Set<Integer> getProfileIds(int userId) {
841 Set<Integer> userIds = new ArraySet<>();
842 final List<UserInfo> profiles = mService.getUserManager().getProfiles(userId,
843 false /* enabledOnly */);
844 for (int i = profiles.size() - 1; i >= 0; --i) {
845 userIds.add(profiles.get(i).id);
846 }
847 return userIds;
848 }
849
850 @VisibleForTesting
851 UserInfo getUserInfo(int userId) {
852 return mService.getUserManager().getUserInfo(userId);
853 }
854
855 @VisibleForTesting
856 int[] getCurrentProfileIds() {
857 return mService.mAmInternal.getCurrentProfileIds();
858 }
859
Winson Chungd2730072019-02-22 14:10:27 -0800860 @VisibleForTesting
861 boolean isUserRunning(int userId, int flags) {
862 return mService.mAmInternal.isUserRunning(userId, flags);
863 }
864
Winson Chung1dbc8112017-09-28 18:05:31 -0700865 /**
866 * @return the list of recent tasks for presentation.
867 */
868 ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
869 boolean getTasksAllowed, boolean getDetailedTasks, int userId, int callingUid) {
Winson Chungb4132992018-07-03 15:52:38 -0700870 return new ParceledListSlice<>(getRecentTasksImpl(maxNum, flags, getTasksAllowed,
871 getDetailedTasks, userId, callingUid));
872 }
873
Winson Chungb4132992018-07-03 15:52:38 -0700874 /**
875 * @return the list of recent tasks for presentation.
876 */
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800877 private ArrayList<ActivityManager.RecentTaskInfo> getRecentTasksImpl(int maxNum, int flags,
Winson Chungb4132992018-07-03 15:52:38 -0700878 boolean getTasksAllowed, boolean getDetailedTasks, int userId, int callingUid) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700879 final boolean withExcluded = (flags & RECENT_WITH_EXCLUDED) != 0;
880
Winson Chungd2730072019-02-22 14:10:27 -0800881 if (!isUserRunning(userId, FLAG_AND_UNLOCKED)) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700882 Slog.i(TAG, "user " + userId + " is still locked. Cannot load recents");
Winson Chungb4132992018-07-03 15:52:38 -0700883 return new ArrayList<>();
Winson Chung1dbc8112017-09-28 18:05:31 -0700884 }
885 loadUserRecentsLocked(userId);
886
Wale Ogunwale86b74462018-07-02 08:42:43 -0700887 final Set<Integer> includedUsers = getProfileIds(userId);
Winson Chung1dbc8112017-09-28 18:05:31 -0700888 includedUsers.add(Integer.valueOf(userId));
889
890 final ArrayList<ActivityManager.RecentTaskInfo> res = new ArrayList<>();
891 final int size = mTasks.size();
Winson Chungfb44d212017-10-04 11:39:10 -0700892 int numVisibleTasks = 0;
Winson Chung1dbc8112017-09-28 18:05:31 -0700893 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800894 final Task task = mTasks.get(i);
Winson Chungfb44d212017-10-04 11:39:10 -0700895
Louis Changcdec0802019-11-11 11:45:07 +0800896 if (isVisibleRecentTask(task)) {
Winson Chungfb44d212017-10-04 11:39:10 -0700897 numVisibleTasks++;
Louis Changcdec0802019-11-11 11:45:07 +0800898 if (isInVisibleRange(task, i, numVisibleTasks, withExcluded)) {
Winson Chungfb44d212017-10-04 11:39:10 -0700899 // Fall through
900 } else {
901 // Not in visible range
902 continue;
903 }
904 } else {
905 // Not visible
906 continue;
907 }
908
Winson Chung1dbc8112017-09-28 18:05:31 -0700909 // Skip remaining tasks once we reach the requested size
910 if (res.size() >= maxNum) {
911 continue;
912 }
913
914 // Only add calling user or related users recent tasks
Louis Changcdec0802019-11-11 11:45:07 +0800915 if (!includedUsers.contains(Integer.valueOf(task.mUserId))) {
916 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700917 continue;
918 }
919
Louis Changcdec0802019-11-11 11:45:07 +0800920 if (task.realActivitySuspended) {
921 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, activity suspended: " + task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700922 continue;
923 }
924
Winson Chungd2730072019-02-22 14:10:27 -0800925 if (!getTasksAllowed) {
926 // If the caller doesn't have the GET_TASKS permission, then only
927 // allow them to see a small subset of tasks -- their own and home.
Louis Changcdec0802019-11-11 11:45:07 +0800928 if (!task.isActivityTypeHome() && task.effectiveUid != callingUid) {
929 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700930 continue;
931 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700932 }
Winson Chungd2730072019-02-22 14:10:27 -0800933
Wale Ogunwale21e06482019-11-18 05:14:15 -0800934 if (task.autoRemoveRecents && task.getTopNonFinishingActivity() == null) {
Winson Chungd2730072019-02-22 14:10:27 -0800935 // Don't include auto remove tasks that are finished or finishing.
936 if (DEBUG_RECENTS) {
Louis Changcdec0802019-11-11 11:45:07 +0800937 Slog.d(TAG_RECENTS, "Skipping, auto-remove without activity: " + task);
Winson Chungd2730072019-02-22 14:10:27 -0800938 }
939 continue;
940 }
Louis Changcdec0802019-11-11 11:45:07 +0800941 if ((flags & RECENT_IGNORE_UNAVAILABLE) != 0 && !task.isAvailable) {
Winson Chungd2730072019-02-22 14:10:27 -0800942 if (DEBUG_RECENTS) {
Louis Changcdec0802019-11-11 11:45:07 +0800943 Slog.d(TAG_RECENTS, "Skipping, unavail real act: " + task);
Winson Chungd2730072019-02-22 14:10:27 -0800944 }
945 continue;
946 }
947
Louis Changcdec0802019-11-11 11:45:07 +0800948 if (!task.mUserSetupComplete) {
Winson Chungd2730072019-02-22 14:10:27 -0800949 // Don't include task launched while user is not done setting-up.
950 if (DEBUG_RECENTS) {
Louis Changcdec0802019-11-11 11:45:07 +0800951 Slog.d(TAG_RECENTS, "Skipping, user setup not complete: " + task);
Winson Chungd2730072019-02-22 14:10:27 -0800952 }
953 continue;
954 }
955
Louis Changcdec0802019-11-11 11:45:07 +0800956 final ActivityManager.RecentTaskInfo rti = createRecentTaskInfo(task);
Winson Chungd2730072019-02-22 14:10:27 -0800957 if (!getDetailedTasks) {
958 rti.baseIntent.replaceExtras((Bundle) null);
959 }
960
961 res.add(rti);
Winson Chung1dbc8112017-09-28 18:05:31 -0700962 }
Winson Chungb4132992018-07-03 15:52:38 -0700963 return res;
Winson Chung1dbc8112017-09-28 18:05:31 -0700964 }
965
966 /**
967 * @return the list of persistable task ids.
968 */
969 void getPersistableTaskIds(ArraySet<Integer> persistentTaskIds) {
970 final int size = mTasks.size();
971 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800972 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -0700973 if (TaskPersister.DEBUG) Slog.d(TAG, "LazyTaskWriter: task=" + task
974 + " persistable=" + task.isPersistable);
975 final ActivityStack stack = task.getStack();
976 if ((task.isPersistable || task.inRecents)
977 && (stack == null || !stack.isHomeOrRecentsStack())) {
978 if (TaskPersister.DEBUG) Slog.d(TAG, "adding to persistentTaskIds task=" + task);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700979 persistentTaskIds.add(task.mTaskId);
Winson Chung1dbc8112017-09-28 18:05:31 -0700980 } else {
981 if (TaskPersister.DEBUG) Slog.d(TAG, "omitting from persistentTaskIds task="
982 + task);
983 }
984 }
985 }
986
Winson Chungd6aa3db2017-10-05 17:18:43 -0700987 @VisibleForTesting
Louis Changcdec0802019-11-11 11:45:07 +0800988 ArrayList<Task> getRawTasks() {
Winson Chungd6aa3db2017-10-05 17:18:43 -0700989 return mTasks;
990 }
991
Winson Chung1dbc8112017-09-28 18:05:31 -0700992 /**
Vadim Tryshev593e9562018-03-08 17:15:45 -0800993 * @return ids of tasks that are presented in Recents UI.
994 */
995 SparseBooleanArray getRecentTaskIds() {
996 final SparseBooleanArray res = new SparseBooleanArray();
997 final int size = mTasks.size();
998 int numVisibleTasks = 0;
999 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001000 final Task task = mTasks.get(i);
1001 if (isVisibleRecentTask(task)) {
Vadim Tryshev593e9562018-03-08 17:15:45 -08001002 numVisibleTasks++;
Louis Changcdec0802019-11-11 11:45:07 +08001003 if (isInVisibleRange(task, i, numVisibleTasks, false /* skipExcludedCheck */)) {
1004 res.put(task.mTaskId, true);
Vadim Tryshev593e9562018-03-08 17:15:45 -08001005 }
1006 }
1007 }
1008 return res;
1009 }
1010
1011 /**
Winson Chung1dbc8112017-09-28 18:05:31 -07001012 * @return the task in the task list with the given {@param id} if one exists.
1013 */
Louis Changcdec0802019-11-11 11:45:07 +08001014 Task getTask(int id) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001015 final int recentsCount = mTasks.size();
1016 for (int i = 0; i < recentsCount; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001017 Task task = mTasks.get(i);
1018 if (task.mTaskId == id) {
1019 return task;
Winson Chung1dbc8112017-09-28 18:05:31 -07001020 }
1021 }
1022 return null;
1023 }
1024
1025 /**
1026 * Add a new task to the recent tasks list.
1027 */
Louis Changcdec0802019-11-11 11:45:07 +08001028 void add(Task task) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001029 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "add: task=" + task);
1030
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001031 final boolean isAffiliated = task.mAffiliatedTaskId != task.mTaskId
Winson Chung1dbc8112017-09-28 18:05:31 -07001032 || task.mNextAffiliateTaskId != INVALID_TASK_ID
1033 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
1034
1035 int recentsCount = mTasks.size();
1036 // Quick case: never add voice sessions.
1037 // TODO: VI what about if it's just an activity?
1038 // Probably nothing to do here
1039 if (task.voiceSession != null) {
1040 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1041 "addRecent: not adding voice interaction " + task);
1042 return;
1043 }
1044 // Another quick case: check if the top-most recent task is the same.
1045 if (!isAffiliated && recentsCount > 0 && mTasks.get(0) == task) {
1046 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: already at top: " + task);
1047 return;
1048 }
1049 // Another quick case: check if this is part of a set of affiliated
1050 // tasks that are at the top.
1051 if (isAffiliated && recentsCount > 0 && task.inRecents
1052 && task.mAffiliatedTaskId == mTasks.get(0).mAffiliatedTaskId) {
1053 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: affiliated " + mTasks.get(0)
1054 + " at top when adding " + task);
1055 return;
1056 }
1057
1058 boolean needAffiliationFix = false;
1059
1060 // Slightly less quick case: the task is already in recents, so all we need
1061 // to do is move it.
1062 if (task.inRecents) {
1063 int taskIndex = mTasks.indexOf(task);
1064 if (taskIndex >= 0) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001065 if (!isAffiliated) {
1066 if (!mFreezeTaskListReordering) {
1067 // Simple case: this is not an affiliated task, so we just move it to the
1068 // front unless overridden by the provided activity options
1069 mTasks.remove(taskIndex);
1070 mTasks.add(0, task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001071
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001072 if (DEBUG_RECENTS) {
1073 Slog.d(TAG_RECENTS, "addRecent: moving to top " + task
1074 + " from " + taskIndex);
1075 }
1076 }
1077 notifyTaskPersisterLocked(task, false);
1078 return;
Winson Chung1dbc8112017-09-28 18:05:31 -07001079 }
1080 } else {
1081 Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
1082 needAffiliationFix = true;
1083 }
1084 }
1085
1086 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: trimming tasks for " + task);
Winson Chung079221f2017-12-13 17:43:34 -08001087 removeForAddTask(task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001088
1089 task.inRecents = true;
1090 if (!isAffiliated || needAffiliationFix) {
1091 // If this is a simple non-affiliated task, or we had some failure trying to
1092 // handle it as part of an affilated task, then just place it at the top.
1093 mTasks.add(0, task);
1094 notifyTaskAdded(task);
1095 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding " + task);
1096 } else if (isAffiliated) {
1097 // If this is a new affiliated task, then move all of the affiliated tasks
1098 // to the front and insert this new one.
Louis Changcdec0802019-11-11 11:45:07 +08001099 Task other = task.mNextAffiliate;
Winson Chung1dbc8112017-09-28 18:05:31 -07001100 if (other == null) {
1101 other = task.mPrevAffiliate;
1102 }
1103 if (other != null) {
1104 int otherIndex = mTasks.indexOf(other);
1105 if (otherIndex >= 0) {
1106 // Insert new task at appropriate location.
1107 int taskIndex;
1108 if (other == task.mNextAffiliate) {
1109 // We found the index of our next affiliation, which is who is
1110 // before us in the list, so add after that point.
1111 taskIndex = otherIndex+1;
1112 } else {
1113 // We found the index of our previous affiliation, which is who is
1114 // after us in the list, so add at their position.
1115 taskIndex = otherIndex;
1116 }
1117 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1118 "addRecent: new affiliated task added at " + taskIndex + ": " + task);
1119 mTasks.add(taskIndex, task);
1120 notifyTaskAdded(task);
1121
1122 // Now move everything to the front.
1123 if (moveAffiliatedTasksToFront(task, taskIndex)) {
1124 // All went well.
1125 return;
1126 }
1127
1128 // Uh oh... something bad in the affiliation chain, try to rebuild
1129 // everything and then go through our general path of adding a new task.
1130 needAffiliationFix = true;
1131 } else {
1132 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1133 "addRecent: couldn't find other affiliation " + other);
1134 needAffiliationFix = true;
1135 }
1136 } else {
1137 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1138 "addRecent: adding affiliated task without next/prev:" + task);
1139 needAffiliationFix = true;
1140 }
1141 }
1142
1143 if (needAffiliationFix) {
1144 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: regrouping affiliations");
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001145 cleanupLocked(task.mUserId);
Winson Chung1dbc8112017-09-28 18:05:31 -07001146 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001147
1148 // Trim the set of tasks to the active set
1149 trimInactiveRecentTasks();
Winson Chung1dbc8112017-09-28 18:05:31 -07001150 }
1151
1152 /**
1153 * Add the task to the bottom if possible.
1154 */
Louis Changcdec0802019-11-11 11:45:07 +08001155 boolean addToBottom(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001156 if (!canAddTaskWithoutTrim(task)) {
1157 // Adding this task would cause the task to be removed (since it's appended at
1158 // the bottom and would be trimmed) so just return now
1159 return false;
1160 }
1161
1162 add(task);
1163 return true;
1164 }
1165
1166 /**
1167 * Remove a task from the recent tasks list.
1168 */
Louis Changcdec0802019-11-11 11:45:07 +08001169 void remove(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001170 mTasks.remove(task);
Winson Chunge6439102018-07-30 15:48:01 -07001171 notifyTaskRemoved(task, false /* wasTrimmed */, false /* killProcess */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001172 }
1173
1174 /**
1175 * Trims the recents task list to the global max number of recents.
1176 */
Winson Chungd6aa3db2017-10-05 17:18:43 -07001177 private void trimInactiveRecentTasks() {
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001178 if (mFreezeTaskListReordering) {
1179 // Defer trimming inactive recent tasks until we are unfrozen
1180 return;
1181 }
1182
Winson Chung1dbc8112017-09-28 18:05:31 -07001183 int recentsCount = mTasks.size();
Winson Chungd6aa3db2017-10-05 17:18:43 -07001184
1185 // Remove from the end of the list until we reach the max number of recents
1186 while (recentsCount > mGlobalMaxNumTasks) {
Louis Changcdec0802019-11-11 11:45:07 +08001187 final Task task = mTasks.remove(recentsCount - 1);
1188 notifyTaskRemoved(task, true /* wasTrimmed */, false /* killProcess */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001189 recentsCount--;
Louis Changcdec0802019-11-11 11:45:07 +08001190 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming over max-recents task=" + task
Winson Chungd6aa3db2017-10-05 17:18:43 -07001191 + " max=" + mGlobalMaxNumTasks);
Winson Chung1dbc8112017-09-28 18:05:31 -07001192 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001193
1194 // Remove any tasks that belong to currently quiet profiles
Wale Ogunwale86b74462018-07-02 08:42:43 -07001195 final int[] profileUserIds = getCurrentProfileIds();
Winson Chungd6aa3db2017-10-05 17:18:43 -07001196 mTmpQuietProfileUserIds.clear();
1197 for (int userId : profileUserIds) {
Wale Ogunwale86b74462018-07-02 08:42:43 -07001198 final UserInfo userInfo = getUserInfo(userId);
Winson Chung129771a02017-10-18 13:49:42 -07001199 if (userInfo != null && userInfo.isManagedProfile() && userInfo.isQuietModeEnabled()) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001200 mTmpQuietProfileUserIds.put(userId, true);
1201 }
1202 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "User: " + userInfo
1203 + " quiet=" + mTmpQuietProfileUserIds.get(userId));
1204 }
1205
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001206 // Remove any inactive tasks, calculate the latest set of visible tasks.
Winson Chungd6aa3db2017-10-05 17:18:43 -07001207 int numVisibleTasks = 0;
1208 for (int i = 0; i < mTasks.size();) {
Louis Changcdec0802019-11-11 11:45:07 +08001209 final Task task = mTasks.get(i);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001210
1211 if (isActiveRecentTask(task, mTmpQuietProfileUserIds)) {
1212 if (!mHasVisibleRecentTasks) {
1213 // Keep all active tasks if visible recent tasks is not supported
1214 i++;
1215 continue;
1216 }
1217
1218 if (!isVisibleRecentTask(task)) {
1219 // Keep all active-but-invisible tasks
1220 i++;
1221 continue;
1222 } else {
1223 numVisibleTasks++;
Winson Chung0a10c3a2019-04-23 15:53:08 -07001224 if (isInVisibleRange(task, i, numVisibleTasks, false /* skipExcludedCheck */)
Winson Chungd2730072019-02-22 14:10:27 -08001225 || !isTrimmable(task)) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001226 // Keep visible tasks in range
1227 i++;
1228 continue;
1229 } else {
Winson Chung0ec2a352017-10-26 11:38:30 -07001230 // Fall through to trim visible tasks that are no longer in range and
1231 // trimmable
Winson Chungd6aa3db2017-10-05 17:18:43 -07001232 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG,
1233 "Trimming out-of-range visible task=" + task);
1234 }
1235 }
1236 } else {
1237 // Fall through to trim inactive tasks
1238 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming inactive task=" + task);
1239 }
1240
1241 // Task is no longer active, trim it from the list
1242 mTasks.remove(task);
Winson Chunge6439102018-07-30 15:48:01 -07001243 notifyTaskRemoved(task, true /* wasTrimmed */, false /* killProcess */);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001244 notifyTaskPersisterLocked(task, false /* flush */);
1245 }
1246 }
1247
1248 /**
1249 * @return whether the given task should be considered active.
1250 */
Louis Changcdec0802019-11-11 11:45:07 +08001251 private boolean isActiveRecentTask(Task task, SparseBooleanArray quietProfileUserIds) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001252 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isActiveRecentTask: task=" + task
1253 + " globalMax=" + mGlobalMaxNumTasks);
1254
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001255 if (quietProfileUserIds.get(task.mUserId)) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001256 // Quiet profile user's tasks are never active
1257 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\tisQuietProfileTask=true");
1258 return false;
1259 }
1260
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001261 if (task.mAffiliatedTaskId != INVALID_TASK_ID && task.mAffiliatedTaskId != task.mTaskId) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001262 // Keep the task active if its affiliated task is also active
Louis Changcdec0802019-11-11 11:45:07 +08001263 final Task affiliatedTask = getTask(task.mAffiliatedTaskId);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001264 if (affiliatedTask != null) {
1265 if (!isActiveRecentTask(affiliatedTask, quietProfileUserIds)) {
1266 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG,
1267 "\taffiliatedWithTask=" + affiliatedTask + " is not active");
1268 return false;
1269 }
1270 }
1271 }
1272
1273 // All other tasks are considered active
1274 return true;
1275 }
1276
1277 /**
1278 * @return whether the given active task should be presented to the user through SystemUI.
1279 */
Mark Renouf2aaf4cd2019-02-19 17:24:43 -05001280 @VisibleForTesting
Louis Changcdec0802019-11-11 11:45:07 +08001281 boolean isVisibleRecentTask(Task task) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001282 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isVisibleRecentTask: task=" + task
1283 + " minVis=" + mMinNumVisibleTasks + " maxVis=" + mMaxNumVisibleTasks
1284 + " sessionDuration=" + mActiveTasksSessionDurationMs
1285 + " inactiveDuration=" + task.getInactiveDuration()
1286 + " activityType=" + task.getActivityType()
Vadim Trysheveff42d32018-03-05 18:33:48 -08001287 + " windowingMode=" + task.getWindowingMode()
1288 + " intentFlags=" + task.getBaseIntent().getFlags());
Winson Chungd6aa3db2017-10-05 17:18:43 -07001289
Winson Chungd6aa3db2017-10-05 17:18:43 -07001290 switch (task.getActivityType()) {
1291 case ACTIVITY_TYPE_HOME:
1292 case ACTIVITY_TYPE_RECENTS:
Vadim Trysheveff42d32018-03-05 18:33:48 -08001293 // Ignore certain activity types completely
Winson Chungd6aa3db2017-10-05 17:18:43 -07001294 return false;
Vadim Trysheveff42d32018-03-05 18:33:48 -08001295 case ACTIVITY_TYPE_ASSISTANT:
1296 // Ignore assistant that chose to be excluded from Recents, even if it's a top
1297 // task.
Winson Chungb4132992018-07-03 15:52:38 -07001298 if ((task.getBaseIntent().getFlags() & FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
1299 == FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) {
Vadim Trysheveff42d32018-03-05 18:33:48 -08001300 return false;
1301 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001302 }
1303
1304 // Ignore certain windowing modes
1305 switch (task.getWindowingMode()) {
1306 case WINDOWING_MODE_PINNED:
1307 return false;
1308 case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
1309 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\ttop=" + task.getStack().topTask());
1310 final ActivityStack stack = task.getStack();
1311 if (stack != null && stack.topTask() == task) {
1312 // Only the non-top task of the primary split screen mode is visible
1313 return false;
1314 }
1315 }
1316
Mark Renouf2aaf4cd2019-02-19 17:24:43 -05001317 // Tasks managed by/associated with an ActivityView should be excluded from recents.
1318 // singleTaskInstance is set on the VirtualDisplay managed by ActivityView
1319 // TODO(b/126185105): Find a different signal to use besides isSingleTaskInstance
1320 final ActivityStack stack = task.getStack();
1321 if (stack != null) {
1322 ActivityDisplay display = stack.getDisplay();
1323 if (display != null && display.isSingleTaskInstance()) {
1324 return false;
1325 }
1326 }
1327
Benjamin Franz7dcbfb02018-01-16 15:16:16 +00001328 // If we're in lock task mode, ignore the root task
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001329 if (task == mService.getLockTaskController().getRootTask()) {
Benjamin Franz7dcbfb02018-01-16 15:16:16 +00001330 return false;
1331 }
1332
Winson Chungd6aa3db2017-10-05 17:18:43 -07001333 return true;
1334 }
1335
1336 /**
1337 * @return whether the given visible task is within the policy range.
1338 */
Louis Changcdec0802019-11-11 11:45:07 +08001339 private boolean isInVisibleRange(Task task, int taskIndex, int numVisibleTasks,
Winson Chungd2730072019-02-22 14:10:27 -08001340 boolean skipExcludedCheck) {
1341 if (!skipExcludedCheck) {
1342 // Keep the most recent task even if it is excluded from recents
1343 final boolean isExcludeFromRecents =
1344 (task.getBaseIntent().getFlags() & FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
1345 == FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
1346 if (isExcludeFromRecents) {
1347 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\texcludeFromRecents=true");
Winson Chung0a10c3a2019-04-23 15:53:08 -07001348 return taskIndex == 0;
Winson Chungd2730072019-02-22 14:10:27 -08001349 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001350 }
1351
1352 if (mMinNumVisibleTasks >= 0 && numVisibleTasks <= mMinNumVisibleTasks) {
1353 // Always keep up to the min number of recent tasks, after that fall through to the
1354 // checks below
1355 return true;
1356 }
1357
1358 if (mMaxNumVisibleTasks >= 0) {
1359 // Always keep up to the max number of recent tasks, but return false afterwards
1360 return numVisibleTasks <= mMaxNumVisibleTasks;
1361 }
1362
1363 if (mActiveTasksSessionDurationMs > 0) {
1364 // Keep the task if the inactive time is within the session window, this check must come
1365 // after the checks for the min/max visible task range
1366 if (task.getInactiveDuration() <= mActiveTasksSessionDurationMs) {
1367 return true;
1368 }
1369 }
1370
1371 return false;
Winson Chung1dbc8112017-09-28 18:05:31 -07001372 }
1373
1374 /**
Winson Chung0ec2a352017-10-26 11:38:30 -07001375 * @return whether the given task can be trimmed even if it is outside the visible range.
1376 */
Louis Changcdec0802019-11-11 11:45:07 +08001377 protected boolean isTrimmable(Task task) {
Winson Chung0ec2a352017-10-26 11:38:30 -07001378 final ActivityStack stack = task.getStack();
Winson Chung0ec2a352017-10-26 11:38:30 -07001379
1380 // No stack for task, just trim it
1381 if (stack == null) {
1382 return true;
1383 }
1384
1385 // Ignore tasks from different displays
Louis Changbd48dca2018-08-29 17:44:34 +08001386 // TODO (b/115289124): No Recents on non-default displays.
1387 if (stack.mDisplayId != DEFAULT_DISPLAY) {
Winson Chung0ec2a352017-10-26 11:38:30 -07001388 return false;
1389 }
1390
1391 // Trim tasks that are in stacks that are behind the home stack
1392 final ActivityDisplay display = stack.getDisplay();
Louis Changbd48dca2018-08-29 17:44:34 +08001393 return display.getIndexOf(stack) < display.getIndexOf(display.getHomeStack());
Winson Chung0ec2a352017-10-26 11:38:30 -07001394 }
1395
1396 /**
Winson Chung1dbc8112017-09-28 18:05:31 -07001397 * If needed, remove oldest existing entries in recents that are for the same kind
1398 * of task as the given one.
1399 */
Louis Changcdec0802019-11-11 11:45:07 +08001400 private void removeForAddTask(Task task) {
Winson Chung079221f2017-12-13 17:43:34 -08001401 final int removeIndex = findRemoveIndexForAddTask(task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001402 if (removeIndex == -1) {
1403 // Nothing to trim
1404 return;
1405 }
1406
Winson Chungd6aa3db2017-10-05 17:18:43 -07001407 // There is a similar task that will be removed for the addition of {@param task}, but it
1408 // can be the same task, and if so, the task will be re-added in add(), so skip the
1409 // callbacks here.
Louis Changcdec0802019-11-11 11:45:07 +08001410 final Task removedTask = mTasks.remove(removeIndex);
Winson Chung1dbc8112017-09-28 18:05:31 -07001411 if (removedTask != task) {
Winson Chunge6439102018-07-30 15:48:01 -07001412 notifyTaskRemoved(removedTask, false /* wasTrimmed */, false /* killProcess */);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001413 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming task=" + removedTask
1414 + " for addition of task=" + task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001415 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001416 notifyTaskPersisterLocked(removedTask, false /* flush */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001417 }
1418
1419 /**
1420 * Find the task that would be removed if the given {@param task} is added to the recent tasks
1421 * list (if any).
1422 */
Louis Changcdec0802019-11-11 11:45:07 +08001423 private int findRemoveIndexForAddTask(Task task) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001424 if (mFreezeTaskListReordering) {
1425 // Defer removing tasks due to the addition of new tasks until the task list is unfrozen
1426 return -1;
1427 }
1428
Winson Chung6c9dcad2018-03-13 16:57:55 -07001429 final int recentsCount = mTasks.size();
Winson Chung1dbc8112017-09-28 18:05:31 -07001430 final Intent intent = task.intent;
1431 final boolean document = intent != null && intent.isDocument();
1432 int maxRecents = task.maxRecents - 1;
Winson Chung1dbc8112017-09-28 18:05:31 -07001433 for (int i = 0; i < recentsCount; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001434 final Task t = mTasks.get(i);
1435 if (task != t) {
1436 if (!hasCompatibleActivityTypeAndWindowingMode(task, t)
1437 || task.mUserId != t.mUserId) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001438 continue;
1439 }
Louis Changcdec0802019-11-11 11:45:07 +08001440 final Intent trIntent = t.intent;
Winson Chung1dbc8112017-09-28 18:05:31 -07001441 final boolean sameAffinity =
Louis Changcdec0802019-11-11 11:45:07 +08001442 task.affinity != null && task.affinity.equals(t.affinity);
Winson Chung1dbc8112017-09-28 18:05:31 -07001443 final boolean sameIntent = intent != null && intent.filterEquals(trIntent);
1444 boolean multiTasksAllowed = false;
1445 final int flags = intent.getFlags();
1446 if ((flags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_NEW_DOCUMENT)) != 0
1447 && (flags & FLAG_ACTIVITY_MULTIPLE_TASK) != 0) {
1448 multiTasksAllowed = true;
1449 }
1450 final boolean trIsDocument = trIntent != null && trIntent.isDocument();
1451 final boolean bothDocuments = document && trIsDocument;
1452 if (!sameAffinity && !sameIntent && !bothDocuments) {
1453 continue;
1454 }
1455
1456 if (bothDocuments) {
1457 // Do these documents belong to the same activity?
1458 final boolean sameActivity = task.realActivity != null
Louis Changcdec0802019-11-11 11:45:07 +08001459 && t.realActivity != null
1460 && task.realActivity.equals(t.realActivity);
Winson Chung1dbc8112017-09-28 18:05:31 -07001461 if (!sameActivity) {
1462 // If the document is open in another app or is not the same document, we
1463 // don't need to trim it.
1464 continue;
1465 } else if (maxRecents > 0) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001466 --maxRecents;
1467 if (!sameIntent || multiTasksAllowed) {
1468 // We don't want to trim if we are not over the max allowed entries and
1469 // the tasks are not of the same intent filter, or multiple entries for
1470 // the task is allowed.
1471 continue;
1472 }
1473 }
1474 // Hit the maximum number of documents for this task. Fall through
1475 // and remove this document from recents.
1476 } else if (document || trIsDocument) {
1477 // Only one of these is a document. Not the droid we're looking for.
1478 continue;
1479 }
1480 }
1481 return i;
1482 }
1483 return -1;
1484 }
1485
1486 // Extract the affiliates of the chain containing recent at index start.
1487 private int processNextAffiliateChainLocked(int start) {
Louis Changcdec0802019-11-11 11:45:07 +08001488 final Task startTask = mTasks.get(start);
Winson Chung1dbc8112017-09-28 18:05:31 -07001489 final int affiliateId = startTask.mAffiliatedTaskId;
1490
1491 // Quick identification of isolated tasks. I.e. those not launched behind.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001492 if (startTask.mTaskId == affiliateId && startTask.mPrevAffiliate == null &&
Winson Chung1dbc8112017-09-28 18:05:31 -07001493 startTask.mNextAffiliate == null) {
1494 // There is still a slim chance that there are other tasks that point to this task
1495 // and that the chain is so messed up that this task no longer points to them but
1496 // the gain of this optimization outweighs the risk.
1497 startTask.inRecents = true;
1498 return start + 1;
1499 }
1500
1501 // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
1502 mTmpRecents.clear();
1503 for (int i = mTasks.size() - 1; i >= start; --i) {
Louis Changcdec0802019-11-11 11:45:07 +08001504 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -07001505 if (task.mAffiliatedTaskId == affiliateId) {
1506 mTasks.remove(i);
1507 mTmpRecents.add(task);
1508 }
1509 }
1510
1511 // Sort them all by taskId. That is the order they were create in and that order will
1512 // always be correct.
1513 Collections.sort(mTmpRecents, TASK_ID_COMPARATOR);
1514
1515 // Go through and fix up the linked list.
1516 // The first one is the end of the chain and has no next.
Louis Changcdec0802019-11-11 11:45:07 +08001517 final Task first = mTmpRecents.get(0);
Winson Chung1dbc8112017-09-28 18:05:31 -07001518 first.inRecents = true;
1519 if (first.mNextAffiliate != null) {
1520 Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
1521 first.setNextAffiliate(null);
1522 notifyTaskPersisterLocked(first, false);
1523 }
1524 // Everything in the middle is doubly linked from next to prev.
1525 final int tmpSize = mTmpRecents.size();
1526 for (int i = 0; i < tmpSize - 1; ++i) {
Louis Changcdec0802019-11-11 11:45:07 +08001527 final Task next = mTmpRecents.get(i);
1528 final Task prev = mTmpRecents.get(i + 1);
Winson Chung1dbc8112017-09-28 18:05:31 -07001529 if (next.mPrevAffiliate != prev) {
1530 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
1531 " setting prev=" + prev);
1532 next.setPrevAffiliate(prev);
1533 notifyTaskPersisterLocked(next, false);
1534 }
1535 if (prev.mNextAffiliate != next) {
1536 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
1537 " setting next=" + next);
1538 prev.setNextAffiliate(next);
1539 notifyTaskPersisterLocked(prev, false);
1540 }
1541 prev.inRecents = true;
1542 }
1543 // The last one is the beginning of the list and has no prev.
Louis Changcdec0802019-11-11 11:45:07 +08001544 final Task last = mTmpRecents.get(tmpSize - 1);
Winson Chung1dbc8112017-09-28 18:05:31 -07001545 if (last.mPrevAffiliate != null) {
1546 Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
1547 last.setPrevAffiliate(null);
1548 notifyTaskPersisterLocked(last, false);
1549 }
1550
Winson Chungd6aa3db2017-10-05 17:18:43 -07001551 // Insert the group back into mTmpTasks at start.
Winson Chung1dbc8112017-09-28 18:05:31 -07001552 mTasks.addAll(start, mTmpRecents);
1553 mTmpRecents.clear();
1554
1555 // Let the caller know where we left off.
1556 return start + tmpSize;
1557 }
1558
Louis Changcdec0802019-11-11 11:45:07 +08001559 private boolean moveAffiliatedTasksToFront(Task task, int taskIndex) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001560 int recentsCount = mTasks.size();
Louis Changcdec0802019-11-11 11:45:07 +08001561 Task top = task;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001562 int topIndex = taskIndex;
1563 while (top.mNextAffiliate != null && topIndex > 0) {
1564 top = top.mNextAffiliate;
1565 topIndex--;
1566 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001567 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding affilliates starting at "
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001568 + topIndex + " from intial " + taskIndex);
1569 // Find the end of the chain, doing a sanity check along the way.
1570 boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
1571 int endIndex = topIndex;
Louis Changcdec0802019-11-11 11:45:07 +08001572 Task prev = top;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001573 while (endIndex < recentsCount) {
Louis Changcdec0802019-11-11 11:45:07 +08001574 Task cur = mTasks.get(endIndex);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001575 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: looking at next chain @"
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001576 + endIndex + " " + cur);
1577 if (cur == top) {
1578 // Verify start of the chain.
1579 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != INVALID_TASK_ID) {
1580 Slog.wtf(TAG, "Bad chain @" + endIndex
1581 + ": first task has next affiliate: " + prev);
1582 sane = false;
1583 break;
1584 }
1585 } else {
1586 // Verify middle of the chain's next points back to the one before.
1587 if (cur.mNextAffiliate != prev
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001588 || cur.mNextAffiliateTaskId != prev.mTaskId) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001589 Slog.wtf(TAG, "Bad chain @" + endIndex
1590 + ": middle task " + cur + " @" + endIndex
1591 + " has bad next affiliate "
1592 + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
1593 + ", expected " + prev);
1594 sane = false;
1595 break;
1596 }
1597 }
1598 if (cur.mPrevAffiliateTaskId == INVALID_TASK_ID) {
1599 // Chain ends here.
1600 if (cur.mPrevAffiliate != null) {
1601 Slog.wtf(TAG, "Bad chain @" + endIndex
1602 + ": last task " + cur + " has previous affiliate "
1603 + cur.mPrevAffiliate);
1604 sane = false;
1605 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001606 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: end of chain @" + endIndex);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001607 break;
1608 } else {
1609 // Verify middle of the chain's prev points to a valid item.
1610 if (cur.mPrevAffiliate == null) {
1611 Slog.wtf(TAG, "Bad chain @" + endIndex
1612 + ": task " + cur + " has previous affiliate "
1613 + cur.mPrevAffiliate + " but should be id "
1614 + cur.mPrevAffiliate);
1615 sane = false;
1616 break;
1617 }
1618 }
1619 if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
1620 Slog.wtf(TAG, "Bad chain @" + endIndex
1621 + ": task " + cur + " has affiliated id "
1622 + cur.mAffiliatedTaskId + " but should be "
1623 + task.mAffiliatedTaskId);
1624 sane = false;
1625 break;
1626 }
1627 prev = cur;
1628 endIndex++;
1629 if (endIndex >= recentsCount) {
1630 Slog.wtf(TAG, "Bad chain ran off index " + endIndex
1631 + ": last task " + prev);
1632 sane = false;
1633 break;
1634 }
1635 }
1636 if (sane) {
1637 if (endIndex < taskIndex) {
1638 Slog.wtf(TAG, "Bad chain @" + endIndex
1639 + ": did not extend to task " + task + " @" + taskIndex);
1640 sane = false;
1641 }
1642 }
1643 if (sane) {
1644 // All looks good, we can just move all of the affiliated tasks
1645 // to the top.
1646 for (int i=topIndex; i<=endIndex; i++) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001647 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving affiliated " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001648 + " from " + i + " to " + (i-topIndex));
Louis Changcdec0802019-11-11 11:45:07 +08001649 Task cur = mTasks.remove(i);
Winson Chung1dbc8112017-09-28 18:05:31 -07001650 mTasks.add(i - topIndex, cur);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001651 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001652 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: done moving tasks " + topIndex
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001653 + " to " + endIndex);
1654 return true;
1655 }
1656
1657 // Whoops, couldn't do it.
1658 return false;
1659 }
1660
Winson Chung1dbc8112017-09-28 18:05:31 -07001661 void dump(PrintWriter pw, boolean dumpAll, String dumpPackage) {
1662 pw.println("ACTIVITY MANAGER RECENT TASKS (dumpsys activity recents)");
Winson Chung3f0e59a2017-10-25 10:19:05 -07001663 pw.println("mRecentsUid=" + mRecentsUid);
1664 pw.println("mRecentsComponent=" + mRecentsComponent);
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001665 pw.println("mFreezeTaskListReordering=" + mFreezeTaskListReordering);
Winson Chung1fe58e92019-04-10 14:18:06 -07001666 pw.println("mFreezeTaskListReorderingPendingTimeout="
1667 + mService.mH.hasCallbacks(mResetFreezeTaskListOnTimeoutRunnable));
Winson Chung1dbc8112017-09-28 18:05:31 -07001668 if (mTasks.isEmpty()) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001669 return;
1670 }
1671
Winson Chungb4132992018-07-03 15:52:38 -07001672 // Dump raw recent task list
Winson Chung3f0e59a2017-10-25 10:19:05 -07001673 boolean printedAnything = false;
1674 boolean printedHeader = false;
Winson Chung1dbc8112017-09-28 18:05:31 -07001675 final int size = mTasks.size();
1676 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001677 final Task task = mTasks.get(i);
1678 if (dumpPackage != null && (task.realActivity == null ||
1679 !dumpPackage.equals(task.realActivity.getPackageName()))) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001680 continue;
1681 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001682
Winson Chung3f0e59a2017-10-25 10:19:05 -07001683 if (!printedHeader) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001684 pw.println(" Recent tasks:");
Winson Chung3f0e59a2017-10-25 10:19:05 -07001685 printedHeader = true;
1686 printedAnything = true;
Winson Chung1dbc8112017-09-28 18:05:31 -07001687 }
1688 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
Louis Changcdec0802019-11-11 11:45:07 +08001689 pw.println(task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001690 if (dumpAll) {
Louis Changcdec0802019-11-11 11:45:07 +08001691 task.dump(pw, " ");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001692 }
1693 }
1694
Winson Chungb4132992018-07-03 15:52:38 -07001695 // Dump visible recent task list
1696 if (mHasVisibleRecentTasks) {
1697 // Reset the header flag for the next block
1698 printedHeader = false;
1699 ArrayList<ActivityManager.RecentTaskInfo> tasks = getRecentTasksImpl(Integer.MAX_VALUE,
1700 0, true /* getTasksAllowed */, false /* getDetailedTasks */,
1701 mService.getCurrentUserId(), SYSTEM_UID);
1702 for (int i = 0; i < tasks.size(); i++) {
1703 final ActivityManager.RecentTaskInfo taskInfo = tasks.get(i);
1704 if (!printedHeader) {
1705 if (printedAnything) {
1706 // Separate from the last block if it printed
1707 pw.println();
1708 }
1709 pw.println(" Visible recent tasks (most recent first):");
1710 printedHeader = true;
1711 printedAnything = true;
1712 }
1713
1714 pw.print(" * RecentTaskInfo #"); pw.print(i); pw.print(": ");
1715 taskInfo.dump(pw, " ");
1716 }
1717 }
1718
Winson Chung3f0e59a2017-10-25 10:19:05 -07001719 if (!printedAnything) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001720 pw.println(" (nothing)");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001721 }
1722 }
1723
1724 /**
Louis Changcdec0802019-11-11 11:45:07 +08001725 * Creates a new RecentTaskInfo from a Task.
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001726 */
Louis Changcdec0802019-11-11 11:45:07 +08001727 ActivityManager.RecentTaskInfo createRecentTaskInfo(Task tr) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001728 ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo();
Mark Renoufc808f062019-02-07 15:20:37 -05001729 tr.fillTaskInfo(rti);
Winson Chungabfdcce2018-07-02 17:23:33 -07001730 // Fill in some deprecated values
1731 rti.id = rti.isRunning ? rti.taskId : INVALID_TASK_ID;
1732 rti.persistentId = rti.taskId;
Winson Chung1dbc8112017-09-28 18:05:31 -07001733 return rti;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001734 }
Winson Chung27f81882018-04-19 14:45:03 -07001735
1736 /**
1737 * @return Whether the activity types and windowing modes of the two tasks are considered
1738 * compatible. This is necessary because we currently don't persist the activity type
1739 * or the windowing mode with the task, so they can be undefined when restored.
1740 */
Louis Changcdec0802019-11-11 11:45:07 +08001741 private boolean hasCompatibleActivityTypeAndWindowingMode(Task t1, Task t2) {
Winson Chung27f81882018-04-19 14:45:03 -07001742 final int activityType = t1.getActivityType();
1743 final int windowingMode = t1.getWindowingMode();
1744 final boolean isUndefinedType = activityType == ACTIVITY_TYPE_UNDEFINED;
1745 final boolean isUndefinedMode = windowingMode == WINDOWING_MODE_UNDEFINED;
1746 final int otherActivityType = t2.getActivityType();
1747 final int otherWindowingMode = t2.getWindowingMode();
1748 final boolean isOtherUndefinedType = otherActivityType == ACTIVITY_TYPE_UNDEFINED;
1749 final boolean isOtherUndefinedMode = otherWindowingMode == WINDOWING_MODE_UNDEFINED;
1750
1751 // An activity type and windowing mode is compatible if they are the exact same type/mode,
1752 // or if one of the type/modes is undefined
1753 final boolean isCompatibleType = activityType == otherActivityType
1754 || isUndefinedType || isOtherUndefinedType;
1755 final boolean isCompatibleMode = windowingMode == otherWindowingMode
1756 || isUndefinedMode || isOtherUndefinedMode;
1757
1758 return isCompatibleType && isCompatibleMode;
1759 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001760}