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