blob: 91f2aa8fe4f943288a509fc5b16ed8aabbfc2505 [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
Suprabh Shukla09a88f52015-12-02 14:36:31 -080019import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
20import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
21import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
22import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
23import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
24import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Wale Ogunwalee23149f2015-03-06 15:39:44 -080025import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
26
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +000027import com.google.android.collect.Sets;
28
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080029import android.app.ActivityManager;
30import android.app.AppGlobals;
31import android.content.ComponentName;
32import android.content.Intent;
33import android.content.pm.ActivityInfo;
34import android.content.pm.ApplicationInfo;
35import android.content.pm.IPackageManager;
36import android.content.pm.PackageManager;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080037import android.graphics.Bitmap;
38import android.os.Environment;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080039import android.os.RemoteException;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080040import android.os.SystemClock;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080041import android.os.UserHandle;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080042import android.provider.Settings.System;
43import android.util.ArraySet;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080044import 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
Suprabh Shukla09a88f52015-12-02 14:36:31 -080068 /**
69 * Save recent tasks information across reboots.
70 */
71 private final TaskPersister mTaskPersister;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080072 private final ActivityManagerService mService;
73 private final SparseBooleanArray mUsersWithRecentsLoaded = new SparseBooleanArray(
74 DEFAULT_INITIAL_CAPACITY);
75
76 /**
77 * Stores for each user task ids that are taken by tasks residing in persistent storage. These
78 * tasks may or may not currently be in memory.
79 */
80 final SparseArray<SparseBooleanArray> mPersistedTaskIds = new SparseArray<>(
81 DEFAULT_INITIAL_CAPACITY);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080082
83 // Mainly to avoid object recreation on multiple calls.
84 private final ArrayList<TaskRecord> mTmpRecents = new ArrayList<TaskRecord>();
Suprabh Shukla09a88f52015-12-02 14:36:31 -080085 private final HashMap<ComponentName, ActivityInfo> mTmpAvailActCache = new HashMap<>();
86 private final HashMap<String, ApplicationInfo> mTmpAvailAppCache = new HashMap<>();
87 private final ActivityInfo mTmpActivityInfo = new ActivityInfo();
88 private final ApplicationInfo mTmpAppInfo = new ApplicationInfo();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080089
Suprabh Shukla09a88f52015-12-02 14:36:31 -080090 RecentTasks(ActivityManagerService service, ActivityStackSupervisor mStackSupervisor) {
91 File systemDir = Environment.getDataSystemDirectory();
Suprabh Shukla4bccb462016-02-10 18:45:12 -080092 mService = service;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080093 mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, service, this);
94 mStackSupervisor.setRecentTasks(this);
95 }
96
97 /**
Suprabh Shuklaf5bf0cb2016-01-19 17:42:03 -080098 * Loads the persistent recentTasks for {@code userId} into this list from persistent storage.
99 * Does nothing if they are already loaded.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800100 *
101 * @param userId the user Id
102 */
103 void loadUserRecentsLocked(int userId) {
104 if (!mUsersWithRecentsLoaded.get(userId)) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800105 // Load the task ids if not loaded.
106 loadPersistedTaskIdsForUserLocked(userId);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800107 Slog.i(TAG, "Loading recents for user " + userId + " into memory.");
108 addAll(mTaskPersister.restoreTasksForUserLocked(userId));
109 cleanupLocked(userId);
110 mUsersWithRecentsLoaded.put(userId, true);
111 }
112 }
113
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800114 private void loadPersistedTaskIdsForUserLocked(int userId) {
115 // An empty instead of a null set here means that no persistent taskIds were present
116 // on file when we loaded them.
117 if (mPersistedTaskIds.get(userId) == null) {
118 mPersistedTaskIds.put(userId, mTaskPersister.loadPersistedTaskIdsForUser(userId));
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700119 Slog.i(TAG, "Loaded persisted task ids for user " + userId);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800120 }
121 }
122
123 boolean taskIdTakenForUserLocked(int taskId, int userId) {
124 loadPersistedTaskIdsForUserLocked(userId);
125 return mPersistedTaskIds.get(userId).get(taskId);
126 }
127
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800128 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
129 if (task != null && task.stack != null && task.stack.isHomeStack()) {
130 // Never persist the home stack.
131 return;
132 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800133 syncPersistentTaskIdsLocked();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800134 mTaskPersister.wakeup(task, flush);
135 }
136
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800137 private void syncPersistentTaskIdsLocked() {
138 for (int i = mPersistedTaskIds.size() - 1; i >= 0; i--) {
139 int userId = mPersistedTaskIds.keyAt(i);
140 if (mUsersWithRecentsLoaded.get(userId)) {
141 // Recents are loaded only after task ids are loaded. Therefore, the set of taskids
142 // referenced here should not be null.
143 mPersistedTaskIds.valueAt(i).clear();
144 }
145 }
146 for (int i = size() - 1; i >= 0; i--) {
147 TaskRecord task = get(i);
148 if (task.isPersistable && (task.stack == null || !task.stack.isHomeStack())) {
149 // Set of persisted taskIds for task.userId should not be null here
Fyodor Kupolovc4b46dd2016-03-17 12:57:36 -0700150 // TODO Investigate why it can happen. For now initialize with an empty set
151 if (mPersistedTaskIds.get(task.userId) == null) {
152 Slog.wtf(TAG, "No task ids found for userId " + task.userId + ". task=" + task
153 + " mPersistedTaskIds=" + mPersistedTaskIds);
154 mPersistedTaskIds.put(task.userId, new SparseBooleanArray());
155 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800156 mPersistedTaskIds.get(task.userId).put(task.taskId, true);
157 }
158 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800159 }
160
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800161
162 void onSystemReadyLocked() {
163 clear();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800164 mTaskPersister.startPersisting();
165 }
166
167 Bitmap getTaskDescriptionIcon(String path) {
168 return mTaskPersister.getTaskDescriptionIcon(path);
169 }
170
171 Bitmap getImageFromWriteQueue(String path) {
172 return mTaskPersister.getImageFromWriteQueue(path);
173 }
174
175 void saveImage(Bitmap image, String path) {
176 mTaskPersister.saveImage(image, path);
177 }
178
179 void flush() {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800180 synchronized (mService) {
181 syncPersistentTaskIdsLocked();
182 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800183 mTaskPersister.flush();
184 }
185
186 /**
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800187 * Returns all userIds for which recents from persistent storage are loaded into this list.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800188 *
189 * @return an array of userIds.
190 */
191 int[] usersWithRecentsLoadedLocked() {
192 int[] usersWithRecentsLoaded = new int[mUsersWithRecentsLoaded.size()];
193 int len = 0;
194 for (int i = 0; i < usersWithRecentsLoaded.length; i++) {
195 int userId = mUsersWithRecentsLoaded.keyAt(i);
196 if (mUsersWithRecentsLoaded.valueAt(i)) {
197 usersWithRecentsLoaded[len++] = userId;
198 }
199 }
200 if (len < usersWithRecentsLoaded.length) {
201 // should never happen.
202 return Arrays.copyOf(usersWithRecentsLoaded, len);
203 }
204 return usersWithRecentsLoaded;
205 }
206
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800207 private void unloadUserRecentsLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800208 if (mUsersWithRecentsLoaded.get(userId)) {
209 Slog.i(TAG, "Unloading recents for user " + userId + " from memory.");
210 mUsersWithRecentsLoaded.delete(userId);
211 removeTasksForUserLocked(userId);
212 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800213 }
214
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800215 /**
216 * Removes recent tasks and any other state kept in memory for the passed in user. Does not
217 * touch the information present on persistent storage.
218 *
219 * @param userId the id of the user
220 */
221 void unloadUserDataFromMemoryLocked(int userId) {
222 unloadUserRecentsLocked(userId);
223 mPersistedTaskIds.delete(userId);
224 mTaskPersister.unloadUserDataFromMemory(userId);
225 }
226
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800227 TaskRecord taskForIdLocked(int id) {
228 final int recentsCount = size();
229 for (int i = 0; i < recentsCount; i++) {
230 TaskRecord tr = get(i);
231 if (tr.taskId == id) {
232 return tr;
233 }
234 }
235 return null;
236 }
237
238 /** Remove recent tasks for a user. */
239 void removeTasksForUserLocked(int userId) {
240 if(userId <= 0) {
241 Slog.i(TAG, "Can't remove recent task on user " + userId);
242 return;
243 }
244
245 for (int i = size() - 1; i >= 0; --i) {
246 TaskRecord tr = get(i);
247 if (tr.userId == userId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700248 if(DEBUG_TASKS) Slog.i(TAG_TASKS,
249 "remove RecentTask " + tr + " when finishing user" + userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800250 remove(i);
251 tr.removedFromRecents();
252 }
253 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800254 }
255
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000256 void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
257 final Set<String> packageNames = Sets.newHashSet(packages);
258 for (int i = size() - 1; i >= 0; --i) {
259 final TaskRecord tr = get(i);
260 if (tr.realActivity != null
261 && packageNames.contains(tr.realActivity.getPackageName())
262 && tr.userId == userId
263 && tr.realActivitySuspended != suspended) {
264 tr.realActivitySuspended = suspended;
265 notifyTaskPersisterLocked(tr, false);
266 }
267 }
268
269 }
270
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800271 /**
272 * Update the recent tasks lists: make sure tasks should still be here (their
273 * applications / activities still exist), update their availability, fix-up ordering
274 * of affiliations.
275 */
276 void cleanupLocked(int userId) {
277 int recentsCount = size();
278 if (recentsCount == 0) {
279 // Happens when called from the packagemanager broadcast before boot,
280 // or just any empty list.
281 return;
282 }
283
284 final IPackageManager pm = AppGlobals.getPackageManager();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800285 for (int i = recentsCount - 1; i >= 0; i--) {
286 final TaskRecord task = get(i);
287 if (userId != UserHandle.USER_ALL && task.userId != userId) {
288 // Only look at tasks for the user ID of interest.
289 continue;
290 }
291 if (task.autoRemoveRecents && task.getTopActivity() == null) {
292 // This situation is broken, and we should just get rid of it now.
293 remove(i);
294 task.removedFromRecents();
295 Slog.w(TAG, "Removing auto-remove without activity: " + task);
296 continue;
297 }
298 // Check whether this activity is currently available.
299 if (task.realActivity != null) {
300 ActivityInfo ai = mTmpAvailActCache.get(task.realActivity);
301 if (ai == null) {
302 try {
303 // At this first cut, we're only interested in
304 // activities that are fully runnable based on
305 // current system state.
306 ai = pm.getActivityInfo(task.realActivity,
307 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
308 } catch (RemoteException e) {
309 // Will never happen.
310 continue;
311 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800312 if (ai == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800313 ai = mTmpActivityInfo;
314 }
315 mTmpAvailActCache.put(task.realActivity, ai);
316 }
317 if (ai == mTmpActivityInfo) {
318 // This could be either because the activity no longer exists, or the
319 // app is temporarily gone. For the former we want to remove the recents
320 // entry; for the latter we want to mark it as unavailable.
321 ApplicationInfo app = mTmpAvailAppCache
322 .get(task.realActivity.getPackageName());
323 if (app == null) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800324 try {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800325 app = pm.getApplicationInfo(task.realActivity.getPackageName(),
326 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800327 } catch (RemoteException e) {
328 // Will never happen.
329 continue;
330 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800331 if (app == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800332 app = mTmpAppInfo;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800333 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800334 mTmpAvailAppCache.put(task.realActivity.getPackageName(), app);
335 }
336 if (app == mTmpAppInfo
337 || (app.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
338 // Doesn't exist any more! Good-bye.
339 remove(i);
340 task.removedFromRecents();
341 Slog.w(TAG, "Removing no longer valid recent: " + task);
342 continue;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800343 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800344 // Otherwise just not available for now.
345 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
346 "Making recent unavailable: " + task);
347 task.isAvailable = false;
348 }
349 } else {
350 if (!ai.enabled || !ai.applicationInfo.enabled
351 || (ai.applicationInfo.flags
352 & ApplicationInfo.FLAG_INSTALLED) == 0) {
353 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
354 "Making recent unavailable: " + task
355 + " (enabled=" + ai.enabled + "/"
356 + ai.applicationInfo.enabled
357 + " flags="
358 + Integer.toHexString(ai.applicationInfo.flags)
359 + ")");
360 task.isAvailable = false;
361 } else {
362 if (DEBUG_RECENTS && !task.isAvailable) Slog.d(TAG_RECENTS,
363 "Making recent available: " + task);
364 task.isAvailable = true;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800365 }
366 }
367 }
368 }
369
370 // Verify the affiliate chain for each task.
371 int i = 0;
372 recentsCount = size();
373 while (i < recentsCount) {
374 i = processNextAffiliateChainLocked(i);
375 }
376 // recent tasks are now in sorted, affiliated order.
377 }
378
379 private final boolean moveAffiliatedTasksToFront(TaskRecord task, int taskIndex) {
380 int recentsCount = size();
381 TaskRecord top = task;
382 int topIndex = taskIndex;
383 while (top.mNextAffiliate != null && topIndex > 0) {
384 top = top.mNextAffiliate;
385 topIndex--;
386 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700387 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding affilliates starting at "
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800388 + topIndex + " from intial " + taskIndex);
389 // Find the end of the chain, doing a sanity check along the way.
390 boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
391 int endIndex = topIndex;
392 TaskRecord prev = top;
393 while (endIndex < recentsCount) {
394 TaskRecord cur = get(endIndex);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700395 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: looking at next chain @"
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800396 + endIndex + " " + cur);
397 if (cur == top) {
398 // Verify start of the chain.
399 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != INVALID_TASK_ID) {
400 Slog.wtf(TAG, "Bad chain @" + endIndex
401 + ": first task has next affiliate: " + prev);
402 sane = false;
403 break;
404 }
405 } else {
406 // Verify middle of the chain's next points back to the one before.
407 if (cur.mNextAffiliate != prev
408 || cur.mNextAffiliateTaskId != prev.taskId) {
409 Slog.wtf(TAG, "Bad chain @" + endIndex
410 + ": middle task " + cur + " @" + endIndex
411 + " has bad next affiliate "
412 + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
413 + ", expected " + prev);
414 sane = false;
415 break;
416 }
417 }
418 if (cur.mPrevAffiliateTaskId == INVALID_TASK_ID) {
419 // Chain ends here.
420 if (cur.mPrevAffiliate != null) {
421 Slog.wtf(TAG, "Bad chain @" + endIndex
422 + ": last task " + cur + " has previous affiliate "
423 + cur.mPrevAffiliate);
424 sane = false;
425 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700426 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: end of chain @" + endIndex);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800427 break;
428 } else {
429 // Verify middle of the chain's prev points to a valid item.
430 if (cur.mPrevAffiliate == null) {
431 Slog.wtf(TAG, "Bad chain @" + endIndex
432 + ": task " + cur + " has previous affiliate "
433 + cur.mPrevAffiliate + " but should be id "
434 + cur.mPrevAffiliate);
435 sane = false;
436 break;
437 }
438 }
439 if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
440 Slog.wtf(TAG, "Bad chain @" + endIndex
441 + ": task " + cur + " has affiliated id "
442 + cur.mAffiliatedTaskId + " but should be "
443 + task.mAffiliatedTaskId);
444 sane = false;
445 break;
446 }
447 prev = cur;
448 endIndex++;
449 if (endIndex >= recentsCount) {
450 Slog.wtf(TAG, "Bad chain ran off index " + endIndex
451 + ": last task " + prev);
452 sane = false;
453 break;
454 }
455 }
456 if (sane) {
457 if (endIndex < taskIndex) {
458 Slog.wtf(TAG, "Bad chain @" + endIndex
459 + ": did not extend to task " + task + " @" + taskIndex);
460 sane = false;
461 }
462 }
463 if (sane) {
464 // All looks good, we can just move all of the affiliated tasks
465 // to the top.
466 for (int i=topIndex; i<=endIndex; i++) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700467 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving affiliated " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800468 + " from " + i + " to " + (i-topIndex));
469 TaskRecord cur = remove(i);
470 add(i - topIndex, cur);
471 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700472 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: done moving tasks " + topIndex
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800473 + " to " + endIndex);
474 return true;
475 }
476
477 // Whoops, couldn't do it.
478 return false;
479 }
480
481 final void addLocked(TaskRecord task) {
482 final boolean isAffiliated = task.mAffiliatedTaskId != task.taskId
483 || task.mNextAffiliateTaskId != INVALID_TASK_ID
484 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
485
486 int recentsCount = size();
487 // Quick case: never add voice sessions.
Amith Yamasani0af6fa72016-01-17 15:36:19 -0800488 // TODO: VI what about if it's just an activity?
489 // Probably nothing to do here
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800490 if (task.voiceSession != null) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700491 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
492 "addRecent: not adding voice interaction " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800493 return;
494 }
495 // Another quick case: check if the top-most recent task is the same.
496 if (!isAffiliated && recentsCount > 0 && get(0) == task) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700497 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: already at top: " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800498 return;
499 }
500 // Another quick case: check if this is part of a set of affiliated
501 // tasks that are at the top.
502 if (isAffiliated && recentsCount > 0 && task.inRecents
503 && task.mAffiliatedTaskId == get(0).mAffiliatedTaskId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700504 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: affiliated " + get(0)
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800505 + " at top when adding " + task);
506 return;
507 }
508
509 boolean needAffiliationFix = false;
510
511 // Slightly less quick case: the task is already in recents, so all we need
512 // to do is move it.
513 if (task.inRecents) {
514 int taskIndex = indexOf(task);
515 if (taskIndex >= 0) {
516 if (!isAffiliated) {
517 // Simple case: this is not an affiliated task, so we just move it to the front.
518 remove(taskIndex);
519 add(0, task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800520 notifyTaskPersisterLocked(task, false);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700521 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving to top " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800522 + " from " + taskIndex);
523 return;
524 } else {
525 // More complicated: need to keep all affiliated tasks together.
526 if (moveAffiliatedTasksToFront(task, taskIndex)) {
527 // All went well.
528 return;
529 }
530
531 // Uh oh... something bad in the affiliation chain, try to rebuild
532 // everything and then go through our general path of adding a new task.
533 needAffiliationFix = true;
534 }
535 } else {
536 Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
537 needAffiliationFix = true;
538 }
539 }
540
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700541 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: trimming tasks for " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800542 trimForTaskLocked(task, true);
543
544 recentsCount = size();
545 final int maxRecents = ActivityManager.getMaxRecentTasksStatic();
546 while (recentsCount >= maxRecents) {
547 final TaskRecord tr = remove(recentsCount - 1);
548 tr.removedFromRecents();
549 recentsCount--;
550 }
551 task.inRecents = true;
552 if (!isAffiliated || needAffiliationFix) {
553 // If this is a simple non-affiliated task, or we had some failure trying to
554 // handle it as part of an affilated task, then just place it at the top.
555 add(0, task);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700556 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800557 } else if (isAffiliated) {
558 // If this is a new affiliated task, then move all of the affiliated tasks
559 // to the front and insert this new one.
560 TaskRecord other = task.mNextAffiliate;
561 if (other == null) {
562 other = task.mPrevAffiliate;
563 }
564 if (other != null) {
565 int otherIndex = indexOf(other);
566 if (otherIndex >= 0) {
567 // Insert new task at appropriate location.
568 int taskIndex;
569 if (other == task.mNextAffiliate) {
570 // We found the index of our next affiliation, which is who is
571 // before us in the list, so add after that point.
572 taskIndex = otherIndex+1;
573 } else {
574 // We found the index of our previous affiliation, which is who is
575 // after us in the list, so add at their position.
576 taskIndex = otherIndex;
577 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700578 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
579 "addRecent: new affiliated task added at " + taskIndex + ": " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800580 add(taskIndex, task);
581
582 // Now move everything to the front.
583 if (moveAffiliatedTasksToFront(task, taskIndex)) {
584 // All went well.
585 return;
586 }
587
588 // Uh oh... something bad in the affiliation chain, try to rebuild
589 // everything and then go through our general path of adding a new task.
590 needAffiliationFix = true;
591 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700592 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
593 "addRecent: couldn't find other affiliation " + other);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800594 needAffiliationFix = true;
595 }
596 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700597 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800598 "addRecent: adding affiliated task without next/prev:" + task);
599 needAffiliationFix = true;
600 }
601 }
602
603 if (needAffiliationFix) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700604 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: regrouping affiliations");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800605 cleanupLocked(task.userId);
606 }
607 }
608
609 /**
610 * If needed, remove oldest existing entries in recents that are for the same kind
611 * of task as the given one.
612 */
613 int trimForTaskLocked(TaskRecord task, boolean doTrim) {
614 int recentsCount = size();
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700615 final Intent intent = task.intent;
616 final boolean document = intent != null && intent.isDocument();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800617 int maxRecents = task.maxRecents - 1;
618 for (int i = 0; i < recentsCount; i++) {
619 final TaskRecord tr = get(i);
620 if (task != tr) {
621 if (task.userId != tr.userId) {
622 continue;
623 }
624 if (i > MAX_RECENT_BITMAPS) {
625 tr.freeLastThumbnail();
626 }
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700627 final Intent trIntent = tr.intent;
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700628 final boolean sameAffinity =
629 task.affinity != null && task.affinity.equals(tr.affinity);
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700630 final boolean sameIntent = (intent != null && intent.filterEquals(trIntent));
631 final boolean trIsDocument = trIntent != null && trIntent.isDocument();
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700632 final boolean bothDocuments = document && trIsDocument;
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700633 if (!sameAffinity && !sameIntent && !bothDocuments) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800634 continue;
635 }
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700636
637 if (bothDocuments) {
638 // Do these documents belong to the same activity?
639 final boolean sameActivity = task.realActivity != null
640 && tr.realActivity != null
641 && task.realActivity.equals(tr.realActivity);
Robert Carr7cb57e12015-11-10 13:44:02 -0800642 // If the document is open in another app or is not the same
643 // document, we don't need to trim it.
644 if (!sameActivity || !sameIntent) {
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700645 continue;
Robert Carr7cb57e12015-11-10 13:44:02 -0800646 // Otherwise only trim if we are over our max recents for this task
647 } else if (maxRecents > 0 && !doTrim) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800648 --maxRecents;
649 continue;
650 }
651 // Hit the maximum number of documents for this task. Fall through
652 // and remove this document from recents.
653 } else if (document || trIsDocument) {
654 // Only one of these is a document. Not the droid we're looking for.
655 continue;
656 }
657 }
658
659 if (!doTrim) {
660 // If the caller is not actually asking for a trim, just tell them we reached
661 // a point where the trim would happen.
662 return i;
663 }
664
665 // Either task and tr are the same or, their affinities match or their intents match
666 // and neither of them is a document, or they are documents using the same activity
667 // and their maxRecents has been reached.
668 tr.disposeThumbnail();
669 remove(i);
670 if (task != tr) {
671 tr.removedFromRecents();
672 }
673 i--;
674 recentsCount--;
675 if (task.intent == null) {
676 // If the new recent task we are adding is not fully
677 // specified, then replace it with the existing recent task.
678 task = tr;
679 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800680 notifyTaskPersisterLocked(tr, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800681 }
682
683 return -1;
684 }
685
686 // Sort by taskId
687 private static Comparator<TaskRecord> sTaskRecordComparator = new Comparator<TaskRecord>() {
688 @Override
689 public int compare(TaskRecord lhs, TaskRecord rhs) {
690 return rhs.taskId - lhs.taskId;
691 }
692 };
693
694 // Extract the affiliates of the chain containing recent at index start.
695 private int processNextAffiliateChainLocked(int start) {
696 final TaskRecord startTask = get(start);
697 final int affiliateId = startTask.mAffiliatedTaskId;
698
699 // Quick identification of isolated tasks. I.e. those not launched behind.
700 if (startTask.taskId == affiliateId && startTask.mPrevAffiliate == null &&
701 startTask.mNextAffiliate == null) {
702 // There is still a slim chance that there are other tasks that point to this task
703 // and that the chain is so messed up that this task no longer points to them but
704 // the gain of this optimization outweighs the risk.
705 startTask.inRecents = true;
706 return start + 1;
707 }
708
709 // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
710 mTmpRecents.clear();
711 for (int i = size() - 1; i >= start; --i) {
712 final TaskRecord task = get(i);
713 if (task.mAffiliatedTaskId == affiliateId) {
714 remove(i);
715 mTmpRecents.add(task);
716 }
717 }
718
719 // Sort them all by taskId. That is the order they were create in and that order will
720 // always be correct.
721 Collections.sort(mTmpRecents, sTaskRecordComparator);
722
723 // Go through and fix up the linked list.
724 // The first one is the end of the chain and has no next.
725 final TaskRecord first = mTmpRecents.get(0);
726 first.inRecents = true;
727 if (first.mNextAffiliate != null) {
728 Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
729 first.setNextAffiliate(null);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800730 notifyTaskPersisterLocked(first, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800731 }
732 // Everything in the middle is doubly linked from next to prev.
733 final int tmpSize = mTmpRecents.size();
734 for (int i = 0; i < tmpSize - 1; ++i) {
735 final TaskRecord next = mTmpRecents.get(i);
736 final TaskRecord prev = mTmpRecents.get(i + 1);
737 if (next.mPrevAffiliate != prev) {
738 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
739 " setting prev=" + prev);
740 next.setPrevAffiliate(prev);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800741 notifyTaskPersisterLocked(next, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800742 }
743 if (prev.mNextAffiliate != next) {
744 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
745 " setting next=" + next);
746 prev.setNextAffiliate(next);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800747 notifyTaskPersisterLocked(prev, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800748 }
749 prev.inRecents = true;
750 }
751 // The last one is the beginning of the list and has no prev.
752 final TaskRecord last = mTmpRecents.get(tmpSize - 1);
753 if (last.mPrevAffiliate != null) {
754 Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
755 last.setPrevAffiliate(null);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800756 notifyTaskPersisterLocked(last, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800757 }
758
759 // Insert the group back into mRecentTasks at start.
760 addAll(start, mTmpRecents);
761 mTmpRecents.clear();
762
763 // Let the caller know where we left off.
764 return start + tmpSize;
765 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800766}