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