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