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