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