ActivityStack.java revision 8de4311c51229efbe2f2d0afbf298982c5cadd96
1/* 2 * Copyright (C) 2010 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 static com.android.server.am.ActivityManagerService.TAG; 20import static com.android.server.am.ActivityManagerService.localLOGV; 21import static com.android.server.am.ActivityManagerService.DEBUG_CLEANUP; 22import static com.android.server.am.ActivityManagerService.DEBUG_CONFIGURATION; 23import static com.android.server.am.ActivityManagerService.DEBUG_PAUSE; 24import static com.android.server.am.ActivityManagerService.DEBUG_RESULTS; 25import static com.android.server.am.ActivityManagerService.DEBUG_STACK; 26import static com.android.server.am.ActivityManagerService.DEBUG_SWITCH; 27import static com.android.server.am.ActivityManagerService.DEBUG_TASKS; 28import static com.android.server.am.ActivityManagerService.DEBUG_TRANSITION; 29import static com.android.server.am.ActivityManagerService.DEBUG_USER_LEAVING; 30import static com.android.server.am.ActivityManagerService.DEBUG_VISBILITY; 31import static com.android.server.am.ActivityManagerService.VALIDATE_TOKENS; 32 33import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE; 34import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE; 35 36import static com.android.server.am.ActivityStackSupervisor.DEBUG_ADD_REMOVE; 37import static com.android.server.am.ActivityStackSupervisor.DEBUG_APP; 38import static com.android.server.am.ActivityStackSupervisor.DEBUG_CONTAINERS; 39import static com.android.server.am.ActivityStackSupervisor.DEBUG_SAVED_STATE; 40import static com.android.server.am.ActivityStackSupervisor.DEBUG_SCREENSHOTS; 41import static com.android.server.am.ActivityStackSupervisor.DEBUG_STATES; 42import static com.android.server.am.ActivityStackSupervisor.HOME_STACK_ID; 43 44import com.android.internal.app.IVoiceInteractor; 45import com.android.internal.os.BatteryStatsImpl; 46import com.android.server.Watchdog; 47import com.android.server.am.ActivityManagerService.ItemMatcher; 48import com.android.server.am.ActivityStackSupervisor.ActivityContainer; 49import com.android.server.wm.AppTransition; 50import com.android.server.wm.TaskGroup; 51import com.android.server.wm.WindowManagerService; 52 53import android.app.Activity; 54import android.app.ActivityManager; 55import android.app.ActivityOptions; 56import android.app.AppGlobals; 57import android.app.IActivityController; 58import android.app.ResultInfo; 59import android.app.ActivityManager.RunningTaskInfo; 60import android.content.ComponentName; 61import android.content.Intent; 62import android.content.pm.ActivityInfo; 63import android.content.pm.PackageManager; 64import android.content.res.Configuration; 65import android.content.res.Resources; 66import android.graphics.Bitmap; 67import android.net.Uri; 68import android.os.Binder; 69import android.os.Bundle; 70import android.os.Debug; 71import android.os.Handler; 72import android.os.IBinder; 73import android.os.Looper; 74import android.os.Message; 75import android.os.PersistableBundle; 76import android.os.RemoteException; 77import android.os.SystemClock; 78import android.os.Trace; 79import android.os.UserHandle; 80import android.service.voice.IVoiceInteractionSession; 81import android.util.EventLog; 82import android.util.Slog; 83import android.view.Display; 84 85import java.io.FileDescriptor; 86import java.io.PrintWriter; 87import java.lang.ref.WeakReference; 88import java.util.ArrayList; 89import java.util.Iterator; 90import java.util.List; 91import java.util.Objects; 92 93/** 94 * State and management of a single stack of activities. 95 */ 96final class ActivityStack { 97 98 // Ticks during which we check progress while waiting for an app to launch. 99 static final int LAUNCH_TICK = 500; 100 101 // How long we wait until giving up on the last activity to pause. This 102 // is short because it directly impacts the responsiveness of starting the 103 // next activity. 104 static final int PAUSE_TIMEOUT = 500; 105 106 // How long we wait for the activity to tell us it has stopped before 107 // giving up. This is a good amount of time because we really need this 108 // from the application in order to get its saved state. 109 static final int STOP_TIMEOUT = 10*1000; 110 111 // How long we wait until giving up on an activity telling us it has 112 // finished destroying itself. 113 static final int DESTROY_TIMEOUT = 10*1000; 114 115 // How long until we reset a task when the user returns to it. Currently 116 // disabled. 117 static final long ACTIVITY_INACTIVE_RESET_TIME = 0; 118 119 // How long between activity launches that we consider safe to not warn 120 // the user about an unexpected activity being launched on top. 121 static final long START_WARN_TIME = 5*1000; 122 123 // Set to false to disable the preview that is shown while a new activity 124 // is being started. 125 static final boolean SHOW_APP_STARTING_PREVIEW = true; 126 127 // How long to wait for all background Activities to redraw following a call to 128 // convertToTranslucent(). 129 static final long TRANSLUCENT_CONVERSION_TIMEOUT = 2000; 130 131 static final boolean SCREENSHOT_FORCE_565 = ActivityManager.isLowRamDeviceStatic(); 132 133 enum ActivityState { 134 INITIALIZING, 135 RESUMED, 136 PAUSING, 137 PAUSED, 138 STOPPING, 139 STOPPED, 140 FINISHING, 141 DESTROYING, 142 DESTROYED 143 } 144 145 final ActivityManagerService mService; 146 final WindowManagerService mWindowManager; 147 148 /** 149 * The back history of all previous (and possibly still 150 * running) activities. It contains #TaskRecord objects. 151 */ 152 private ArrayList<TaskRecord> mTaskHistory = new ArrayList<TaskRecord>(); 153 154 /** 155 * Used for validating app tokens with window manager. 156 */ 157 final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>(); 158 159 /** 160 * List of running activities, sorted by recent usage. 161 * The first entry in the list is the least recently used. 162 * It contains HistoryRecord objects. 163 */ 164 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>(); 165 166 /** 167 * Animations that for the current transition have requested not to 168 * be considered for the transition animation. 169 */ 170 final ArrayList<ActivityRecord> mNoAnimActivities = new ArrayList<ActivityRecord>(); 171 172 /** 173 * When we are in the process of pausing an activity, before starting the 174 * next one, this variable holds the activity that is currently being paused. 175 */ 176 ActivityRecord mPausingActivity = null; 177 178 /** 179 * This is the last activity that we put into the paused state. This is 180 * used to determine if we need to do an activity transition while sleeping, 181 * when we normally hold the top activity paused. 182 */ 183 ActivityRecord mLastPausedActivity = null; 184 185 /** 186 * Activities that specify No History must be removed once the user navigates away from them. 187 * If the device goes to sleep with such an activity in the paused state then we save it here 188 * and finish it later if another activity replaces it on wakeup. 189 */ 190 ActivityRecord mLastNoHistoryActivity = null; 191 192 /** 193 * Current activity that is resumed, or null if there is none. 194 */ 195 ActivityRecord mResumedActivity = null; 196 197 /** 198 * This is the last activity that has been started. It is only used to 199 * identify when multiple activities are started at once so that the user 200 * can be warned they may not be in the activity they think they are. 201 */ 202 ActivityRecord mLastStartedActivity = null; 203 204 // The topmost Activity passed to convertToTranslucent(). When non-null it means we are 205 // waiting for all Activities in mUndrawnActivitiesBelowTopTranslucent to be removed as they 206 // are drawn. When the last member of mUndrawnActivitiesBelowTopTranslucent is removed the 207 // Activity in mTranslucentActivityWaiting is notified via 208 // Activity.onTranslucentConversionComplete(false). If a timeout occurs prior to the last 209 // background activity being drawn then the same call will be made with a true value. 210 ActivityRecord mTranslucentActivityWaiting = null; 211 private ArrayList<ActivityRecord> mUndrawnActivitiesBelowTopTranslucent = 212 new ArrayList<ActivityRecord>(); 213 214 /** 215 * Set when we know we are going to be calling updateConfiguration() 216 * soon, so want to skip intermediate config checks. 217 */ 218 boolean mConfigWillChange; 219 220 long mLaunchStartTime = 0; 221 long mFullyDrawnStartTime = 0; 222 223 /** 224 * Save the most recent screenshot for reuse. This keeps Recents from taking two identical 225 * screenshots, one for the Recents thumbnail and one for the pauseActivity thumbnail. 226 */ 227 private ActivityRecord mLastScreenshotActivity = null; 228 private Bitmap mLastScreenshotBitmap = null; 229 230 int mThumbnailWidth = -1; 231 int mThumbnailHeight = -1; 232 233 int mCurrentUser; 234 235 final int mStackId; 236 final ActivityContainer mActivityContainer; 237 /** The other stacks, in order, on the attached display. Updated at attach/detach time. */ 238 ArrayList<ActivityStack> mStacks; 239 /** The attached Display's unique identifier, or -1 if detached */ 240 int mDisplayId; 241 242 /** Run all ActivityStacks through this */ 243 final ActivityStackSupervisor mStackSupervisor; 244 245 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1; 246 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2; 247 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3; 248 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4; 249 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5; 250 static final int TRANSLUCENT_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6; 251 static final int STOP_MEDIA_PLAYING_TIMEOUT_MSG = 252 ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7; 253 254 static class ScheduleDestroyArgs { 255 final ProcessRecord mOwner; 256 final String mReason; 257 ScheduleDestroyArgs(ProcessRecord owner, String reason) { 258 mOwner = owner; 259 mReason = reason; 260 } 261 } 262 263 final Handler mHandler; 264 265 final class ActivityStackHandler extends Handler { 266 //public Handler() { 267 // if (localLOGV) Slog.v(TAG, "Handler started!"); 268 //} 269 ActivityStackHandler(Looper looper) { 270 super(looper); 271 } 272 273 @Override 274 public void handleMessage(Message msg) { 275 switch (msg.what) { 276 case PAUSE_TIMEOUT_MSG: { 277 ActivityRecord r = (ActivityRecord)msg.obj; 278 // We don't at this point know if the activity is fullscreen, 279 // so we need to be conservative and assume it isn't. 280 Slog.w(TAG, "Activity pause timeout for " + r); 281 synchronized (mService) { 282 if (r.app != null) { 283 mService.logAppTooSlow(r.app, r.pauseTime, "pausing " + r); 284 } 285 activityPausedLocked(r.appToken, true, r.persistentState); 286 } 287 } break; 288 case LAUNCH_TICK_MSG: { 289 ActivityRecord r = (ActivityRecord)msg.obj; 290 synchronized (mService) { 291 if (r.continueLaunchTickingLocked()) { 292 mService.logAppTooSlow(r.app, r.launchTickTime, "launching " + r); 293 } 294 } 295 } break; 296 case DESTROY_TIMEOUT_MSG: { 297 ActivityRecord r = (ActivityRecord)msg.obj; 298 // We don't at this point know if the activity is fullscreen, 299 // so we need to be conservative and assume it isn't. 300 Slog.w(TAG, "Activity destroy timeout for " + r); 301 synchronized (mService) { 302 activityDestroyedLocked(r != null ? r.appToken : null); 303 } 304 } break; 305 case STOP_TIMEOUT_MSG: { 306 ActivityRecord r = (ActivityRecord)msg.obj; 307 // We don't at this point know if the activity is fullscreen, 308 // so we need to be conservative and assume it isn't. 309 Slog.w(TAG, "Activity stop timeout for " + r); 310 synchronized (mService) { 311 if (r.isInHistory()) { 312 activityStoppedLocked(r, null, null, null); 313 } 314 } 315 } break; 316 case DESTROY_ACTIVITIES_MSG: { 317 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj; 318 synchronized (mService) { 319 destroyActivitiesLocked(args.mOwner, args.mReason); 320 } 321 } break; 322 case TRANSLUCENT_TIMEOUT_MSG: { 323 synchronized (mService) { 324 notifyActivityDrawnLocked(null); 325 } 326 } break; 327 case STOP_MEDIA_PLAYING_TIMEOUT_MSG: { 328 synchronized (mService) { 329 final ActivityRecord r = getMediaPlayer(); 330 Slog.e(TAG, "Timeout waiting for stopMediaPlaying player=" + r); 331 if (r != null) { 332 mService.killAppAtUsersRequest(r.app, null); 333 } 334 } 335 } break; 336 } 337 } 338 } 339 340 int numActivities() { 341 int count = 0; 342 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 343 count += mTaskHistory.get(taskNdx).mActivities.size(); 344 } 345 return count; 346 } 347 348 ActivityStack(ActivityStackSupervisor.ActivityContainer activityContainer) { 349 mActivityContainer = activityContainer; 350 mStackSupervisor = activityContainer.getOuter(); 351 mService = mStackSupervisor.mService; 352 mHandler = new ActivityStackHandler(mService.mHandler.getLooper()); 353 mWindowManager = mService.mWindowManager; 354 mStackId = activityContainer.mStackId; 355 mCurrentUser = mService.mCurrentUserId; 356 // Get the activity screenshot thumbnail dimensions 357 Resources res = mService.mContext.getResources(); 358 mThumbnailWidth = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width); 359 mThumbnailHeight = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height); 360 } 361 362 /** 363 * Checks whether the userid is a profile of the current user. 364 */ 365 private boolean isCurrentProfileLocked(int userId) { 366 if (userId == mCurrentUser) return true; 367 for (int i = 0; i < mService.mCurrentProfileIds.length; i++) { 368 if (mService.mCurrentProfileIds[i] == userId) return true; 369 } 370 return false; 371 } 372 373 boolean okToShowLocked(ActivityRecord r) { 374 return isCurrentProfileLocked(r.userId) 375 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0; 376 } 377 378 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) { 379 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 380 ActivityRecord r = mTaskHistory.get(taskNdx).topRunningActivityLocked(notTop); 381 if (r != null) { 382 return r; 383 } 384 } 385 return null; 386 } 387 388 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) { 389 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 390 final TaskRecord task = mTaskHistory.get(taskNdx); 391 final ArrayList<ActivityRecord> activities = task.mActivities; 392 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 393 ActivityRecord r = activities.get(activityNdx); 394 if (!r.finishing && !r.delayedResume && r != notTop && okToShowLocked(r)) { 395 return r; 396 } 397 } 398 } 399 return null; 400 } 401 402 /** 403 * This is a simplified version of topRunningActivityLocked that provides a number of 404 * optional skip-over modes. It is intended for use with the ActivityController hook only. 405 * 406 * @param token If non-null, any history records matching this token will be skipped. 407 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID. 408 * 409 * @return Returns the HistoryRecord of the next activity on the stack. 410 */ 411 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) { 412 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 413 TaskRecord task = mTaskHistory.get(taskNdx); 414 if (task.taskId == taskId) { 415 continue; 416 } 417 ArrayList<ActivityRecord> activities = task.mActivities; 418 for (int i = activities.size() - 1; i >= 0; --i) { 419 final ActivityRecord r = activities.get(i); 420 // Note: the taskId check depends on real taskId fields being non-zero 421 if (!r.finishing && (token != r.appToken) && okToShowLocked(r)) { 422 return r; 423 } 424 } 425 } 426 return null; 427 } 428 429 final ActivityRecord topActivity() { 430 // Iterate to find the first non-empty task stack. Note that this code can 431 // be simplified once we stop storing tasks with empty mActivities lists. 432 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 433 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 434 final int topActivityNdx = activities.size() - 1; 435 if (topActivityNdx >= 0) { 436 return activities.get(topActivityNdx); 437 } 438 } 439 return null; 440 } 441 442 final TaskRecord topTask() { 443 final int size = mTaskHistory.size(); 444 if (size > 0) { 445 return mTaskHistory.get(size - 1); 446 } 447 return null; 448 } 449 450 TaskRecord taskForIdLocked(int id) { 451 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 452 final TaskRecord task = mTaskHistory.get(taskNdx); 453 if (task.taskId == id) { 454 return task; 455 } 456 } 457 return null; 458 } 459 460 ActivityRecord isInStackLocked(IBinder token) { 461 final ActivityRecord r = ActivityRecord.forToken(token); 462 if (r != null) { 463 final TaskRecord task = r.task; 464 if (task.mActivities.contains(r) && mTaskHistory.contains(task)) { 465 if (task.stack != this) Slog.w(TAG, 466 "Illegal state! task does not point to stack it is in."); 467 return r; 468 } 469 } 470 return null; 471 } 472 473 final boolean updateLRUListLocked(ActivityRecord r) { 474 final boolean hadit = mLRUActivities.remove(r); 475 mLRUActivities.add(r); 476 return hadit; 477 } 478 479 final boolean isHomeStack() { 480 return mStackId == HOME_STACK_ID; 481 } 482 483 final boolean isOnHomeDisplay() { 484 return isAttached() && 485 mActivityContainer.mActivityDisplay.mDisplayId == Display.DEFAULT_DISPLAY; 486 } 487 488 final void moveToFront() { 489 if (isAttached()) { 490 if (isOnHomeDisplay()) { 491 mStackSupervisor.moveHomeStack(isHomeStack()); 492 } 493 mStacks.remove(this); 494 mStacks.add(this); 495 } 496 } 497 498 final boolean isAttached() { 499 return mStacks != null; 500 } 501 502 /** 503 * Returns the top activity in any existing task matching the given 504 * Intent. Returns null if no such task is found. 505 */ 506 ActivityRecord findTaskLocked(ActivityRecord target) { 507 Intent intent = target.intent; 508 ActivityInfo info = target.info; 509 ComponentName cls = intent.getComponent(); 510 if (info.targetActivity != null) { 511 cls = new ComponentName(info.packageName, info.targetActivity); 512 } 513 final int userId = UserHandle.getUserId(info.applicationInfo.uid); 514 boolean isDocument = intent != null & intent.isDocument(); 515 // If documentData is non-null then it must match the existing task data. 516 Uri documentData = isDocument ? intent.getData() : null; 517 518 if (DEBUG_TASKS) Slog.d(TAG, "Looking for task of " + target + " in " + this); 519 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 520 final TaskRecord task = mTaskHistory.get(taskNdx); 521 if (task.voiceSession != null) { 522 // We never match voice sessions; those always run independently. 523 if (DEBUG_TASKS) Slog.d(TAG, "Skipping " + task + ": voice session"); 524 continue; 525 } 526 if (task.userId != userId) { 527 // Looking for a different task. 528 if (DEBUG_TASKS) Slog.d(TAG, "Skipping " + task + ": different user"); 529 continue; 530 } 531 final ActivityRecord r = task.getTopActivity(); 532 if (r == null || r.finishing || r.userId != userId || 533 r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) { 534 if (DEBUG_TASKS) Slog.d(TAG, "Skipping " + task + ": mismatch root " + r); 535 continue; 536 } 537 538 final Intent taskIntent = task.intent; 539 final Intent affinityIntent = task.affinityIntent; 540 final boolean taskIsDocument; 541 final Uri taskDocumentData; 542 if (taskIntent != null && taskIntent.isDocument()) { 543 taskIsDocument = true; 544 taskDocumentData = taskIntent.getData(); 545 } else if (affinityIntent != null && affinityIntent.isDocument()) { 546 taskIsDocument = true; 547 taskDocumentData = affinityIntent.getData(); 548 } else { 549 taskIsDocument = false; 550 taskDocumentData = null; 551 } 552 553 if (DEBUG_TASKS) Slog.d(TAG, "Comparing existing cls=" 554 + taskIntent.getComponent().flattenToShortString() 555 + "/aff=" + r.task.affinity + " to new cls=" 556 + intent.getComponent().flattenToShortString() + "/aff=" + info.taskAffinity); 557 if (!isDocument && !taskIsDocument && task.affinity != null) { 558 if (task.affinity.equals(target.taskAffinity)) { 559 if (DEBUG_TASKS) Slog.d(TAG, "Found matching affinity!"); 560 return r; 561 } 562 } else if (taskIntent != null && taskIntent.getComponent() != null && 563 taskIntent.getComponent().compareTo(cls) == 0 && 564 Objects.equals(documentData, taskDocumentData)) { 565 if (DEBUG_TASKS) Slog.d(TAG, "Found matching class!"); 566 //dump(); 567 if (DEBUG_TASKS) Slog.d(TAG, "For Intent " + intent + " bringing to top: " 568 + r.intent); 569 return r; 570 } else if (affinityIntent != null && affinityIntent.getComponent() != null && 571 affinityIntent.getComponent().compareTo(cls) == 0 && 572 Objects.equals(documentData, taskDocumentData)) { 573 if (DEBUG_TASKS) Slog.d(TAG, "Found matching class!"); 574 //dump(); 575 if (DEBUG_TASKS) Slog.d(TAG, "For Intent " + intent + " bringing to top: " 576 + r.intent); 577 return r; 578 } else if (DEBUG_TASKS) { 579 Slog.d(TAG, "Not a match: " + task); 580 } 581 } 582 583 return null; 584 } 585 586 /** 587 * Returns the first activity (starting from the top of the stack) that 588 * is the same as the given activity. Returns null if no such activity 589 * is found. 590 */ 591 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) { 592 ComponentName cls = intent.getComponent(); 593 if (info.targetActivity != null) { 594 cls = new ComponentName(info.packageName, info.targetActivity); 595 } 596 final int userId = UserHandle.getUserId(info.applicationInfo.uid); 597 598 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 599 TaskRecord task = mTaskHistory.get(taskNdx); 600 if (!isCurrentProfileLocked(task.userId)) { 601 return null; 602 } 603 final ArrayList<ActivityRecord> activities = task.mActivities; 604 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 605 ActivityRecord r = activities.get(activityNdx); 606 if (!r.finishing && r.intent.getComponent().equals(cls) && r.userId == userId) { 607 //Slog.i(TAG, "Found matching class!"); 608 //dump(); 609 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent); 610 return r; 611 } 612 } 613 } 614 615 return null; 616 } 617 618 /* 619 * Move the activities around in the stack to bring a user to the foreground. 620 */ 621 final void switchUserLocked(int userId) { 622 if (mCurrentUser == userId) { 623 return; 624 } 625 mCurrentUser = userId; 626 627 // Move userId's tasks to the top. 628 int index = mTaskHistory.size(); 629 for (int i = 0; i < index; ) { 630 TaskRecord task = mTaskHistory.get(i); 631 if (isCurrentProfileLocked(task.userId)) { 632 if (DEBUG_TASKS) Slog.d(TAG, "switchUserLocked: stack=" + getStackId() + 633 " moving " + task + " to top"); 634 mTaskHistory.remove(i); 635 mTaskHistory.add(task); 636 --index; 637 // Use same value for i. 638 } else { 639 ++i; 640 } 641 } 642 if (VALIDATE_TOKENS) { 643 validateAppTokensLocked(); 644 } 645 } 646 647 void minimalResumeActivityLocked(ActivityRecord r) { 648 r.state = ActivityState.RESUMED; 649 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r 650 + " (starting new instance)"); 651 r.stopped = false; 652 mResumedActivity = r; 653 r.task.touchActiveTime(); 654 mService.addRecentTaskLocked(r.task); 655 completeResumeLocked(r); 656 mStackSupervisor.checkReadyForSleepLocked(); 657 setLaunchTime(r); 658 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle); 659 } 660 661 private void startLaunchTraces() { 662 if (mFullyDrawnStartTime != 0) { 663 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0); 664 } 665 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching", 0); 666 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0); 667 } 668 669 private void stopFullyDrawnTraceIfNeeded() { 670 if (mFullyDrawnStartTime != 0 && mLaunchStartTime == 0) { 671 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0); 672 mFullyDrawnStartTime = 0; 673 } 674 } 675 676 void setLaunchTime(ActivityRecord r) { 677 if (r.displayStartTime == 0) { 678 r.fullyDrawnStartTime = r.displayStartTime = SystemClock.uptimeMillis(); 679 if (mLaunchStartTime == 0) { 680 startLaunchTraces(); 681 mLaunchStartTime = mFullyDrawnStartTime = r.displayStartTime; 682 } 683 } else if (mLaunchStartTime == 0) { 684 startLaunchTraces(); 685 mLaunchStartTime = mFullyDrawnStartTime = SystemClock.uptimeMillis(); 686 } 687 } 688 689 void clearLaunchTime(ActivityRecord r) { 690 // Make sure that there is no activity waiting for this to launch. 691 if (mStackSupervisor.mWaitingActivityLaunched.isEmpty()) { 692 r.displayStartTime = r.fullyDrawnStartTime = 0; 693 } else { 694 mStackSupervisor.removeTimeoutsForActivityLocked(r); 695 mStackSupervisor.scheduleIdleTimeoutLocked(r); 696 } 697 } 698 699 void awakeFromSleepingLocked() { 700 // Ensure activities are no longer sleeping. 701 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 702 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 703 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 704 activities.get(activityNdx).setSleeping(false); 705 } 706 } 707 } 708 709 /** 710 * @return true if something must be done before going to sleep. 711 */ 712 boolean checkReadyForSleepLocked() { 713 if (mResumedActivity != null) { 714 // Still have something resumed; can't sleep until it is paused. 715 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity); 716 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false"); 717 startPausingLocked(false, true); 718 return true; 719 } 720 if (mPausingActivity != null) { 721 // Still waiting for something to pause; can't sleep yet. 722 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity); 723 return true; 724 } 725 726 return false; 727 } 728 729 void goToSleep() { 730 ensureActivitiesVisibleLocked(null, 0); 731 732 // Make sure any stopped but visible activities are now sleeping. 733 // This ensures that the activity's onStop() is called. 734 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 735 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 736 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 737 final ActivityRecord r = activities.get(activityNdx); 738 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) { 739 r.setSleeping(true); 740 } 741 } 742 } 743 } 744 745 /** 746 * This resets the saved state from the last screenshot, forcing a new screenshot to be taken 747 * again when requested. 748 */ 749 private void invalidateLastScreenshot() { 750 mLastScreenshotActivity = null; 751 if (mLastScreenshotBitmap != null) { 752 mLastScreenshotBitmap.recycle(); 753 } 754 mLastScreenshotBitmap = null; 755 } 756 757 public final Bitmap screenshotActivities(ActivityRecord who) { 758 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "screenshotActivities: " + who); 759 if (who.noDisplay) { 760 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tNo display"); 761 return null; 762 } 763 764 if (isHomeStack()) { 765 // This is an optimization -- since we never show Home or Recents within Recents itself, 766 // we can just go ahead and skip taking the screenshot if this is the home stack. In 767 // the case where the most recent task is not the task that was supplied, then the stack 768 // has changed, so invalidate the last screenshot(). 769 invalidateLastScreenshot(); 770 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tIs Home stack? " + isHomeStack()); 771 return null; 772 } 773 774 int w = mThumbnailWidth; 775 int h = mThumbnailHeight; 776 if (w > 0) { 777 if (who != mLastScreenshotActivity || mLastScreenshotBitmap == null 778 || mLastScreenshotActivity.state == ActivityState.RESUMED 779 || mLastScreenshotBitmap.getWidth() != w 780 || mLastScreenshotBitmap.getHeight() != h) { 781 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tUpdating screenshot"); 782 mLastScreenshotActivity = who; 783 mLastScreenshotBitmap = mWindowManager.screenshotApplications( 784 who.appToken, Display.DEFAULT_DISPLAY, w, h, SCREENSHOT_FORCE_565); 785 } 786 if (mLastScreenshotBitmap != null) { 787 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tReusing last screenshot"); 788 return mLastScreenshotBitmap.copy(mLastScreenshotBitmap.getConfig(), true); 789 } 790 } 791 Slog.e(TAG, "Invalid thumbnail dimensions: " + w + "x" + h); 792 return null; 793 } 794 795 final void startPausingLocked(boolean userLeaving, boolean uiSleeping) { 796 if (mPausingActivity != null) { 797 Slog.e(TAG, "Trying to pause when pause is already pending for " 798 + mPausingActivity, new RuntimeException("here").fillInStackTrace()); 799 } 800 ActivityRecord prev = mResumedActivity; 801 if (prev == null) { 802 Slog.e(TAG, "Trying to pause when nothing is resumed", 803 new RuntimeException("here").fillInStackTrace()); 804 mStackSupervisor.resumeTopActivitiesLocked(); 805 return; 806 } 807 808 if (mActivityContainer.mParentActivity == null) { 809 // Top level stack, not a child. Look for child stacks. 810 mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping); 811 } 812 813 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev); 814 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev); 815 mResumedActivity = null; 816 mPausingActivity = prev; 817 mLastPausedActivity = prev; 818 mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0 819 || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null; 820 prev.state = ActivityState.PAUSING; 821 prev.task.touchActiveTime(); 822 clearLaunchTime(prev); 823 final ActivityRecord next = mStackSupervisor.topRunningActivityLocked(); 824 if (mService.mHasRecents && (next == null || next.noDisplay || next.task != prev.task)) { 825 prev.updateThumbnail(screenshotActivities(prev), null); 826 } 827 stopFullyDrawnTraceIfNeeded(); 828 829 mService.updateCpuStats(); 830 831 if (prev.app != null && prev.app.thread != null) { 832 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev); 833 try { 834 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY, 835 prev.userId, System.identityHashCode(prev), 836 prev.shortComponentName); 837 mService.updateUsageStats(prev, false); 838 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing, 839 userLeaving, prev.configChangeFlags); 840 } catch (Exception e) { 841 // Ignore exception, if process died other code will cleanup. 842 Slog.w(TAG, "Exception thrown during pause", e); 843 mPausingActivity = null; 844 mLastPausedActivity = null; 845 mLastNoHistoryActivity = null; 846 } 847 } else { 848 mPausingActivity = null; 849 mLastPausedActivity = null; 850 mLastNoHistoryActivity = null; 851 } 852 853 // If we are not going to sleep, we want to ensure the device is 854 // awake until the next activity is started. 855 if (!mService.isSleepingOrShuttingDown()) { 856 mStackSupervisor.acquireLaunchWakelock(); 857 } 858 859 if (mPausingActivity != null) { 860 // Have the window manager pause its key dispatching until the new 861 // activity has started. If we're pausing the activity just because 862 // the screen is being turned off and the UI is sleeping, don't interrupt 863 // key dispatch; the same activity will pick it up again on wakeup. 864 if (!uiSleeping) { 865 prev.pauseKeyDispatchingLocked(); 866 } else { 867 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off"); 868 } 869 870 // Schedule a pause timeout in case the app doesn't respond. 871 // We don't give it much time because this directly impacts the 872 // responsiveness seen by the user. 873 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG); 874 msg.obj = prev; 875 prev.pauseTime = SystemClock.uptimeMillis(); 876 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT); 877 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete..."); 878 } else { 879 // This activity failed to schedule the 880 // pause, so just treat it as being paused now. 881 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next."); 882 mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null); 883 } 884 } 885 886 final void activityPausedLocked(IBinder token, boolean timeout, 887 PersistableBundle persistentState) { 888 if (DEBUG_PAUSE) Slog.v( 889 TAG, "Activity paused: token=" + token + ", timeout=" + timeout); 890 891 final ActivityRecord r = isInStackLocked(token); 892 if (r != null) { 893 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 894 if (persistentState != null) { 895 r.persistentState = persistentState; 896 mService.notifyTaskPersisterLocked(r.task, false); 897 } 898 if (mPausingActivity == r) { 899 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r 900 + (timeout ? " (due to timeout)" : " (pause complete)")); 901 r.state = ActivityState.PAUSED; 902 completePauseLocked(); 903 } else { 904 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE, 905 r.userId, System.identityHashCode(r), r.shortComponentName, 906 mPausingActivity != null 907 ? mPausingActivity.shortComponentName : "(none)"); 908 } 909 } 910 } 911 912 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, 913 PersistableBundle persistentState, CharSequence description) { 914 if (r.state != ActivityState.STOPPING) { 915 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r); 916 mHandler.removeMessages(STOP_TIMEOUT_MSG, r); 917 return; 918 } 919 if (persistentState != null) { 920 r.persistentState = persistentState; 921 mService.notifyTaskPersisterLocked(r.task, false); 922 } 923 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle); 924 if (icicle != null) { 925 // If icicle is null, this is happening due to a timeout, so we 926 // haven't really saved the state. 927 r.icicle = icicle; 928 r.haveState = true; 929 r.launchCount = 0; 930 r.updateThumbnail(null, description); 931 } 932 if (!r.stopped) { 933 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)"); 934 mHandler.removeMessages(STOP_TIMEOUT_MSG, r); 935 r.stopped = true; 936 r.state = ActivityState.STOPPED; 937 if (mActivityContainer.mActivityDisplay.mMediaPlayingActivity == r) { 938 mStackSupervisor.setMediaPlayingLocked(r, false); 939 } 940 if (r.finishing) { 941 r.clearOptionsLocked(); 942 } else { 943 if (r.configDestroy) { 944 destroyActivityLocked(r, true, "stop-config"); 945 mStackSupervisor.resumeTopActivitiesLocked(); 946 } else { 947 mStackSupervisor.updatePreviousProcessLocked(r); 948 } 949 } 950 } 951 } 952 953 private void completePauseLocked() { 954 ActivityRecord prev = mPausingActivity; 955 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev); 956 957 if (prev != null) { 958 if (prev.finishing) { 959 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev); 960 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false); 961 } else if (prev.app != null) { 962 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev); 963 if (prev.waitingVisible) { 964 prev.waitingVisible = false; 965 mStackSupervisor.mWaitingVisibleActivities.remove(prev); 966 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v( 967 TAG, "Complete pause, no longer waiting: " + prev); 968 } 969 if (prev.configDestroy) { 970 // The previous is being paused because the configuration 971 // is changing, which means it is actually stopping... 972 // To juggle the fact that we are also starting a new 973 // instance right now, we need to first completely stop 974 // the current instance before starting the new one. 975 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev); 976 destroyActivityLocked(prev, true, "pause-config"); 977 } else if (!isMediaPlaying()) { 978 // If we were playing then resumeTopActivities will release resources before 979 // stopping. 980 mStackSupervisor.mStoppingActivities.add(prev); 981 if (mStackSupervisor.mStoppingActivities.size() > 3 || 982 prev.frontOfTask && mTaskHistory.size() <= 1) { 983 // If we already have a few activities waiting to stop, 984 // then give up on things going idle and start clearing 985 // them out. Or if r is the last of activity of the last task the stack 986 // will be empty and must be cleared immediately. 987 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle"); 988 mStackSupervisor.scheduleIdleLocked(); 989 } else { 990 mStackSupervisor.checkReadyForSleepLocked(); 991 } 992 } 993 } else { 994 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev); 995 prev = null; 996 } 997 mPausingActivity = null; 998 } 999 1000 final ActivityStack topStack = mStackSupervisor.getFocusedStack(); 1001 if (!mService.isSleepingOrShuttingDown()) { 1002 mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null); 1003 } else { 1004 mStackSupervisor.checkReadyForSleepLocked(); 1005 ActivityRecord top = topStack.topRunningActivityLocked(null); 1006 if (top == null || (prev != null && top != prev)) { 1007 // If there are no more activities available to run, 1008 // do resume anyway to start something. Also if the top 1009 // activity on the stack is not the just paused activity, 1010 // we need to go ahead and resume it to ensure we complete 1011 // an in-flight app switch. 1012 mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null); 1013 } 1014 } 1015 1016 if (prev != null) { 1017 prev.resumeKeyDispatchingLocked(); 1018 1019 if (prev.app != null && prev.cpuTimeAtResume > 0 1020 && mService.mBatteryStatsService.isOnBattery()) { 1021 long diff; 1022 synchronized (mService.mProcessCpuThread) { 1023 diff = mService.mProcessCpuTracker.getCpuTimeForPid(prev.app.pid) 1024 - prev.cpuTimeAtResume; 1025 } 1026 if (diff > 0) { 1027 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics(); 1028 synchronized (bsi) { 1029 BatteryStatsImpl.Uid.Proc ps = 1030 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid, 1031 prev.info.packageName); 1032 if (ps != null) { 1033 ps.addForegroundTimeLocked(diff); 1034 } 1035 } 1036 } 1037 } 1038 prev.cpuTimeAtResume = 0; // reset it 1039 } 1040 } 1041 1042 /** 1043 * Once we know that we have asked an application to put an activity in 1044 * the resumed state (either by launching it or explicitly telling it), 1045 * this function updates the rest of our state to match that fact. 1046 */ 1047 private void completeResumeLocked(ActivityRecord next) { 1048 next.idle = false; 1049 next.results = null; 1050 next.newIntents = null; 1051 1052 if (next.isHomeActivity() && next.isNotResolverActivity()) { 1053 ProcessRecord app = next.task.mActivities.get(0).app; 1054 if (app != null && app != mService.mHomeProcess) { 1055 mService.mHomeProcess = app; 1056 } 1057 } 1058 1059 if (next.nowVisible) { 1060 // We won't get a call to reportActivityVisibleLocked() so dismiss lockscreen now. 1061 mStackSupervisor.notifyActivityDrawnForKeyguard(); 1062 } 1063 1064 // schedule an idle timeout in case the app doesn't do it for us. 1065 mStackSupervisor.scheduleIdleTimeoutLocked(next); 1066 1067 mStackSupervisor.reportResumedActivityLocked(next); 1068 1069 next.resumeKeyDispatchingLocked(); 1070 mNoAnimActivities.clear(); 1071 1072 // Mark the point when the activity is resuming 1073 // TODO: To be more accurate, the mark should be before the onCreate, 1074 // not after the onResume. But for subsequent starts, onResume is fine. 1075 if (next.app != null) { 1076 synchronized (mService.mProcessCpuThread) { 1077 next.cpuTimeAtResume = mService.mProcessCpuTracker.getCpuTimeForPid(next.app.pid); 1078 } 1079 } else { 1080 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process 1081 } 1082 1083 // If we are resuming the activity that we had last screenshotted, then we know it will be 1084 // updated, so invalidate the last screenshot to ensure we take a fresh one when requested 1085 if (next == mLastScreenshotActivity) { 1086 invalidateLastScreenshot(); 1087 } 1088 next.returningOptions = null; 1089 } 1090 1091 private void setVisibile(ActivityRecord r, boolean visible) { 1092 r.visible = visible; 1093 mWindowManager.setAppVisibility(r.appToken, visible); 1094 final ArrayList<ActivityContainer> containers = r.mChildContainers; 1095 for (int containerNdx = containers.size() - 1; containerNdx >= 0; --containerNdx) { 1096 ActivityContainer container = containers.get(containerNdx); 1097 container.setVisible(visible); 1098 } 1099 } 1100 1101 // Find the first visible activity above the passed activity and if it is translucent return it 1102 // otherwise return null; 1103 ActivityRecord findNextTranslucentActivity(ActivityRecord r) { 1104 TaskRecord task = r.task; 1105 if (task == null) { 1106 return null; 1107 } 1108 1109 ActivityStack stack = task.stack; 1110 if (stack == null) { 1111 return null; 1112 } 1113 1114 int stackNdx = mStacks.indexOf(stack); 1115 1116 ArrayList<TaskRecord> tasks = stack.mTaskHistory; 1117 int taskNdx = tasks.indexOf(task); 1118 1119 ArrayList<ActivityRecord> activities = task.mActivities; 1120 int activityNdx = activities.indexOf(r) + 1; 1121 1122 final int numStacks = mStacks.size(); 1123 while (stackNdx < numStacks) { 1124 tasks = mStacks.get(stackNdx).mTaskHistory; 1125 final int numTasks = tasks.size(); 1126 while (taskNdx < numTasks) { 1127 activities = tasks.get(taskNdx).mActivities; 1128 final int numActivities = activities.size(); 1129 while (activityNdx < numActivities) { 1130 final ActivityRecord activity = activities.get(activityNdx); 1131 if (!activity.finishing) { 1132 return activity.fullscreen ? null : activity; 1133 } 1134 ++activityNdx; 1135 } 1136 activityNdx = 0; 1137 ++taskNdx; 1138 } 1139 taskNdx = 0; 1140 ++stackNdx; 1141 } 1142 1143 return null; 1144 } 1145 1146 // Checks if any of the stacks above this one has a fullscreen activity behind it. 1147 // If so, this stack is hidden, otherwise it is visible. 1148 private boolean isStackVisible() { 1149 if (!isAttached()) { 1150 return false; 1151 } 1152 1153 if (mStackSupervisor.isFrontStack(this)) { 1154 return true; 1155 } 1156 1157 /** 1158 * Start at the task above this one and go up, looking for a visible 1159 * fullscreen activity, or a translucent activity that requested the 1160 * wallpaper to be shown behind it. 1161 */ 1162 for (int i = mStacks.indexOf(this) + 1; i < mStacks.size(); i++) { 1163 final ArrayList<TaskRecord> tasks = mStacks.get(i).getAllTasks(); 1164 for (int taskNdx = 0; taskNdx < tasks.size(); taskNdx++) { 1165 final TaskRecord task = tasks.get(taskNdx); 1166 final ArrayList<ActivityRecord> activities = task.mActivities; 1167 for (int activityNdx = 0; activityNdx < activities.size(); activityNdx++) { 1168 final ActivityRecord r = activities.get(activityNdx); 1169 1170 // Conditions for an activity to obscure the stack we're 1171 // examining: 1172 // 1. Not Finishing AND Visible AND: 1173 // 2. Either: 1174 // - Full Screen Activity OR 1175 // - On top of Home and our stack is NOT home 1176 if (!r.finishing && r.visible && (r.fullscreen || 1177 (!isHomeStack() && r.frontOfTask && task.isOverHomeStack()))) { 1178 return false; 1179 } 1180 } 1181 } 1182 } 1183 1184 return true; 1185 } 1186 1187 /** 1188 * Make sure that all activities that need to be visible (that is, they 1189 * currently can be seen by the user) actually are. 1190 */ 1191 final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges) { 1192 ActivityRecord top = topRunningActivityLocked(null); 1193 if (top == null) { 1194 return; 1195 } 1196 if (DEBUG_VISBILITY) Slog.v( 1197 TAG, "ensureActivitiesVisible behind " + top 1198 + " configChanges=0x" + Integer.toHexString(configChanges)); 1199 1200 if (mTranslucentActivityWaiting != top) { 1201 mUndrawnActivitiesBelowTopTranslucent.clear(); 1202 if (mTranslucentActivityWaiting != null) { 1203 // Call the callback with a timeout indication. 1204 notifyActivityDrawnLocked(null); 1205 mTranslucentActivityWaiting = null; 1206 } 1207 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG); 1208 } 1209 1210 // If the top activity is not fullscreen, then we need to 1211 // make sure any activities under it are now visible. 1212 boolean aboveTop = true; 1213 boolean behindFullscreen = !isStackVisible(); 1214 1215 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1216 final TaskRecord task = mTaskHistory.get(taskNdx); 1217 final ArrayList<ActivityRecord> activities = task.mActivities; 1218 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1219 final ActivityRecord r = activities.get(activityNdx); 1220 if (r.finishing) { 1221 continue; 1222 } 1223 if (aboveTop && r != top) { 1224 continue; 1225 } 1226 aboveTop = false; 1227 // mLaunchingBehind: Activities launching behind are at the back of the task stack 1228 // but must be drawn initially for the animation as though they were visible. 1229 if (!behindFullscreen || r.mLaunchTaskBehind) { 1230 if (DEBUG_VISBILITY) Slog.v( 1231 TAG, "Make visible? " + r + " finishing=" + r.finishing 1232 + " state=" + r.state); 1233 1234 // First: if this is not the current activity being started, make 1235 // sure it matches the current configuration. 1236 if (r != starting) { 1237 ensureActivityConfigurationLocked(r, 0); 1238 } 1239 1240 if (r.app == null || r.app.thread == null) { 1241 // This activity needs to be visible, but isn't even 1242 // running... get it started, but don't resume it 1243 // at this point. 1244 if (DEBUG_VISBILITY) Slog.v(TAG, "Start and freeze screen for " + r); 1245 if (r != starting) { 1246 r.startFreezingScreenLocked(r.app, configChanges); 1247 } 1248 if (!r.visible || r.mLaunchTaskBehind) { 1249 if (DEBUG_VISBILITY) Slog.v( 1250 TAG, "Starting and making visible: " + r); 1251 setVisibile(r, true); 1252 } 1253 if (r != starting) { 1254 mStackSupervisor.startSpecificActivityLocked(r, false, false); 1255 } 1256 1257 } else if (r.visible) { 1258 // If this activity is already visible, then there is nothing 1259 // else to do here. 1260 if (DEBUG_VISBILITY) Slog.v(TAG, "Skipping: already visible at " + r); 1261 r.stopFreezingScreenLocked(false); 1262 try { 1263 if (r.returningOptions != null) { 1264 r.app.thread.scheduleOnNewActivityOptions(r.appToken, 1265 r.returningOptions); 1266 } 1267 } catch(RemoteException e) { 1268 } 1269 } else { 1270 // This activity is not currently visible, but is running. 1271 // Tell it to become visible. 1272 r.visible = true; 1273 if (r.state != ActivityState.RESUMED && r != starting) { 1274 // If this activity is paused, tell it 1275 // to now show its window. 1276 if (DEBUG_VISBILITY) Slog.v( 1277 TAG, "Making visible and scheduling visibility: " + r); 1278 try { 1279 if (mTranslucentActivityWaiting != null) { 1280 r.updateOptionsLocked(r.returningOptions); 1281 mUndrawnActivitiesBelowTopTranslucent.add(r); 1282 } 1283 setVisibile(r, true); 1284 r.sleeping = false; 1285 r.app.pendingUiClean = true; 1286 r.app.thread.scheduleWindowVisibility(r.appToken, true); 1287 r.stopFreezingScreenLocked(false); 1288 } catch (Exception e) { 1289 // Just skip on any failure; we'll make it 1290 // visible when it next restarts. 1291 Slog.w(TAG, "Exception thrown making visibile: " 1292 + r.intent.getComponent(), e); 1293 } 1294 } 1295 } 1296 1297 // Aggregate current change flags. 1298 configChanges |= r.configChangeFlags; 1299 1300 if (r.fullscreen) { 1301 // At this point, nothing else needs to be shown 1302 if (DEBUG_VISBILITY) Slog.v(TAG, "Fullscreen: at " + r); 1303 behindFullscreen = true; 1304 } else if (!isHomeStack() && r.frontOfTask && task.isOverHomeStack()) { 1305 if (DEBUG_VISBILITY) Slog.v(TAG, "Showing home: at " + r); 1306 behindFullscreen = true; 1307 } 1308 } else { 1309 if (DEBUG_VISBILITY) Slog.v( 1310 TAG, "Make invisible? " + r + " finishing=" + r.finishing 1311 + " state=" + r.state 1312 + " behindFullscreen=" + behindFullscreen); 1313 // Now for any activities that aren't visible to the user, make 1314 // sure they no longer are keeping the screen frozen. 1315 if (r.visible) { 1316 if (DEBUG_VISBILITY) Slog.v(TAG, "Making invisible: " + r); 1317 try { 1318 setVisibile(r, false); 1319 switch (r.state) { 1320 case STOPPING: 1321 case STOPPED: 1322 if (r.app != null && r.app.thread != null) { 1323 if (DEBUG_VISBILITY) Slog.v( 1324 TAG, "Scheduling invisibility: " + r); 1325 r.app.thread.scheduleWindowVisibility(r.appToken, false); 1326 } 1327 break; 1328 1329 case INITIALIZING: 1330 case RESUMED: 1331 case PAUSING: 1332 case PAUSED: 1333 // This case created for transitioning activities from 1334 // translucent to opaque {@link Activity#convertToOpaque}. 1335 if (getMediaPlayer() == r) { 1336 releaseMediaResources(); 1337 } else { 1338 if (!mStackSupervisor.mStoppingActivities.contains(r)) { 1339 mStackSupervisor.mStoppingActivities.add(r); 1340 } 1341 mStackSupervisor.scheduleIdleLocked(); 1342 } 1343 break; 1344 1345 default: 1346 break; 1347 } 1348 } catch (Exception e) { 1349 // Just skip on any failure; we'll make it 1350 // visible when it next restarts. 1351 Slog.w(TAG, "Exception thrown making hidden: " 1352 + r.intent.getComponent(), e); 1353 } 1354 } else { 1355 if (DEBUG_VISBILITY) Slog.v(TAG, "Already invisible: " + r); 1356 } 1357 } 1358 } 1359 } 1360 1361 if (mTranslucentActivityWaiting != null && 1362 mUndrawnActivitiesBelowTopTranslucent.isEmpty()) { 1363 // Nothing is getting drawn or everything was already visible, don't wait for timeout. 1364 notifyActivityDrawnLocked(null); 1365 } 1366 } 1367 1368 void convertToTranslucent(ActivityRecord r) { 1369 mTranslucentActivityWaiting = r; 1370 mUndrawnActivitiesBelowTopTranslucent.clear(); 1371 mHandler.sendEmptyMessageDelayed(TRANSLUCENT_TIMEOUT_MSG, TRANSLUCENT_CONVERSION_TIMEOUT); 1372 } 1373 1374 /** 1375 * Called as activities below the top translucent activity are redrawn. When the last one is 1376 * redrawn notify the top activity by calling 1377 * {@link Activity#onTranslucentConversionComplete}. 1378 * 1379 * @param r The most recent background activity to be drawn. Or, if r is null then a timeout 1380 * occurred and the activity will be notified immediately. 1381 */ 1382 void notifyActivityDrawnLocked(ActivityRecord r) { 1383 mActivityContainer.setDrawn(); 1384 if ((r == null) 1385 || (mUndrawnActivitiesBelowTopTranslucent.remove(r) && 1386 mUndrawnActivitiesBelowTopTranslucent.isEmpty())) { 1387 // The last undrawn activity below the top has just been drawn. If there is an 1388 // opaque activity at the top, notify it that it can become translucent safely now. 1389 final ActivityRecord waitingActivity = mTranslucentActivityWaiting; 1390 mTranslucentActivityWaiting = null; 1391 mUndrawnActivitiesBelowTopTranslucent.clear(); 1392 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG); 1393 1394 if (waitingActivity != null) { 1395 mWindowManager.setWindowOpaque(waitingActivity.appToken, false); 1396 if (waitingActivity.app != null && waitingActivity.app.thread != null) { 1397 try { 1398 waitingActivity.app.thread.scheduleTranslucentConversionComplete( 1399 waitingActivity.appToken, r != null); 1400 } catch (RemoteException e) { 1401 } 1402 } 1403 } 1404 } 1405 } 1406 1407 /** If any activities below the top running one are in the INITIALIZING state and they have a 1408 * starting window displayed then remove that starting window. It is possible that the activity 1409 * in this state will never resumed in which case that starting window will be orphaned. */ 1410 void cancelInitializingActivities() { 1411 final ActivityRecord topActivity = topRunningActivityLocked(null); 1412 boolean aboveTop = true; 1413 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1414 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 1415 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1416 final ActivityRecord r = activities.get(activityNdx); 1417 if (aboveTop) { 1418 if (r == topActivity) { 1419 aboveTop = false; 1420 } 1421 continue; 1422 } 1423 1424 if (r.state == ActivityState.INITIALIZING && r.mStartingWindowShown) { 1425 if (DEBUG_VISBILITY) Slog.w(TAG, "Found orphaned starting window " + r); 1426 r.mStartingWindowShown = false; 1427 mWindowManager.removeAppStartingWindow(r.appToken); 1428 } 1429 } 1430 } 1431 } 1432 1433 /** 1434 * Ensure that the top activity in the stack is resumed. 1435 * 1436 * @param prev The previously resumed activity, for when in the process 1437 * of pausing; can be null to call from elsewhere. 1438 * 1439 * @return Returns true if something is being resumed, or false if 1440 * nothing happened. 1441 */ 1442 final boolean resumeTopActivityLocked(ActivityRecord prev) { 1443 return resumeTopActivityLocked(prev, null); 1444 } 1445 1446 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) { 1447 if (ActivityManagerService.DEBUG_LOCKSCREEN) mService.logLockScreen(""); 1448 1449 ActivityRecord parent = mActivityContainer.mParentActivity; 1450 if ((parent != null && parent.state != ActivityState.RESUMED) || 1451 !mActivityContainer.isAttachedLocked()) { 1452 // Do not resume this stack if its parent is not resumed. 1453 // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st. 1454 return false; 1455 } 1456 1457 cancelInitializingActivities(); 1458 1459 // Find the first activity that is not finishing. 1460 ActivityRecord next = topRunningActivityLocked(null); 1461 1462 // Remember how we'll process this pause/resume situation, and ensure 1463 // that the state is reset however we wind up proceeding. 1464 final boolean userLeaving = mStackSupervisor.mUserLeaving; 1465 mStackSupervisor.mUserLeaving = false; 1466 1467 final TaskRecord prevTask = prev != null ? prev.task : null; 1468 if (next == null) { 1469 // There are no more activities! Let's just start up the 1470 // Launcher... 1471 ActivityOptions.abort(options); 1472 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: No more activities go home"); 1473 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1474 // Only resume home if on home display 1475 final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ? 1476 HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo(); 1477 return isOnHomeDisplay() && 1478 mStackSupervisor.resumeHomeStackTask(returnTaskType, prev); 1479 } 1480 1481 next.delayedResume = false; 1482 1483 // If the top activity is the resumed one, nothing to do. 1484 if (mResumedActivity == next && next.state == ActivityState.RESUMED && 1485 mStackSupervisor.allResumedActivitiesComplete()) { 1486 // Make sure we have executed any pending transitions, since there 1487 // should be nothing left to do at this point. 1488 mWindowManager.executeAppTransition(); 1489 mNoAnimActivities.clear(); 1490 ActivityOptions.abort(options); 1491 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Top activity resumed " + next); 1492 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1493 return false; 1494 } 1495 1496 final TaskRecord nextTask = next.task; 1497 if (prevTask != null && prevTask.stack == this && 1498 prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) { 1499 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1500 if (prevTask == nextTask) { 1501 prevTask.setFrontOfTask(); 1502 } else if (prevTask != topTask()) { 1503 // This task is going away but it was supposed to return to the home stack. 1504 // Now the task above it has to return to the home task instead. 1505 final int taskNdx = mTaskHistory.indexOf(prevTask) + 1; 1506 mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE); 1507 } else { 1508 if (DEBUG_STATES && isOnHomeDisplay()) Slog.d(TAG, 1509 "resumeTopActivityLocked: Launching home next"); 1510 // Only resume home if on home display 1511 final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ? 1512 HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo(); 1513 return isOnHomeDisplay() && 1514 mStackSupervisor.resumeHomeStackTask(returnTaskType, prev); 1515 } 1516 } 1517 1518 // If we are sleeping, and there is no resumed activity, and the top 1519 // activity is paused, well that is the state we want. 1520 if (mService.isSleepingOrShuttingDown() 1521 && mLastPausedActivity == next 1522 && mStackSupervisor.allPausedActivitiesComplete()) { 1523 // Make sure we have executed any pending transitions, since there 1524 // should be nothing left to do at this point. 1525 mWindowManager.executeAppTransition(); 1526 mNoAnimActivities.clear(); 1527 ActivityOptions.abort(options); 1528 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Going to sleep and all paused"); 1529 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1530 return false; 1531 } 1532 1533 // Make sure that the user who owns this activity is started. If not, 1534 // we will just leave it as is because someone should be bringing 1535 // another user's activities to the top of the stack. 1536 if (mService.mStartedUsers.get(next.userId) == null) { 1537 Slog.w(TAG, "Skipping resume of top activity " + next 1538 + ": user " + next.userId + " is stopped"); 1539 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1540 return false; 1541 } 1542 1543 // The activity may be waiting for stop, but that is no longer 1544 // appropriate for it. 1545 mStackSupervisor.mStoppingActivities.remove(next); 1546 mStackSupervisor.mGoingToSleepActivities.remove(next); 1547 next.sleeping = false; 1548 mStackSupervisor.mWaitingVisibleActivities.remove(next); 1549 1550 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next); 1551 1552 // If we are currently pausing an activity, then don't do anything 1553 // until that is done. 1554 if (!mStackSupervisor.allPausedActivitiesComplete()) { 1555 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG, 1556 "resumeTopActivityLocked: Skip resume: some activity pausing."); 1557 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1558 return false; 1559 } 1560 1561 // Okay we are now going to start a switch, to 'next'. We may first 1562 // have to pause the current activity, but this is an important point 1563 // where we have decided to go to 'next' so keep track of that. 1564 // XXX "App Redirected" dialog is getting too many false positives 1565 // at this point, so turn off for now. 1566 if (false) { 1567 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) { 1568 long now = SystemClock.uptimeMillis(); 1569 final boolean inTime = mLastStartedActivity.startTime != 0 1570 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now; 1571 final int lastUid = mLastStartedActivity.info.applicationInfo.uid; 1572 final int nextUid = next.info.applicationInfo.uid; 1573 if (inTime && lastUid != nextUid 1574 && lastUid != next.launchedFromUid 1575 && mService.checkPermission( 1576 android.Manifest.permission.STOP_APP_SWITCHES, 1577 -1, next.launchedFromUid) 1578 != PackageManager.PERMISSION_GRANTED) { 1579 mService.showLaunchWarningLocked(mLastStartedActivity, next); 1580 } else { 1581 next.startTime = now; 1582 mLastStartedActivity = next; 1583 } 1584 } else { 1585 next.startTime = SystemClock.uptimeMillis(); 1586 mLastStartedActivity = next; 1587 } 1588 } 1589 1590 // We need to start pausing the current activity so the top one 1591 // can be resumed... 1592 boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving); 1593 if (mResumedActivity != null) { 1594 pausing = true; 1595 startPausingLocked(userLeaving, false); 1596 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Pausing " + mResumedActivity); 1597 } 1598 if (pausing) { 1599 if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG, 1600 "resumeTopActivityLocked: Skip resume: need to start pausing"); 1601 // At this point we want to put the upcoming activity's process 1602 // at the top of the LRU list, since we know we will be needing it 1603 // very soon and it would be a waste to let it get killed if it 1604 // happens to be sitting towards the end. 1605 if (next.app != null && next.app.thread != null) { 1606 mService.updateLruProcessLocked(next.app, true, null); 1607 } 1608 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1609 return true; 1610 } 1611 1612 // If the most recent activity was noHistory but was only stopped rather 1613 // than stopped+finished because the device went to sleep, we need to make 1614 // sure to finish it as we're making a new activity topmost. 1615 if (mService.isSleeping() && mLastNoHistoryActivity != null && 1616 !mLastNoHistoryActivity.finishing) { 1617 if (DEBUG_STATES) Slog.d(TAG, "no-history finish of " + mLastNoHistoryActivity + 1618 " on new resume"); 1619 requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED, 1620 null, "no-history", false); 1621 mLastNoHistoryActivity = null; 1622 } 1623 1624 if (prev != null && prev != next) { 1625 if (!prev.waitingVisible && next != null && !next.nowVisible) { 1626 prev.waitingVisible = true; 1627 mStackSupervisor.mWaitingVisibleActivities.add(prev); 1628 if (DEBUG_SWITCH) Slog.v( 1629 TAG, "Resuming top, waiting visible to hide: " + prev); 1630 } else { 1631 // The next activity is already visible, so hide the previous 1632 // activity's windows right now so we can show the new one ASAP. 1633 // We only do this if the previous is finishing, which should mean 1634 // it is on top of the one being resumed so hiding it quickly 1635 // is good. Otherwise, we want to do the normal route of allowing 1636 // the resumed activity to be shown so we can decide if the 1637 // previous should actually be hidden depending on whether the 1638 // new one is found to be full-screen or not. 1639 if (prev.finishing) { 1640 mWindowManager.setAppVisibility(prev.appToken, false); 1641 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: " 1642 + prev + ", waitingVisible=" 1643 + (prev != null ? prev.waitingVisible : null) 1644 + ", nowVisible=" + next.nowVisible); 1645 } else { 1646 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: " 1647 + prev + ", waitingVisible=" 1648 + (prev != null ? prev.waitingVisible : null) 1649 + ", nowVisible=" + next.nowVisible); 1650 } 1651 } 1652 } 1653 1654 // Launching this app's activity, make sure the app is no longer 1655 // considered stopped. 1656 try { 1657 AppGlobals.getPackageManager().setPackageStoppedState( 1658 next.packageName, false, next.userId); /* TODO: Verify if correct userid */ 1659 } catch (RemoteException e1) { 1660 } catch (IllegalArgumentException e) { 1661 Slog.w(TAG, "Failed trying to unstop package " 1662 + next.packageName + ": " + e); 1663 } 1664 1665 // We are starting up the next activity, so tell the window manager 1666 // that the previous one will be hidden soon. This way it can know 1667 // to ignore it when computing the desired screen orientation. 1668 boolean anim = true; 1669 if (prev != null) { 1670 if (prev.finishing) { 1671 if (DEBUG_TRANSITION) Slog.v(TAG, 1672 "Prepare close transition: prev=" + prev); 1673 if (mNoAnimActivities.contains(prev)) { 1674 anim = false; 1675 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 1676 } else { 1677 mWindowManager.prepareAppTransition(prev.task == next.task 1678 ? AppTransition.TRANSIT_ACTIVITY_CLOSE 1679 : AppTransition.TRANSIT_TASK_CLOSE, false); 1680 } 1681 mWindowManager.setAppWillBeHidden(prev.appToken); 1682 mWindowManager.setAppVisibility(prev.appToken, false); 1683 } else { 1684 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: prev=" + prev); 1685 if (mNoAnimActivities.contains(next)) { 1686 anim = false; 1687 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 1688 } else { 1689 mWindowManager.prepareAppTransition(prev.task == next.task 1690 ? AppTransition.TRANSIT_ACTIVITY_OPEN 1691 : next.mLaunchTaskBehind 1692 ? AppTransition.TRANSIT_TASK_OPEN_BEHIND 1693 : AppTransition.TRANSIT_TASK_OPEN, false); 1694 } 1695 } 1696 if (false) { 1697 mWindowManager.setAppWillBeHidden(prev.appToken); 1698 mWindowManager.setAppVisibility(prev.appToken, false); 1699 } 1700 } else { 1701 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: no previous"); 1702 if (mNoAnimActivities.contains(next)) { 1703 anim = false; 1704 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 1705 } else { 1706 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_ACTIVITY_OPEN, false); 1707 } 1708 } 1709 1710 Bundle resumeAnimOptions = null; 1711 if (anim) { 1712 ActivityOptions opts = next.getOptionsForTargetActivityLocked(); 1713 if (opts != null) { 1714 resumeAnimOptions = opts.toBundle(); 1715 } 1716 next.applyOptionsLocked(); 1717 } else { 1718 next.clearOptionsLocked(); 1719 } 1720 1721 ActivityStack lastStack = mStackSupervisor.getLastStack(); 1722 if (next.app != null && next.app.thread != null) { 1723 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next); 1724 1725 // This activity is now becoming visible. 1726 mWindowManager.setAppVisibility(next.appToken, true); 1727 1728 // schedule launch ticks to collect information about slow apps. 1729 next.startLaunchTickingLocked(); 1730 1731 ActivityRecord lastResumedActivity = 1732 lastStack == null ? null :lastStack.mResumedActivity; 1733 ActivityState lastState = next.state; 1734 1735 mService.updateCpuStats(); 1736 1737 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)"); 1738 next.state = ActivityState.RESUMED; 1739 mResumedActivity = next; 1740 next.task.touchActiveTime(); 1741 mService.addRecentTaskLocked(next.task); 1742 mService.updateLruProcessLocked(next.app, true, null); 1743 updateLRUListLocked(next); 1744 mService.updateOomAdjLocked(); 1745 1746 // Have the window manager re-evaluate the orientation of 1747 // the screen based on the new activity order. 1748 boolean notUpdated = true; 1749 if (mStackSupervisor.isFrontStack(this)) { 1750 Configuration config = mWindowManager.updateOrientationFromAppTokens( 1751 mService.mConfiguration, 1752 next.mayFreezeScreenLocked(next.app) ? next.appToken : null); 1753 if (config != null) { 1754 next.frozenBeforeDestroy = true; 1755 } 1756 notUpdated = !mService.updateConfigurationLocked(config, next, false, false); 1757 } 1758 1759 if (notUpdated) { 1760 // The configuration update wasn't able to keep the existing 1761 // instance of the activity, and instead started a new one. 1762 // We should be all done, but let's just make sure our activity 1763 // is still at the top and schedule another run if something 1764 // weird happened. 1765 ActivityRecord nextNext = topRunningActivityLocked(null); 1766 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, 1767 "Activity config changed during resume: " + next 1768 + ", new next: " + nextNext); 1769 if (nextNext != next) { 1770 // Do over! 1771 mStackSupervisor.scheduleResumeTopActivities(); 1772 } 1773 if (mStackSupervisor.reportResumedActivityLocked(next)) { 1774 mNoAnimActivities.clear(); 1775 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1776 return true; 1777 } 1778 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1779 return false; 1780 } 1781 1782 try { 1783 // Deliver all pending results. 1784 ArrayList<ResultInfo> a = next.results; 1785 if (a != null) { 1786 final int N = a.size(); 1787 if (!next.finishing && N > 0) { 1788 if (DEBUG_RESULTS) Slog.v( 1789 TAG, "Delivering results to " + next 1790 + ": " + a); 1791 next.app.thread.scheduleSendResult(next.appToken, a); 1792 } 1793 } 1794 1795 if (next.newIntents != null) { 1796 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken); 1797 } 1798 1799 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, 1800 next.userId, System.identityHashCode(next), 1801 next.task.taskId, next.shortComponentName); 1802 1803 next.sleeping = false; 1804 mService.showAskCompatModeDialogLocked(next); 1805 next.app.pendingUiClean = true; 1806 next.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_TOP); 1807 next.clearOptionsLocked(); 1808 next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState, 1809 mService.isNextTransitionForward(), resumeAnimOptions); 1810 1811 mStackSupervisor.checkReadyForSleepLocked(); 1812 1813 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Resumed " + next); 1814 } catch (Exception e) { 1815 // Whoops, need to restart this activity! 1816 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to " 1817 + lastState + ": " + next); 1818 next.state = lastState; 1819 if (lastStack != null) { 1820 lastStack.mResumedActivity = lastResumedActivity; 1821 } 1822 Slog.i(TAG, "Restarting because process died: " + next); 1823 if (!next.hasBeenLaunched) { 1824 next.hasBeenLaunched = true; 1825 } else if (SHOW_APP_STARTING_PREVIEW && lastStack != null && 1826 mStackSupervisor.isFrontStack(lastStack)) { 1827 mWindowManager.setAppStartingWindow( 1828 next.appToken, next.packageName, next.theme, 1829 mService.compatibilityInfoForPackageLocked(next.info.applicationInfo), 1830 next.nonLocalizedLabel, next.labelRes, next.icon, next.logo, 1831 next.windowFlags, null, true); 1832 } 1833 mStackSupervisor.startSpecificActivityLocked(next, true, false); 1834 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1835 return true; 1836 } 1837 1838 // From this point on, if something goes wrong there is no way 1839 // to recover the activity. 1840 try { 1841 next.visible = true; 1842 completeResumeLocked(next); 1843 } catch (Exception e) { 1844 // If any exception gets thrown, toss away this 1845 // activity and try the next one. 1846 Slog.w(TAG, "Exception thrown during resume of " + next, e); 1847 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null, 1848 "resume-exception", true); 1849 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1850 return true; 1851 } 1852 next.stopped = false; 1853 1854 } else { 1855 // Whoops, need to restart this activity! 1856 if (!next.hasBeenLaunched) { 1857 next.hasBeenLaunched = true; 1858 } else { 1859 if (SHOW_APP_STARTING_PREVIEW) { 1860 mWindowManager.setAppStartingWindow( 1861 next.appToken, next.packageName, next.theme, 1862 mService.compatibilityInfoForPackageLocked( 1863 next.info.applicationInfo), 1864 next.nonLocalizedLabel, 1865 next.labelRes, next.icon, next.logo, next.windowFlags, 1866 null, true); 1867 } 1868 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next); 1869 } 1870 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Restarting " + next); 1871 mStackSupervisor.startSpecificActivityLocked(next, true, true); 1872 } 1873 1874 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1875 return true; 1876 } 1877 1878 private void insertTaskAtTop(TaskRecord task) { 1879 // If this is being moved to the top by another activity or being launched from the home 1880 // activity, set mOnTopOfHome accordingly. 1881 if (isOnHomeDisplay()) { 1882 ActivityStack lastStack = mStackSupervisor.getLastStack(); 1883 final boolean fromHome = lastStack.isHomeStack(); 1884 if (!isHomeStack() && (fromHome || topTask() != task)) { 1885 task.setTaskToReturnTo(fromHome 1886 ? lastStack.topTask() == null 1887 ? HOME_ACTIVITY_TYPE 1888 : lastStack.topTask().taskType 1889 : APPLICATION_ACTIVITY_TYPE); 1890 } 1891 } else { 1892 task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE); 1893 } 1894 1895 mTaskHistory.remove(task); 1896 // Now put task at top. 1897 int taskNdx = mTaskHistory.size(); 1898 if (!isCurrentProfileLocked(task.userId)) { 1899 // Put non-current user tasks below current user tasks. 1900 while (--taskNdx >= 0) { 1901 if (!isCurrentProfileLocked(mTaskHistory.get(taskNdx).userId)) { 1902 break; 1903 } 1904 } 1905 ++taskNdx; 1906 } 1907 mTaskHistory.add(taskNdx, task); 1908 updateTaskMovement(task, true); 1909 } 1910 1911 final void startActivityLocked(ActivityRecord r, boolean newTask, 1912 boolean doResume, boolean keepCurTransition, Bundle options) { 1913 TaskRecord rTask = r.task; 1914 final int taskId = rTask.taskId; 1915 // mLaunchTaskBehind tasks get placed at the back of the task stack. 1916 if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) { 1917 // Last activity in task had been removed or ActivityManagerService is reusing task. 1918 // Insert or replace. 1919 // Might not even be in. 1920 insertTaskAtTop(rTask); 1921 mWindowManager.moveTaskToTop(taskId); 1922 } 1923 TaskRecord task = null; 1924 if (!newTask) { 1925 // If starting in an existing task, find where that is... 1926 boolean startIt = true; 1927 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1928 task = mTaskHistory.get(taskNdx); 1929 if (task.getTopActivity() == null) { 1930 // All activities in task are finishing. 1931 continue; 1932 } 1933 if (task == r.task) { 1934 // Here it is! Now, if this is not yet visible to the 1935 // user, then just add it without starting; it will 1936 // get started when the user navigates back to it. 1937 if (!startIt) { 1938 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task " 1939 + task, new RuntimeException("here").fillInStackTrace()); 1940 task.addActivityToTop(r); 1941 r.putInHistory(); 1942 mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken, 1943 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, 1944 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, 1945 r.userId, r.info.configChanges, task.voiceSession != null, 1946 r.mLaunchTaskBehind); 1947 if (VALIDATE_TOKENS) { 1948 validateAppTokensLocked(); 1949 } 1950 ActivityOptions.abort(options); 1951 return; 1952 } 1953 break; 1954 } else if (task.numFullscreen > 0) { 1955 startIt = false; 1956 } 1957 } 1958 } 1959 1960 // Place a new activity at top of stack, so it is next to interact 1961 // with the user. 1962 1963 // If we are not placing the new activity frontmost, we do not want 1964 // to deliver the onUserLeaving callback to the actual frontmost 1965 // activity 1966 if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) { 1967 mStackSupervisor.mUserLeaving = false; 1968 if (DEBUG_USER_LEAVING) Slog.v(TAG, 1969 "startActivity() behind front, mUserLeaving=false"); 1970 } 1971 1972 task = r.task; 1973 1974 // Slot the activity into the history stack and proceed 1975 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task, 1976 new RuntimeException("here").fillInStackTrace()); 1977 task.addActivityToTop(r); 1978 task.setFrontOfTask(); 1979 1980 r.putInHistory(); 1981 if (!isHomeStack() || numActivities() > 0) { 1982 // We want to show the starting preview window if we are 1983 // switching to a new task, or the next activity's process is 1984 // not currently running. 1985 boolean showStartingIcon = newTask; 1986 ProcessRecord proc = r.app; 1987 if (proc == null) { 1988 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid); 1989 } 1990 if (proc == null || proc.thread == null) { 1991 showStartingIcon = true; 1992 } 1993 if (DEBUG_TRANSITION) Slog.v(TAG, 1994 "Prepare open transition: starting " + r); 1995 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 1996 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition); 1997 mNoAnimActivities.add(r); 1998 } else { 1999 mWindowManager.prepareAppTransition(newTask 2000 ? r.mLaunchTaskBehind 2001 ? AppTransition.TRANSIT_TASK_OPEN_BEHIND 2002 : AppTransition.TRANSIT_TASK_OPEN 2003 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition); 2004 mNoAnimActivities.remove(r); 2005 } 2006 mWindowManager.addAppToken(task.mActivities.indexOf(r), 2007 r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, 2008 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId, 2009 r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind); 2010 boolean doShow = true; 2011 if (newTask) { 2012 // Even though this activity is starting fresh, we still need 2013 // to reset it to make sure we apply affinities to move any 2014 // existing activities from other tasks in to it. 2015 // If the caller has requested that the target task be 2016 // reset, then do so. 2017 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) { 2018 resetTaskIfNeededLocked(r, r); 2019 doShow = topRunningNonDelayedActivityLocked(null) == r; 2020 } 2021 } else if (options != null && new ActivityOptions(options).getAnimationType() 2022 == ActivityOptions.ANIM_SCENE_TRANSITION) { 2023 doShow = false; 2024 } 2025 if (r.mLaunchTaskBehind) { 2026 // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we 2027 // tell WindowManager that r is visible even though it is at the back of the stack. 2028 mWindowManager.setAppVisibility(r.appToken, true); 2029 ensureActivitiesVisibleLocked(null, 0); 2030 } else if (SHOW_APP_STARTING_PREVIEW && doShow) { 2031 // Figure out if we are transitioning from another activity that is 2032 // "has the same starting icon" as the next one. This allows the 2033 // window manager to keep the previous window it had previously 2034 // created, if it still had one. 2035 ActivityRecord prev = mResumedActivity; 2036 if (prev != null) { 2037 // We don't want to reuse the previous starting preview if: 2038 // (1) The current activity is in a different task. 2039 if (prev.task != r.task) { 2040 prev = null; 2041 } 2042 // (2) The current activity is already displayed. 2043 else if (prev.nowVisible) { 2044 prev = null; 2045 } 2046 } 2047 mWindowManager.setAppStartingWindow( 2048 r.appToken, r.packageName, r.theme, 2049 mService.compatibilityInfoForPackageLocked( 2050 r.info.applicationInfo), r.nonLocalizedLabel, 2051 r.labelRes, r.icon, r.logo, r.windowFlags, 2052 prev != null ? prev.appToken : null, showStartingIcon); 2053 r.mStartingWindowShown = true; 2054 } 2055 } else { 2056 // If this is the first activity, don't do any fancy animations, 2057 // because there is nothing for it to animate on top of. 2058 mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken, 2059 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, 2060 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId, 2061 r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind); 2062 ActivityOptions.abort(options); 2063 options = null; 2064 } 2065 if (VALIDATE_TOKENS) { 2066 validateAppTokensLocked(); 2067 } 2068 2069 if (doResume) { 2070 mStackSupervisor.resumeTopActivitiesLocked(this, r, options); 2071 } 2072 } 2073 2074 final void validateAppTokensLocked() { 2075 mValidateAppTokens.clear(); 2076 mValidateAppTokens.ensureCapacity(numActivities()); 2077 final int numTasks = mTaskHistory.size(); 2078 for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) { 2079 TaskRecord task = mTaskHistory.get(taskNdx); 2080 final ArrayList<ActivityRecord> activities = task.mActivities; 2081 if (activities.isEmpty()) { 2082 continue; 2083 } 2084 TaskGroup group = new TaskGroup(); 2085 group.taskId = task.taskId; 2086 mValidateAppTokens.add(group); 2087 final int numActivities = activities.size(); 2088 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) { 2089 final ActivityRecord r = activities.get(activityNdx); 2090 group.tokens.add(r.appToken); 2091 } 2092 } 2093 mWindowManager.validateAppTokens(mStackId, mValidateAppTokens); 2094 } 2095 2096 /** 2097 * Perform a reset of the given task, if needed as part of launching it. 2098 * Returns the new HistoryRecord at the top of the task. 2099 */ 2100 /** 2101 * Helper method for #resetTaskIfNeededLocked. 2102 * We are inside of the task being reset... we'll either finish this activity, push it out 2103 * for another task, or leave it as-is. 2104 * @param task The task containing the Activity (taskTop) that might be reset. 2105 * @param forceReset 2106 * @return An ActivityOptions that needs to be processed. 2107 */ 2108 final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task, boolean forceReset) { 2109 ActivityOptions topOptions = null; 2110 2111 int replyChainEnd = -1; 2112 boolean canMoveOptions = true; 2113 2114 // We only do this for activities that are not the root of the task (since if we finish 2115 // the root, we may no longer have the task!). 2116 final ArrayList<ActivityRecord> activities = task.mActivities; 2117 final int numActivities = activities.size(); 2118 final int rootActivityNdx = task.findEffectiveRootIndex(); 2119 for (int i = numActivities - 1; i > rootActivityNdx; --i ) { 2120 ActivityRecord target = activities.get(i); 2121 if (target.frontOfTask) 2122 break; 2123 2124 final int flags = target.info.flags; 2125 final boolean finishOnTaskLaunch = 2126 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; 2127 final boolean allowTaskReparenting = 2128 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; 2129 final boolean clearWhenTaskReset = 2130 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0; 2131 2132 if (!finishOnTaskLaunch 2133 && !clearWhenTaskReset 2134 && target.resultTo != null) { 2135 // If this activity is sending a reply to a previous 2136 // activity, we can't do anything with it now until 2137 // we reach the start of the reply chain. 2138 // XXX note that we are assuming the result is always 2139 // to the previous activity, which is almost always 2140 // the case but we really shouldn't count on. 2141 if (replyChainEnd < 0) { 2142 replyChainEnd = i; 2143 } 2144 } else if (!finishOnTaskLaunch 2145 && !clearWhenTaskReset 2146 && allowTaskReparenting 2147 && target.taskAffinity != null 2148 && !target.taskAffinity.equals(task.affinity)) { 2149 // If this activity has an affinity for another 2150 // task, then we need to move it out of here. We will 2151 // move it as far out of the way as possible, to the 2152 // bottom of the activity stack. This also keeps it 2153 // correctly ordered with any activities we previously 2154 // moved. 2155 final TaskRecord targetTask; 2156 final ActivityRecord bottom = 2157 !mTaskHistory.isEmpty() && !mTaskHistory.get(0).mActivities.isEmpty() ? 2158 mTaskHistory.get(0).mActivities.get(0) : null; 2159 if (bottom != null && target.taskAffinity != null 2160 && target.taskAffinity.equals(bottom.task.affinity)) { 2161 // If the activity currently at the bottom has the 2162 // same task affinity as the one we are moving, 2163 // then merge it into the same task. 2164 targetTask = bottom.task; 2165 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target 2166 + " out to bottom task " + bottom.task); 2167 } else { 2168 targetTask = createTaskRecord(mStackSupervisor.getNextTaskId(), target.info, 2169 null, null, null, false); 2170 targetTask.affinityIntent = target.intent; 2171 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target 2172 + " out to new task " + target.task); 2173 } 2174 2175 final int targetTaskId = targetTask.taskId; 2176 mWindowManager.setAppGroupId(target.appToken, targetTaskId); 2177 2178 boolean noOptions = canMoveOptions; 2179 final int start = replyChainEnd < 0 ? i : replyChainEnd; 2180 for (int srcPos = start; srcPos >= i; --srcPos) { 2181 final ActivityRecord p = activities.get(srcPos); 2182 if (p.finishing) { 2183 continue; 2184 } 2185 2186 canMoveOptions = false; 2187 if (noOptions && topOptions == null) { 2188 topOptions = p.takeOptionsLocked(); 2189 if (topOptions != null) { 2190 noOptions = false; 2191 } 2192 } 2193 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task=" 2194 + task + " adding to task=" + targetTask 2195 + " Callers=" + Debug.getCallers(4)); 2196 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p 2197 + " out to target's task " + target.task); 2198 p.setTask(targetTask, null); 2199 targetTask.addActivityAtBottom(p); 2200 2201 mWindowManager.setAppGroupId(p.appToken, targetTaskId); 2202 } 2203 2204 mWindowManager.moveTaskToBottom(targetTaskId); 2205 if (VALIDATE_TOKENS) { 2206 validateAppTokensLocked(); 2207 } 2208 2209 replyChainEnd = -1; 2210 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) { 2211 // If the activity should just be removed -- either 2212 // because it asks for it, or the task should be 2213 // cleared -- then finish it and anything that is 2214 // part of its reply chain. 2215 int end; 2216 if (clearWhenTaskReset) { 2217 // In this case, we want to finish this activity 2218 // and everything above it, so be sneaky and pretend 2219 // like these are all in the reply chain. 2220 end = numActivities - 1; 2221 } else if (replyChainEnd < 0) { 2222 end = i; 2223 } else { 2224 end = replyChainEnd; 2225 } 2226 boolean noOptions = canMoveOptions; 2227 for (int srcPos = i; srcPos <= end; srcPos++) { 2228 ActivityRecord p = activities.get(srcPos); 2229 if (p.finishing) { 2230 continue; 2231 } 2232 canMoveOptions = false; 2233 if (noOptions && topOptions == null) { 2234 topOptions = p.takeOptionsLocked(); 2235 if (topOptions != null) { 2236 noOptions = false; 2237 } 2238 } 2239 if (DEBUG_TASKS) Slog.w(TAG, 2240 "resetTaskIntendedTask: calling finishActivity on " + p); 2241 if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) { 2242 end--; 2243 srcPos--; 2244 } 2245 } 2246 replyChainEnd = -1; 2247 } else { 2248 // If we were in the middle of a chain, well the 2249 // activity that started it all doesn't want anything 2250 // special, so leave it all as-is. 2251 replyChainEnd = -1; 2252 } 2253 } 2254 2255 return topOptions; 2256 } 2257 2258 /** 2259 * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given 2260 * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop. 2261 * @param affinityTask The task we are looking for an affinity to. 2262 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to. 2263 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked. 2264 * @param forceReset Flag passed in to resetTaskIfNeededLocked. 2265 */ 2266 private int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task, 2267 boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) { 2268 int replyChainEnd = -1; 2269 final int taskId = task.taskId; 2270 final String taskAffinity = task.affinity; 2271 2272 final ArrayList<ActivityRecord> activities = affinityTask.mActivities; 2273 final int numActivities = activities.size(); 2274 final int rootActivityNdx = affinityTask.findEffectiveRootIndex(); 2275 2276 // Do not operate on or below the effective root Activity. 2277 for (int i = numActivities - 1; i > rootActivityNdx; --i) { 2278 ActivityRecord target = activities.get(i); 2279 if (target.frontOfTask) 2280 break; 2281 2282 final int flags = target.info.flags; 2283 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; 2284 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; 2285 2286 if (target.resultTo != null) { 2287 // If this activity is sending a reply to a previous 2288 // activity, we can't do anything with it now until 2289 // we reach the start of the reply chain. 2290 // XXX note that we are assuming the result is always 2291 // to the previous activity, which is almost always 2292 // the case but we really shouldn't count on. 2293 if (replyChainEnd < 0) { 2294 replyChainEnd = i; 2295 } 2296 } else if (topTaskIsHigher 2297 && allowTaskReparenting 2298 && taskAffinity != null 2299 && taskAffinity.equals(target.taskAffinity)) { 2300 // This activity has an affinity for our task. Either remove it if we are 2301 // clearing or move it over to our task. Note that 2302 // we currently punt on the case where we are resetting a 2303 // task that is not at the top but who has activities above 2304 // with an affinity to it... this is really not a normal 2305 // case, and we will need to later pull that task to the front 2306 // and usually at that point we will do the reset and pick 2307 // up those remaining activities. (This only happens if 2308 // someone starts an activity in a new task from an activity 2309 // in a task that is not currently on top.) 2310 if (forceReset || finishOnTaskLaunch) { 2311 final int start = replyChainEnd >= 0 ? replyChainEnd : i; 2312 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i); 2313 for (int srcPos = start; srcPos >= i; --srcPos) { 2314 final ActivityRecord p = activities.get(srcPos); 2315 if (p.finishing) { 2316 continue; 2317 } 2318 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false); 2319 } 2320 } else { 2321 if (taskInsertionPoint < 0) { 2322 taskInsertionPoint = task.mActivities.size(); 2323 2324 } 2325 2326 final int start = replyChainEnd >= 0 ? replyChainEnd : i; 2327 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting from task=" + affinityTask + ":" 2328 + start + "-" + i + " to task=" + task + ":" + taskInsertionPoint); 2329 for (int srcPos = start; srcPos >= i; --srcPos) { 2330 final ActivityRecord p = activities.get(srcPos); 2331 p.setTask(task, null); 2332 task.addActivityAtIndex(taskInsertionPoint, p); 2333 2334 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p 2335 + " to stack at " + task, 2336 new RuntimeException("here").fillInStackTrace()); 2337 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos 2338 + " in to resetting task " + task); 2339 mWindowManager.setAppGroupId(p.appToken, taskId); 2340 } 2341 mWindowManager.moveTaskToTop(taskId); 2342 if (VALIDATE_TOKENS) { 2343 validateAppTokensLocked(); 2344 } 2345 2346 // Now we've moved it in to place... but what if this is 2347 // a singleTop activity and we have put it on top of another 2348 // instance of the same activity? Then we drop the instance 2349 // below so it remains singleTop. 2350 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { 2351 ArrayList<ActivityRecord> taskActivities = task.mActivities; 2352 int targetNdx = taskActivities.indexOf(target); 2353 if (targetNdx > 0) { 2354 ActivityRecord p = taskActivities.get(targetNdx - 1); 2355 if (p.intent.getComponent().equals(target.intent.getComponent())) { 2356 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace", 2357 false); 2358 } 2359 } 2360 } 2361 } 2362 2363 replyChainEnd = -1; 2364 } 2365 } 2366 return taskInsertionPoint; 2367 } 2368 2369 final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop, 2370 ActivityRecord newActivity) { 2371 boolean forceReset = 2372 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0; 2373 if (ACTIVITY_INACTIVE_RESET_TIME > 0 2374 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) { 2375 if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) { 2376 forceReset = true; 2377 } 2378 } 2379 2380 final TaskRecord task = taskTop.task; 2381 2382 /** False until we evaluate the TaskRecord associated with taskTop. Switches to true 2383 * for remaining tasks. Used for later tasks to reparent to task. */ 2384 boolean taskFound = false; 2385 2386 /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */ 2387 ActivityOptions topOptions = null; 2388 2389 // Preserve the location for reparenting in the new task. 2390 int reparentInsertionPoint = -1; 2391 2392 for (int i = mTaskHistory.size() - 1; i >= 0; --i) { 2393 final TaskRecord targetTask = mTaskHistory.get(i); 2394 2395 if (targetTask == task) { 2396 topOptions = resetTargetTaskIfNeededLocked(task, forceReset); 2397 taskFound = true; 2398 } else { 2399 reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task, 2400 taskFound, forceReset, reparentInsertionPoint); 2401 } 2402 } 2403 2404 int taskNdx = mTaskHistory.indexOf(task); 2405 do { 2406 taskTop = mTaskHistory.get(taskNdx--).getTopActivity(); 2407 } while (taskTop == null && taskNdx >= 0); 2408 2409 if (topOptions != null) { 2410 // If we got some ActivityOptions from an activity on top that 2411 // was removed from the task, propagate them to the new real top. 2412 if (taskTop != null) { 2413 taskTop.updateOptionsLocked(topOptions); 2414 } else { 2415 topOptions.abort(); 2416 } 2417 } 2418 2419 return taskTop; 2420 } 2421 2422 void sendActivityResultLocked(int callingUid, ActivityRecord r, 2423 String resultWho, int requestCode, int resultCode, Intent data) { 2424 2425 if (callingUid > 0) { 2426 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName, 2427 data, r.getUriPermissionsLocked(), r.userId); 2428 } 2429 2430 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r 2431 + " : who=" + resultWho + " req=" + requestCode 2432 + " res=" + resultCode + " data=" + data); 2433 if (mResumedActivity == r && r.app != null && r.app.thread != null) { 2434 try { 2435 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>(); 2436 list.add(new ResultInfo(resultWho, requestCode, 2437 resultCode, data)); 2438 r.app.thread.scheduleSendResult(r.appToken, list); 2439 return; 2440 } catch (Exception e) { 2441 Slog.w(TAG, "Exception thrown sending result to " + r, e); 2442 } 2443 } 2444 2445 r.addResultLocked(null, resultWho, requestCode, resultCode, data); 2446 } 2447 2448 private void adjustFocusedActivityLocked(ActivityRecord r) { 2449 if (mStackSupervisor.isFrontStack(this) && mService.mFocusedActivity == r) { 2450 ActivityRecord next = topRunningActivityLocked(null); 2451 if (next != r) { 2452 final TaskRecord task = r.task; 2453 if (r.frontOfTask && task == topTask() && task.isOverHomeStack()) { 2454 mStackSupervisor.moveHomeStackTaskToTop(task.getTaskToReturnTo()); 2455 } 2456 } 2457 ActivityRecord top = mStackSupervisor.topRunningActivityLocked(); 2458 if (top != null) { 2459 mService.setFocusedActivityLocked(top); 2460 } 2461 } 2462 } 2463 2464 final void stopActivityLocked(ActivityRecord r) { 2465 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r); 2466 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0 2467 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) { 2468 if (!r.finishing) { 2469 if (!mService.isSleeping()) { 2470 if (DEBUG_STATES) { 2471 Slog.d(TAG, "no-history finish of " + r); 2472 } 2473 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null, 2474 "no-history", false); 2475 } else { 2476 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r 2477 + " on stop because we're just sleeping"); 2478 } 2479 } 2480 } 2481 2482 if (r.app != null && r.app.thread != null) { 2483 adjustFocusedActivityLocked(r); 2484 r.resumeKeyDispatchingLocked(); 2485 try { 2486 r.stopped = false; 2487 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r 2488 + " (stop requested)"); 2489 r.state = ActivityState.STOPPING; 2490 if (DEBUG_VISBILITY) Slog.v( 2491 TAG, "Stopping visible=" + r.visible + " for " + r); 2492 if (!r.visible) { 2493 mWindowManager.setAppVisibility(r.appToken, false); 2494 } 2495 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags); 2496 if (mService.isSleepingOrShuttingDown()) { 2497 r.setSleeping(true); 2498 } 2499 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r); 2500 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT); 2501 } catch (Exception e) { 2502 // Maybe just ignore exceptions here... if the process 2503 // has crashed, our death notification will clean things 2504 // up. 2505 Slog.w(TAG, "Exception thrown during pause", e); 2506 // Just in case, assume it to be stopped. 2507 r.stopped = true; 2508 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r); 2509 r.state = ActivityState.STOPPED; 2510 if (r.configDestroy) { 2511 destroyActivityLocked(r, true, "stop-except"); 2512 } 2513 } 2514 } 2515 } 2516 2517 /** 2518 * @return Returns true if the activity is being finished, false if for 2519 * some reason it is being left as-is. 2520 */ 2521 final boolean requestFinishActivityLocked(IBinder token, int resultCode, 2522 Intent resultData, String reason, boolean oomAdj) { 2523 ActivityRecord r = isInStackLocked(token); 2524 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v( 2525 TAG, "Finishing activity token=" + token + " r=" 2526 + ", result=" + resultCode + ", data=" + resultData 2527 + ", reason=" + reason); 2528 if (r == null) { 2529 return false; 2530 } 2531 2532 finishActivityLocked(r, resultCode, resultData, reason, oomAdj); 2533 return true; 2534 } 2535 2536 final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) { 2537 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2538 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 2539 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2540 ActivityRecord r = activities.get(activityNdx); 2541 if (r.resultTo == self && r.requestCode == requestCode) { 2542 if ((r.resultWho == null && resultWho == null) || 2543 (r.resultWho != null && r.resultWho.equals(resultWho))) { 2544 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub", 2545 false); 2546 } 2547 } 2548 } 2549 } 2550 mService.updateOomAdjLocked(); 2551 } 2552 2553 final void finishTopRunningActivityLocked(ProcessRecord app) { 2554 ActivityRecord r = topRunningActivityLocked(null); 2555 if (r != null && r.app == app) { 2556 // If the top running activity is from this crashing 2557 // process, then terminate it to avoid getting in a loop. 2558 Slog.w(TAG, " Force finishing activity " 2559 + r.intent.getComponent().flattenToShortString()); 2560 int taskNdx = mTaskHistory.indexOf(r.task); 2561 int activityNdx = r.task.mActivities.indexOf(r); 2562 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false); 2563 // Also terminate any activities below it that aren't yet 2564 // stopped, to avoid a situation where one will get 2565 // re-start our crashing activity once it gets resumed again. 2566 --activityNdx; 2567 if (activityNdx < 0) { 2568 do { 2569 --taskNdx; 2570 if (taskNdx < 0) { 2571 break; 2572 } 2573 activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1; 2574 } while (activityNdx < 0); 2575 } 2576 if (activityNdx >= 0) { 2577 r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx); 2578 if (r.state == ActivityState.RESUMED 2579 || r.state == ActivityState.PAUSING 2580 || r.state == ActivityState.PAUSED) { 2581 if (!r.isHomeActivity() || mService.mHomeProcess != r.app) { 2582 Slog.w(TAG, " Force finishing activity " 2583 + r.intent.getComponent().flattenToShortString()); 2584 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false); 2585 } 2586 } 2587 } 2588 } 2589 } 2590 2591 final void finishVoiceTask(IVoiceInteractionSession session) { 2592 IBinder sessionBinder = session.asBinder(); 2593 boolean didOne = false; 2594 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2595 TaskRecord tr = mTaskHistory.get(taskNdx); 2596 if (tr.voiceSession != null && tr.voiceSession.asBinder() == sessionBinder) { 2597 for (int activityNdx = tr.mActivities.size() - 1; activityNdx >= 0; --activityNdx) { 2598 ActivityRecord r = tr.mActivities.get(activityNdx); 2599 if (!r.finishing) { 2600 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "finish-voice", 2601 false); 2602 didOne = true; 2603 } 2604 } 2605 } 2606 } 2607 if (didOne) { 2608 mService.updateOomAdjLocked(); 2609 } 2610 } 2611 2612 final boolean finishActivityAffinityLocked(ActivityRecord r) { 2613 ArrayList<ActivityRecord> activities = r.task.mActivities; 2614 for (int index = activities.indexOf(r); index >= 0; --index) { 2615 ActivityRecord cur = activities.get(index); 2616 if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) { 2617 break; 2618 } 2619 finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true); 2620 } 2621 return true; 2622 } 2623 2624 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) { 2625 // send the result 2626 ActivityRecord resultTo = r.resultTo; 2627 if (resultTo != null) { 2628 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo 2629 + " who=" + r.resultWho + " req=" + r.requestCode 2630 + " res=" + resultCode + " data=" + resultData); 2631 if (resultTo.userId != r.userId) { 2632 if (resultData != null) { 2633 resultData.setContentUserHint(r.userId); 2634 } 2635 } 2636 if (r.info.applicationInfo.uid > 0) { 2637 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid, 2638 resultTo.packageName, resultData, 2639 resultTo.getUriPermissionsLocked(), resultTo.userId); 2640 } 2641 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode, 2642 resultData); 2643 r.resultTo = null; 2644 } 2645 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r); 2646 2647 // Make sure this HistoryRecord is not holding on to other resources, 2648 // because clients have remote IPC references to this object so we 2649 // can't assume that will go away and want to avoid circular IPC refs. 2650 r.results = null; 2651 r.pendingResults = null; 2652 r.newIntents = null; 2653 r.icicle = null; 2654 } 2655 2656 /** 2657 * @return Returns true if this activity has been removed from the history 2658 * list, or false if it is still in the list and will be removed later. 2659 */ 2660 final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData, 2661 String reason, boolean oomAdj) { 2662 if (r.finishing) { 2663 Slog.w(TAG, "Duplicate finish request for " + r); 2664 return false; 2665 } 2666 2667 r.makeFinishing(); 2668 final TaskRecord task = r.task; 2669 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, 2670 r.userId, System.identityHashCode(r), 2671 task.taskId, r.shortComponentName, reason); 2672 final ArrayList<ActivityRecord> activities = task.mActivities; 2673 final int index = activities.indexOf(r); 2674 if (index < (activities.size() - 1)) { 2675 task.setFrontOfTask(); 2676 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) { 2677 // If the caller asked that this activity (and all above it) 2678 // be cleared when the task is reset, don't lose that information, 2679 // but propagate it up to the next activity. 2680 ActivityRecord next = activities.get(index+1); 2681 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 2682 } 2683 } 2684 2685 r.pauseKeyDispatchingLocked(); 2686 2687 adjustFocusedActivityLocked(r); 2688 2689 finishActivityResultsLocked(r, resultCode, resultData); 2690 2691 if (mResumedActivity == r) { 2692 boolean endTask = index <= 0; 2693 if (DEBUG_VISBILITY || DEBUG_TRANSITION) Slog.v(TAG, 2694 "Prepare close transition: finishing " + r); 2695 mWindowManager.prepareAppTransition(endTask 2696 ? AppTransition.TRANSIT_TASK_CLOSE 2697 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false); 2698 2699 // Tell window manager to prepare for this one to be removed. 2700 mWindowManager.setAppVisibility(r.appToken, false); 2701 2702 if (mPausingActivity == null) { 2703 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r); 2704 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false"); 2705 startPausingLocked(false, false); 2706 } 2707 2708 if (endTask) { 2709 mStackSupervisor.endLockTaskModeIfTaskEnding(task); 2710 } 2711 } else if (r.state != ActivityState.PAUSING) { 2712 // If the activity is PAUSING, we will complete the finish once 2713 // it is done pausing; else we can just directly finish it here. 2714 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r); 2715 return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null; 2716 } else { 2717 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r); 2718 } 2719 2720 return false; 2721 } 2722 2723 static final int FINISH_IMMEDIATELY = 0; 2724 static final int FINISH_AFTER_PAUSE = 1; 2725 static final int FINISH_AFTER_VISIBLE = 2; 2726 2727 final ActivityRecord finishCurrentActivityLocked(ActivityRecord r, int mode, boolean oomAdj) { 2728 // First things first: if this activity is currently visible, 2729 // and the resumed activity is not yet visible, then hold off on 2730 // finishing until the resumed one becomes visible. 2731 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) { 2732 if (!mStackSupervisor.mStoppingActivities.contains(r)) { 2733 mStackSupervisor.mStoppingActivities.add(r); 2734 if (mStackSupervisor.mStoppingActivities.size() > 3 2735 || r.frontOfTask && mTaskHistory.size() <= 1) { 2736 // If we already have a few activities waiting to stop, 2737 // then give up on things going idle and start clearing 2738 // them out. Or if r is the last of activity of the last task the stack 2739 // will be empty and must be cleared immediately. 2740 mStackSupervisor.scheduleIdleLocked(); 2741 } else { 2742 mStackSupervisor.checkReadyForSleepLocked(); 2743 } 2744 } 2745 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r 2746 + " (finish requested)"); 2747 r.state = ActivityState.STOPPING; 2748 if (oomAdj) { 2749 mService.updateOomAdjLocked(); 2750 } 2751 return r; 2752 } 2753 2754 // make sure the record is cleaned out of other places. 2755 mStackSupervisor.mStoppingActivities.remove(r); 2756 mStackSupervisor.mGoingToSleepActivities.remove(r); 2757 mStackSupervisor.mWaitingVisibleActivities.remove(r); 2758 if (mResumedActivity == r) { 2759 mResumedActivity = null; 2760 } 2761 final ActivityState prevState = r.state; 2762 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r); 2763 r.state = ActivityState.FINISHING; 2764 2765 if (mode == FINISH_IMMEDIATELY 2766 || prevState == ActivityState.STOPPED 2767 || prevState == ActivityState.INITIALIZING) { 2768 // If this activity is already stopped, we can just finish 2769 // it right now. 2770 r.makeFinishing(); 2771 boolean activityRemoved = destroyActivityLocked(r, true, "finish-imm"); 2772 if (activityRemoved) { 2773 mStackSupervisor.resumeTopActivitiesLocked(); 2774 } 2775 if (DEBUG_CONTAINERS) Slog.d(TAG, 2776 "destroyActivityLocked: finishCurrentActivityLocked r=" + r + 2777 " destroy returned removed=" + activityRemoved); 2778 return activityRemoved ? null : r; 2779 } 2780 2781 // Need to go through the full pause cycle to get this 2782 // activity into the stopped state and then finish it. 2783 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r); 2784 mStackSupervisor.mFinishingActivities.add(r); 2785 r.resumeKeyDispatchingLocked(); 2786 mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null); 2787 return r; 2788 } 2789 2790 void finishAllActivitiesLocked(boolean immediately) { 2791 boolean noActivitiesInStack = true; 2792 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2793 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 2794 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2795 final ActivityRecord r = activities.get(activityNdx); 2796 noActivitiesInStack = false; 2797 if (r.finishing && !immediately) { 2798 continue; 2799 } 2800 Slog.d(TAG, "finishAllActivitiesLocked: finishing " + r + " immediately"); 2801 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false); 2802 } 2803 } 2804 if (noActivitiesInStack) { 2805 mActivityContainer.onTaskListEmptyLocked(); 2806 } 2807 } 2808 2809 final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode, 2810 Intent resultData) { 2811 final ActivityRecord srec = ActivityRecord.forToken(token); 2812 final TaskRecord task = srec.task; 2813 final ArrayList<ActivityRecord> activities = task.mActivities; 2814 final int start = activities.indexOf(srec); 2815 if (!mTaskHistory.contains(task) || (start < 0)) { 2816 return false; 2817 } 2818 int finishTo = start - 1; 2819 ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo); 2820 boolean foundParentInTask = false; 2821 final ComponentName dest = destIntent.getComponent(); 2822 if (start > 0 && dest != null) { 2823 for (int i = finishTo; i >= 0; i--) { 2824 ActivityRecord r = activities.get(i); 2825 if (r.info.packageName.equals(dest.getPackageName()) && 2826 r.info.name.equals(dest.getClassName())) { 2827 finishTo = i; 2828 parent = r; 2829 foundParentInTask = true; 2830 break; 2831 } 2832 } 2833 } 2834 2835 IActivityController controller = mService.mController; 2836 if (controller != null) { 2837 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0); 2838 if (next != null) { 2839 // ask watcher if this is allowed 2840 boolean resumeOK = true; 2841 try { 2842 resumeOK = controller.activityResuming(next.packageName); 2843 } catch (RemoteException e) { 2844 mService.mController = null; 2845 Watchdog.getInstance().setActivityController(null); 2846 } 2847 2848 if (!resumeOK) { 2849 return false; 2850 } 2851 } 2852 } 2853 final long origId = Binder.clearCallingIdentity(); 2854 for (int i = start; i > finishTo; i--) { 2855 ActivityRecord r = activities.get(i); 2856 requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true); 2857 // Only return the supplied result for the first activity finished 2858 resultCode = Activity.RESULT_CANCELED; 2859 resultData = null; 2860 } 2861 2862 if (parent != null && foundParentInTask) { 2863 final int parentLaunchMode = parent.info.launchMode; 2864 final int destIntentFlags = destIntent.getFlags(); 2865 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE || 2866 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK || 2867 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP || 2868 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) { 2869 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent); 2870 } else { 2871 try { 2872 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo( 2873 destIntent.getComponent(), 0, srec.userId); 2874 int res = mStackSupervisor.startActivityLocked(srec.app.thread, destIntent, 2875 null, aInfo, null, null, parent.appToken, null, 2876 0, -1, parent.launchedFromUid, parent.launchedFromPackage, 2877 0, null, true, null, null); 2878 foundParentInTask = res == ActivityManager.START_SUCCESS; 2879 } catch (RemoteException e) { 2880 foundParentInTask = false; 2881 } 2882 requestFinishActivityLocked(parent.appToken, resultCode, 2883 resultData, "navigate-up", true); 2884 } 2885 } 2886 Binder.restoreCallingIdentity(origId); 2887 return foundParentInTask; 2888 } 2889 /** 2890 * Perform the common clean-up of an activity record. This is called both 2891 * as part of destroyActivityLocked() (when destroying the client-side 2892 * representation) and cleaning things up as a result of its hosting 2893 * processing going away, in which case there is no remaining client-side 2894 * state to destroy so only the cleanup here is needed. 2895 */ 2896 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices, 2897 boolean setState) { 2898 if (mResumedActivity == r) { 2899 mResumedActivity = null; 2900 } 2901 if (mPausingActivity == r) { 2902 mPausingActivity = null; 2903 } 2904 mService.clearFocusedActivity(r); 2905 2906 r.configDestroy = false; 2907 r.frozenBeforeDestroy = false; 2908 2909 if (setState) { 2910 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)"); 2911 r.state = ActivityState.DESTROYED; 2912 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r); 2913 r.app = null; 2914 } 2915 2916 // Make sure this record is no longer in the pending finishes list. 2917 // This could happen, for example, if we are trimming activities 2918 // down to the max limit while they are still waiting to finish. 2919 mStackSupervisor.mFinishingActivities.remove(r); 2920 mStackSupervisor.mWaitingVisibleActivities.remove(r); 2921 2922 // Remove any pending results. 2923 if (r.finishing && r.pendingResults != null) { 2924 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) { 2925 PendingIntentRecord rec = apr.get(); 2926 if (rec != null) { 2927 mService.cancelIntentSenderLocked(rec, false); 2928 } 2929 } 2930 r.pendingResults = null; 2931 } 2932 2933 if (cleanServices) { 2934 cleanUpActivityServicesLocked(r); 2935 } 2936 2937 // Get rid of any pending idle timeouts. 2938 removeTimeoutsForActivityLocked(r); 2939 if (getMediaPlayer() == r) { 2940 mStackSupervisor.setMediaPlayingLocked(r, false); 2941 } 2942 } 2943 2944 private void removeTimeoutsForActivityLocked(ActivityRecord r) { 2945 mStackSupervisor.removeTimeoutsForActivityLocked(r); 2946 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 2947 mHandler.removeMessages(STOP_TIMEOUT_MSG, r); 2948 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r); 2949 r.finishLaunchTickingLocked(); 2950 } 2951 2952 private void removeActivityFromHistoryLocked(ActivityRecord r) { 2953 mStackSupervisor.removeChildActivityContainers(r); 2954 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null); 2955 r.makeFinishing(); 2956 if (DEBUG_ADD_REMOVE) { 2957 RuntimeException here = new RuntimeException("here"); 2958 here.fillInStackTrace(); 2959 Slog.i(TAG, "Removing activity " + r + " from stack"); 2960 } 2961 r.takeFromHistory(); 2962 removeTimeoutsForActivityLocked(r); 2963 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)"); 2964 r.state = ActivityState.DESTROYED; 2965 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r); 2966 r.app = null; 2967 mWindowManager.removeAppToken(r.appToken); 2968 if (VALIDATE_TOKENS) { 2969 validateAppTokensLocked(); 2970 } 2971 final TaskRecord task = r.task; 2972 if (task != null && task.removeActivity(r)) { 2973 if (DEBUG_STACK) Slog.i(TAG, 2974 "removeActivityFromHistoryLocked: last activity removed from " + this); 2975 if (mStackSupervisor.isFrontStack(this) && task == topTask() && 2976 task.isOverHomeStack()) { 2977 mStackSupervisor.moveHomeStackTaskToTop(task.getTaskToReturnTo()); 2978 } 2979 removeTask(task); 2980 } 2981 cleanUpActivityServicesLocked(r); 2982 r.removeUriPermissionsLocked(); 2983 } 2984 2985 /** 2986 * Perform clean-up of service connections in an activity record. 2987 */ 2988 final void cleanUpActivityServicesLocked(ActivityRecord r) { 2989 // Throw away any services that have been bound by this activity. 2990 if (r.connections != null) { 2991 Iterator<ConnectionRecord> it = r.connections.iterator(); 2992 while (it.hasNext()) { 2993 ConnectionRecord c = it.next(); 2994 mService.mServices.removeConnectionLocked(c, null, r); 2995 } 2996 r.connections = null; 2997 } 2998 } 2999 3000 final void scheduleDestroyActivities(ProcessRecord owner, String reason) { 3001 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG); 3002 msg.obj = new ScheduleDestroyArgs(owner, reason); 3003 mHandler.sendMessage(msg); 3004 } 3005 3006 final void destroyActivitiesLocked(ProcessRecord owner, String reason) { 3007 boolean lastIsOpaque = false; 3008 boolean activityRemoved = false; 3009 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3010 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3011 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3012 final ActivityRecord r = activities.get(activityNdx); 3013 if (r.finishing) { 3014 continue; 3015 } 3016 if (r.fullscreen) { 3017 lastIsOpaque = true; 3018 } 3019 if (owner != null && r.app != owner) { 3020 continue; 3021 } 3022 if (!lastIsOpaque) { 3023 continue; 3024 } 3025 // We can destroy this one if we have its icicle saved and 3026 // it is not in the process of pausing/stopping/finishing. 3027 if (r.app != null && r != mResumedActivity && r != mPausingActivity 3028 && r.haveState && !r.visible && r.stopped 3029 && r.state != ActivityState.DESTROYING 3030 && r.state != ActivityState.DESTROYED) { 3031 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state 3032 + " resumed=" + mResumedActivity 3033 + " pausing=" + mPausingActivity); 3034 if (destroyActivityLocked(r, true, reason)) { 3035 activityRemoved = true; 3036 } 3037 } 3038 } 3039 } 3040 if (activityRemoved) { 3041 mStackSupervisor.resumeTopActivitiesLocked(); 3042 } 3043 } 3044 3045 /** 3046 * Destroy the current CLIENT SIDE instance of an activity. This may be 3047 * called both when actually finishing an activity, or when performing 3048 * a configuration switch where we destroy the current client-side object 3049 * but then create a new client-side object for this same HistoryRecord. 3050 */ 3051 final boolean destroyActivityLocked(ActivityRecord r, boolean removeFromApp, String reason) { 3052 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v( 3053 TAG, "Removing activity from " + reason + ": token=" + r 3054 + ", app=" + (r.app != null ? r.app.processName : "(null)")); 3055 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY, 3056 r.userId, System.identityHashCode(r), 3057 r.task.taskId, r.shortComponentName, reason); 3058 3059 boolean removedFromHistory = false; 3060 3061 cleanUpActivityLocked(r, false, false); 3062 3063 final boolean hadApp = r.app != null; 3064 3065 if (hadApp) { 3066 if (removeFromApp) { 3067 r.app.activities.remove(r); 3068 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) { 3069 mService.mHeavyWeightProcess = null; 3070 mService.mHandler.sendEmptyMessage( 3071 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG); 3072 } 3073 if (r.app.activities.isEmpty()) { 3074 // No longer have activities, so update LRU list and oom adj. 3075 mService.updateLruProcessLocked(r.app, false, null); 3076 mService.updateOomAdjLocked(); 3077 } 3078 } 3079 3080 boolean skipDestroy = false; 3081 3082 try { 3083 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r); 3084 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing, 3085 r.configChangeFlags); 3086 } catch (Exception e) { 3087 // We can just ignore exceptions here... if the process 3088 // has crashed, our death notification will clean things 3089 // up. 3090 //Slog.w(TAG, "Exception thrown during finish", e); 3091 if (r.finishing) { 3092 removeActivityFromHistoryLocked(r); 3093 removedFromHistory = true; 3094 skipDestroy = true; 3095 } 3096 } 3097 3098 r.nowVisible = false; 3099 3100 // If the activity is finishing, we need to wait on removing it 3101 // from the list to give it a chance to do its cleanup. During 3102 // that time it may make calls back with its token so we need to 3103 // be able to find it on the list and so we don't want to remove 3104 // it from the list yet. Otherwise, we can just immediately put 3105 // it in the destroyed state since we are not removing it from the 3106 // list. 3107 if (r.finishing && !skipDestroy) { 3108 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r 3109 + " (destroy requested)"); 3110 r.state = ActivityState.DESTROYING; 3111 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r); 3112 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT); 3113 } else { 3114 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (destroy skipped)"); 3115 r.state = ActivityState.DESTROYED; 3116 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r); 3117 r.app = null; 3118 } 3119 } else { 3120 // remove this record from the history. 3121 if (r.finishing) { 3122 removeActivityFromHistoryLocked(r); 3123 removedFromHistory = true; 3124 } else { 3125 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (no app)"); 3126 r.state = ActivityState.DESTROYED; 3127 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r); 3128 r.app = null; 3129 } 3130 } 3131 3132 r.configChangeFlags = 0; 3133 3134 if (!mLRUActivities.remove(r) && hadApp) { 3135 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list"); 3136 } 3137 3138 return removedFromHistory; 3139 } 3140 3141 final void activityDestroyedLocked(IBinder token) { 3142 final long origId = Binder.clearCallingIdentity(); 3143 try { 3144 ActivityRecord r = ActivityRecord.forToken(token); 3145 if (r != null) { 3146 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r); 3147 } 3148 if (DEBUG_CONTAINERS) Slog.d(TAG, "activityDestroyedLocked: r=" + r); 3149 3150 if (isInStackLocked(token) != null) { 3151 if (r.state == ActivityState.DESTROYING) { 3152 cleanUpActivityLocked(r, true, false); 3153 removeActivityFromHistoryLocked(r); 3154 } 3155 } 3156 mStackSupervisor.resumeTopActivitiesLocked(); 3157 } finally { 3158 Binder.restoreCallingIdentity(origId); 3159 } 3160 } 3161 3162 void releaseMediaResources() { 3163 if (isMediaPlaying() && !mHandler.hasMessages(STOP_MEDIA_PLAYING_TIMEOUT_MSG)) { 3164 final ActivityRecord r = getMediaPlayer(); 3165 if (DEBUG_STATES) Slog.d(TAG, "releaseMediaResources activtyDisplay=" + 3166 mActivityContainer.mActivityDisplay + " mediaPlayer=" + r + " app=" + r.app + 3167 " thread=" + r.app.thread); 3168 if (r != null && r.app != null && r.app.thread != null) { 3169 try { 3170 r.app.thread.scheduleStopMediaPlaying(r.appToken); 3171 } catch (RemoteException e) { 3172 } 3173 mHandler.sendEmptyMessageDelayed(STOP_MEDIA_PLAYING_TIMEOUT_MSG, 500); 3174 } else { 3175 Slog.e(TAG, "releaseMediaResources: activity " + r + " no longer running"); 3176 mediaResourcesReleased(r.appToken); 3177 } 3178 } 3179 } 3180 3181 final void mediaResourcesReleased(IBinder token) { 3182 mHandler.removeMessages(STOP_MEDIA_PLAYING_TIMEOUT_MSG); 3183 final ActivityRecord r = getMediaPlayer(); 3184 if (r != null) { 3185 mStackSupervisor.mStoppingActivities.add(r); 3186 setMediaPlayer(null); 3187 } 3188 mStackSupervisor.resumeTopActivitiesLocked(); 3189 } 3190 3191 boolean isMediaPlaying() { 3192 return isAttached() && mActivityContainer.mActivityDisplay.isMediaPlaying(); 3193 } 3194 3195 void setMediaPlayer(ActivityRecord r) { 3196 if (isAttached()) { 3197 mActivityContainer.mActivityDisplay.setMediaPlaying(r); 3198 } 3199 } 3200 3201 ActivityRecord getMediaPlayer() { 3202 return isAttached() ? mActivityContainer.mActivityDisplay.mMediaPlayingActivity : null; 3203 } 3204 3205 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list, 3206 ProcessRecord app, String listName) { 3207 int i = list.size(); 3208 if (DEBUG_CLEANUP) Slog.v( 3209 TAG, "Removing app " + app + " from list " + listName 3210 + " with " + i + " entries"); 3211 while (i > 0) { 3212 i--; 3213 ActivityRecord r = list.get(i); 3214 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r); 3215 if (r.app == app) { 3216 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!"); 3217 list.remove(i); 3218 removeTimeoutsForActivityLocked(r); 3219 } 3220 } 3221 } 3222 3223 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) { 3224 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities"); 3225 removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app, 3226 "mStoppingActivities"); 3227 removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app, 3228 "mGoingToSleepActivities"); 3229 removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app, 3230 "mWaitingVisibleActivities"); 3231 removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app, 3232 "mFinishingActivities"); 3233 3234 boolean hasVisibleActivities = false; 3235 3236 // Clean out the history list. 3237 int i = numActivities(); 3238 if (DEBUG_CLEANUP) Slog.v( 3239 TAG, "Removing app " + app + " from history with " + i + " entries"); 3240 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3241 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3242 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3243 final ActivityRecord r = activities.get(activityNdx); 3244 --i; 3245 if (DEBUG_CLEANUP) Slog.v( 3246 TAG, "Record #" + i + " " + r + ": app=" + r.app); 3247 if (r.app == app) { 3248 boolean remove; 3249 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) { 3250 // Don't currently have state for the activity, or 3251 // it is finishing -- always remove it. 3252 remove = true; 3253 } else if (r.launchCount > 2 && 3254 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) { 3255 // We have launched this activity too many times since it was 3256 // able to run, so give up and remove it. 3257 remove = true; 3258 } else { 3259 // The process may be gone, but the activity lives on! 3260 remove = false; 3261 } 3262 if (remove) { 3263 if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) { 3264 RuntimeException here = new RuntimeException("here"); 3265 here.fillInStackTrace(); 3266 Slog.i(TAG, "Removing activity " + r + " from stack at " + i 3267 + ": haveState=" + r.haveState 3268 + " stateNotNeeded=" + r.stateNotNeeded 3269 + " finishing=" + r.finishing 3270 + " state=" + r.state, here); 3271 } 3272 if (!r.finishing) { 3273 Slog.w(TAG, "Force removing " + r + ": app died, no saved state"); 3274 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, 3275 r.userId, System.identityHashCode(r), 3276 r.task.taskId, r.shortComponentName, 3277 "proc died without state saved"); 3278 if (r.state == ActivityState.RESUMED) { 3279 mService.updateUsageStats(r, false); 3280 } 3281 } 3282 removeActivityFromHistoryLocked(r); 3283 3284 } else { 3285 // We have the current state for this activity, so 3286 // it can be restarted later when needed. 3287 if (localLOGV) Slog.v( 3288 TAG, "Keeping entry, setting app to null"); 3289 if (r.visible) { 3290 hasVisibleActivities = true; 3291 } 3292 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity " 3293 + r); 3294 r.app = null; 3295 r.nowVisible = false; 3296 if (!r.haveState) { 3297 if (DEBUG_SAVED_STATE) Slog.i(TAG, 3298 "App died, clearing saved state of " + r); 3299 r.icicle = null; 3300 } 3301 } 3302 3303 cleanUpActivityLocked(r, true, true); 3304 } 3305 } 3306 } 3307 3308 return hasVisibleActivities; 3309 } 3310 3311 final void updateTransitLocked(int transit, Bundle options) { 3312 if (options != null) { 3313 ActivityRecord r = topRunningActivityLocked(null); 3314 if (r != null && r.state != ActivityState.RESUMED) { 3315 r.updateOptionsLocked(options); 3316 } else { 3317 ActivityOptions.abort(options); 3318 } 3319 } 3320 mWindowManager.prepareAppTransition(transit, false); 3321 } 3322 3323 void updateTaskMovement(TaskRecord task, boolean toFront) { 3324 if (task.isPersistable) { 3325 task.mLastTimeMoved = System.currentTimeMillis(); 3326 // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most 3327 // recently will be most negative, tasks sent to the bottom before that will be less 3328 // negative. Similarly for recent tasks moved to the top which will be most positive. 3329 if (!toFront) { 3330 task.mLastTimeMoved *= -1; 3331 } 3332 } 3333 } 3334 3335 void moveHomeStackTaskToTop(int homeStackTaskType) { 3336 final int top = mTaskHistory.size() - 1; 3337 for (int taskNdx = top; taskNdx >= 0; --taskNdx) { 3338 final TaskRecord task = mTaskHistory.get(taskNdx); 3339 if (task.taskType == homeStackTaskType) { 3340 if (DEBUG_TASKS || DEBUG_STACK) 3341 Slog.d(TAG, "moveHomeStackTaskToTop: moving " + task); 3342 mTaskHistory.remove(taskNdx); 3343 mTaskHistory.add(top, task); 3344 updateTaskMovement(task, true); 3345 mWindowManager.moveTaskToTop(task.taskId); 3346 return; 3347 } 3348 } 3349 } 3350 3351 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) { 3352 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr); 3353 3354 final int numTasks = mTaskHistory.size(); 3355 final int index = mTaskHistory.indexOf(tr); 3356 if (numTasks == 0 || index < 0) { 3357 // nothing to do! 3358 if (reason != null && 3359 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 3360 ActivityOptions.abort(options); 3361 } else { 3362 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options); 3363 } 3364 return; 3365 } 3366 3367 moveToFront(); 3368 3369 // Shift all activities with this task up to the top 3370 // of the stack, keeping them in the same internal order. 3371 insertTaskAtTop(tr); 3372 3373 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr); 3374 if (reason != null && 3375 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 3376 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 3377 ActivityRecord r = topRunningActivityLocked(null); 3378 if (r != null) { 3379 mNoAnimActivities.add(r); 3380 } 3381 ActivityOptions.abort(options); 3382 } else { 3383 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options); 3384 } 3385 3386 mWindowManager.moveTaskToTop(tr.taskId); 3387 3388 mStackSupervisor.resumeTopActivitiesLocked(); 3389 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId); 3390 3391 if (VALIDATE_TOKENS) { 3392 validateAppTokensLocked(); 3393 } 3394 } 3395 3396 /** 3397 * Worker method for rearranging history stack. Implements the function of moving all 3398 * activities for a specific task (gathering them if disjoint) into a single group at the 3399 * bottom of the stack. 3400 * 3401 * If a watcher is installed, the action is preflighted and the watcher has an opportunity 3402 * to premeptively cancel the move. 3403 * 3404 * @param taskId The taskId to collect and move to the bottom. 3405 * @return Returns true if the move completed, false if not. 3406 */ 3407 final boolean moveTaskToBackLocked(int taskId, ActivityRecord reason) { 3408 final TaskRecord tr = taskForIdLocked(taskId); 3409 if (tr == null) { 3410 Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId); 3411 return false; 3412 } 3413 3414 Slog.i(TAG, "moveTaskToBack: " + tr); 3415 3416 mStackSupervisor.endLockTaskModeIfTaskEnding(tr); 3417 3418 // If we have a watcher, preflight the move before committing to it. First check 3419 // for *other* available tasks, but if none are available, then try again allowing the 3420 // current task to be selected. 3421 if (mStackSupervisor.isFrontStack(this) && mService.mController != null) { 3422 ActivityRecord next = topRunningActivityLocked(null, taskId); 3423 if (next == null) { 3424 next = topRunningActivityLocked(null, 0); 3425 } 3426 if (next != null) { 3427 // ask watcher if this is allowed 3428 boolean moveOK = true; 3429 try { 3430 moveOK = mService.mController.activityResuming(next.packageName); 3431 } catch (RemoteException e) { 3432 mService.mController = null; 3433 Watchdog.getInstance().setActivityController(null); 3434 } 3435 if (!moveOK) { 3436 return false; 3437 } 3438 } 3439 } 3440 3441 if (DEBUG_TRANSITION) Slog.v(TAG, 3442 "Prepare to back transition: task=" + taskId); 3443 3444 mTaskHistory.remove(tr); 3445 mTaskHistory.add(0, tr); 3446 updateTaskMovement(tr, false); 3447 3448 // There is an assumption that moving a task to the back moves it behind the home activity. 3449 // We make sure here that some activity in the stack will launch home. 3450 int numTasks = mTaskHistory.size(); 3451 for (int taskNdx = numTasks - 1; taskNdx >= 1; --taskNdx) { 3452 final TaskRecord task = mTaskHistory.get(taskNdx); 3453 if (task.isOverHomeStack()) { 3454 break; 3455 } 3456 if (taskNdx == 1) { 3457 // Set the last task before tr to go to home. 3458 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE); 3459 } 3460 } 3461 3462 if (reason != null && 3463 (reason.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 3464 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 3465 ActivityRecord r = topRunningActivityLocked(null); 3466 if (r != null) { 3467 mNoAnimActivities.add(r); 3468 } 3469 } else { 3470 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_TASK_TO_BACK, false); 3471 } 3472 mWindowManager.moveTaskToBottom(taskId); 3473 3474 if (VALIDATE_TOKENS) { 3475 validateAppTokensLocked(); 3476 } 3477 3478 final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null; 3479 if (task == tr && tr.isOverHomeStack() || numTasks <= 1 && isOnHomeDisplay()) { 3480 final int taskToReturnTo = tr.getTaskToReturnTo(); 3481 tr.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE); 3482 return mStackSupervisor.resumeHomeStackTask(taskToReturnTo, null); 3483 } 3484 3485 mStackSupervisor.resumeTopActivitiesLocked(); 3486 return true; 3487 } 3488 3489 static final void logStartActivity(int tag, ActivityRecord r, 3490 TaskRecord task) { 3491 final Uri data = r.intent.getData(); 3492 final String strData = data != null ? data.toSafeString() : null; 3493 3494 EventLog.writeEvent(tag, 3495 r.userId, System.identityHashCode(r), task.taskId, 3496 r.shortComponentName, r.intent.getAction(), 3497 r.intent.getType(), strData, r.intent.getFlags()); 3498 } 3499 3500 /** 3501 * Make sure the given activity matches the current configuration. Returns 3502 * false if the activity had to be destroyed. Returns true if the 3503 * configuration is the same, or the activity will remain running as-is 3504 * for whatever reason. Ensures the HistoryRecord is updated with the 3505 * correct configuration and all other bookkeeping is handled. 3506 */ 3507 final boolean ensureActivityConfigurationLocked(ActivityRecord r, 3508 int globalChanges) { 3509 if (mConfigWillChange) { 3510 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3511 "Skipping config check (will change): " + r); 3512 return true; 3513 } 3514 3515 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3516 "Ensuring correct configuration: " + r); 3517 3518 // Short circuit: if the two configurations are the exact same 3519 // object (the common case), then there is nothing to do. 3520 Configuration newConfig = mService.mConfiguration; 3521 if (r.configuration == newConfig && !r.forceNewConfig) { 3522 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3523 "Configuration unchanged in " + r); 3524 return true; 3525 } 3526 3527 // We don't worry about activities that are finishing. 3528 if (r.finishing) { 3529 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3530 "Configuration doesn't matter in finishing " + r); 3531 r.stopFreezingScreenLocked(false); 3532 return true; 3533 } 3534 3535 // Okay we now are going to make this activity have the new config. 3536 // But then we need to figure out how it needs to deal with that. 3537 Configuration oldConfig = r.configuration; 3538 r.configuration = newConfig; 3539 3540 // Determine what has changed. May be nothing, if this is a config 3541 // that has come back from the app after going idle. In that case 3542 // we just want to leave the official config object now in the 3543 // activity and do nothing else. 3544 final int changes = oldConfig.diff(newConfig); 3545 if (changes == 0 && !r.forceNewConfig) { 3546 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3547 "Configuration no differences in " + r); 3548 return true; 3549 } 3550 3551 // If the activity isn't currently running, just leave the new 3552 // configuration and it will pick that up next time it starts. 3553 if (r.app == null || r.app.thread == null) { 3554 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3555 "Configuration doesn't matter not running " + r); 3556 r.stopFreezingScreenLocked(false); 3557 r.forceNewConfig = false; 3558 return true; 3559 } 3560 3561 // Figure out how to handle the changes between the configurations. 3562 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) { 3563 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x" 3564 + Integer.toHexString(changes) + ", handles=0x" 3565 + Integer.toHexString(r.info.getRealConfigChanged()) 3566 + ", newConfig=" + newConfig); 3567 } 3568 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) { 3569 // Aha, the activity isn't handling the change, so DIE DIE DIE. 3570 r.configChangeFlags |= changes; 3571 r.startFreezingScreenLocked(r.app, globalChanges); 3572 r.forceNewConfig = false; 3573 if (r.app == null || r.app.thread == null) { 3574 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3575 "Config is destroying non-running " + r); 3576 destroyActivityLocked(r, true, "config"); 3577 } else if (r.state == ActivityState.PAUSING) { 3578 // A little annoying: we are waiting for this activity to 3579 // finish pausing. Let's not do anything now, but just 3580 // flag that it needs to be restarted when done pausing. 3581 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3582 "Config is skipping already pausing " + r); 3583 r.configDestroy = true; 3584 return true; 3585 } else if (r.state == ActivityState.RESUMED) { 3586 // Try to optimize this case: the configuration is changing 3587 // and we need to restart the top, resumed activity. 3588 // Instead of doing the normal handshaking, just say 3589 // "restart!". 3590 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3591 "Config is relaunching resumed " + r); 3592 relaunchActivityLocked(r, r.configChangeFlags, true); 3593 r.configChangeFlags = 0; 3594 } else { 3595 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3596 "Config is relaunching non-resumed " + r); 3597 relaunchActivityLocked(r, r.configChangeFlags, false); 3598 r.configChangeFlags = 0; 3599 } 3600 3601 // All done... tell the caller we weren't able to keep this 3602 // activity around. 3603 return false; 3604 } 3605 3606 // Default case: the activity can handle this new configuration, so 3607 // hand it over. Note that we don't need to give it the new 3608 // configuration, since we always send configuration changes to all 3609 // process when they happen so it can just use whatever configuration 3610 // it last got. 3611 if (r.app != null && r.app.thread != null) { 3612 try { 3613 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r); 3614 r.app.thread.scheduleActivityConfigurationChanged(r.appToken); 3615 } catch (RemoteException e) { 3616 // If process died, whatever. 3617 } 3618 } 3619 r.stopFreezingScreenLocked(false); 3620 3621 return true; 3622 } 3623 3624 private boolean relaunchActivityLocked(ActivityRecord r, 3625 int changes, boolean andResume) { 3626 List<ResultInfo> results = null; 3627 List<Intent> newIntents = null; 3628 if (andResume) { 3629 results = r.results; 3630 newIntents = r.newIntents; 3631 } 3632 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r 3633 + " with results=" + results + " newIntents=" + newIntents 3634 + " andResume=" + andResume); 3635 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY 3636 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r), 3637 r.task.taskId, r.shortComponentName); 3638 3639 r.startFreezingScreenLocked(r.app, 0); 3640 3641 mStackSupervisor.removeChildActivityContainers(r); 3642 3643 try { 3644 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, 3645 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ") 3646 + r); 3647 r.forceNewConfig = false; 3648 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents, 3649 changes, !andResume, new Configuration(mService.mConfiguration)); 3650 // Note: don't need to call pauseIfSleepingLocked() here, because 3651 // the caller will only pass in 'andResume' if this activity is 3652 // currently resumed, which implies we aren't sleeping. 3653 } catch (RemoteException e) { 3654 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e); 3655 } 3656 3657 if (andResume) { 3658 r.results = null; 3659 r.newIntents = null; 3660 r.state = ActivityState.RESUMED; 3661 } else { 3662 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 3663 r.state = ActivityState.PAUSED; 3664 } 3665 3666 return true; 3667 } 3668 3669 boolean willActivityBeVisibleLocked(IBinder token) { 3670 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3671 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3672 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3673 final ActivityRecord r = activities.get(activityNdx); 3674 if (r.appToken == token) { 3675 return true; 3676 } 3677 if (r.fullscreen && !r.finishing) { 3678 return false; 3679 } 3680 } 3681 } 3682 final ActivityRecord r = ActivityRecord.forToken(token); 3683 if (r == null) { 3684 return false; 3685 } 3686 if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false," 3687 + " would have returned true for r=" + r); 3688 return !r.finishing; 3689 } 3690 3691 void closeSystemDialogsLocked() { 3692 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3693 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3694 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3695 final ActivityRecord r = activities.get(activityNdx); 3696 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) { 3697 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true); 3698 } 3699 } 3700 } 3701 } 3702 3703 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) { 3704 boolean didSomething = false; 3705 TaskRecord lastTask = null; 3706 ComponentName homeActivity = null; 3707 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3708 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3709 int numActivities = activities.size(); 3710 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) { 3711 ActivityRecord r = activities.get(activityNdx); 3712 final boolean samePackage = r.packageName.equals(name) 3713 || (name == null && r.userId == userId); 3714 if ((userId == UserHandle.USER_ALL || r.userId == userId) 3715 && (samePackage || r.task == lastTask) 3716 && (r.app == null || evenPersistent || !r.app.persistent)) { 3717 if (!doit) { 3718 if (r.finishing) { 3719 // If this activity is just finishing, then it is not 3720 // interesting as far as something to stop. 3721 continue; 3722 } 3723 return true; 3724 } 3725 if (r.isHomeActivity()) { 3726 if (homeActivity != null && homeActivity.equals(r.realActivity)) { 3727 Slog.i(TAG, "Skip force-stop again " + r); 3728 continue; 3729 } else { 3730 homeActivity = r.realActivity; 3731 } 3732 } 3733 didSomething = true; 3734 Slog.i(TAG, " Force finishing activity " + r); 3735 if (samePackage) { 3736 if (r.app != null) { 3737 r.app.removed = true; 3738 } 3739 r.app = null; 3740 } 3741 lastTask = r.task; 3742 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop", 3743 true)) { 3744 // r has been deleted from mActivities, accommodate. 3745 --numActivities; 3746 --activityNdx; 3747 } 3748 } 3749 } 3750 } 3751 return didSomething; 3752 } 3753 3754 void getTasksLocked(List<RunningTaskInfo> list, int callingUid, boolean allowed) { 3755 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3756 final TaskRecord task = mTaskHistory.get(taskNdx); 3757 ActivityRecord r = null; 3758 ActivityRecord top = null; 3759 int numActivities = 0; 3760 int numRunning = 0; 3761 final ArrayList<ActivityRecord> activities = task.mActivities; 3762 if (activities.isEmpty()) { 3763 continue; 3764 } 3765 if (!allowed && !task.isHomeTask() && task.creatorUid != callingUid) { 3766 continue; 3767 } 3768 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3769 r = activities.get(activityNdx); 3770 3771 // Initialize state for next task if needed. 3772 if (top == null || (top.state == ActivityState.INITIALIZING)) { 3773 top = r; 3774 numActivities = numRunning = 0; 3775 } 3776 3777 // Add 'r' into the current task. 3778 numActivities++; 3779 if (r.app != null && r.app.thread != null) { 3780 numRunning++; 3781 } 3782 3783 if (localLOGV) Slog.v( 3784 TAG, r.intent.getComponent().flattenToShortString() 3785 + ": task=" + r.task); 3786 } 3787 3788 RunningTaskInfo ci = new RunningTaskInfo(); 3789 ci.id = task.taskId; 3790 ci.baseActivity = r.intent.getComponent(); 3791 ci.topActivity = top.intent.getComponent(); 3792 ci.lastActiveTime = task.lastActiveTime; 3793 3794 if (top.task != null) { 3795 ci.description = top.task.lastDescription; 3796 } 3797 ci.numActivities = numActivities; 3798 ci.numRunning = numRunning; 3799 //System.out.println( 3800 // "#" + maxNum + ": " + " descr=" + ci.description); 3801 list.add(ci); 3802 } 3803 } 3804 3805 public void unhandledBackLocked() { 3806 final int top = mTaskHistory.size() - 1; 3807 if (DEBUG_SWITCH) Slog.d( 3808 TAG, "Performing unhandledBack(): top activity at " + top); 3809 if (top >= 0) { 3810 final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities; 3811 int activityTop = activities.size() - 1; 3812 if (activityTop > 0) { 3813 finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null, 3814 "unhandled-back", true); 3815 } 3816 } 3817 } 3818 3819 /** 3820 * Reset local parameters because an app's activity died. 3821 * @param app The app of the activity that died. 3822 * @return result from removeHistoryRecordsForAppLocked. 3823 */ 3824 boolean handleAppDiedLocked(ProcessRecord app) { 3825 if (mPausingActivity != null && mPausingActivity.app == app) { 3826 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG, 3827 "App died while pausing: " + mPausingActivity); 3828 mPausingActivity = null; 3829 } 3830 if (mLastPausedActivity != null && mLastPausedActivity.app == app) { 3831 mLastPausedActivity = null; 3832 mLastNoHistoryActivity = null; 3833 } 3834 3835 return removeHistoryRecordsForAppLocked(app); 3836 } 3837 3838 void handleAppCrashLocked(ProcessRecord app) { 3839 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3840 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3841 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3842 final ActivityRecord r = activities.get(activityNdx); 3843 if (r.app == app) { 3844 Slog.w(TAG, " Force finishing activity " 3845 + r.intent.getComponent().flattenToShortString()); 3846 // Force the destroy to skip right to removal. 3847 r.app = null; 3848 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false); 3849 } 3850 } 3851 } 3852 } 3853 3854 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll, 3855 boolean dumpClient, String dumpPackage, boolean needSep, String header) { 3856 boolean printed = false; 3857 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3858 final TaskRecord task = mTaskHistory.get(taskNdx); 3859 printed |= ActivityStackSupervisor.dumpHistoryList(fd, pw, 3860 mTaskHistory.get(taskNdx).mActivities, " ", "Hist", true, !dumpAll, 3861 dumpClient, dumpPackage, needSep, header, 3862 " Task id #" + task.taskId); 3863 if (printed) { 3864 header = null; 3865 } 3866 } 3867 return printed; 3868 } 3869 3870 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) { 3871 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(); 3872 3873 if ("all".equals(name)) { 3874 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3875 activities.addAll(mTaskHistory.get(taskNdx).mActivities); 3876 } 3877 } else if ("top".equals(name)) { 3878 final int top = mTaskHistory.size() - 1; 3879 if (top >= 0) { 3880 final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities; 3881 int listTop = list.size() - 1; 3882 if (listTop >= 0) { 3883 activities.add(list.get(listTop)); 3884 } 3885 } 3886 } else { 3887 ItemMatcher matcher = new ItemMatcher(); 3888 matcher.build(name); 3889 3890 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3891 for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) { 3892 if (matcher.match(r1, r1.intent.getComponent())) { 3893 activities.add(r1); 3894 } 3895 } 3896 } 3897 } 3898 3899 return activities; 3900 } 3901 3902 ActivityRecord restartPackage(String packageName) { 3903 ActivityRecord starting = topRunningActivityLocked(null); 3904 3905 // All activities that came from the package must be 3906 // restarted as if there was a config change. 3907 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3908 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3909 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3910 final ActivityRecord a = activities.get(activityNdx); 3911 if (a.info.packageName.equals(packageName)) { 3912 a.forceNewConfig = true; 3913 if (starting != null && a == starting && a.visible) { 3914 a.startFreezingScreenLocked(starting.app, 3915 ActivityInfo.CONFIG_SCREEN_LAYOUT); 3916 } 3917 } 3918 } 3919 } 3920 3921 return starting; 3922 } 3923 3924 void removeTask(TaskRecord task) { 3925 mStackSupervisor.endLockTaskModeIfTaskEnding(task); 3926 mWindowManager.removeTask(task.taskId); 3927 final ActivityRecord r = mResumedActivity; 3928 if (r != null && r.task == task) { 3929 mResumedActivity = null; 3930 } 3931 3932 final int taskNdx = mTaskHistory.indexOf(task); 3933 final int topTaskNdx = mTaskHistory.size() - 1; 3934 if (task.isOverHomeStack() && taskNdx < topTaskNdx) { 3935 final TaskRecord nextTask = mTaskHistory.get(taskNdx + 1); 3936 if (!nextTask.isOverHomeStack()) { 3937 nextTask.setTaskToReturnTo(HOME_ACTIVITY_TYPE); 3938 } 3939 } 3940 mTaskHistory.remove(task); 3941 updateTaskMovement(task, true); 3942 3943 if (task.mActivities.isEmpty()) { 3944 final boolean isVoiceSession = task.voiceSession != null; 3945 if (isVoiceSession) { 3946 try { 3947 task.voiceSession.taskFinished(task.intent, task.taskId); 3948 } catch (RemoteException e) { 3949 } 3950 } 3951 if (task.autoRemoveFromRecents() || isVoiceSession) { 3952 // Task creator asked to remove this when done, or this task was a voice 3953 // interaction, so it should not remain on the recent tasks list. 3954 mService.mRecentTasks.remove(task); 3955 task.closeRecentsChain(); 3956 } 3957 } 3958 3959 if (mTaskHistory.isEmpty()) { 3960 if (DEBUG_STACK) Slog.i(TAG, "removeTask: moving to back stack=" + this); 3961 if (isOnHomeDisplay()) { 3962 mStackSupervisor.moveHomeStack(!isHomeStack()); 3963 } 3964 if (mStacks != null) { 3965 mStacks.remove(this); 3966 mStacks.add(0, this); 3967 } 3968 mActivityContainer.onTaskListEmptyLocked(); 3969 } 3970 } 3971 3972 TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent, 3973 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, 3974 boolean toTop) { 3975 TaskRecord task = new TaskRecord(mService, taskId, info, intent, voiceSession, 3976 voiceInteractor); 3977 addTask(task, toTop, false); 3978 return task; 3979 } 3980 3981 ArrayList<TaskRecord> getAllTasks() { 3982 return new ArrayList<TaskRecord>(mTaskHistory); 3983 } 3984 3985 void addTask(final TaskRecord task, final boolean toTop, boolean moving) { 3986 task.stack = this; 3987 if (toTop) { 3988 insertTaskAtTop(task); 3989 } else { 3990 mTaskHistory.add(0, task); 3991 updateTaskMovement(task, false); 3992 } 3993 if (!moving && task.voiceSession != null) { 3994 try { 3995 task.voiceSession.taskStarted(task.intent, task.taskId); 3996 } catch (RemoteException e) { 3997 } 3998 } 3999 } 4000 4001 public int getStackId() { 4002 return mStackId; 4003 } 4004 4005 @Override 4006 public String toString() { 4007 return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this)) 4008 + " stackId=" + mStackId + ", " + mTaskHistory.size() + " tasks}"; 4009 } 4010} 4011