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