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