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