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