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