blob: c54fbd6b1726871ab0d6fbcdf1a3491c5a591816 [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();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900214 final Task topTask = stack != null ? stack.getTopMostTask() : 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();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900322 final Task topTask = focusedStack != null ? focusedStack.getTopMostTask() : 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) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900633 mSupervisor.removeTask(task, false, REMOVE_FROM_RECENTS, "suspended-package");
Suprabh Shukla021b57a2018-03-08 18:21:50 -0800634 }
Louis Changcdec0802019-11-11 11:45:07 +0800635 notifyTaskPersisterLocked(task, false);
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000636 }
637 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700638 }
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000639
Charles Hed62f9652017-11-01 10:05:51 +0000640 void onLockTaskModeStateChanged(int lockTaskModeState, int userId) {
641 if (lockTaskModeState != ActivityManager.LOCK_TASK_MODE_LOCKED) {
642 return;
643 }
644 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800645 final Task task = mTasks.get(i);
646 if (task.mUserId == userId && !mService.getLockTaskController().isTaskWhitelisted(task)) {
647 remove(task);
Charles Hed62f9652017-11-01 10:05:51 +0000648 }
649 }
650 }
651
Winson Chung1dbc8112017-09-28 18:05:31 -0700652 void removeTasksByPackageName(String packageName, int userId) {
Winson Chung63085842017-10-13 17:18:58 -0700653 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800654 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -0700655 final String taskPackageName =
Louis Changcdec0802019-11-11 11:45:07 +0800656 task.getBaseIntent().getComponent().getPackageName();
657 if (task.mUserId != userId) continue;
Winson Chung99720d42018-04-09 11:28:46 -0700658 if (!taskPackageName.equals(packageName)) continue;
Winson Chung1dbc8112017-09-28 18:05:31 -0700659
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900660 mSupervisor.removeTask(task, true, REMOVE_FROM_RECENTS, "remove-package-task");
Winson Chung1dbc8112017-09-28 18:05:31 -0700661 }
662 }
663
Winson Chung42fa21f2019-04-02 16:23:46 -0700664 void removeAllVisibleTasks(int userId) {
Winson Chungcdd4c3f2019-04-17 15:40:11 -0700665 Set<Integer> profileIds = getProfileIds(userId);
Winson Chunge6439102018-07-30 15:48:01 -0700666 for (int i = mTasks.size() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +0800667 final Task task = mTasks.get(i);
668 if (!profileIds.contains(task.mUserId)) continue;
669 if (isVisibleRecentTask(task)) {
Winson Chunge6439102018-07-30 15:48:01 -0700670 mTasks.remove(i);
Louis Changcdec0802019-11-11 11:45:07 +0800671 notifyTaskRemoved(task, true /* wasTrimmed */, true /* killProcess */);
Winson Chunge6439102018-07-30 15:48:01 -0700672 }
673 }
674 }
675
Winson Chung1dbc8112017-09-28 18:05:31 -0700676 void cleanupDisabledPackageTasksLocked(String packageName, Set<String> filterByClasses,
677 int userId) {
Winson Chung63085842017-10-13 17:18:58 -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 (userId != UserHandle.USER_ALL && task.mUserId != userId) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700681 continue;
682 }
683
Louis Changcdec0802019-11-11 11:45:07 +0800684 ComponentName cn = task.intent != null ? task.intent.getComponent() : null;
Winson Chung1dbc8112017-09-28 18:05:31 -0700685 final boolean sameComponent = cn != null && cn.getPackageName().equals(packageName)
686 && (filterByClasses == null || filterByClasses.contains(cn.getClassName()));
687 if (sameComponent) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900688 mSupervisor.removeTask(task, false, REMOVE_FROM_RECENTS, "disabled-package");
Winson Chung1dbc8112017-09-28 18:05:31 -0700689 }
690 }
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000691 }
692
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800693 /**
694 * Update the recent tasks lists: make sure tasks should still be here (their
695 * applications / activities still exist), update their availability, fix-up ordering
696 * of affiliations.
697 */
698 void cleanupLocked(int userId) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700699 int recentsCount = mTasks.size();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800700 if (recentsCount == 0) {
701 // Happens when called from the packagemanager broadcast before boot,
702 // or just any empty list.
703 return;
704 }
705
Winson Chung1dbc8112017-09-28 18:05:31 -0700706 // Clear the temp lists
707 mTmpAvailActCache.clear();
708 mTmpAvailAppCache.clear();
709
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800710 final IPackageManager pm = AppGlobals.getPackageManager();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800711 for (int i = recentsCount - 1; i >= 0; i--) {
Louis Changcdec0802019-11-11 11:45:07 +0800712 final Task task = mTasks.get(i);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700713 if (userId != UserHandle.USER_ALL && task.mUserId != userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800714 // Only look at tasks for the user ID of interest.
715 continue;
716 }
Wale Ogunwale21e06482019-11-18 05:14:15 -0800717 if (task.autoRemoveRecents && task.getTopNonFinishingActivity() == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800718 // This situation is broken, and we should just get rid of it now.
Winson Chungb4132992018-07-03 15:52:38 -0700719 remove(task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800720 Slog.w(TAG, "Removing auto-remove without activity: " + task);
721 continue;
722 }
723 // Check whether this activity is currently available.
724 if (task.realActivity != null) {
725 ActivityInfo ai = mTmpAvailActCache.get(task.realActivity);
726 if (ai == null) {
727 try {
728 // At this first cut, we're only interested in
729 // activities that are fully runnable based on
730 // current system state.
731 ai = pm.getActivityInfo(task.realActivity,
Philip P. Moltmanncff8f0f2018-03-27 12:51:51 -0700732 PackageManager.MATCH_DEBUG_TRIAGED_MISSING
733 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800734 } catch (RemoteException e) {
735 // Will never happen.
736 continue;
737 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800738 if (ai == null) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700739 ai = NO_ACTIVITY_INFO_TOKEN;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800740 }
741 mTmpAvailActCache.put(task.realActivity, ai);
742 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700743 if (ai == NO_ACTIVITY_INFO_TOKEN) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800744 // This could be either because the activity no longer exists, or the
745 // app is temporarily gone. For the former we want to remove the recents
746 // entry; for the latter we want to mark it as unavailable.
747 ApplicationInfo app = mTmpAvailAppCache
748 .get(task.realActivity.getPackageName());
749 if (app == null) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800750 try {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800751 app = pm.getApplicationInfo(task.realActivity.getPackageName(),
752 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800753 } catch (RemoteException e) {
754 // Will never happen.
755 continue;
756 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800757 if (app == null) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700758 app = NO_APPLICATION_INFO_TOKEN;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800759 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800760 mTmpAvailAppCache.put(task.realActivity.getPackageName(), app);
761 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700762 if (app == NO_APPLICATION_INFO_TOKEN
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800763 || (app.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
764 // Doesn't exist any more! Good-bye.
Winson Chungb4132992018-07-03 15:52:38 -0700765 remove(task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800766 Slog.w(TAG, "Removing no longer valid recent: " + task);
767 continue;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800768 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800769 // Otherwise just not available for now.
770 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
771 "Making recent unavailable: " + task);
772 task.isAvailable = false;
773 }
774 } else {
775 if (!ai.enabled || !ai.applicationInfo.enabled
776 || (ai.applicationInfo.flags
777 & ApplicationInfo.FLAG_INSTALLED) == 0) {
778 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
779 "Making recent unavailable: " + task
780 + " (enabled=" + ai.enabled + "/"
781 + ai.applicationInfo.enabled
782 + " flags="
783 + Integer.toHexString(ai.applicationInfo.flags)
784 + ")");
785 task.isAvailable = false;
786 } else {
787 if (DEBUG_RECENTS && !task.isAvailable) Slog.d(TAG_RECENTS,
788 "Making recent available: " + task);
789 task.isAvailable = true;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800790 }
791 }
792 }
793 }
794
795 // Verify the affiliate chain for each task.
796 int i = 0;
Winson Chung1dbc8112017-09-28 18:05:31 -0700797 recentsCount = mTasks.size();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800798 while (i < recentsCount) {
799 i = processNextAffiliateChainLocked(i);
800 }
801 // recent tasks are now in sorted, affiliated order.
802 }
803
Winson Chung1dbc8112017-09-28 18:05:31 -0700804 /**
805 * @return whether the given {@param task} can be added to the list without causing another
806 * task to be trimmed as a result of that add.
807 */
Louis Changcdec0802019-11-11 11:45:07 +0800808 private boolean canAddTaskWithoutTrim(Task task) {
Winson Chung079221f2017-12-13 17:43:34 -0800809 return findRemoveIndexForAddTask(task) == -1;
Winson Chung1dbc8112017-09-28 18:05:31 -0700810 }
811
812 /**
813 * Returns the list of {@link ActivityManager.AppTask}s.
814 */
815 ArrayList<IBinder> getAppTasksList(int callingUid, String callingPackage) {
816 final ArrayList<IBinder> list = new ArrayList<>();
817 final int size = mTasks.size();
818 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800819 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -0700820 // Skip tasks that do not match the caller. We don't need to verify
821 // callingPackage, because we are also limiting to callingUid and know
822 // that will limit to the correct security sandbox.
Louis Changcdec0802019-11-11 11:45:07 +0800823 if (task.effectiveUid != callingUid) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700824 continue;
825 }
Louis Changcdec0802019-11-11 11:45:07 +0800826 Intent intent = task.getBaseIntent();
Winson Chung1dbc8112017-09-28 18:05:31 -0700827 if (intent == null || !callingPackage.equals(intent.getComponent().getPackageName())) {
828 continue;
829 }
Louis Changcdec0802019-11-11 11:45:07 +0800830 AppTaskImpl taskImpl = new AppTaskImpl(mService, task.mTaskId, callingUid);
Winson Chung1dbc8112017-09-28 18:05:31 -0700831 list.add(taskImpl.asBinder());
832 }
833 return list;
834 }
835
Wale Ogunwale86b74462018-07-02 08:42:43 -0700836 @VisibleForTesting
837 Set<Integer> getProfileIds(int userId) {
838 Set<Integer> userIds = new ArraySet<>();
839 final List<UserInfo> profiles = mService.getUserManager().getProfiles(userId,
840 false /* enabledOnly */);
841 for (int i = profiles.size() - 1; i >= 0; --i) {
842 userIds.add(profiles.get(i).id);
843 }
844 return userIds;
845 }
846
847 @VisibleForTesting
848 UserInfo getUserInfo(int userId) {
849 return mService.getUserManager().getUserInfo(userId);
850 }
851
852 @VisibleForTesting
853 int[] getCurrentProfileIds() {
854 return mService.mAmInternal.getCurrentProfileIds();
855 }
856
Winson Chungd2730072019-02-22 14:10:27 -0800857 @VisibleForTesting
858 boolean isUserRunning(int userId, int flags) {
859 return mService.mAmInternal.isUserRunning(userId, flags);
860 }
861
Winson Chung1dbc8112017-09-28 18:05:31 -0700862 /**
863 * @return the list of recent tasks for presentation.
864 */
865 ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
866 boolean getTasksAllowed, boolean getDetailedTasks, int userId, int callingUid) {
Winson Chungb4132992018-07-03 15:52:38 -0700867 return new ParceledListSlice<>(getRecentTasksImpl(maxNum, flags, getTasksAllowed,
868 getDetailedTasks, userId, callingUid));
869 }
870
Winson Chungb4132992018-07-03 15:52:38 -0700871 /**
872 * @return the list of recent tasks for presentation.
873 */
Winson Chungc5fe7ff2019-02-19 14:49:25 -0800874 private ArrayList<ActivityManager.RecentTaskInfo> getRecentTasksImpl(int maxNum, int flags,
Winson Chungb4132992018-07-03 15:52:38 -0700875 boolean getTasksAllowed, boolean getDetailedTasks, int userId, int callingUid) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700876 final boolean withExcluded = (flags & RECENT_WITH_EXCLUDED) != 0;
877
Winson Chungd2730072019-02-22 14:10:27 -0800878 if (!isUserRunning(userId, FLAG_AND_UNLOCKED)) {
Winson Chung1dbc8112017-09-28 18:05:31 -0700879 Slog.i(TAG, "user " + userId + " is still locked. Cannot load recents");
Winson Chungb4132992018-07-03 15:52:38 -0700880 return new ArrayList<>();
Winson Chung1dbc8112017-09-28 18:05:31 -0700881 }
882 loadUserRecentsLocked(userId);
883
Wale Ogunwale86b74462018-07-02 08:42:43 -0700884 final Set<Integer> includedUsers = getProfileIds(userId);
Winson Chung1dbc8112017-09-28 18:05:31 -0700885 includedUsers.add(Integer.valueOf(userId));
886
887 final ArrayList<ActivityManager.RecentTaskInfo> res = new ArrayList<>();
888 final int size = mTasks.size();
Winson Chungfb44d212017-10-04 11:39:10 -0700889 int numVisibleTasks = 0;
Winson Chung1dbc8112017-09-28 18:05:31 -0700890 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800891 final Task task = mTasks.get(i);
Winson Chungfb44d212017-10-04 11:39:10 -0700892
Louis Changcdec0802019-11-11 11:45:07 +0800893 if (isVisibleRecentTask(task)) {
Winson Chungfb44d212017-10-04 11:39:10 -0700894 numVisibleTasks++;
Louis Changcdec0802019-11-11 11:45:07 +0800895 if (isInVisibleRange(task, i, numVisibleTasks, withExcluded)) {
Winson Chungfb44d212017-10-04 11:39:10 -0700896 // Fall through
897 } else {
898 // Not in visible range
899 continue;
900 }
901 } else {
902 // Not visible
903 continue;
904 }
905
Winson Chung1dbc8112017-09-28 18:05:31 -0700906 // Skip remaining tasks once we reach the requested size
907 if (res.size() >= maxNum) {
908 continue;
909 }
910
911 // Only add calling user or related users recent tasks
Louis Changcdec0802019-11-11 11:45:07 +0800912 if (!includedUsers.contains(Integer.valueOf(task.mUserId))) {
913 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700914 continue;
915 }
916
Louis Changcdec0802019-11-11 11:45:07 +0800917 if (task.realActivitySuspended) {
918 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, activity suspended: " + task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700919 continue;
920 }
921
Winson Chungd2730072019-02-22 14:10:27 -0800922 if (!getTasksAllowed) {
923 // If the caller doesn't have the GET_TASKS permission, then only
924 // allow them to see a small subset of tasks -- their own and home.
Louis Changcdec0802019-11-11 11:45:07 +0800925 if (!task.isActivityTypeHome() && task.effectiveUid != callingUid) {
926 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + task);
Winson Chung1dbc8112017-09-28 18:05:31 -0700927 continue;
928 }
Winson Chung1dbc8112017-09-28 18:05:31 -0700929 }
Winson Chungd2730072019-02-22 14:10:27 -0800930
Wale Ogunwale21e06482019-11-18 05:14:15 -0800931 if (task.autoRemoveRecents && task.getTopNonFinishingActivity() == null) {
Winson Chungd2730072019-02-22 14:10:27 -0800932 // Don't include auto remove tasks that are finished or finishing.
933 if (DEBUG_RECENTS) {
Louis Changcdec0802019-11-11 11:45:07 +0800934 Slog.d(TAG_RECENTS, "Skipping, auto-remove without activity: " + task);
Winson Chungd2730072019-02-22 14:10:27 -0800935 }
936 continue;
937 }
Louis Changcdec0802019-11-11 11:45:07 +0800938 if ((flags & RECENT_IGNORE_UNAVAILABLE) != 0 && !task.isAvailable) {
Winson Chungd2730072019-02-22 14:10:27 -0800939 if (DEBUG_RECENTS) {
Louis Changcdec0802019-11-11 11:45:07 +0800940 Slog.d(TAG_RECENTS, "Skipping, unavail real act: " + task);
Winson Chungd2730072019-02-22 14:10:27 -0800941 }
942 continue;
943 }
944
Louis Changcdec0802019-11-11 11:45:07 +0800945 if (!task.mUserSetupComplete) {
Winson Chungd2730072019-02-22 14:10:27 -0800946 // Don't include task launched while user is not done setting-up.
947 if (DEBUG_RECENTS) {
Louis Changcdec0802019-11-11 11:45:07 +0800948 Slog.d(TAG_RECENTS, "Skipping, user setup not complete: " + task);
Winson Chungd2730072019-02-22 14:10:27 -0800949 }
950 continue;
951 }
952
Louis Changcdec0802019-11-11 11:45:07 +0800953 final ActivityManager.RecentTaskInfo rti = createRecentTaskInfo(task);
Winson Chungd2730072019-02-22 14:10:27 -0800954 if (!getDetailedTasks) {
955 rti.baseIntent.replaceExtras((Bundle) null);
956 }
957
958 res.add(rti);
Winson Chung1dbc8112017-09-28 18:05:31 -0700959 }
Winson Chungb4132992018-07-03 15:52:38 -0700960 return res;
Winson Chung1dbc8112017-09-28 18:05:31 -0700961 }
962
963 /**
964 * @return the list of persistable task ids.
965 */
966 void getPersistableTaskIds(ArraySet<Integer> persistentTaskIds) {
967 final int size = mTasks.size();
968 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800969 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -0700970 if (TaskPersister.DEBUG) Slog.d(TAG, "LazyTaskWriter: task=" + task
971 + " persistable=" + task.isPersistable);
972 final ActivityStack stack = task.getStack();
973 if ((task.isPersistable || task.inRecents)
974 && (stack == null || !stack.isHomeOrRecentsStack())) {
975 if (TaskPersister.DEBUG) Slog.d(TAG, "adding to persistentTaskIds task=" + task);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700976 persistentTaskIds.add(task.mTaskId);
Winson Chung1dbc8112017-09-28 18:05:31 -0700977 } else {
978 if (TaskPersister.DEBUG) Slog.d(TAG, "omitting from persistentTaskIds task="
979 + task);
980 }
981 }
982 }
983
Winson Chungd6aa3db2017-10-05 17:18:43 -0700984 @VisibleForTesting
Louis Changcdec0802019-11-11 11:45:07 +0800985 ArrayList<Task> getRawTasks() {
Winson Chungd6aa3db2017-10-05 17:18:43 -0700986 return mTasks;
987 }
988
Winson Chung1dbc8112017-09-28 18:05:31 -0700989 /**
Vadim Tryshev593e9562018-03-08 17:15:45 -0800990 * @return ids of tasks that are presented in Recents UI.
991 */
992 SparseBooleanArray getRecentTaskIds() {
993 final SparseBooleanArray res = new SparseBooleanArray();
994 final int size = mTasks.size();
995 int numVisibleTasks = 0;
996 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +0800997 final Task task = mTasks.get(i);
998 if (isVisibleRecentTask(task)) {
Vadim Tryshev593e9562018-03-08 17:15:45 -0800999 numVisibleTasks++;
Louis Changcdec0802019-11-11 11:45:07 +08001000 if (isInVisibleRange(task, i, numVisibleTasks, false /* skipExcludedCheck */)) {
1001 res.put(task.mTaskId, true);
Vadim Tryshev593e9562018-03-08 17:15:45 -08001002 }
1003 }
1004 }
1005 return res;
1006 }
1007
1008 /**
Winson Chung1dbc8112017-09-28 18:05:31 -07001009 * @return the task in the task list with the given {@param id} if one exists.
1010 */
Louis Changcdec0802019-11-11 11:45:07 +08001011 Task getTask(int id) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001012 final int recentsCount = mTasks.size();
1013 for (int i = 0; i < recentsCount; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001014 Task task = mTasks.get(i);
1015 if (task.mTaskId == id) {
1016 return task;
Winson Chung1dbc8112017-09-28 18:05:31 -07001017 }
1018 }
1019 return null;
1020 }
1021
1022 /**
1023 * Add a new task to the recent tasks list.
1024 */
Louis Changcdec0802019-11-11 11:45:07 +08001025 void add(Task task) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001026 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "add: task=" + task);
1027
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001028 final boolean isAffiliated = task.mAffiliatedTaskId != task.mTaskId
Winson Chung1dbc8112017-09-28 18:05:31 -07001029 || task.mNextAffiliateTaskId != INVALID_TASK_ID
1030 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
1031
1032 int recentsCount = mTasks.size();
1033 // Quick case: never add voice sessions.
1034 // TODO: VI what about if it's just an activity?
1035 // Probably nothing to do here
1036 if (task.voiceSession != null) {
1037 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1038 "addRecent: not adding voice interaction " + task);
1039 return;
1040 }
1041 // Another quick case: check if the top-most recent task is the same.
1042 if (!isAffiliated && recentsCount > 0 && mTasks.get(0) == task) {
1043 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: already at top: " + task);
1044 return;
1045 }
1046 // Another quick case: check if this is part of a set of affiliated
1047 // tasks that are at the top.
1048 if (isAffiliated && recentsCount > 0 && task.inRecents
1049 && task.mAffiliatedTaskId == mTasks.get(0).mAffiliatedTaskId) {
1050 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: affiliated " + mTasks.get(0)
1051 + " at top when adding " + task);
1052 return;
1053 }
1054
1055 boolean needAffiliationFix = false;
1056
1057 // Slightly less quick case: the task is already in recents, so all we need
1058 // to do is move it.
1059 if (task.inRecents) {
1060 int taskIndex = mTasks.indexOf(task);
1061 if (taskIndex >= 0) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001062 if (!isAffiliated) {
1063 if (!mFreezeTaskListReordering) {
1064 // Simple case: this is not an affiliated task, so we just move it to the
1065 // front unless overridden by the provided activity options
1066 mTasks.remove(taskIndex);
1067 mTasks.add(0, task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001068
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001069 if (DEBUG_RECENTS) {
1070 Slog.d(TAG_RECENTS, "addRecent: moving to top " + task
1071 + " from " + taskIndex);
1072 }
1073 }
1074 notifyTaskPersisterLocked(task, false);
1075 return;
Winson Chung1dbc8112017-09-28 18:05:31 -07001076 }
1077 } else {
1078 Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
1079 needAffiliationFix = true;
1080 }
1081 }
1082
1083 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: trimming tasks for " + task);
Winson Chung079221f2017-12-13 17:43:34 -08001084 removeForAddTask(task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001085
1086 task.inRecents = true;
1087 if (!isAffiliated || needAffiliationFix) {
1088 // If this is a simple non-affiliated task, or we had some failure trying to
1089 // handle it as part of an affilated task, then just place it at the top.
1090 mTasks.add(0, task);
1091 notifyTaskAdded(task);
1092 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding " + task);
1093 } else if (isAffiliated) {
1094 // If this is a new affiliated task, then move all of the affiliated tasks
1095 // to the front and insert this new one.
Louis Changcdec0802019-11-11 11:45:07 +08001096 Task other = task.mNextAffiliate;
Winson Chung1dbc8112017-09-28 18:05:31 -07001097 if (other == null) {
1098 other = task.mPrevAffiliate;
1099 }
1100 if (other != null) {
1101 int otherIndex = mTasks.indexOf(other);
1102 if (otherIndex >= 0) {
1103 // Insert new task at appropriate location.
1104 int taskIndex;
1105 if (other == task.mNextAffiliate) {
1106 // We found the index of our next affiliation, which is who is
1107 // before us in the list, so add after that point.
1108 taskIndex = otherIndex+1;
1109 } else {
1110 // We found the index of our previous affiliation, which is who is
1111 // after us in the list, so add at their position.
1112 taskIndex = otherIndex;
1113 }
1114 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1115 "addRecent: new affiliated task added at " + taskIndex + ": " + task);
1116 mTasks.add(taskIndex, task);
1117 notifyTaskAdded(task);
1118
1119 // Now move everything to the front.
1120 if (moveAffiliatedTasksToFront(task, taskIndex)) {
1121 // All went well.
1122 return;
1123 }
1124
1125 // Uh oh... something bad in the affiliation chain, try to rebuild
1126 // everything and then go through our general path of adding a new task.
1127 needAffiliationFix = true;
1128 } else {
1129 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1130 "addRecent: couldn't find other affiliation " + other);
1131 needAffiliationFix = true;
1132 }
1133 } else {
1134 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
1135 "addRecent: adding affiliated task without next/prev:" + task);
1136 needAffiliationFix = true;
1137 }
1138 }
1139
1140 if (needAffiliationFix) {
1141 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: regrouping affiliations");
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001142 cleanupLocked(task.mUserId);
Winson Chung1dbc8112017-09-28 18:05:31 -07001143 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001144
1145 // Trim the set of tasks to the active set
1146 trimInactiveRecentTasks();
Winson Chung1dbc8112017-09-28 18:05:31 -07001147 }
1148
1149 /**
1150 * Add the task to the bottom if possible.
1151 */
Louis Changcdec0802019-11-11 11:45:07 +08001152 boolean addToBottom(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001153 if (!canAddTaskWithoutTrim(task)) {
1154 // Adding this task would cause the task to be removed (since it's appended at
1155 // the bottom and would be trimmed) so just return now
1156 return false;
1157 }
1158
1159 add(task);
1160 return true;
1161 }
1162
1163 /**
1164 * Remove a task from the recent tasks list.
1165 */
Louis Changcdec0802019-11-11 11:45:07 +08001166 void remove(Task task) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001167 mTasks.remove(task);
Winson Chunge6439102018-07-30 15:48:01 -07001168 notifyTaskRemoved(task, false /* wasTrimmed */, false /* killProcess */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001169 }
1170
1171 /**
1172 * Trims the recents task list to the global max number of recents.
1173 */
Winson Chungd6aa3db2017-10-05 17:18:43 -07001174 private void trimInactiveRecentTasks() {
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001175 if (mFreezeTaskListReordering) {
1176 // Defer trimming inactive recent tasks until we are unfrozen
1177 return;
1178 }
1179
Winson Chung1dbc8112017-09-28 18:05:31 -07001180 int recentsCount = mTasks.size();
Winson Chungd6aa3db2017-10-05 17:18:43 -07001181
1182 // Remove from the end of the list until we reach the max number of recents
1183 while (recentsCount > mGlobalMaxNumTasks) {
Louis Changcdec0802019-11-11 11:45:07 +08001184 final Task task = mTasks.remove(recentsCount - 1);
1185 notifyTaskRemoved(task, true /* wasTrimmed */, false /* killProcess */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001186 recentsCount--;
Louis Changcdec0802019-11-11 11:45:07 +08001187 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming over max-recents task=" + task
Winson Chungd6aa3db2017-10-05 17:18:43 -07001188 + " max=" + mGlobalMaxNumTasks);
Winson Chung1dbc8112017-09-28 18:05:31 -07001189 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001190
1191 // Remove any tasks that belong to currently quiet profiles
Wale Ogunwale86b74462018-07-02 08:42:43 -07001192 final int[] profileUserIds = getCurrentProfileIds();
Winson Chungd6aa3db2017-10-05 17:18:43 -07001193 mTmpQuietProfileUserIds.clear();
1194 for (int userId : profileUserIds) {
Wale Ogunwale86b74462018-07-02 08:42:43 -07001195 final UserInfo userInfo = getUserInfo(userId);
Winson Chung129771a02017-10-18 13:49:42 -07001196 if (userInfo != null && userInfo.isManagedProfile() && userInfo.isQuietModeEnabled()) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001197 mTmpQuietProfileUserIds.put(userId, true);
1198 }
1199 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "User: " + userInfo
1200 + " quiet=" + mTmpQuietProfileUserIds.get(userId));
1201 }
1202
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001203 // Remove any inactive tasks, calculate the latest set of visible tasks.
Winson Chungd6aa3db2017-10-05 17:18:43 -07001204 int numVisibleTasks = 0;
1205 for (int i = 0; i < mTasks.size();) {
Louis Changcdec0802019-11-11 11:45:07 +08001206 final Task task = mTasks.get(i);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001207
1208 if (isActiveRecentTask(task, mTmpQuietProfileUserIds)) {
1209 if (!mHasVisibleRecentTasks) {
1210 // Keep all active tasks if visible recent tasks is not supported
1211 i++;
1212 continue;
1213 }
1214
1215 if (!isVisibleRecentTask(task)) {
1216 // Keep all active-but-invisible tasks
1217 i++;
1218 continue;
1219 } else {
1220 numVisibleTasks++;
Winson Chung0a10c3a2019-04-23 15:53:08 -07001221 if (isInVisibleRange(task, i, numVisibleTasks, false /* skipExcludedCheck */)
Winson Chungd2730072019-02-22 14:10:27 -08001222 || !isTrimmable(task)) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001223 // Keep visible tasks in range
1224 i++;
1225 continue;
1226 } else {
Winson Chung0ec2a352017-10-26 11:38:30 -07001227 // Fall through to trim visible tasks that are no longer in range and
1228 // trimmable
Winson Chungd6aa3db2017-10-05 17:18:43 -07001229 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG,
1230 "Trimming out-of-range visible task=" + task);
1231 }
1232 }
1233 } else {
1234 // Fall through to trim inactive tasks
1235 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming inactive task=" + task);
1236 }
1237
1238 // Task is no longer active, trim it from the list
1239 mTasks.remove(task);
Winson Chunge6439102018-07-30 15:48:01 -07001240 notifyTaskRemoved(task, true /* wasTrimmed */, false /* killProcess */);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001241 notifyTaskPersisterLocked(task, false /* flush */);
1242 }
1243 }
1244
1245 /**
1246 * @return whether the given task should be considered active.
1247 */
Louis Changcdec0802019-11-11 11:45:07 +08001248 private boolean isActiveRecentTask(Task task, SparseBooleanArray quietProfileUserIds) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001249 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isActiveRecentTask: task=" + task
1250 + " globalMax=" + mGlobalMaxNumTasks);
1251
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001252 if (quietProfileUserIds.get(task.mUserId)) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001253 // Quiet profile user's tasks are never active
1254 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\tisQuietProfileTask=true");
1255 return false;
1256 }
1257
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001258 if (task.mAffiliatedTaskId != INVALID_TASK_ID && task.mAffiliatedTaskId != task.mTaskId) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001259 // Keep the task active if its affiliated task is also active
Louis Changcdec0802019-11-11 11:45:07 +08001260 final Task affiliatedTask = getTask(task.mAffiliatedTaskId);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001261 if (affiliatedTask != null) {
1262 if (!isActiveRecentTask(affiliatedTask, quietProfileUserIds)) {
1263 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG,
1264 "\taffiliatedWithTask=" + affiliatedTask + " is not active");
1265 return false;
1266 }
1267 }
1268 }
1269
1270 // All other tasks are considered active
1271 return true;
1272 }
1273
1274 /**
1275 * @return whether the given active task should be presented to the user through SystemUI.
1276 */
Mark Renouf2aaf4cd2019-02-19 17:24:43 -05001277 @VisibleForTesting
Louis Changcdec0802019-11-11 11:45:07 +08001278 boolean isVisibleRecentTask(Task task) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001279 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isVisibleRecentTask: task=" + task
1280 + " minVis=" + mMinNumVisibleTasks + " maxVis=" + mMaxNumVisibleTasks
1281 + " sessionDuration=" + mActiveTasksSessionDurationMs
1282 + " inactiveDuration=" + task.getInactiveDuration()
1283 + " activityType=" + task.getActivityType()
Vadim Trysheveff42d32018-03-05 18:33:48 -08001284 + " windowingMode=" + task.getWindowingMode()
1285 + " intentFlags=" + task.getBaseIntent().getFlags());
Winson Chungd6aa3db2017-10-05 17:18:43 -07001286
Winson Chungd6aa3db2017-10-05 17:18:43 -07001287 switch (task.getActivityType()) {
1288 case ACTIVITY_TYPE_HOME:
1289 case ACTIVITY_TYPE_RECENTS:
Vadim Trysheveff42d32018-03-05 18:33:48 -08001290 // Ignore certain activity types completely
Winson Chungd6aa3db2017-10-05 17:18:43 -07001291 return false;
Vadim Trysheveff42d32018-03-05 18:33:48 -08001292 case ACTIVITY_TYPE_ASSISTANT:
1293 // Ignore assistant that chose to be excluded from Recents, even if it's a top
1294 // task.
Winson Chungb4132992018-07-03 15:52:38 -07001295 if ((task.getBaseIntent().getFlags() & FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
1296 == FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) {
Vadim Trysheveff42d32018-03-05 18:33:48 -08001297 return false;
1298 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001299 }
1300
1301 // Ignore certain windowing modes
1302 switch (task.getWindowingMode()) {
1303 case WINDOWING_MODE_PINNED:
1304 return false;
1305 case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001306 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\ttop=" + task.getStack().getTopMostTask());
Winson Chungd6aa3db2017-10-05 17:18:43 -07001307 final ActivityStack stack = task.getStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001308 if (stack != null && stack.getTopMostTask() == task) {
Winson Chungd6aa3db2017-10-05 17:18:43 -07001309 // Only the non-top task of the primary split screen mode is visible
1310 return false;
1311 }
1312 }
1313
Mark Renouf2aaf4cd2019-02-19 17:24:43 -05001314 // Tasks managed by/associated with an ActivityView should be excluded from recents.
1315 // singleTaskInstance is set on the VirtualDisplay managed by ActivityView
1316 // TODO(b/126185105): Find a different signal to use besides isSingleTaskInstance
1317 final ActivityStack stack = task.getStack();
1318 if (stack != null) {
1319 ActivityDisplay display = stack.getDisplay();
1320 if (display != null && display.isSingleTaskInstance()) {
1321 return false;
1322 }
1323 }
1324
Benjamin Franz7dcbfb02018-01-16 15:16:16 +00001325 // If we're in lock task mode, ignore the root task
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001326 if (task == mService.getLockTaskController().getRootTask()) {
Benjamin Franz7dcbfb02018-01-16 15:16:16 +00001327 return false;
1328 }
1329
Winson Chungd6aa3db2017-10-05 17:18:43 -07001330 return true;
1331 }
1332
1333 /**
1334 * @return whether the given visible task is within the policy range.
1335 */
Louis Changcdec0802019-11-11 11:45:07 +08001336 private boolean isInVisibleRange(Task task, int taskIndex, int numVisibleTasks,
Winson Chungd2730072019-02-22 14:10:27 -08001337 boolean skipExcludedCheck) {
1338 if (!skipExcludedCheck) {
1339 // Keep the most recent task even if it is excluded from recents
1340 final boolean isExcludeFromRecents =
1341 (task.getBaseIntent().getFlags() & FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
1342 == FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
1343 if (isExcludeFromRecents) {
1344 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\texcludeFromRecents=true");
Winson Chung0a10c3a2019-04-23 15:53:08 -07001345 return taskIndex == 0;
Winson Chungd2730072019-02-22 14:10:27 -08001346 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001347 }
1348
1349 if (mMinNumVisibleTasks >= 0 && numVisibleTasks <= mMinNumVisibleTasks) {
1350 // Always keep up to the min number of recent tasks, after that fall through to the
1351 // checks below
1352 return true;
1353 }
1354
1355 if (mMaxNumVisibleTasks >= 0) {
1356 // Always keep up to the max number of recent tasks, but return false afterwards
1357 return numVisibleTasks <= mMaxNumVisibleTasks;
1358 }
1359
1360 if (mActiveTasksSessionDurationMs > 0) {
1361 // Keep the task if the inactive time is within the session window, this check must come
1362 // after the checks for the min/max visible task range
1363 if (task.getInactiveDuration() <= mActiveTasksSessionDurationMs) {
1364 return true;
1365 }
1366 }
1367
1368 return false;
Winson Chung1dbc8112017-09-28 18:05:31 -07001369 }
1370
1371 /**
Winson Chung0ec2a352017-10-26 11:38:30 -07001372 * @return whether the given task can be trimmed even if it is outside the visible range.
1373 */
Louis Changcdec0802019-11-11 11:45:07 +08001374 protected boolean isTrimmable(Task task) {
Winson Chung0ec2a352017-10-26 11:38:30 -07001375 final ActivityStack stack = task.getStack();
Winson Chung0ec2a352017-10-26 11:38:30 -07001376
1377 // No stack for task, just trim it
1378 if (stack == null) {
1379 return true;
1380 }
1381
1382 // Ignore tasks from different displays
Louis Changbd48dca2018-08-29 17:44:34 +08001383 // TODO (b/115289124): No Recents on non-default displays.
1384 if (stack.mDisplayId != DEFAULT_DISPLAY) {
Winson Chung0ec2a352017-10-26 11:38:30 -07001385 return false;
1386 }
1387
1388 // Trim tasks that are in stacks that are behind the home stack
1389 final ActivityDisplay display = stack.getDisplay();
Louis Changbd48dca2018-08-29 17:44:34 +08001390 return display.getIndexOf(stack) < display.getIndexOf(display.getHomeStack());
Winson Chung0ec2a352017-10-26 11:38:30 -07001391 }
1392
1393 /**
Winson Chung1dbc8112017-09-28 18:05:31 -07001394 * If needed, remove oldest existing entries in recents that are for the same kind
1395 * of task as the given one.
1396 */
Louis Changcdec0802019-11-11 11:45:07 +08001397 private void removeForAddTask(Task task) {
Winson Chung079221f2017-12-13 17:43:34 -08001398 final int removeIndex = findRemoveIndexForAddTask(task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001399 if (removeIndex == -1) {
1400 // Nothing to trim
1401 return;
1402 }
1403
Winson Chungd6aa3db2017-10-05 17:18:43 -07001404 // There is a similar task that will be removed for the addition of {@param task}, but it
1405 // can be the same task, and if so, the task will be re-added in add(), so skip the
1406 // callbacks here.
Louis Changcdec0802019-11-11 11:45:07 +08001407 final Task removedTask = mTasks.remove(removeIndex);
Winson Chung1dbc8112017-09-28 18:05:31 -07001408 if (removedTask != task) {
Winson Chunge6439102018-07-30 15:48:01 -07001409 notifyTaskRemoved(removedTask, false /* wasTrimmed */, false /* killProcess */);
Winson Chungd6aa3db2017-10-05 17:18:43 -07001410 if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming task=" + removedTask
1411 + " for addition of task=" + task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001412 }
Winson Chungd6aa3db2017-10-05 17:18:43 -07001413 notifyTaskPersisterLocked(removedTask, false /* flush */);
Winson Chung1dbc8112017-09-28 18:05:31 -07001414 }
1415
1416 /**
1417 * Find the task that would be removed if the given {@param task} is added to the recent tasks
1418 * list (if any).
1419 */
Louis Changcdec0802019-11-11 11:45:07 +08001420 private int findRemoveIndexForAddTask(Task task) {
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001421 if (mFreezeTaskListReordering) {
1422 // Defer removing tasks due to the addition of new tasks until the task list is unfrozen
1423 return -1;
1424 }
1425
Winson Chung6c9dcad2018-03-13 16:57:55 -07001426 final int recentsCount = mTasks.size();
Winson Chung1dbc8112017-09-28 18:05:31 -07001427 final Intent intent = task.intent;
1428 final boolean document = intent != null && intent.isDocument();
1429 int maxRecents = task.maxRecents - 1;
Winson Chung1dbc8112017-09-28 18:05:31 -07001430 for (int i = 0; i < recentsCount; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001431 final Task t = mTasks.get(i);
1432 if (task != t) {
1433 if (!hasCompatibleActivityTypeAndWindowingMode(task, t)
1434 || task.mUserId != t.mUserId) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001435 continue;
1436 }
Louis Changcdec0802019-11-11 11:45:07 +08001437 final Intent trIntent = t.intent;
Winson Chung1dbc8112017-09-28 18:05:31 -07001438 final boolean sameAffinity =
Louis Changcdec0802019-11-11 11:45:07 +08001439 task.affinity != null && task.affinity.equals(t.affinity);
Winson Chung1dbc8112017-09-28 18:05:31 -07001440 final boolean sameIntent = intent != null && intent.filterEquals(trIntent);
1441 boolean multiTasksAllowed = false;
1442 final int flags = intent.getFlags();
1443 if ((flags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_NEW_DOCUMENT)) != 0
1444 && (flags & FLAG_ACTIVITY_MULTIPLE_TASK) != 0) {
1445 multiTasksAllowed = true;
1446 }
1447 final boolean trIsDocument = trIntent != null && trIntent.isDocument();
1448 final boolean bothDocuments = document && trIsDocument;
1449 if (!sameAffinity && !sameIntent && !bothDocuments) {
1450 continue;
1451 }
1452
1453 if (bothDocuments) {
1454 // Do these documents belong to the same activity?
1455 final boolean sameActivity = task.realActivity != null
Louis Changcdec0802019-11-11 11:45:07 +08001456 && t.realActivity != null
1457 && task.realActivity.equals(t.realActivity);
Winson Chung1dbc8112017-09-28 18:05:31 -07001458 if (!sameActivity) {
1459 // If the document is open in another app or is not the same document, we
1460 // don't need to trim it.
1461 continue;
1462 } else if (maxRecents > 0) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001463 --maxRecents;
1464 if (!sameIntent || multiTasksAllowed) {
1465 // We don't want to trim if we are not over the max allowed entries and
1466 // the tasks are not of the same intent filter, or multiple entries for
1467 // the task is allowed.
1468 continue;
1469 }
1470 }
1471 // Hit the maximum number of documents for this task. Fall through
1472 // and remove this document from recents.
1473 } else if (document || trIsDocument) {
1474 // Only one of these is a document. Not the droid we're looking for.
1475 continue;
1476 }
1477 }
1478 return i;
1479 }
1480 return -1;
1481 }
1482
1483 // Extract the affiliates of the chain containing recent at index start.
1484 private int processNextAffiliateChainLocked(int start) {
Louis Changcdec0802019-11-11 11:45:07 +08001485 final Task startTask = mTasks.get(start);
Winson Chung1dbc8112017-09-28 18:05:31 -07001486 final int affiliateId = startTask.mAffiliatedTaskId;
1487
1488 // Quick identification of isolated tasks. I.e. those not launched behind.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001489 if (startTask.mTaskId == affiliateId && startTask.mPrevAffiliate == null &&
Winson Chung1dbc8112017-09-28 18:05:31 -07001490 startTask.mNextAffiliate == null) {
1491 // There is still a slim chance that there are other tasks that point to this task
1492 // and that the chain is so messed up that this task no longer points to them but
1493 // the gain of this optimization outweighs the risk.
1494 startTask.inRecents = true;
1495 return start + 1;
1496 }
1497
1498 // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
1499 mTmpRecents.clear();
1500 for (int i = mTasks.size() - 1; i >= start; --i) {
Louis Changcdec0802019-11-11 11:45:07 +08001501 final Task task = mTasks.get(i);
Winson Chung1dbc8112017-09-28 18:05:31 -07001502 if (task.mAffiliatedTaskId == affiliateId) {
1503 mTasks.remove(i);
1504 mTmpRecents.add(task);
1505 }
1506 }
1507
1508 // Sort them all by taskId. That is the order they were create in and that order will
1509 // always be correct.
1510 Collections.sort(mTmpRecents, TASK_ID_COMPARATOR);
1511
1512 // Go through and fix up the linked list.
1513 // The first one is the end of the chain and has no next.
Louis Changcdec0802019-11-11 11:45:07 +08001514 final Task first = mTmpRecents.get(0);
Winson Chung1dbc8112017-09-28 18:05:31 -07001515 first.inRecents = true;
1516 if (first.mNextAffiliate != null) {
1517 Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
1518 first.setNextAffiliate(null);
1519 notifyTaskPersisterLocked(first, false);
1520 }
1521 // Everything in the middle is doubly linked from next to prev.
1522 final int tmpSize = mTmpRecents.size();
1523 for (int i = 0; i < tmpSize - 1; ++i) {
Louis Changcdec0802019-11-11 11:45:07 +08001524 final Task next = mTmpRecents.get(i);
1525 final Task prev = mTmpRecents.get(i + 1);
Winson Chung1dbc8112017-09-28 18:05:31 -07001526 if (next.mPrevAffiliate != prev) {
1527 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
1528 " setting prev=" + prev);
1529 next.setPrevAffiliate(prev);
1530 notifyTaskPersisterLocked(next, false);
1531 }
1532 if (prev.mNextAffiliate != next) {
1533 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
1534 " setting next=" + next);
1535 prev.setNextAffiliate(next);
1536 notifyTaskPersisterLocked(prev, false);
1537 }
1538 prev.inRecents = true;
1539 }
1540 // The last one is the beginning of the list and has no prev.
Louis Changcdec0802019-11-11 11:45:07 +08001541 final Task last = mTmpRecents.get(tmpSize - 1);
Winson Chung1dbc8112017-09-28 18:05:31 -07001542 if (last.mPrevAffiliate != null) {
1543 Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
1544 last.setPrevAffiliate(null);
1545 notifyTaskPersisterLocked(last, false);
1546 }
1547
Winson Chungd6aa3db2017-10-05 17:18:43 -07001548 // Insert the group back into mTmpTasks at start.
Winson Chung1dbc8112017-09-28 18:05:31 -07001549 mTasks.addAll(start, mTmpRecents);
1550 mTmpRecents.clear();
1551
1552 // Let the caller know where we left off.
1553 return start + tmpSize;
1554 }
1555
Louis Changcdec0802019-11-11 11:45:07 +08001556 private boolean moveAffiliatedTasksToFront(Task task, int taskIndex) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001557 int recentsCount = mTasks.size();
Louis Changcdec0802019-11-11 11:45:07 +08001558 Task top = task;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001559 int topIndex = taskIndex;
1560 while (top.mNextAffiliate != null && topIndex > 0) {
1561 top = top.mNextAffiliate;
1562 topIndex--;
1563 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001564 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding affilliates starting at "
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001565 + topIndex + " from intial " + taskIndex);
1566 // Find the end of the chain, doing a sanity check along the way.
1567 boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
1568 int endIndex = topIndex;
Louis Changcdec0802019-11-11 11:45:07 +08001569 Task prev = top;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001570 while (endIndex < recentsCount) {
Louis Changcdec0802019-11-11 11:45:07 +08001571 Task cur = mTasks.get(endIndex);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001572 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: looking at next chain @"
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001573 + endIndex + " " + cur);
1574 if (cur == top) {
1575 // Verify start of the chain.
1576 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != INVALID_TASK_ID) {
1577 Slog.wtf(TAG, "Bad chain @" + endIndex
1578 + ": first task has next affiliate: " + prev);
1579 sane = false;
1580 break;
1581 }
1582 } else {
1583 // Verify middle of the chain's next points back to the one before.
1584 if (cur.mNextAffiliate != prev
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001585 || cur.mNextAffiliateTaskId != prev.mTaskId) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001586 Slog.wtf(TAG, "Bad chain @" + endIndex
1587 + ": middle task " + cur + " @" + endIndex
1588 + " has bad next affiliate "
1589 + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
1590 + ", expected " + prev);
1591 sane = false;
1592 break;
1593 }
1594 }
1595 if (cur.mPrevAffiliateTaskId == INVALID_TASK_ID) {
1596 // Chain ends here.
1597 if (cur.mPrevAffiliate != null) {
1598 Slog.wtf(TAG, "Bad chain @" + endIndex
1599 + ": last task " + cur + " has previous affiliate "
1600 + cur.mPrevAffiliate);
1601 sane = false;
1602 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001603 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: end of chain @" + endIndex);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001604 break;
1605 } else {
1606 // Verify middle of the chain's prev points to a valid item.
1607 if (cur.mPrevAffiliate == null) {
1608 Slog.wtf(TAG, "Bad chain @" + endIndex
1609 + ": task " + cur + " has previous affiliate "
1610 + cur.mPrevAffiliate + " but should be id "
1611 + cur.mPrevAffiliate);
1612 sane = false;
1613 break;
1614 }
1615 }
1616 if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
1617 Slog.wtf(TAG, "Bad chain @" + endIndex
1618 + ": task " + cur + " has affiliated id "
1619 + cur.mAffiliatedTaskId + " but should be "
1620 + task.mAffiliatedTaskId);
1621 sane = false;
1622 break;
1623 }
1624 prev = cur;
1625 endIndex++;
1626 if (endIndex >= recentsCount) {
1627 Slog.wtf(TAG, "Bad chain ran off index " + endIndex
1628 + ": last task " + prev);
1629 sane = false;
1630 break;
1631 }
1632 }
1633 if (sane) {
1634 if (endIndex < taskIndex) {
1635 Slog.wtf(TAG, "Bad chain @" + endIndex
1636 + ": did not extend to task " + task + " @" + taskIndex);
1637 sane = false;
1638 }
1639 }
1640 if (sane) {
1641 // All looks good, we can just move all of the affiliated tasks
1642 // to the top.
1643 for (int i=topIndex; i<=endIndex; i++) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001644 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving affiliated " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001645 + " from " + i + " to " + (i-topIndex));
Louis Changcdec0802019-11-11 11:45:07 +08001646 Task cur = mTasks.remove(i);
Winson Chung1dbc8112017-09-28 18:05:31 -07001647 mTasks.add(i - topIndex, cur);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001648 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001649 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: done moving tasks " + topIndex
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001650 + " to " + endIndex);
1651 return true;
1652 }
1653
1654 // Whoops, couldn't do it.
1655 return false;
1656 }
1657
Winson Chung1dbc8112017-09-28 18:05:31 -07001658 void dump(PrintWriter pw, boolean dumpAll, String dumpPackage) {
1659 pw.println("ACTIVITY MANAGER RECENT TASKS (dumpsys activity recents)");
Winson Chung3f0e59a2017-10-25 10:19:05 -07001660 pw.println("mRecentsUid=" + mRecentsUid);
1661 pw.println("mRecentsComponent=" + mRecentsComponent);
Winson Chungc5fe7ff2019-02-19 14:49:25 -08001662 pw.println("mFreezeTaskListReordering=" + mFreezeTaskListReordering);
Winson Chung1fe58e92019-04-10 14:18:06 -07001663 pw.println("mFreezeTaskListReorderingPendingTimeout="
1664 + mService.mH.hasCallbacks(mResetFreezeTaskListOnTimeoutRunnable));
Winson Chung1dbc8112017-09-28 18:05:31 -07001665 if (mTasks.isEmpty()) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001666 return;
1667 }
1668
Winson Chungb4132992018-07-03 15:52:38 -07001669 // Dump raw recent task list
Winson Chung3f0e59a2017-10-25 10:19:05 -07001670 boolean printedAnything = false;
1671 boolean printedHeader = false;
Winson Chung1dbc8112017-09-28 18:05:31 -07001672 final int size = mTasks.size();
1673 for (int i = 0; i < size; i++) {
Louis Changcdec0802019-11-11 11:45:07 +08001674 final Task task = mTasks.get(i);
1675 if (dumpPackage != null && (task.realActivity == null ||
1676 !dumpPackage.equals(task.realActivity.getPackageName()))) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001677 continue;
1678 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001679
Winson Chung3f0e59a2017-10-25 10:19:05 -07001680 if (!printedHeader) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001681 pw.println(" Recent tasks:");
Winson Chung3f0e59a2017-10-25 10:19:05 -07001682 printedHeader = true;
1683 printedAnything = true;
Winson Chung1dbc8112017-09-28 18:05:31 -07001684 }
1685 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
Louis Changcdec0802019-11-11 11:45:07 +08001686 pw.println(task);
Winson Chung1dbc8112017-09-28 18:05:31 -07001687 if (dumpAll) {
Louis Changcdec0802019-11-11 11:45:07 +08001688 task.dump(pw, " ");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001689 }
1690 }
1691
Winson Chungb4132992018-07-03 15:52:38 -07001692 // Dump visible recent task list
1693 if (mHasVisibleRecentTasks) {
1694 // Reset the header flag for the next block
1695 printedHeader = false;
1696 ArrayList<ActivityManager.RecentTaskInfo> tasks = getRecentTasksImpl(Integer.MAX_VALUE,
1697 0, true /* getTasksAllowed */, false /* getDetailedTasks */,
1698 mService.getCurrentUserId(), SYSTEM_UID);
1699 for (int i = 0; i < tasks.size(); i++) {
1700 final ActivityManager.RecentTaskInfo taskInfo = tasks.get(i);
1701 if (!printedHeader) {
1702 if (printedAnything) {
1703 // Separate from the last block if it printed
1704 pw.println();
1705 }
1706 pw.println(" Visible recent tasks (most recent first):");
1707 printedHeader = true;
1708 printedAnything = true;
1709 }
1710
1711 pw.print(" * RecentTaskInfo #"); pw.print(i); pw.print(": ");
1712 taskInfo.dump(pw, " ");
1713 }
1714 }
1715
Winson Chung3f0e59a2017-10-25 10:19:05 -07001716 if (!printedAnything) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001717 pw.println(" (nothing)");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001718 }
1719 }
1720
1721 /**
Louis Changcdec0802019-11-11 11:45:07 +08001722 * Creates a new RecentTaskInfo from a Task.
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001723 */
Louis Changcdec0802019-11-11 11:45:07 +08001724 ActivityManager.RecentTaskInfo createRecentTaskInfo(Task tr) {
Winson Chung1dbc8112017-09-28 18:05:31 -07001725 ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo();
Mark Renoufc808f062019-02-07 15:20:37 -05001726 tr.fillTaskInfo(rti);
Winson Chungabfdcce2018-07-02 17:23:33 -07001727 // Fill in some deprecated values
1728 rti.id = rti.isRunning ? rti.taskId : INVALID_TASK_ID;
1729 rti.persistentId = rti.taskId;
Winson Chung1dbc8112017-09-28 18:05:31 -07001730 return rti;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001731 }
Winson Chung27f81882018-04-19 14:45:03 -07001732
1733 /**
1734 * @return Whether the activity types and windowing modes of the two tasks are considered
1735 * compatible. This is necessary because we currently don't persist the activity type
1736 * or the windowing mode with the task, so they can be undefined when restored.
1737 */
Louis Changcdec0802019-11-11 11:45:07 +08001738 private boolean hasCompatibleActivityTypeAndWindowingMode(Task t1, Task t2) {
Winson Chung27f81882018-04-19 14:45:03 -07001739 final int activityType = t1.getActivityType();
1740 final int windowingMode = t1.getWindowingMode();
1741 final boolean isUndefinedType = activityType == ACTIVITY_TYPE_UNDEFINED;
1742 final boolean isUndefinedMode = windowingMode == WINDOWING_MODE_UNDEFINED;
1743 final int otherActivityType = t2.getActivityType();
1744 final int otherWindowingMode = t2.getWindowingMode();
1745 final boolean isOtherUndefinedType = otherActivityType == ACTIVITY_TYPE_UNDEFINED;
1746 final boolean isOtherUndefinedMode = otherWindowingMode == WINDOWING_MODE_UNDEFINED;
1747
1748 // An activity type and windowing mode is compatible if they are the exact same type/mode,
1749 // or if one of the type/modes is undefined
1750 final boolean isCompatibleType = activityType == otherActivityType
1751 || isUndefinedType || isOtherUndefinedType;
1752 final boolean isCompatibleMode = windowingMode == otherWindowingMode
1753 || isUndefinedMode || isOtherUndefinedMode;
1754
1755 return isCompatibleType && isCompatibleMode;
1756 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001757}