blob: 04912d0a31c6c7440e52803ad40b35b7ae925a0e [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 Ogunwalee23149f2015-03-06 15:39:44 -080019import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
20import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
21import static com.android.server.am.ActivityManagerService.DEBUG_RECENTS;
22import static com.android.server.am.ActivityManagerService.DEBUG_TASKS;
23import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
24
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080025import android.app.ActivityManager;
26import android.app.AppGlobals;
27import android.content.ComponentName;
28import android.content.Intent;
29import android.content.pm.ActivityInfo;
30import android.content.pm.ApplicationInfo;
31import android.content.pm.IPackageManager;
32import android.content.pm.PackageManager;
33import android.os.RemoteException;
34import android.os.UserHandle;
35import android.util.Slog;
36
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080037import java.util.ArrayList;
38import java.util.Collections;
39import java.util.Comparator;
40import java.util.HashMap;
41
42/**
43 * Class for managing the recent tasks list.
44 */
45class RecentTasks extends ArrayList<TaskRecord> {
Wale Ogunwalee23149f2015-03-06 15:39:44 -080046 private static final String TAG = TAG_WITH_CLASS_NAME ? "RecentTasks" : TAG_AM;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080047
48 // Maximum number recent bitmaps to keep in memory.
49 private static final int MAX_RECENT_BITMAPS = 3;
50
51 // Activity manager service.
52 private final ActivityManagerService mService;
53
54 // Mainly to avoid object recreation on multiple calls.
55 private final ArrayList<TaskRecord> mTmpRecents = new ArrayList<TaskRecord>();
56 private final HashMap<ComponentName, ActivityInfo> tmpAvailActCache = new HashMap<>();
57 private final HashMap<String, ApplicationInfo> tmpAvailAppCache = new HashMap<>();
58 private final ActivityInfo tmpActivityInfo = new ActivityInfo();
59 private final ApplicationInfo tmpAppInfo = new ApplicationInfo();
60
61 RecentTasks(ActivityManagerService service) {
62 mService = service;
63 }
64
65 TaskRecord taskForIdLocked(int id) {
66 final int recentsCount = size();
67 for (int i = 0; i < recentsCount; i++) {
68 TaskRecord tr = get(i);
69 if (tr.taskId == id) {
70 return tr;
71 }
72 }
73 return null;
74 }
75
76 /** Remove recent tasks for a user. */
77 void removeTasksForUserLocked(int userId) {
78 if(userId <= 0) {
79 Slog.i(TAG, "Can't remove recent task on user " + userId);
80 return;
81 }
82
83 for (int i = size() - 1; i >= 0; --i) {
84 TaskRecord tr = get(i);
85 if (tr.userId == userId) {
86 if(DEBUG_TASKS) Slog.i(TAG, "remove RecentTask " + tr
87 + " when finishing user" + userId);
88 remove(i);
89 tr.removedFromRecents();
90 }
91 }
92
93 // Remove tasks from persistent storage.
94 mService.notifyTaskPersisterLocked(null, true);
95 }
96
97 /**
98 * Update the recent tasks lists: make sure tasks should still be here (their
99 * applications / activities still exist), update their availability, fix-up ordering
100 * of affiliations.
101 */
102 void cleanupLocked(int userId) {
103 int recentsCount = size();
104 if (recentsCount == 0) {
105 // Happens when called from the packagemanager broadcast before boot,
106 // or just any empty list.
107 return;
108 }
109
110 final IPackageManager pm = AppGlobals.getPackageManager();
111 final int[] users = (userId == UserHandle.USER_ALL)
112 ? mService.getUsersLocked() : new int[] { userId };
113 for (int userIdx = 0; userIdx < users.length; userIdx++) {
114 final int user = users[userIdx];
115 recentsCount = size() - 1;
116 for (int i = recentsCount; i >= 0; i--) {
117 TaskRecord task = get(i);
118 if (task.userId != user) {
119 // Only look at tasks for the user ID of interest.
120 continue;
121 }
122 if (task.autoRemoveRecents && task.getTopActivity() == null) {
123 // This situation is broken, and we should just get rid of it now.
124 remove(i);
125 task.removedFromRecents();
126 Slog.w(TAG, "Removing auto-remove without activity: " + task);
127 continue;
128 }
129 // Check whether this activity is currently available.
130 if (task.realActivity != null) {
131 ActivityInfo ai = tmpAvailActCache.get(task.realActivity);
132 if (ai == null) {
133 try {
134 ai = pm.getActivityInfo(task.realActivity,
135 PackageManager.GET_UNINSTALLED_PACKAGES
136 | PackageManager.GET_DISABLED_COMPONENTS, user);
137 } catch (RemoteException e) {
138 // Will never happen.
139 continue;
140 }
141 if (ai == null) {
142 ai = tmpActivityInfo;
143 }
144 tmpAvailActCache.put(task.realActivity, ai);
145 }
146 if (ai == tmpActivityInfo) {
147 // This could be either because the activity no longer exists, or the
148 // app is temporarily gone. For the former we want to remove the recents
149 // entry; for the latter we want to mark it as unavailable.
150 ApplicationInfo app = tmpAvailAppCache.get(task.realActivity.getPackageName());
151 if (app == null) {
152 try {
153 app = pm.getApplicationInfo(task.realActivity.getPackageName(),
154 PackageManager.GET_UNINSTALLED_PACKAGES
155 | PackageManager.GET_DISABLED_COMPONENTS, user);
156 } catch (RemoteException e) {
157 // Will never happen.
158 continue;
159 }
160 if (app == null) {
161 app = tmpAppInfo;
162 }
163 tmpAvailAppCache.put(task.realActivity.getPackageName(), app);
164 }
165 if (app == tmpAppInfo || (app.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
166 // Doesn't exist any more! Good-bye.
167 remove(i);
168 task.removedFromRecents();
169 Slog.w(TAG, "Removing no longer valid recent: " + task);
170 continue;
171 } else {
172 // Otherwise just not available for now.
173 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG,
174 "Making recent unavailable: " + task);
175 task.isAvailable = false;
176 }
177 } else {
178 if (!ai.enabled || !ai.applicationInfo.enabled
179 || (ai.applicationInfo.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
180 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG,
181 "Making recent unavailable: " + task
182 + " (enabled=" + ai.enabled + "/" + ai.applicationInfo.enabled
183 + " flags=" + Integer.toHexString(ai.applicationInfo.flags)
184 + ")");
185 task.isAvailable = false;
186 } else {
187 if (DEBUG_RECENTS && !task.isAvailable) Slog.d(TAG,
188 "Making recent available: " + task);
189 task.isAvailable = true;
190 }
191 }
192 }
193 }
194 }
195
196 // Verify the affiliate chain for each task.
197 int i = 0;
198 recentsCount = size();
199 while (i < recentsCount) {
200 i = processNextAffiliateChainLocked(i);
201 }
202 // recent tasks are now in sorted, affiliated order.
203 }
204
205 private final boolean moveAffiliatedTasksToFront(TaskRecord task, int taskIndex) {
206 int recentsCount = size();
207 TaskRecord top = task;
208 int topIndex = taskIndex;
209 while (top.mNextAffiliate != null && topIndex > 0) {
210 top = top.mNextAffiliate;
211 topIndex--;
212 }
213 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: adding affilliates starting at "
214 + topIndex + " from intial " + taskIndex);
215 // Find the end of the chain, doing a sanity check along the way.
216 boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
217 int endIndex = topIndex;
218 TaskRecord prev = top;
219 while (endIndex < recentsCount) {
220 TaskRecord cur = get(endIndex);
221 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: looking at next chain @"
222 + endIndex + " " + cur);
223 if (cur == top) {
224 // Verify start of the chain.
225 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != INVALID_TASK_ID) {
226 Slog.wtf(TAG, "Bad chain @" + endIndex
227 + ": first task has next affiliate: " + prev);
228 sane = false;
229 break;
230 }
231 } else {
232 // Verify middle of the chain's next points back to the one before.
233 if (cur.mNextAffiliate != prev
234 || cur.mNextAffiliateTaskId != prev.taskId) {
235 Slog.wtf(TAG, "Bad chain @" + endIndex
236 + ": middle task " + cur + " @" + endIndex
237 + " has bad next affiliate "
238 + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
239 + ", expected " + prev);
240 sane = false;
241 break;
242 }
243 }
244 if (cur.mPrevAffiliateTaskId == INVALID_TASK_ID) {
245 // Chain ends here.
246 if (cur.mPrevAffiliate != null) {
247 Slog.wtf(TAG, "Bad chain @" + endIndex
248 + ": last task " + cur + " has previous affiliate "
249 + cur.mPrevAffiliate);
250 sane = false;
251 }
252 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: end of chain @" + endIndex);
253 break;
254 } else {
255 // Verify middle of the chain's prev points to a valid item.
256 if (cur.mPrevAffiliate == null) {
257 Slog.wtf(TAG, "Bad chain @" + endIndex
258 + ": task " + cur + " has previous affiliate "
259 + cur.mPrevAffiliate + " but should be id "
260 + cur.mPrevAffiliate);
261 sane = false;
262 break;
263 }
264 }
265 if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
266 Slog.wtf(TAG, "Bad chain @" + endIndex
267 + ": task " + cur + " has affiliated id "
268 + cur.mAffiliatedTaskId + " but should be "
269 + task.mAffiliatedTaskId);
270 sane = false;
271 break;
272 }
273 prev = cur;
274 endIndex++;
275 if (endIndex >= recentsCount) {
276 Slog.wtf(TAG, "Bad chain ran off index " + endIndex
277 + ": last task " + prev);
278 sane = false;
279 break;
280 }
281 }
282 if (sane) {
283 if (endIndex < taskIndex) {
284 Slog.wtf(TAG, "Bad chain @" + endIndex
285 + ": did not extend to task " + task + " @" + taskIndex);
286 sane = false;
287 }
288 }
289 if (sane) {
290 // All looks good, we can just move all of the affiliated tasks
291 // to the top.
292 for (int i=topIndex; i<=endIndex; i++) {
293 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: moving affiliated " + task
294 + " from " + i + " to " + (i-topIndex));
295 TaskRecord cur = remove(i);
296 add(i - topIndex, cur);
297 }
298 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: done moving tasks " + topIndex
299 + " to " + endIndex);
300 return true;
301 }
302
303 // Whoops, couldn't do it.
304 return false;
305 }
306
307 final void addLocked(TaskRecord task) {
308 final boolean isAffiliated = task.mAffiliatedTaskId != task.taskId
309 || task.mNextAffiliateTaskId != INVALID_TASK_ID
310 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
311
312 int recentsCount = size();
313 // Quick case: never add voice sessions.
314 if (task.voiceSession != null) {
315 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: not adding voice interaction " + task);
316 return;
317 }
318 // Another quick case: check if the top-most recent task is the same.
319 if (!isAffiliated && recentsCount > 0 && get(0) == task) {
320 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: already at top: " + task);
321 return;
322 }
323 // Another quick case: check if this is part of a set of affiliated
324 // tasks that are at the top.
325 if (isAffiliated && recentsCount > 0 && task.inRecents
326 && task.mAffiliatedTaskId == get(0).mAffiliatedTaskId) {
327 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: affiliated " + get(0)
328 + " at top when adding " + task);
329 return;
330 }
331
332 boolean needAffiliationFix = false;
333
334 // Slightly less quick case: the task is already in recents, so all we need
335 // to do is move it.
336 if (task.inRecents) {
337 int taskIndex = indexOf(task);
338 if (taskIndex >= 0) {
339 if (!isAffiliated) {
340 // Simple case: this is not an affiliated task, so we just move it to the front.
341 remove(taskIndex);
342 add(0, task);
343 mService.notifyTaskPersisterLocked(task, false);
344 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: moving to top " + task
345 + " from " + taskIndex);
346 return;
347 } else {
348 // More complicated: need to keep all affiliated tasks together.
349 if (moveAffiliatedTasksToFront(task, taskIndex)) {
350 // All went well.
351 return;
352 }
353
354 // Uh oh... something bad in the affiliation chain, try to rebuild
355 // everything and then go through our general path of adding a new task.
356 needAffiliationFix = true;
357 }
358 } else {
359 Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
360 needAffiliationFix = true;
361 }
362 }
363
364 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: trimming tasks for " + task);
365 trimForTaskLocked(task, true);
366
367 recentsCount = size();
368 final int maxRecents = ActivityManager.getMaxRecentTasksStatic();
369 while (recentsCount >= maxRecents) {
370 final TaskRecord tr = remove(recentsCount - 1);
371 tr.removedFromRecents();
372 recentsCount--;
373 }
374 task.inRecents = true;
375 if (!isAffiliated || needAffiliationFix) {
376 // If this is a simple non-affiliated task, or we had some failure trying to
377 // handle it as part of an affilated task, then just place it at the top.
378 add(0, task);
379 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: adding " + task);
380 } else if (isAffiliated) {
381 // If this is a new affiliated task, then move all of the affiliated tasks
382 // to the front and insert this new one.
383 TaskRecord other = task.mNextAffiliate;
384 if (other == null) {
385 other = task.mPrevAffiliate;
386 }
387 if (other != null) {
388 int otherIndex = indexOf(other);
389 if (otherIndex >= 0) {
390 // Insert new task at appropriate location.
391 int taskIndex;
392 if (other == task.mNextAffiliate) {
393 // We found the index of our next affiliation, which is who is
394 // before us in the list, so add after that point.
395 taskIndex = otherIndex+1;
396 } else {
397 // We found the index of our previous affiliation, which is who is
398 // after us in the list, so add at their position.
399 taskIndex = otherIndex;
400 }
401 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: new affiliated task added at "
402 + taskIndex + ": " + task);
403 add(taskIndex, task);
404
405 // Now move everything to the front.
406 if (moveAffiliatedTasksToFront(task, taskIndex)) {
407 // All went well.
408 return;
409 }
410
411 // Uh oh... something bad in the affiliation chain, try to rebuild
412 // everything and then go through our general path of adding a new task.
413 needAffiliationFix = true;
414 } else {
415 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: couldn't find other affiliation "
416 + other);
417 needAffiliationFix = true;
418 }
419 } else {
420 if (DEBUG_RECENTS) Slog.d(TAG,
421 "addRecent: adding affiliated task without next/prev:" + task);
422 needAffiliationFix = true;
423 }
424 }
425
426 if (needAffiliationFix) {
427 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: regrouping affiliations");
428 cleanupLocked(task.userId);
429 }
430 }
431
432 /**
433 * If needed, remove oldest existing entries in recents that are for the same kind
434 * of task as the given one.
435 */
436 int trimForTaskLocked(TaskRecord task, boolean doTrim) {
437 int recentsCount = size();
438 final Intent intent = task.intent;
439 final boolean document = intent != null && intent.isDocument();
440
441 int maxRecents = task.maxRecents - 1;
442 for (int i = 0; i < recentsCount; i++) {
443 final TaskRecord tr = get(i);
444 if (task != tr) {
445 if (task.userId != tr.userId) {
446 continue;
447 }
448 if (i > MAX_RECENT_BITMAPS) {
449 tr.freeLastThumbnail();
450 }
451 final Intent trIntent = tr.intent;
452 if ((task.affinity == null || !task.affinity.equals(tr.affinity)) &&
453 (intent == null || !intent.filterEquals(trIntent))) {
454 continue;
455 }
456 final boolean trIsDocument = trIntent != null && trIntent.isDocument();
457 if (document && trIsDocument) {
458 // These are the same document activity (not necessarily the same doc).
459 if (maxRecents > 0) {
460 --maxRecents;
461 continue;
462 }
463 // Hit the maximum number of documents for this task. Fall through
464 // and remove this document from recents.
465 } else if (document || trIsDocument) {
466 // Only one of these is a document. Not the droid we're looking for.
467 continue;
468 }
469 }
470
471 if (!doTrim) {
472 // If the caller is not actually asking for a trim, just tell them we reached
473 // a point where the trim would happen.
474 return i;
475 }
476
477 // Either task and tr are the same or, their affinities match or their intents match
478 // and neither of them is a document, or they are documents using the same activity
479 // and their maxRecents has been reached.
480 tr.disposeThumbnail();
481 remove(i);
482 if (task != tr) {
483 tr.removedFromRecents();
484 }
485 i--;
486 recentsCount--;
487 if (task.intent == null) {
488 // If the new recent task we are adding is not fully
489 // specified, then replace it with the existing recent task.
490 task = tr;
491 }
492 mService.notifyTaskPersisterLocked(tr, false);
493 }
494
495 return -1;
496 }
497
498 // Sort by taskId
499 private static Comparator<TaskRecord> sTaskRecordComparator = new Comparator<TaskRecord>() {
500 @Override
501 public int compare(TaskRecord lhs, TaskRecord rhs) {
502 return rhs.taskId - lhs.taskId;
503 }
504 };
505
506 // Extract the affiliates of the chain containing recent at index start.
507 private int processNextAffiliateChainLocked(int start) {
508 final TaskRecord startTask = get(start);
509 final int affiliateId = startTask.mAffiliatedTaskId;
510
511 // Quick identification of isolated tasks. I.e. those not launched behind.
512 if (startTask.taskId == affiliateId && startTask.mPrevAffiliate == null &&
513 startTask.mNextAffiliate == null) {
514 // There is still a slim chance that there are other tasks that point to this task
515 // and that the chain is so messed up that this task no longer points to them but
516 // the gain of this optimization outweighs the risk.
517 startTask.inRecents = true;
518 return start + 1;
519 }
520
521 // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
522 mTmpRecents.clear();
523 for (int i = size() - 1; i >= start; --i) {
524 final TaskRecord task = get(i);
525 if (task.mAffiliatedTaskId == affiliateId) {
526 remove(i);
527 mTmpRecents.add(task);
528 }
529 }
530
531 // Sort them all by taskId. That is the order they were create in and that order will
532 // always be correct.
533 Collections.sort(mTmpRecents, sTaskRecordComparator);
534
535 // Go through and fix up the linked list.
536 // The first one is the end of the chain and has no next.
537 final TaskRecord first = mTmpRecents.get(0);
538 first.inRecents = true;
539 if (first.mNextAffiliate != null) {
540 Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
541 first.setNextAffiliate(null);
542 mService.notifyTaskPersisterLocked(first, false);
543 }
544 // Everything in the middle is doubly linked from next to prev.
545 final int tmpSize = mTmpRecents.size();
546 for (int i = 0; i < tmpSize - 1; ++i) {
547 final TaskRecord next = mTmpRecents.get(i);
548 final TaskRecord prev = mTmpRecents.get(i + 1);
549 if (next.mPrevAffiliate != prev) {
550 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
551 " setting prev=" + prev);
552 next.setPrevAffiliate(prev);
553 mService.notifyTaskPersisterLocked(next, false);
554 }
555 if (prev.mNextAffiliate != next) {
556 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
557 " setting next=" + next);
558 prev.setNextAffiliate(next);
559 mService.notifyTaskPersisterLocked(prev, false);
560 }
561 prev.inRecents = true;
562 }
563 // The last one is the beginning of the list and has no prev.
564 final TaskRecord last = mTmpRecents.get(tmpSize - 1);
565 if (last.mPrevAffiliate != null) {
566 Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
567 last.setPrevAffiliate(null);
568 mService.notifyTaskPersisterLocked(last, false);
569 }
570
571 // Insert the group back into mRecentTasks at start.
572 addAll(start, mTmpRecents);
573 mTmpRecents.clear();
574
575 // Let the caller know where we left off.
576 return start + tmpSize;
577 }
578
579}