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