blob: 7209814312af838a41a06c8bebc3d4ea0fd54e3e [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));
119 }
120 }
121
122 boolean taskIdTakenForUserLocked(int taskId, int userId) {
123 loadPersistedTaskIdsForUserLocked(userId);
124 return mPersistedTaskIds.get(userId).get(taskId);
125 }
126
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800127 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
128 if (task != null && task.stack != null && task.stack.isHomeStack()) {
129 // Never persist the home stack.
130 return;
131 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800132 syncPersistentTaskIdsLocked();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800133 mTaskPersister.wakeup(task, flush);
134 }
135
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800136 private void syncPersistentTaskIdsLocked() {
137 for (int i = mPersistedTaskIds.size() - 1; i >= 0; i--) {
138 int userId = mPersistedTaskIds.keyAt(i);
139 if (mUsersWithRecentsLoaded.get(userId)) {
140 // Recents are loaded only after task ids are loaded. Therefore, the set of taskids
141 // referenced here should not be null.
142 mPersistedTaskIds.valueAt(i).clear();
143 }
144 }
145 for (int i = size() - 1; i >= 0; i--) {
146 TaskRecord task = get(i);
147 if (task.isPersistable && (task.stack == null || !task.stack.isHomeStack())) {
148 // Set of persisted taskIds for task.userId should not be null here
149 mPersistedTaskIds.get(task.userId).put(task.taskId, true);
150 }
151 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800152 }
153
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800154
155 void onSystemReadyLocked() {
156 clear();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800157 mTaskPersister.startPersisting();
158 }
159
160 Bitmap getTaskDescriptionIcon(String path) {
161 return mTaskPersister.getTaskDescriptionIcon(path);
162 }
163
164 Bitmap getImageFromWriteQueue(String path) {
165 return mTaskPersister.getImageFromWriteQueue(path);
166 }
167
168 void saveImage(Bitmap image, String path) {
169 mTaskPersister.saveImage(image, path);
170 }
171
172 void flush() {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800173 synchronized (mService) {
174 syncPersistentTaskIdsLocked();
175 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800176 mTaskPersister.flush();
177 }
178
179 /**
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800180 * Returns all userIds for which recents from persistent storage are loaded into this list.
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800181 *
182 * @return an array of userIds.
183 */
184 int[] usersWithRecentsLoadedLocked() {
185 int[] usersWithRecentsLoaded = new int[mUsersWithRecentsLoaded.size()];
186 int len = 0;
187 for (int i = 0; i < usersWithRecentsLoaded.length; i++) {
188 int userId = mUsersWithRecentsLoaded.keyAt(i);
189 if (mUsersWithRecentsLoaded.valueAt(i)) {
190 usersWithRecentsLoaded[len++] = userId;
191 }
192 }
193 if (len < usersWithRecentsLoaded.length) {
194 // should never happen.
195 return Arrays.copyOf(usersWithRecentsLoaded, len);
196 }
197 return usersWithRecentsLoaded;
198 }
199
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800200 private void unloadUserRecentsLocked(int userId) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800201 if (mUsersWithRecentsLoaded.get(userId)) {
202 Slog.i(TAG, "Unloading recents for user " + userId + " from memory.");
203 mUsersWithRecentsLoaded.delete(userId);
204 removeTasksForUserLocked(userId);
205 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800206 }
207
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800208 /**
209 * Removes recent tasks and any other state kept in memory for the passed in user. Does not
210 * touch the information present on persistent storage.
211 *
212 * @param userId the id of the user
213 */
214 void unloadUserDataFromMemoryLocked(int userId) {
215 unloadUserRecentsLocked(userId);
216 mPersistedTaskIds.delete(userId);
217 mTaskPersister.unloadUserDataFromMemory(userId);
218 }
219
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800220 TaskRecord taskForIdLocked(int id) {
221 final int recentsCount = size();
222 for (int i = 0; i < recentsCount; i++) {
223 TaskRecord tr = get(i);
224 if (tr.taskId == id) {
225 return tr;
226 }
227 }
228 return null;
229 }
230
231 /** Remove recent tasks for a user. */
232 void removeTasksForUserLocked(int userId) {
233 if(userId <= 0) {
234 Slog.i(TAG, "Can't remove recent task on user " + userId);
235 return;
236 }
237
238 for (int i = size() - 1; i >= 0; --i) {
239 TaskRecord tr = get(i);
240 if (tr.userId == userId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700241 if(DEBUG_TASKS) Slog.i(TAG_TASKS,
242 "remove RecentTask " + tr + " when finishing user" + userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800243 remove(i);
244 tr.removedFromRecents();
245 }
246 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800247 }
248
Andrei Stingaceanu4ccec532016-01-13 12:10:21 +0000249 void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
250 final Set<String> packageNames = Sets.newHashSet(packages);
251 for (int i = size() - 1; i >= 0; --i) {
252 final TaskRecord tr = get(i);
253 if (tr.realActivity != null
254 && packageNames.contains(tr.realActivity.getPackageName())
255 && tr.userId == userId
256 && tr.realActivitySuspended != suspended) {
257 tr.realActivitySuspended = suspended;
258 notifyTaskPersisterLocked(tr, false);
259 }
260 }
261
262 }
263
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800264 /**
265 * Update the recent tasks lists: make sure tasks should still be here (their
266 * applications / activities still exist), update their availability, fix-up ordering
267 * of affiliations.
268 */
269 void cleanupLocked(int userId) {
270 int recentsCount = size();
271 if (recentsCount == 0) {
272 // Happens when called from the packagemanager broadcast before boot,
273 // or just any empty list.
274 return;
275 }
276
277 final IPackageManager pm = AppGlobals.getPackageManager();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800278 for (int i = recentsCount - 1; i >= 0; i--) {
279 final TaskRecord task = get(i);
280 if (userId != UserHandle.USER_ALL && task.userId != userId) {
281 // Only look at tasks for the user ID of interest.
282 continue;
283 }
284 if (task.autoRemoveRecents && task.getTopActivity() == null) {
285 // This situation is broken, and we should just get rid of it now.
286 remove(i);
287 task.removedFromRecents();
288 Slog.w(TAG, "Removing auto-remove without activity: " + task);
289 continue;
290 }
291 // Check whether this activity is currently available.
292 if (task.realActivity != null) {
293 ActivityInfo ai = mTmpAvailActCache.get(task.realActivity);
294 if (ai == null) {
295 try {
296 // At this first cut, we're only interested in
297 // activities that are fully runnable based on
298 // current system state.
299 ai = pm.getActivityInfo(task.realActivity,
300 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
301 } catch (RemoteException e) {
302 // Will never happen.
303 continue;
304 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800305 if (ai == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800306 ai = mTmpActivityInfo;
307 }
308 mTmpAvailActCache.put(task.realActivity, ai);
309 }
310 if (ai == mTmpActivityInfo) {
311 // This could be either because the activity no longer exists, or the
312 // app is temporarily gone. For the former we want to remove the recents
313 // entry; for the latter we want to mark it as unavailable.
314 ApplicationInfo app = mTmpAvailAppCache
315 .get(task.realActivity.getPackageName());
316 if (app == null) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800317 try {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800318 app = pm.getApplicationInfo(task.realActivity.getPackageName(),
319 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800320 } catch (RemoteException e) {
321 // Will never happen.
322 continue;
323 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800324 if (app == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800325 app = mTmpAppInfo;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800326 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800327 mTmpAvailAppCache.put(task.realActivity.getPackageName(), app);
328 }
329 if (app == mTmpAppInfo
330 || (app.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
331 // Doesn't exist any more! Good-bye.
332 remove(i);
333 task.removedFromRecents();
334 Slog.w(TAG, "Removing no longer valid recent: " + task);
335 continue;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800336 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800337 // Otherwise just not available for now.
338 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
339 "Making recent unavailable: " + task);
340 task.isAvailable = false;
341 }
342 } else {
343 if (!ai.enabled || !ai.applicationInfo.enabled
344 || (ai.applicationInfo.flags
345 & ApplicationInfo.FLAG_INSTALLED) == 0) {
346 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
347 "Making recent unavailable: " + task
348 + " (enabled=" + ai.enabled + "/"
349 + ai.applicationInfo.enabled
350 + " flags="
351 + Integer.toHexString(ai.applicationInfo.flags)
352 + ")");
353 task.isAvailable = false;
354 } else {
355 if (DEBUG_RECENTS && !task.isAvailable) Slog.d(TAG_RECENTS,
356 "Making recent available: " + task);
357 task.isAvailable = true;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800358 }
359 }
360 }
361 }
362
363 // Verify the affiliate chain for each task.
364 int i = 0;
365 recentsCount = size();
366 while (i < recentsCount) {
367 i = processNextAffiliateChainLocked(i);
368 }
369 // recent tasks are now in sorted, affiliated order.
370 }
371
372 private final boolean moveAffiliatedTasksToFront(TaskRecord task, int taskIndex) {
373 int recentsCount = size();
374 TaskRecord top = task;
375 int topIndex = taskIndex;
376 while (top.mNextAffiliate != null && topIndex > 0) {
377 top = top.mNextAffiliate;
378 topIndex--;
379 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700380 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding affilliates starting at "
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800381 + topIndex + " from intial " + taskIndex);
382 // Find the end of the chain, doing a sanity check along the way.
383 boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
384 int endIndex = topIndex;
385 TaskRecord prev = top;
386 while (endIndex < recentsCount) {
387 TaskRecord cur = get(endIndex);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700388 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: looking at next chain @"
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800389 + endIndex + " " + cur);
390 if (cur == top) {
391 // Verify start of the chain.
392 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != INVALID_TASK_ID) {
393 Slog.wtf(TAG, "Bad chain @" + endIndex
394 + ": first task has next affiliate: " + prev);
395 sane = false;
396 break;
397 }
398 } else {
399 // Verify middle of the chain's next points back to the one before.
400 if (cur.mNextAffiliate != prev
401 || cur.mNextAffiliateTaskId != prev.taskId) {
402 Slog.wtf(TAG, "Bad chain @" + endIndex
403 + ": middle task " + cur + " @" + endIndex
404 + " has bad next affiliate "
405 + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
406 + ", expected " + prev);
407 sane = false;
408 break;
409 }
410 }
411 if (cur.mPrevAffiliateTaskId == INVALID_TASK_ID) {
412 // Chain ends here.
413 if (cur.mPrevAffiliate != null) {
414 Slog.wtf(TAG, "Bad chain @" + endIndex
415 + ": last task " + cur + " has previous affiliate "
416 + cur.mPrevAffiliate);
417 sane = false;
418 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700419 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: end of chain @" + endIndex);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800420 break;
421 } else {
422 // Verify middle of the chain's prev points to a valid item.
423 if (cur.mPrevAffiliate == null) {
424 Slog.wtf(TAG, "Bad chain @" + endIndex
425 + ": task " + cur + " has previous affiliate "
426 + cur.mPrevAffiliate + " but should be id "
427 + cur.mPrevAffiliate);
428 sane = false;
429 break;
430 }
431 }
432 if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
433 Slog.wtf(TAG, "Bad chain @" + endIndex
434 + ": task " + cur + " has affiliated id "
435 + cur.mAffiliatedTaskId + " but should be "
436 + task.mAffiliatedTaskId);
437 sane = false;
438 break;
439 }
440 prev = cur;
441 endIndex++;
442 if (endIndex >= recentsCount) {
443 Slog.wtf(TAG, "Bad chain ran off index " + endIndex
444 + ": last task " + prev);
445 sane = false;
446 break;
447 }
448 }
449 if (sane) {
450 if (endIndex < taskIndex) {
451 Slog.wtf(TAG, "Bad chain @" + endIndex
452 + ": did not extend to task " + task + " @" + taskIndex);
453 sane = false;
454 }
455 }
456 if (sane) {
457 // All looks good, we can just move all of the affiliated tasks
458 // to the top.
459 for (int i=topIndex; i<=endIndex; i++) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700460 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving affiliated " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800461 + " from " + i + " to " + (i-topIndex));
462 TaskRecord cur = remove(i);
463 add(i - topIndex, cur);
464 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700465 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: done moving tasks " + topIndex
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800466 + " to " + endIndex);
467 return true;
468 }
469
470 // Whoops, couldn't do it.
471 return false;
472 }
473
474 final void addLocked(TaskRecord task) {
475 final boolean isAffiliated = task.mAffiliatedTaskId != task.taskId
476 || task.mNextAffiliateTaskId != INVALID_TASK_ID
477 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
478
479 int recentsCount = size();
480 // Quick case: never add voice sessions.
Amith Yamasani0af6fa72016-01-17 15:36:19 -0800481 // TODO: VI what about if it's just an activity?
482 // Probably nothing to do here
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800483 if (task.voiceSession != null) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700484 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
485 "addRecent: not adding voice interaction " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800486 return;
487 }
488 // Another quick case: check if the top-most recent task is the same.
489 if (!isAffiliated && recentsCount > 0 && get(0) == task) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700490 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: already at top: " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800491 return;
492 }
493 // Another quick case: check if this is part of a set of affiliated
494 // tasks that are at the top.
495 if (isAffiliated && recentsCount > 0 && task.inRecents
496 && task.mAffiliatedTaskId == get(0).mAffiliatedTaskId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700497 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: affiliated " + get(0)
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800498 + " at top when adding " + task);
499 return;
500 }
501
502 boolean needAffiliationFix = false;
503
504 // Slightly less quick case: the task is already in recents, so all we need
505 // to do is move it.
506 if (task.inRecents) {
507 int taskIndex = indexOf(task);
508 if (taskIndex >= 0) {
509 if (!isAffiliated) {
510 // Simple case: this is not an affiliated task, so we just move it to the front.
511 remove(taskIndex);
512 add(0, task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800513 notifyTaskPersisterLocked(task, false);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700514 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving to top " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800515 + " from " + taskIndex);
516 return;
517 } else {
518 // More complicated: need to keep all affiliated tasks together.
519 if (moveAffiliatedTasksToFront(task, taskIndex)) {
520 // All went well.
521 return;
522 }
523
524 // Uh oh... something bad in the affiliation chain, try to rebuild
525 // everything and then go through our general path of adding a new task.
526 needAffiliationFix = true;
527 }
528 } else {
529 Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
530 needAffiliationFix = true;
531 }
532 }
533
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700534 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: trimming tasks for " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800535 trimForTaskLocked(task, true);
536
537 recentsCount = size();
538 final int maxRecents = ActivityManager.getMaxRecentTasksStatic();
539 while (recentsCount >= maxRecents) {
540 final TaskRecord tr = remove(recentsCount - 1);
541 tr.removedFromRecents();
542 recentsCount--;
543 }
544 task.inRecents = true;
545 if (!isAffiliated || needAffiliationFix) {
546 // If this is a simple non-affiliated task, or we had some failure trying to
547 // handle it as part of an affilated task, then just place it at the top.
548 add(0, task);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700549 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800550 } else if (isAffiliated) {
551 // If this is a new affiliated task, then move all of the affiliated tasks
552 // to the front and insert this new one.
553 TaskRecord other = task.mNextAffiliate;
554 if (other == null) {
555 other = task.mPrevAffiliate;
556 }
557 if (other != null) {
558 int otherIndex = indexOf(other);
559 if (otherIndex >= 0) {
560 // Insert new task at appropriate location.
561 int taskIndex;
562 if (other == task.mNextAffiliate) {
563 // We found the index of our next affiliation, which is who is
564 // before us in the list, so add after that point.
565 taskIndex = otherIndex+1;
566 } else {
567 // We found the index of our previous affiliation, which is who is
568 // after us in the list, so add at their position.
569 taskIndex = otherIndex;
570 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700571 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
572 "addRecent: new affiliated task added at " + taskIndex + ": " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800573 add(taskIndex, task);
574
575 // Now move everything to the front.
576 if (moveAffiliatedTasksToFront(task, taskIndex)) {
577 // All went well.
578 return;
579 }
580
581 // Uh oh... something bad in the affiliation chain, try to rebuild
582 // everything and then go through our general path of adding a new task.
583 needAffiliationFix = true;
584 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700585 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
586 "addRecent: couldn't find other affiliation " + other);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800587 needAffiliationFix = true;
588 }
589 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700590 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800591 "addRecent: adding affiliated task without next/prev:" + task);
592 needAffiliationFix = true;
593 }
594 }
595
596 if (needAffiliationFix) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700597 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: regrouping affiliations");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800598 cleanupLocked(task.userId);
599 }
600 }
601
602 /**
603 * If needed, remove oldest existing entries in recents that are for the same kind
604 * of task as the given one.
605 */
606 int trimForTaskLocked(TaskRecord task, boolean doTrim) {
607 int recentsCount = size();
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700608 final Intent intent = task.intent;
609 final boolean document = intent != null && intent.isDocument();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800610 int maxRecents = task.maxRecents - 1;
611 for (int i = 0; i < recentsCount; i++) {
612 final TaskRecord tr = get(i);
613 if (task != tr) {
614 if (task.userId != tr.userId) {
615 continue;
616 }
617 if (i > MAX_RECENT_BITMAPS) {
618 tr.freeLastThumbnail();
619 }
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700620 final Intent trIntent = tr.intent;
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700621 final boolean sameAffinity =
622 task.affinity != null && task.affinity.equals(tr.affinity);
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700623 final boolean sameIntent = (intent != null && intent.filterEquals(trIntent));
624 final boolean trIsDocument = trIntent != null && trIntent.isDocument();
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700625 final boolean bothDocuments = document && trIsDocument;
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700626 if (!sameAffinity && !sameIntent && !bothDocuments) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800627 continue;
628 }
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700629
630 if (bothDocuments) {
631 // Do these documents belong to the same activity?
632 final boolean sameActivity = task.realActivity != null
633 && tr.realActivity != null
634 && task.realActivity.equals(tr.realActivity);
Robert Carr7cb57e12015-11-10 13:44:02 -0800635 // If the document is open in another app or is not the same
636 // document, we don't need to trim it.
637 if (!sameActivity || !sameIntent) {
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700638 continue;
Robert Carr7cb57e12015-11-10 13:44:02 -0800639 // Otherwise only trim if we are over our max recents for this task
640 } else if (maxRecents > 0 && !doTrim) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800641 --maxRecents;
642 continue;
643 }
644 // Hit the maximum number of documents for this task. Fall through
645 // and remove this document from recents.
646 } else if (document || trIsDocument) {
647 // Only one of these is a document. Not the droid we're looking for.
648 continue;
649 }
650 }
651
652 if (!doTrim) {
653 // If the caller is not actually asking for a trim, just tell them we reached
654 // a point where the trim would happen.
655 return i;
656 }
657
658 // Either task and tr are the same or, their affinities match or their intents match
659 // and neither of them is a document, or they are documents using the same activity
660 // and their maxRecents has been reached.
661 tr.disposeThumbnail();
662 remove(i);
663 if (task != tr) {
664 tr.removedFromRecents();
665 }
666 i--;
667 recentsCount--;
668 if (task.intent == null) {
669 // If the new recent task we are adding is not fully
670 // specified, then replace it with the existing recent task.
671 task = tr;
672 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800673 notifyTaskPersisterLocked(tr, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800674 }
675
676 return -1;
677 }
678
679 // Sort by taskId
680 private static Comparator<TaskRecord> sTaskRecordComparator = new Comparator<TaskRecord>() {
681 @Override
682 public int compare(TaskRecord lhs, TaskRecord rhs) {
683 return rhs.taskId - lhs.taskId;
684 }
685 };
686
687 // Extract the affiliates of the chain containing recent at index start.
688 private int processNextAffiliateChainLocked(int start) {
689 final TaskRecord startTask = get(start);
690 final int affiliateId = startTask.mAffiliatedTaskId;
691
692 // Quick identification of isolated tasks. I.e. those not launched behind.
693 if (startTask.taskId == affiliateId && startTask.mPrevAffiliate == null &&
694 startTask.mNextAffiliate == null) {
695 // There is still a slim chance that there are other tasks that point to this task
696 // and that the chain is so messed up that this task no longer points to them but
697 // the gain of this optimization outweighs the risk.
698 startTask.inRecents = true;
699 return start + 1;
700 }
701
702 // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
703 mTmpRecents.clear();
704 for (int i = size() - 1; i >= start; --i) {
705 final TaskRecord task = get(i);
706 if (task.mAffiliatedTaskId == affiliateId) {
707 remove(i);
708 mTmpRecents.add(task);
709 }
710 }
711
712 // Sort them all by taskId. That is the order they were create in and that order will
713 // always be correct.
714 Collections.sort(mTmpRecents, sTaskRecordComparator);
715
716 // Go through and fix up the linked list.
717 // The first one is the end of the chain and has no next.
718 final TaskRecord first = mTmpRecents.get(0);
719 first.inRecents = true;
720 if (first.mNextAffiliate != null) {
721 Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
722 first.setNextAffiliate(null);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800723 notifyTaskPersisterLocked(first, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800724 }
725 // Everything in the middle is doubly linked from next to prev.
726 final int tmpSize = mTmpRecents.size();
727 for (int i = 0; i < tmpSize - 1; ++i) {
728 final TaskRecord next = mTmpRecents.get(i);
729 final TaskRecord prev = mTmpRecents.get(i + 1);
730 if (next.mPrevAffiliate != prev) {
731 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
732 " setting prev=" + prev);
733 next.setPrevAffiliate(prev);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800734 notifyTaskPersisterLocked(next, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800735 }
736 if (prev.mNextAffiliate != next) {
737 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
738 " setting next=" + next);
739 prev.setNextAffiliate(next);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800740 notifyTaskPersisterLocked(prev, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800741 }
742 prev.inRecents = true;
743 }
744 // The last one is the beginning of the list and has no prev.
745 final TaskRecord last = mTmpRecents.get(tmpSize - 1);
746 if (last.mPrevAffiliate != null) {
747 Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
748 last.setPrevAffiliate(null);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800749 notifyTaskPersisterLocked(last, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800750 }
751
752 // Insert the group back into mRecentTasks at start.
753 addAll(start, mTmpRecents);
754 mTmpRecents.clear();
755
756 // Let the caller know where we left off.
757 return start + tmpSize;
758 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800759}