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