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