blob: 6a13d369e70b4c6803c230a7022a88ba4fdafb60 [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
17package com.android.server.am;
18
Wale Ogunwalee8d5f652016-04-22 16:27:39 -070019import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
21import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080022import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
23import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
24import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
25import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
26import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
27import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Wale Ogunwalee23149f2015-03-06 15:39:44 -080028import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
29
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +000030import com.google.android.collect.Sets;
31
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080032import android.app.ActivityManager;
33import android.app.AppGlobals;
34import android.content.ComponentName;
35import android.content.Intent;
36import android.content.pm.ActivityInfo;
37import android.content.pm.ApplicationInfo;
38import android.content.pm.IPackageManager;
39import android.content.pm.PackageManager;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080040import android.graphics.Bitmap;
41import android.os.Environment;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080042import android.os.RemoteException;
43import android.os.UserHandle;
44import android.util.Slog;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080045import android.util.SparseArray;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080046import android.util.SparseBooleanArray;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080047
Suprabh Shukla09a88f52015-12-02 14:36:31 -080048import java.io.File;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080049import java.util.ArrayList;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080050import java.util.Arrays;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080051import java.util.Collections;
52import java.util.Comparator;
53import java.util.HashMap;
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +000054import java.util.Set;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080055
56/**
57 * Class for managing the recent tasks list.
58 */
59class RecentTasks extends ArrayList<TaskRecord> {
Wale Ogunwalee23149f2015-03-06 15:39:44 -080060 private static final String TAG = TAG_WITH_CLASS_NAME ? "RecentTasks" : TAG_AM;
Wale Ogunwaleee006da2015-03-30 14:49:25 -070061 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
62 private static final String TAG_TASKS = TAG + POSTFIX_TASKS;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080063
64 // Maximum number recent bitmaps to keep in memory.
65 private static final int MAX_RECENT_BITMAPS = 3;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080066 private static final int DEFAULT_INITIAL_CAPACITY = 5;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080067
Winson6976f7b2016-05-03 14:58:12 -070068 // Whether or not to move all affiliated tasks to the front when one of the tasks is launched
69 private static final boolean MOVE_AFFILIATED_TASKS_TO_FRONT = false;
70
Suprabh Shukla09a88f52015-12-02 14:36:31 -080071 /**
72 * Save recent tasks information across reboots.
73 */
74 private final TaskPersister mTaskPersister;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080075 private final ActivityManagerService mService;
76 private final SparseBooleanArray mUsersWithRecentsLoaded = new SparseBooleanArray(
77 DEFAULT_INITIAL_CAPACITY);
78
79 /**
80 * Stores for each user task ids that are taken by tasks residing in persistent storage. These
81 * tasks may or may not currently be in memory.
82 */
83 final SparseArray<SparseBooleanArray> mPersistedTaskIds = new SparseArray<>(
84 DEFAULT_INITIAL_CAPACITY);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080085
86 // Mainly to avoid object recreation on multiple calls.
87 private final ArrayList<TaskRecord> mTmpRecents = new ArrayList<TaskRecord>();
Suprabh Shukla09a88f52015-12-02 14:36:31 -080088 private final HashMap<ComponentName, ActivityInfo> mTmpAvailActCache = new HashMap<>();
89 private final HashMap<String, ApplicationInfo> mTmpAvailAppCache = new HashMap<>();
90 private final ActivityInfo mTmpActivityInfo = new ActivityInfo();
91 private final ApplicationInfo mTmpAppInfo = new ApplicationInfo();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080092
Suprabh Shukla09a88f52015-12-02 14:36:31 -080093 RecentTasks(ActivityManagerService service, ActivityStackSupervisor mStackSupervisor) {
94 File systemDir = Environment.getDataSystemDirectory();
Suprabh Shukla4bccb462016-02-10 18:45:12 -080095 mService = service;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080096 mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, service, this);
97 mStackSupervisor.setRecentTasks(this);
98 }
99
100 /**
Suprabh Shuklaf5bf0cb2016-01-19 17:42:03 -0800101 * Loads the persistent recentTasks for {@code userId} into this list from persistent storage.
102 * Does nothing if they are already loaded.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800103 *
104 * @param userId the user Id
105 */
106 void loadUserRecentsLocked(int userId) {
107 if (!mUsersWithRecentsLoaded.get(userId)) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800108 // Load the task ids if not loaded.
109 loadPersistedTaskIdsForUserLocked(userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800110 Slog.i(TAG, "Loading recents for user " + userId + " into memory.");
111 addAll(mTaskPersister.restoreTasksForUserLocked(userId));
112 cleanupLocked(userId);
113 mUsersWithRecentsLoaded.put(userId, true);
114 }
115 }
116
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800117 private void loadPersistedTaskIdsForUserLocked(int userId) {
118 // An empty instead of a null set here means that no persistent taskIds were present
119 // on file when we loaded them.
120 if (mPersistedTaskIds.get(userId) == null) {
121 mPersistedTaskIds.put(userId, mTaskPersister.loadPersistedTaskIdsForUser(userId));
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700122 Slog.i(TAG, "Loaded persisted task ids for user " + userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800123 }
124 }
125
126 boolean taskIdTakenForUserLocked(int taskId, int userId) {
127 loadPersistedTaskIdsForUserLocked(userId);
128 return mPersistedTaskIds.get(userId).get(taskId);
129 }
130
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800131 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
Andrii Kulian02b7a832016-10-06 23:11:56 -0700132 final ActivityStack stack = task != null ? task.getStack() : null;
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800133 if (stack != null && stack.isHomeOrRecentsStack()) {
134 // Never persist the home or recents stack.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800135 return;
136 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800137 syncPersistentTaskIdsLocked();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800138 mTaskPersister.wakeup(task, flush);
139 }
140
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800141 private void syncPersistentTaskIdsLocked() {
142 for (int i = mPersistedTaskIds.size() - 1; i >= 0; i--) {
143 int userId = mPersistedTaskIds.keyAt(i);
144 if (mUsersWithRecentsLoaded.get(userId)) {
145 // Recents are loaded only after task ids are loaded. Therefore, the set of taskids
146 // referenced here should not be null.
147 mPersistedTaskIds.valueAt(i).clear();
148 }
149 }
150 for (int i = size() - 1; i >= 0; i--) {
Andrii Kulian02b7a832016-10-06 23:11:56 -0700151 final TaskRecord task = get(i);
152 final ActivityStack stack = task.getStack();
Matthew Ngae1ff4f2016-11-10 15:49:14 -0800153 if (task.isPersistable && (stack == null || !stack.isHomeOrRecentsStack())) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800154 // Set of persisted taskIds for task.userId should not be null here
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700155 // TODO Investigate why it can happen. For now initialize with an empty set
156 if (mPersistedTaskIds.get(task.userId) == null) {
157 Slog.wtf(TAG, "No task ids found for userId " + task.userId + ". task=" + task
158 + " mPersistedTaskIds=" + mPersistedTaskIds);
159 mPersistedTaskIds.put(task.userId, new SparseBooleanArray());
160 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800161 mPersistedTaskIds.get(task.userId).put(task.taskId, true);
162 }
163 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800164 }
165
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800166
167 void onSystemReadyLocked() {
168 clear();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800169 mTaskPersister.startPersisting();
170 }
171
172 Bitmap getTaskDescriptionIcon(String path) {
173 return mTaskPersister.getTaskDescriptionIcon(path);
174 }
175
176 Bitmap getImageFromWriteQueue(String path) {
177 return mTaskPersister.getImageFromWriteQueue(path);
178 }
179
180 void saveImage(Bitmap image, String path) {
181 mTaskPersister.saveImage(image, path);
182 }
183
184 void flush() {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800185 synchronized (mService) {
186 syncPersistentTaskIdsLocked();
187 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800188 mTaskPersister.flush();
189 }
190
191 /**
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800192 * Returns all userIds for which recents from persistent storage are loaded into this list.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800193 *
194 * @return an array of userIds.
195 */
196 int[] usersWithRecentsLoadedLocked() {
197 int[] usersWithRecentsLoaded = new int[mUsersWithRecentsLoaded.size()];
198 int len = 0;
199 for (int i = 0; i < usersWithRecentsLoaded.length; i++) {
200 int userId = mUsersWithRecentsLoaded.keyAt(i);
201 if (mUsersWithRecentsLoaded.valueAt(i)) {
202 usersWithRecentsLoaded[len++] = userId;
203 }
204 }
205 if (len < usersWithRecentsLoaded.length) {
206 // should never happen.
207 return Arrays.copyOf(usersWithRecentsLoaded, len);
208 }
209 return usersWithRecentsLoaded;
210 }
211
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800212 private void unloadUserRecentsLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800213 if (mUsersWithRecentsLoaded.get(userId)) {
214 Slog.i(TAG, "Unloading recents for user " + userId + " from memory.");
215 mUsersWithRecentsLoaded.delete(userId);
216 removeTasksForUserLocked(userId);
217 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800218 }
219
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800220 /**
221 * Removes recent tasks and any other state kept in memory for the passed in user. Does not
222 * touch the information present on persistent storage.
223 *
224 * @param userId the id of the user
225 */
226 void unloadUserDataFromMemoryLocked(int userId) {
227 unloadUserRecentsLocked(userId);
228 mPersistedTaskIds.delete(userId);
229 mTaskPersister.unloadUserDataFromMemory(userId);
230 }
231
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800232 TaskRecord taskForIdLocked(int id) {
233 final int recentsCount = size();
234 for (int i = 0; i < recentsCount; i++) {
235 TaskRecord tr = get(i);
236 if (tr.taskId == id) {
237 return tr;
238 }
239 }
240 return null;
241 }
242
243 /** Remove recent tasks for a user. */
244 void removeTasksForUserLocked(int userId) {
245 if(userId <= 0) {
246 Slog.i(TAG, "Can't remove recent task on user " + userId);
247 return;
248 }
249
250 for (int i = size() - 1; i >= 0; --i) {
251 TaskRecord tr = get(i);
252 if (tr.userId == userId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700253 if(DEBUG_TASKS) Slog.i(TAG_TASKS,
254 "remove RecentTask " + tr + " when finishing user" + userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800255 remove(i);
256 tr.removedFromRecents();
257 }
258 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800259 }
260
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000261 void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
262 final Set<String> packageNames = Sets.newHashSet(packages);
263 for (int i = size() - 1; i >= 0; --i) {
264 final TaskRecord tr = get(i);
265 if (tr.realActivity != null
266 && packageNames.contains(tr.realActivity.getPackageName())
267 && tr.userId == userId
268 && tr.realActivitySuspended != suspended) {
269 tr.realActivitySuspended = suspended;
270 notifyTaskPersisterLocked(tr, false);
271 }
272 }
273
274 }
275
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800276 /**
277 * Update the recent tasks lists: make sure tasks should still be here (their
278 * applications / activities still exist), update their availability, fix-up ordering
279 * of affiliations.
280 */
281 void cleanupLocked(int userId) {
282 int recentsCount = size();
283 if (recentsCount == 0) {
284 // Happens when called from the packagemanager broadcast before boot,
285 // or just any empty list.
286 return;
287 }
288
289 final IPackageManager pm = AppGlobals.getPackageManager();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800290 for (int i = recentsCount - 1; i >= 0; i--) {
291 final TaskRecord task = get(i);
292 if (userId != UserHandle.USER_ALL && task.userId != userId) {
293 // Only look at tasks for the user ID of interest.
294 continue;
295 }
296 if (task.autoRemoveRecents && task.getTopActivity() == null) {
297 // This situation is broken, and we should just get rid of it now.
298 remove(i);
299 task.removedFromRecents();
300 Slog.w(TAG, "Removing auto-remove without activity: " + task);
301 continue;
302 }
303 // Check whether this activity is currently available.
304 if (task.realActivity != null) {
305 ActivityInfo ai = mTmpAvailActCache.get(task.realActivity);
306 if (ai == null) {
307 try {
308 // At this first cut, we're only interested in
309 // activities that are fully runnable based on
310 // current system state.
311 ai = pm.getActivityInfo(task.realActivity,
312 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
313 } catch (RemoteException e) {
314 // Will never happen.
315 continue;
316 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800317 if (ai == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800318 ai = mTmpActivityInfo;
319 }
320 mTmpAvailActCache.put(task.realActivity, ai);
321 }
322 if (ai == mTmpActivityInfo) {
323 // This could be either because the activity no longer exists, or the
324 // app is temporarily gone. For the former we want to remove the recents
325 // entry; for the latter we want to mark it as unavailable.
326 ApplicationInfo app = mTmpAvailAppCache
327 .get(task.realActivity.getPackageName());
328 if (app == null) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800329 try {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800330 app = pm.getApplicationInfo(task.realActivity.getPackageName(),
331 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800332 } catch (RemoteException e) {
333 // Will never happen.
334 continue;
335 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800336 if (app == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800337 app = mTmpAppInfo;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800338 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800339 mTmpAvailAppCache.put(task.realActivity.getPackageName(), app);
340 }
341 if (app == mTmpAppInfo
342 || (app.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
343 // Doesn't exist any more! Good-bye.
344 remove(i);
345 task.removedFromRecents();
346 Slog.w(TAG, "Removing no longer valid recent: " + task);
347 continue;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800348 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800349 // Otherwise just not available for now.
350 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
351 "Making recent unavailable: " + task);
352 task.isAvailable = false;
353 }
354 } else {
355 if (!ai.enabled || !ai.applicationInfo.enabled
356 || (ai.applicationInfo.flags
357 & ApplicationInfo.FLAG_INSTALLED) == 0) {
358 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
359 "Making recent unavailable: " + task
360 + " (enabled=" + ai.enabled + "/"
361 + ai.applicationInfo.enabled
362 + " flags="
363 + Integer.toHexString(ai.applicationInfo.flags)
364 + ")");
365 task.isAvailable = false;
366 } else {
367 if (DEBUG_RECENTS && !task.isAvailable) Slog.d(TAG_RECENTS,
368 "Making recent available: " + task);
369 task.isAvailable = true;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800370 }
371 }
372 }
373 }
374
375 // Verify the affiliate chain for each task.
376 int i = 0;
377 recentsCount = size();
378 while (i < recentsCount) {
379 i = processNextAffiliateChainLocked(i);
380 }
381 // recent tasks are now in sorted, affiliated order.
382 }
383
384 private final boolean moveAffiliatedTasksToFront(TaskRecord task, int taskIndex) {
385 int recentsCount = size();
386 TaskRecord top = task;
387 int topIndex = taskIndex;
388 while (top.mNextAffiliate != null && topIndex > 0) {
389 top = top.mNextAffiliate;
390 topIndex--;
391 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700392 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding affilliates starting at "
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800393 + topIndex + " from intial " + taskIndex);
394 // Find the end of the chain, doing a sanity check along the way.
395 boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
396 int endIndex = topIndex;
397 TaskRecord prev = top;
398 while (endIndex < recentsCount) {
399 TaskRecord cur = get(endIndex);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700400 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: looking at next chain @"
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800401 + endIndex + " " + cur);
402 if (cur == top) {
403 // Verify start of the chain.
404 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != INVALID_TASK_ID) {
405 Slog.wtf(TAG, "Bad chain @" + endIndex
406 + ": first task has next affiliate: " + prev);
407 sane = false;
408 break;
409 }
410 } else {
411 // Verify middle of the chain's next points back to the one before.
412 if (cur.mNextAffiliate != prev
413 || cur.mNextAffiliateTaskId != prev.taskId) {
414 Slog.wtf(TAG, "Bad chain @" + endIndex
415 + ": middle task " + cur + " @" + endIndex
416 + " has bad next affiliate "
417 + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
418 + ", expected " + prev);
419 sane = false;
420 break;
421 }
422 }
423 if (cur.mPrevAffiliateTaskId == INVALID_TASK_ID) {
424 // Chain ends here.
425 if (cur.mPrevAffiliate != null) {
426 Slog.wtf(TAG, "Bad chain @" + endIndex
427 + ": last task " + cur + " has previous affiliate "
428 + cur.mPrevAffiliate);
429 sane = false;
430 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700431 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: end of chain @" + endIndex);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800432 break;
433 } else {
434 // Verify middle of the chain's prev points to a valid item.
435 if (cur.mPrevAffiliate == null) {
436 Slog.wtf(TAG, "Bad chain @" + endIndex
437 + ": task " + cur + " has previous affiliate "
438 + cur.mPrevAffiliate + " but should be id "
439 + cur.mPrevAffiliate);
440 sane = false;
441 break;
442 }
443 }
444 if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
445 Slog.wtf(TAG, "Bad chain @" + endIndex
446 + ": task " + cur + " has affiliated id "
447 + cur.mAffiliatedTaskId + " but should be "
448 + task.mAffiliatedTaskId);
449 sane = false;
450 break;
451 }
452 prev = cur;
453 endIndex++;
454 if (endIndex >= recentsCount) {
455 Slog.wtf(TAG, "Bad chain ran off index " + endIndex
456 + ": last task " + prev);
457 sane = false;
458 break;
459 }
460 }
461 if (sane) {
462 if (endIndex < taskIndex) {
463 Slog.wtf(TAG, "Bad chain @" + endIndex
464 + ": did not extend to task " + task + " @" + taskIndex);
465 sane = false;
466 }
467 }
468 if (sane) {
469 // All looks good, we can just move all of the affiliated tasks
470 // to the top.
471 for (int i=topIndex; i<=endIndex; i++) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700472 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving affiliated " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800473 + " from " + i + " to " + (i-topIndex));
474 TaskRecord cur = remove(i);
475 add(i - topIndex, cur);
476 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700477 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: done moving tasks " + topIndex
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800478 + " to " + endIndex);
479 return true;
480 }
481
482 // Whoops, couldn't do it.
483 return false;
484 }
485
486 final void addLocked(TaskRecord task) {
487 final boolean isAffiliated = task.mAffiliatedTaskId != task.taskId
488 || task.mNextAffiliateTaskId != INVALID_TASK_ID
489 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
490
491 int recentsCount = size();
492 // Quick case: never add voice sessions.
Amith Yamasani0af6fa72016-01-17 15:36:19 -0800493 // TODO: VI what about if it's just an activity?
494 // Probably nothing to do here
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800495 if (task.voiceSession != null) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700496 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
497 "addRecent: not adding voice interaction " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800498 return;
499 }
500 // Another quick case: check if the top-most recent task is the same.
501 if (!isAffiliated && recentsCount > 0 && get(0) == task) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700502 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: already at top: " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800503 return;
504 }
505 // Another quick case: check if this is part of a set of affiliated
506 // tasks that are at the top.
507 if (isAffiliated && recentsCount > 0 && task.inRecents
508 && task.mAffiliatedTaskId == get(0).mAffiliatedTaskId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700509 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: affiliated " + get(0)
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800510 + " at top when adding " + task);
511 return;
512 }
513
514 boolean needAffiliationFix = false;
515
516 // Slightly less quick case: the task is already in recents, so all we need
517 // to do is move it.
518 if (task.inRecents) {
519 int taskIndex = indexOf(task);
520 if (taskIndex >= 0) {
Winson6976f7b2016-05-03 14:58:12 -0700521 if (!isAffiliated || MOVE_AFFILIATED_TASKS_TO_FRONT) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800522 // Simple case: this is not an affiliated task, so we just move it to the front.
523 remove(taskIndex);
524 add(0, task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800525 notifyTaskPersisterLocked(task, false);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700526 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving to top " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800527 + " from " + taskIndex);
528 return;
529 } else {
530 // More complicated: need to keep all affiliated tasks together.
531 if (moveAffiliatedTasksToFront(task, taskIndex)) {
532 // All went well.
533 return;
534 }
535
536 // Uh oh... something bad in the affiliation chain, try to rebuild
537 // everything and then go through our general path of adding a new task.
538 needAffiliationFix = true;
539 }
540 } else {
541 Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
542 needAffiliationFix = true;
543 }
544 }
545
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700546 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: trimming tasks for " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800547 trimForTaskLocked(task, true);
548
549 recentsCount = size();
550 final int maxRecents = ActivityManager.getMaxRecentTasksStatic();
551 while (recentsCount >= maxRecents) {
552 final TaskRecord tr = remove(recentsCount - 1);
553 tr.removedFromRecents();
554 recentsCount--;
555 }
556 task.inRecents = true;
557 if (!isAffiliated || needAffiliationFix) {
558 // If this is a simple non-affiliated task, or we had some failure trying to
559 // handle it as part of an affilated task, then just place it at the top.
560 add(0, task);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700561 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800562 } else if (isAffiliated) {
563 // If this is a new affiliated task, then move all of the affiliated tasks
564 // to the front and insert this new one.
565 TaskRecord other = task.mNextAffiliate;
566 if (other == null) {
567 other = task.mPrevAffiliate;
568 }
569 if (other != null) {
570 int otherIndex = indexOf(other);
571 if (otherIndex >= 0) {
572 // Insert new task at appropriate location.
573 int taskIndex;
574 if (other == task.mNextAffiliate) {
575 // We found the index of our next affiliation, which is who is
576 // before us in the list, so add after that point.
577 taskIndex = otherIndex+1;
578 } else {
579 // We found the index of our previous affiliation, which is who is
580 // after us in the list, so add at their position.
581 taskIndex = otherIndex;
582 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700583 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
584 "addRecent: new affiliated task added at " + taskIndex + ": " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800585 add(taskIndex, task);
586
587 // Now move everything to the front.
588 if (moveAffiliatedTasksToFront(task, taskIndex)) {
589 // All went well.
590 return;
591 }
592
593 // Uh oh... something bad in the affiliation chain, try to rebuild
594 // everything and then go through our general path of adding a new task.
595 needAffiliationFix = true;
596 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700597 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
598 "addRecent: couldn't find other affiliation " + other);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800599 needAffiliationFix = true;
600 }
601 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700602 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800603 "addRecent: adding affiliated task without next/prev:" + task);
604 needAffiliationFix = true;
605 }
606 }
607
608 if (needAffiliationFix) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700609 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: regrouping affiliations");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800610 cleanupLocked(task.userId);
611 }
612 }
613
614 /**
615 * If needed, remove oldest existing entries in recents that are for the same kind
616 * of task as the given one.
617 */
618 int trimForTaskLocked(TaskRecord task, boolean doTrim) {
619 int recentsCount = size();
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700620 final Intent intent = task.intent;
621 final boolean document = intent != null && intent.isDocument();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800622 int maxRecents = task.maxRecents - 1;
Andrii Kulian02b7a832016-10-06 23:11:56 -0700623 final ActivityStack stack = task.getStack();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800624 for (int i = 0; i < recentsCount; i++) {
625 final TaskRecord tr = get(i);
Andrii Kulian02b7a832016-10-06 23:11:56 -0700626 final ActivityStack trStack = tr.getStack();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800627 if (task != tr) {
Andrii Kulian02b7a832016-10-06 23:11:56 -0700628 if (stack != null && trStack != null && stack != trStack) {
Winson29dbc3c2016-06-08 12:49:54 -0700629 continue;
630 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800631 if (task.userId != tr.userId) {
632 continue;
633 }
634 if (i > MAX_RECENT_BITMAPS) {
635 tr.freeLastThumbnail();
636 }
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700637 final Intent trIntent = tr.intent;
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700638 final boolean sameAffinity =
639 task.affinity != null && task.affinity.equals(tr.affinity);
Wale Ogunwalee8d5f652016-04-22 16:27:39 -0700640 final boolean sameIntentFilter = intent != null && intent.filterEquals(trIntent);
641 boolean multiTasksAllowed = false;
642 final int flags = intent.getFlags();
643 if ((flags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_NEW_DOCUMENT)) != 0
644 && (flags & FLAG_ACTIVITY_MULTIPLE_TASK) != 0) {
645 multiTasksAllowed = true;
646 }
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700647 final boolean trIsDocument = trIntent != null && trIntent.isDocument();
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700648 final boolean bothDocuments = document && trIsDocument;
Wale Ogunwalee8d5f652016-04-22 16:27:39 -0700649 if (!sameAffinity && !sameIntentFilter && !bothDocuments) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800650 continue;
651 }
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700652
653 if (bothDocuments) {
654 // Do these documents belong to the same activity?
655 final boolean sameActivity = task.realActivity != null
656 && tr.realActivity != null
657 && task.realActivity.equals(tr.realActivity);
Robert Carr7cb57e12015-11-10 13:44:02 -0800658 // If the document is open in another app or is not the same
659 // document, we don't need to trim it.
Wale Ogunwale847167f2016-08-09 09:21:10 -0700660 if (!sameActivity) {
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700661 continue;
Robert Carr7cb57e12015-11-10 13:44:02 -0800662 // Otherwise only trim if we are over our max recents for this task
Wale Ogunwale847167f2016-08-09 09:21:10 -0700663 } else if (maxRecents > 0) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800664 --maxRecents;
Wale Ogunwale847167f2016-08-09 09:21:10 -0700665 if (!doTrim || !sameIntentFilter || multiTasksAllowed) {
666 // We don't want to trim if we are not over the max allowed entries and
667 // the caller doesn't want us to trim, the tasks are not of the same
668 // intent filter, or multiple entries fot the task is allowed.
669 continue;
670 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800671 }
672 // Hit the maximum number of documents for this task. Fall through
673 // and remove this document from recents.
674 } else if (document || trIsDocument) {
675 // Only one of these is a document. Not the droid we're looking for.
676 continue;
677 }
678 }
679
680 if (!doTrim) {
681 // If the caller is not actually asking for a trim, just tell them we reached
682 // a point where the trim would happen.
683 return i;
684 }
685
686 // Either task and tr are the same or, their affinities match or their intents match
687 // and neither of them is a document, or they are documents using the same activity
688 // and their maxRecents has been reached.
689 tr.disposeThumbnail();
690 remove(i);
691 if (task != tr) {
692 tr.removedFromRecents();
693 }
694 i--;
695 recentsCount--;
696 if (task.intent == null) {
697 // If the new recent task we are adding is not fully
698 // specified, then replace it with the existing recent task.
699 task = tr;
700 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800701 notifyTaskPersisterLocked(tr, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800702 }
703
704 return -1;
705 }
706
707 // Sort by taskId
708 private static Comparator<TaskRecord> sTaskRecordComparator = new Comparator<TaskRecord>() {
709 @Override
710 public int compare(TaskRecord lhs, TaskRecord rhs) {
711 return rhs.taskId - lhs.taskId;
712 }
713 };
714
715 // Extract the affiliates of the chain containing recent at index start.
716 private int processNextAffiliateChainLocked(int start) {
717 final TaskRecord startTask = get(start);
718 final int affiliateId = startTask.mAffiliatedTaskId;
719
720 // Quick identification of isolated tasks. I.e. those not launched behind.
721 if (startTask.taskId == affiliateId && startTask.mPrevAffiliate == null &&
722 startTask.mNextAffiliate == null) {
723 // There is still a slim chance that there are other tasks that point to this task
724 // and that the chain is so messed up that this task no longer points to them but
725 // the gain of this optimization outweighs the risk.
726 startTask.inRecents = true;
727 return start + 1;
728 }
729
730 // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
731 mTmpRecents.clear();
732 for (int i = size() - 1; i >= start; --i) {
733 final TaskRecord task = get(i);
734 if (task.mAffiliatedTaskId == affiliateId) {
735 remove(i);
736 mTmpRecents.add(task);
737 }
738 }
739
740 // Sort them all by taskId. That is the order they were create in and that order will
741 // always be correct.
742 Collections.sort(mTmpRecents, sTaskRecordComparator);
743
744 // Go through and fix up the linked list.
745 // The first one is the end of the chain and has no next.
746 final TaskRecord first = mTmpRecents.get(0);
747 first.inRecents = true;
748 if (first.mNextAffiliate != null) {
749 Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
750 first.setNextAffiliate(null);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800751 notifyTaskPersisterLocked(first, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800752 }
753 // Everything in the middle is doubly linked from next to prev.
754 final int tmpSize = mTmpRecents.size();
755 for (int i = 0; i < tmpSize - 1; ++i) {
756 final TaskRecord next = mTmpRecents.get(i);
757 final TaskRecord prev = mTmpRecents.get(i + 1);
758 if (next.mPrevAffiliate != prev) {
759 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
760 " setting prev=" + prev);
761 next.setPrevAffiliate(prev);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800762 notifyTaskPersisterLocked(next, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800763 }
764 if (prev.mNextAffiliate != next) {
765 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
766 " setting next=" + next);
767 prev.setNextAffiliate(next);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800768 notifyTaskPersisterLocked(prev, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800769 }
770 prev.inRecents = true;
771 }
772 // The last one is the beginning of the list and has no prev.
773 final TaskRecord last = mTmpRecents.get(tmpSize - 1);
774 if (last.mPrevAffiliate != null) {
775 Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
776 last.setPrevAffiliate(null);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800777 notifyTaskPersisterLocked(last, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800778 }
779
780 // Insert the group back into mRecentTasks at start.
781 addAll(start, mTmpRecents);
782 mTmpRecents.clear();
783
784 // Let the caller know where we left off.
785 return start + tmpSize;
786 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800787}