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