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