ActivityStack.java revision 1666e317dc1a17e9435246ec6c8209dbb6ee3696
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 android.app.ActivityManager.StackId.DOCKED_STACK_ID; 20import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID; 21import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID; 22import static android.app.ActivityManager.StackId.HOME_STACK_ID; 23import static android.app.ActivityManager.StackId.INVALID_STACK_ID; 24import static android.app.ActivityManager.StackId.PINNED_STACK_ID; 25import static android.content.pm.ActivityInfo.CONFIG_SCREEN_LAYOUT; 26import static android.content.pm.ActivityInfo.FLAG_RESUME_WHILE_PAUSING; 27import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS; 28import static android.view.Display.DEFAULT_DISPLAY; 29import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ADD_REMOVE; 30import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL; 31import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_APP; 32import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CLEANUP; 33import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONTAINERS; 34import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE; 35import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE; 36import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RESULTS; 37import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SAVED_STATE; 38import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK; 39import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES; 40import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH; 41import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS; 42import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TRANSITION; 43import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_USER_LEAVING; 44import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBILITY; 45import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_ADD_REMOVE; 46import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_APP; 47import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP; 48import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONTAINERS; 49import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE; 50import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE; 51import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RESULTS; 52import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SAVED_STATE; 53import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK; 54import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES; 55import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH; 56import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS; 57import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TRANSITION; 58import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_USER_LEAVING; 59import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBILITY; 60import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 61import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 62import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE; 63import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE; 64import static com.android.server.am.ActivityStackSupervisor.FindTaskResult; 65import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS; 66import static com.android.server.wm.AppTransition.TRANSIT_ACTIVITY_CLOSE; 67import static com.android.server.wm.AppTransition.TRANSIT_ACTIVITY_OPEN; 68import static com.android.server.wm.AppTransition.TRANSIT_NONE; 69import static com.android.server.wm.AppTransition.TRANSIT_TASK_CLOSE; 70import static com.android.server.wm.AppTransition.TRANSIT_TASK_OPEN; 71import static com.android.server.wm.AppTransition.TRANSIT_TASK_OPEN_BEHIND; 72import static com.android.server.wm.AppTransition.TRANSIT_TASK_TO_BACK; 73import static com.android.server.wm.AppTransition.TRANSIT_TASK_TO_FRONT; 74import static java.lang.Integer.MAX_VALUE; 75 76import android.app.Activity; 77import android.app.ActivityManager; 78import android.app.ActivityManager.RunningTaskInfo; 79import android.app.ActivityManager.StackId; 80import android.app.ActivityOptions; 81import android.app.AppGlobals; 82import android.app.IActivityController; 83import android.app.RemoteAction; 84import android.app.ResultInfo; 85import android.content.ComponentName; 86import android.content.Intent; 87import android.content.pm.ActivityInfo; 88import android.content.pm.ApplicationInfo; 89import android.content.res.Configuration; 90import android.graphics.Point; 91import android.graphics.Rect; 92import android.net.Uri; 93import android.os.Binder; 94import android.os.Bundle; 95import android.os.Debug; 96import android.os.Handler; 97import android.os.IBinder; 98import android.os.Looper; 99import android.os.Message; 100import android.os.RemoteException; 101import android.os.SystemClock; 102import android.os.Trace; 103import android.os.UserHandle; 104import android.service.voice.IVoiceInteractionSession; 105import android.util.ArraySet; 106import android.util.EventLog; 107import android.util.IntArray; 108import android.util.Log; 109import android.util.Slog; 110import android.util.SparseArray; 111import android.view.Display; 112 113import com.android.internal.app.IVoiceInteractor; 114import com.android.internal.os.BatteryStatsImpl; 115import com.android.server.Watchdog; 116import com.android.server.am.ActivityManagerService.ItemMatcher; 117import com.android.server.am.ActivityStackSupervisor.ActivityContainer; 118import com.android.server.wm.StackWindowController; 119import com.android.server.wm.StackWindowListener; 120import com.android.server.wm.WindowManagerService; 121 122import java.io.FileDescriptor; 123import java.io.PrintWriter; 124import java.lang.ref.WeakReference; 125import java.util.ArrayList; 126import java.util.Iterator; 127import java.util.List; 128import java.util.Objects; 129import java.util.Set; 130 131/** 132 * State and management of a single stack of activities. 133 */ 134final class ActivityStack extends ConfigurationContainer implements StackWindowListener { 135 136 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStack" : TAG_AM; 137 private static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE; 138 private static final String TAG_APP = TAG + POSTFIX_APP; 139 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP; 140 private static final String TAG_CONTAINERS = TAG + POSTFIX_CONTAINERS; 141 private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE; 142 private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE; 143 private static final String TAG_RESULTS = TAG + POSTFIX_RESULTS; 144 private static final String TAG_SAVED_STATE = TAG + POSTFIX_SAVED_STATE; 145 private static final String TAG_STACK = TAG + POSTFIX_STACK; 146 private static final String TAG_STATES = TAG + POSTFIX_STATES; 147 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 148 private static final String TAG_TASKS = TAG + POSTFIX_TASKS; 149 private static final String TAG_TRANSITION = TAG + POSTFIX_TRANSITION; 150 private static final String TAG_USER_LEAVING = TAG + POSTFIX_USER_LEAVING; 151 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY; 152 153 // Ticks during which we check progress while waiting for an app to launch. 154 static final int LAUNCH_TICK = 500; 155 156 // How long we wait until giving up on the last activity to pause. This 157 // is short because it directly impacts the responsiveness of starting the 158 // next activity. 159 private static final int PAUSE_TIMEOUT = 500; 160 161 // How long we wait for the activity to tell us it has stopped before 162 // giving up. This is a good amount of time because we really need this 163 // from the application in order to get its saved state. 164 private static final int STOP_TIMEOUT = 10 * 1000; 165 166 // How long we wait until giving up on an activity telling us it has 167 // finished destroying itself. 168 private static final int DESTROY_TIMEOUT = 10 * 1000; 169 170 // How long until we reset a task when the user returns to it. Currently 171 // disabled. 172 private static final long ACTIVITY_INACTIVE_RESET_TIME = 0; 173 174 // Set to false to disable the preview that is shown while a new activity 175 // is being started. 176 private static final boolean SHOW_APP_STARTING_PREVIEW = true; 177 178 // How long to wait for all background Activities to redraw following a call to 179 // convertToTranslucent(). 180 private static final long TRANSLUCENT_CONVERSION_TIMEOUT = 2000; 181 182 // How many activities have to be scheduled to stop to force a stop pass. 183 private static final int MAX_STOPPING_TO_FORCE = 3; 184 185 @Override 186 protected int getChildCount() { 187 return mTaskHistory.size(); 188 } 189 190 @Override 191 protected ConfigurationContainer getChildAt(int index) { 192 return mTaskHistory.get(index); 193 } 194 195 @Override 196 protected ConfigurationContainer getParent() { 197 return mActivityContainer.mActivityDisplay; 198 } 199 200 @Override 201 void onParentChanged() { 202 super.onParentChanged(); 203 mStackSupervisor.updateUIDsPresentOnDisplay(); 204 } 205 206 enum ActivityState { 207 INITIALIZING, 208 RESUMED, 209 PAUSING, 210 PAUSED, 211 STOPPING, 212 STOPPED, 213 FINISHING, 214 DESTROYING, 215 DESTROYED 216 } 217 218 // Stack is not considered visible. 219 static final int STACK_INVISIBLE = 0; 220 // Stack is considered visible 221 static final int STACK_VISIBLE = 1; 222 // Stack is considered visible, but only becuase it has activity that is visible behind other 223 // activities and there is a specific combination of stacks. 224 private static final int STACK_VISIBLE_ACTIVITY_BEHIND = 2; 225 226 /* The various modes for the method {@link #removeTask}. */ 227 // Task is being completely removed from all stacks in the system. 228 private static final int REMOVE_TASK_MODE_DESTROYING = 0; 229 // Task is being removed from this stack so we can add it to another stack. In the case we are 230 // moving we don't want to perform some operations on the task like removing it from window 231 // manager or recents. 232 static final int REMOVE_TASK_MODE_MOVING = 1; 233 // Similar to {@link #REMOVE_TASK_MODE_MOVING} and the task will be added to the top of its new 234 // stack and the new stack will be on top of all stacks. 235 private static final int REMOVE_TASK_MODE_MOVING_TO_TOP = 2; 236 237 // The height/width divide used when fitting a task within a bounds with method 238 // {@link #fitWithinBounds}. 239 // We always want the task to to be visible in the bounds without affecting its size when 240 // fitting. To make sure this is the case, we don't adjust the task left or top side pass 241 // the input bounds right or bottom side minus the width or height divided by this value. 242 private static final int FIT_WITHIN_BOUNDS_DIVIDER = 3; 243 244 final ActivityManagerService mService; 245 private final WindowManagerService mWindowManager; 246 private StackWindowController mWindowContainerController; 247 private final RecentTasks mRecentTasks; 248 249 /** 250 * The back history of all previous (and possibly still 251 * running) activities. It contains #TaskRecord objects. 252 */ 253 private final ArrayList<TaskRecord> mTaskHistory = new ArrayList<>(); 254 255 /** 256 * List of running activities, sorted by recent usage. 257 * The first entry in the list is the least recently used. 258 * It contains HistoryRecord objects. 259 */ 260 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<>(); 261 262 /** 263 * Animations that for the current transition have requested not to 264 * be considered for the transition animation. 265 */ 266 final ArrayList<ActivityRecord> mNoAnimActivities = new ArrayList<>(); 267 268 /** 269 * When we are in the process of pausing an activity, before starting the 270 * next one, this variable holds the activity that is currently being paused. 271 */ 272 ActivityRecord mPausingActivity = null; 273 274 /** 275 * This is the last activity that we put into the paused state. This is 276 * used to determine if we need to do an activity transition while sleeping, 277 * when we normally hold the top activity paused. 278 */ 279 ActivityRecord mLastPausedActivity = null; 280 281 /** 282 * Activities that specify No History must be removed once the user navigates away from them. 283 * If the device goes to sleep with such an activity in the paused state then we save it here 284 * and finish it later if another activity replaces it on wakeup. 285 */ 286 ActivityRecord mLastNoHistoryActivity = null; 287 288 /** 289 * Current activity that is resumed, or null if there is none. 290 */ 291 ActivityRecord mResumedActivity = null; 292 293 // The topmost Activity passed to convertToTranslucent(). When non-null it means we are 294 // waiting for all Activities in mUndrawnActivitiesBelowTopTranslucent to be removed as they 295 // are drawn. When the last member of mUndrawnActivitiesBelowTopTranslucent is removed the 296 // Activity in mTranslucentActivityWaiting is notified via 297 // Activity.onTranslucentConversionComplete(false). If a timeout occurs prior to the last 298 // background activity being drawn then the same call will be made with a true value. 299 ActivityRecord mTranslucentActivityWaiting = null; 300 ArrayList<ActivityRecord> mUndrawnActivitiesBelowTopTranslucent = new ArrayList<>(); 301 302 /** 303 * Set when we know we are going to be calling updateConfiguration() 304 * soon, so want to skip intermediate config checks. 305 */ 306 boolean mConfigWillChange; 307 308 // Whether or not this stack covers the entire screen; by default stacks are fullscreen 309 boolean mFullscreen = true; 310 // Current bounds of the stack or null if fullscreen. 311 Rect mBounds = null; 312 313 private boolean mUpdateBoundsDeferred; 314 private boolean mUpdateBoundsDeferredCalled; 315 private final Rect mDeferredBounds = new Rect(); 316 private final Rect mDeferredTaskBounds = new Rect(); 317 private final Rect mDeferredTaskInsetBounds = new Rect(); 318 319 long mLaunchStartTime = 0; 320 long mFullyDrawnStartTime = 0; 321 322 int mCurrentUser; 323 324 final int mStackId; 325 final ActivityContainer mActivityContainer; 326 /** The other stacks, in order, on the attached display. Updated at attach/detach time. */ 327 ArrayList<ActivityStack> mStacks; 328 /** The attached Display's unique identifier, or -1 if detached */ 329 int mDisplayId; 330 331 /** Temp variables used during override configuration update. */ 332 private final SparseArray<Configuration> mTmpConfigs = new SparseArray<>(); 333 private final SparseArray<Rect> mTmpBounds = new SparseArray<>(); 334 private final SparseArray<Rect> mTmpInsetBounds = new SparseArray<>(); 335 private final Rect mTmpRect2 = new Rect(); 336 337 /** Run all ActivityStacks through this */ 338 private final ActivityStackSupervisor mStackSupervisor; 339 340 private final LaunchingTaskPositioner mTaskPositioner; 341 342 private boolean mTopActivityOccludesKeyguard; 343 private ActivityRecord mTopDismissingKeyguardActivity; 344 345 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1; 346 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2; 347 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3; 348 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4; 349 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5; 350 static final int TRANSLUCENT_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6; 351 static final int RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG = 352 ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7; 353 354 private static class ScheduleDestroyArgs { 355 final ProcessRecord mOwner; 356 final String mReason; 357 ScheduleDestroyArgs(ProcessRecord owner, String reason) { 358 mOwner = owner; 359 mReason = reason; 360 } 361 } 362 363 final Handler mHandler; 364 365 private class ActivityStackHandler extends Handler { 366 367 ActivityStackHandler(Looper looper) { 368 super(looper); 369 } 370 371 @Override 372 public void handleMessage(Message msg) { 373 switch (msg.what) { 374 case PAUSE_TIMEOUT_MSG: { 375 ActivityRecord r = (ActivityRecord)msg.obj; 376 // We don't at this point know if the activity is fullscreen, 377 // so we need to be conservative and assume it isn't. 378 Slog.w(TAG, "Activity pause timeout for " + r); 379 synchronized (mService) { 380 if (r.app != null) { 381 mService.logAppTooSlow(r.app, r.pauseTime, "pausing " + r); 382 } 383 activityPausedLocked(r.appToken, true); 384 } 385 } break; 386 case LAUNCH_TICK_MSG: { 387 ActivityRecord r = (ActivityRecord)msg.obj; 388 synchronized (mService) { 389 if (r.continueLaunchTickingLocked()) { 390 mService.logAppTooSlow(r.app, r.launchTickTime, "launching " + r); 391 } 392 } 393 } break; 394 case DESTROY_TIMEOUT_MSG: { 395 ActivityRecord r = (ActivityRecord)msg.obj; 396 // We don't at this point know if the activity is fullscreen, 397 // so we need to be conservative and assume it isn't. 398 Slog.w(TAG, "Activity destroy timeout for " + r); 399 synchronized (mService) { 400 activityDestroyedLocked(r != null ? r.appToken : null, "destroyTimeout"); 401 } 402 } break; 403 case STOP_TIMEOUT_MSG: { 404 ActivityRecord r = (ActivityRecord)msg.obj; 405 // We don't at this point know if the activity is fullscreen, 406 // so we need to be conservative and assume it isn't. 407 Slog.w(TAG, "Activity stop timeout for " + r); 408 synchronized (mService) { 409 if (r.isInHistory()) { 410 r.activityStoppedLocked(null /* icicle */, 411 null /* persistentState */, null /* description */); 412 } 413 } 414 } break; 415 case DESTROY_ACTIVITIES_MSG: { 416 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj; 417 synchronized (mService) { 418 destroyActivitiesLocked(args.mOwner, args.mReason); 419 } 420 } break; 421 case TRANSLUCENT_TIMEOUT_MSG: { 422 synchronized (mService) { 423 notifyActivityDrawnLocked(null); 424 } 425 } break; 426 case RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG: { 427 synchronized (mService) { 428 final ActivityRecord r = getVisibleBehindActivity(); 429 Slog.e(TAG, "Timeout waiting for cancelVisibleBehind player=" + r); 430 if (r != null) { 431 mService.killAppAtUsersRequest(r.app, null); 432 } 433 } 434 } break; 435 } 436 } 437 } 438 439 int numActivities() { 440 int count = 0; 441 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 442 count += mTaskHistory.get(taskNdx).mActivities.size(); 443 } 444 return count; 445 } 446 447 ActivityStack(ActivityStackSupervisor.ActivityContainer activityContainer, 448 RecentTasks recentTasks, boolean onTop) { 449 mActivityContainer = activityContainer; 450 mStackSupervisor = activityContainer.getOuter(); 451 mService = mStackSupervisor.mService; 452 mHandler = new ActivityStackHandler(mService.mHandler.getLooper()); 453 mWindowManager = mService.mWindowManager; 454 mStackId = activityContainer.mStackId; 455 mCurrentUser = mService.mUserController.getCurrentUserIdLocked(); 456 mRecentTasks = recentTasks; 457 mTaskPositioner = mStackId == FREEFORM_WORKSPACE_STACK_ID 458 ? new LaunchingTaskPositioner() : null; 459 final ActivityStackSupervisor.ActivityDisplay display = mActivityContainer.mActivityDisplay; 460 mTmpRect2.setEmpty(); 461 mWindowContainerController = new StackWindowController(mStackId, this, 462 display.mDisplayId, onTop, mTmpRect2); 463 activityContainer.mStack = this; 464 mStackSupervisor.mActivityContainers.put(mStackId, activityContainer); 465 postAddToDisplay(display, mTmpRect2.isEmpty() ? null : mTmpRect2, onTop); 466 } 467 468 StackWindowController getWindowContainerController() { 469 return mWindowContainerController; 470 } 471 472 /** Adds the stack to specified display and calls WindowManager to do the same. */ 473 void reparent(ActivityStackSupervisor.ActivityDisplay activityDisplay, boolean onTop) { 474 removeFromDisplay(); 475 mTmpRect2.setEmpty(); 476 mWindowContainerController.reparent(activityDisplay.mDisplayId, mTmpRect2); 477 postAddToDisplay(activityDisplay, mTmpRect2.isEmpty() ? null : mTmpRect2, onTop); 478 } 479 480 /** 481 * Updates internal state after adding to new display. 482 * @param activityDisplay New display to which this stack was attached. 483 * @param bounds Updated bounds. 484 */ 485 private void postAddToDisplay(ActivityStackSupervisor.ActivityDisplay activityDisplay, 486 Rect bounds, boolean onTop) { 487 mDisplayId = activityDisplay.mDisplayId; 488 mStacks = activityDisplay.mStacks; 489 mBounds = bounds != null ? new Rect(bounds) : null; 490 mFullscreen = mBounds == null; 491 if (mTaskPositioner != null) { 492 mTaskPositioner.setDisplay(activityDisplay.mDisplay); 493 mTaskPositioner.configure(mBounds); 494 } 495 onParentChanged(); 496 497 activityDisplay.attachStack(this, onTop); 498 if (mStackId == DOCKED_STACK_ID) { 499 // If we created a docked stack we want to resize it so it resizes all other stacks 500 // in the system. 501 mStackSupervisor.resizeDockedStackLocked( 502 mBounds, null, null, null, null, PRESERVE_WINDOWS); 503 } 504 } 505 506 /** 507 * Updates the inner state of the stack to remove it from its current parent, so it can be 508 * either destroyed completely or re-parented. 509 */ 510 private void removeFromDisplay() { 511 mDisplayId = Display.INVALID_DISPLAY; 512 mStacks = null; 513 if (mTaskPositioner != null) { 514 mTaskPositioner.reset(); 515 } 516 if (mStackId == DOCKED_STACK_ID) { 517 // If we removed a docked stack we want to resize it so it resizes all other stacks 518 // in the system to fullscreen. 519 mStackSupervisor.resizeDockedStackLocked( 520 null, null, null, null, null, PRESERVE_WINDOWS); 521 } 522 } 523 524 /** Removes the stack completely. Also calls WindowManager to do the same on its side. */ 525 void remove() { 526 removeFromDisplay(); 527 mStackSupervisor.deleteActivityContainerRecord(mStackId); 528 mWindowContainerController.removeContainer(); 529 mWindowContainerController = null; 530 onParentChanged(); 531 } 532 533 void getDisplaySize(Point out) { 534 mActivityContainer.mActivityDisplay.mDisplay.getSize(out); 535 } 536 537 void animateResizePinnedStack(Rect bounds, int animationDuration) { 538 mWindowContainerController.animateResizePinnedStack(bounds, animationDuration); 539 } 540 541 void setPictureInPictureAspectRatio(float aspectRatio) { 542 mWindowContainerController.setPictureInPictureAspectRatio(aspectRatio); 543 } 544 545 void getStackDockedModeBounds(Rect outBounds, boolean ignoreVisibility) { 546 mWindowContainerController.getStackDockedModeBounds(outBounds, ignoreVisibility); 547 } 548 549 void prepareFreezingTaskBounds() { 550 mWindowContainerController.prepareFreezingTaskBounds(); 551 } 552 553 void setPictureInPictureActions(List<RemoteAction> actions) { 554 mWindowContainerController.setPictureInPictureActions(actions); 555 } 556 557 void getWindowContainerBounds(Rect outBounds) { 558 if (mWindowContainerController != null) { 559 mWindowContainerController.getBounds(outBounds); 560 } 561 outBounds.setEmpty(); 562 } 563 564 Rect getBoundsForNewConfiguration() { 565 return mWindowContainerController.getBoundsForNewConfiguration(); 566 } 567 568 void positionChildWindowContainerAtTop(TaskRecord child) { 569 mWindowContainerController.positionChildAtTop(child.getWindowContainerController(), 570 true /* includingParents */); 571 } 572 573 /** 574 * Defers updating the bounds of the stack. If the stack was resized/repositioned while 575 * deferring, the bounds will update in {@link #continueUpdateBounds()}. 576 */ 577 void deferUpdateBounds() { 578 if (!mUpdateBoundsDeferred) { 579 mUpdateBoundsDeferred = true; 580 mUpdateBoundsDeferredCalled = false; 581 } 582 } 583 584 /** 585 * Continues updating bounds after updates have been deferred. If there was a resize attempt 586 * between {@link #deferUpdateBounds()} and {@link #continueUpdateBounds()}, the stack will 587 * be resized to that bounds. 588 */ 589 void continueUpdateBounds() { 590 final boolean wasDeferred = mUpdateBoundsDeferred; 591 mUpdateBoundsDeferred = false; 592 if (wasDeferred && mUpdateBoundsDeferredCalled) { 593 resize(mDeferredBounds.isEmpty() ? null : mDeferredBounds, 594 mDeferredTaskBounds.isEmpty() ? null : mDeferredTaskBounds, 595 mDeferredTaskInsetBounds.isEmpty() ? null : mDeferredTaskInsetBounds); 596 } 597 } 598 599 boolean updateBoundsAllowed(Rect bounds, Rect tempTaskBounds, 600 Rect tempTaskInsetBounds) { 601 if (!mUpdateBoundsDeferred) { 602 return true; 603 } 604 if (bounds != null) { 605 mDeferredBounds.set(bounds); 606 } else { 607 mDeferredBounds.setEmpty(); 608 } 609 if (tempTaskBounds != null) { 610 mDeferredTaskBounds.set(tempTaskBounds); 611 } else { 612 mDeferredTaskBounds.setEmpty(); 613 } 614 if (tempTaskInsetBounds != null) { 615 mDeferredTaskInsetBounds.set(tempTaskInsetBounds); 616 } else { 617 mDeferredTaskInsetBounds.setEmpty(); 618 } 619 mUpdateBoundsDeferredCalled = true; 620 return false; 621 } 622 623 void setBounds(Rect bounds) { 624 mBounds = mFullscreen ? null : new Rect(bounds); 625 if (mTaskPositioner != null) { 626 mTaskPositioner.configure(bounds); 627 } 628 } 629 630 final ActivityRecord topRunningActivityLocked() { 631 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 632 ActivityRecord r = mTaskHistory.get(taskNdx).topRunningActivityLocked(); 633 if (r != null) { 634 return r; 635 } 636 } 637 return null; 638 } 639 640 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) { 641 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 642 final TaskRecord task = mTaskHistory.get(taskNdx); 643 final ArrayList<ActivityRecord> activities = task.mActivities; 644 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 645 ActivityRecord r = activities.get(activityNdx); 646 if (!r.finishing && !r.delayedResume && r != notTop && r.okToShowLocked()) { 647 return r; 648 } 649 } 650 } 651 return null; 652 } 653 654 /** 655 * This is a simplified version of topRunningActivityLocked that provides a number of 656 * optional skip-over modes. It is intended for use with the ActivityController hook only. 657 * 658 * @param token If non-null, any history records matching this token will be skipped. 659 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID. 660 * 661 * @return Returns the HistoryRecord of the next activity on the stack. 662 */ 663 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) { 664 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 665 TaskRecord task = mTaskHistory.get(taskNdx); 666 if (task.taskId == taskId) { 667 continue; 668 } 669 ArrayList<ActivityRecord> activities = task.mActivities; 670 for (int i = activities.size() - 1; i >= 0; --i) { 671 final ActivityRecord r = activities.get(i); 672 // Note: the taskId check depends on real taskId fields being non-zero 673 if (!r.finishing && (token != r.appToken) && r.okToShowLocked()) { 674 return r; 675 } 676 } 677 } 678 return null; 679 } 680 681 final ActivityRecord topActivity() { 682 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 683 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 684 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 685 final ActivityRecord r = activities.get(activityNdx); 686 if (!r.finishing) { 687 return r; 688 } 689 } 690 } 691 return null; 692 } 693 694 final TaskRecord topTask() { 695 final int size = mTaskHistory.size(); 696 if (size > 0) { 697 return mTaskHistory.get(size - 1); 698 } 699 return null; 700 } 701 702 TaskRecord taskForIdLocked(int id) { 703 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 704 final TaskRecord task = mTaskHistory.get(taskNdx); 705 if (task.taskId == id) { 706 return task; 707 } 708 } 709 return null; 710 } 711 712 ActivityRecord isInStackLocked(IBinder token) { 713 final ActivityRecord r = ActivityRecord.forTokenLocked(token); 714 return isInStackLocked(r); 715 } 716 717 ActivityRecord isInStackLocked(ActivityRecord r) { 718 if (r == null) { 719 return null; 720 } 721 final TaskRecord task = r.task; 722 final ActivityStack stack = r.getStack(); 723 if (stack != null && task.mActivities.contains(r) && mTaskHistory.contains(task)) { 724 if (stack != this) Slog.w(TAG, 725 "Illegal state! task does not point to stack it is in."); 726 return r; 727 } 728 return null; 729 } 730 731 boolean isInStackLocked(TaskRecord task) { 732 return mTaskHistory.contains(task); 733 } 734 735 /** Checks if there are tasks with specific UID in the stack. */ 736 boolean isUidPresent(int uid) { 737 for (TaskRecord task : mTaskHistory) { 738 if (task.effectiveUid == uid) { 739 return true; 740 } 741 } 742 return false; 743 } 744 745 /** Get all UIDs that are present in the stack. */ 746 void getPresentUIDs(IntArray presentUIDs) { 747 for (TaskRecord task : mTaskHistory) { 748 presentUIDs.add(task.effectiveUid); 749 } 750 } 751 752 final boolean updateLRUListLocked(ActivityRecord r) { 753 final boolean hadit = mLRUActivities.remove(r); 754 mLRUActivities.add(r); 755 return hadit; 756 } 757 758 final boolean isHomeStack() { 759 return mStackId == HOME_STACK_ID; 760 } 761 762 final boolean isHomeOrRecentsStack() { 763 return StackId.isHomeOrRecentsStack(mStackId); 764 } 765 766 final boolean isDockedStack() { 767 return mStackId == DOCKED_STACK_ID; 768 } 769 770 final boolean isPinnedStack() { 771 return mStackId == PINNED_STACK_ID; 772 } 773 774 final boolean isOnHomeDisplay() { 775 return isAttached() && 776 mActivityContainer.mActivityDisplay.mDisplayId == DEFAULT_DISPLAY; 777 } 778 779 void moveToFront(String reason) { 780 moveToFront(reason, null); 781 } 782 783 /** 784 * @param reason The reason for moving the stack to the front. 785 * @param task If non-null, the task will be moved to the top of the stack. 786 * */ 787 void moveToFront(String reason, TaskRecord task) { 788 if (!isAttached()) { 789 return; 790 } 791 792 mStacks.remove(this); 793 int addIndex = mStacks.size(); 794 if (addIndex > 0) { 795 final ActivityStack topStack = mStacks.get(addIndex - 1); 796 if (StackId.isAlwaysOnTop(topStack.mStackId) && topStack != this) { 797 // If the top stack is always on top, we move this stack just below it. 798 addIndex--; 799 } 800 } 801 802 mStacks.add(addIndex, this); 803 mStackSupervisor.setFocusStackUnchecked(reason, this); 804 if (task != null) { 805 insertTaskAtTop(task, null); 806 return; 807 } 808 809 task = topTask(); 810 if (task != null) { 811 mWindowContainerController.positionChildAtTop(task.getWindowContainerController(), 812 true /* includingParents */); 813 } 814 } 815 816 /** 817 * @param task If non-null, the task will be moved to the back of the stack. 818 * */ 819 private void moveToBack(TaskRecord task) { 820 if (!isAttached()) { 821 return; 822 } 823 824 mStacks.remove(this); 825 mStacks.add(0, this); 826 827 if (task != null) { 828 mTaskHistory.remove(task); 829 mTaskHistory.add(0, task); 830 updateTaskMovement(task, false); 831 mWindowContainerController.positionChildAtBottom(task.getWindowContainerController()); 832 } 833 } 834 835 boolean isFocusable() { 836 if (StackId.canReceiveKeys(mStackId)) { 837 return true; 838 } 839 // The stack isn't focusable. See if its top activity is focusable to force focus on the 840 // stack. 841 final ActivityRecord r = topRunningActivityLocked(); 842 return r != null && r.isFocusable(); 843 } 844 845 final boolean isAttached() { 846 return mStacks != null; 847 } 848 849 /** 850 * Returns the top activity in any existing task matching the given Intent in the input result. 851 * Returns null if no such task is found. 852 */ 853 void findTaskLocked(ActivityRecord target, FindTaskResult result) { 854 Intent intent = target.intent; 855 ActivityInfo info = target.info; 856 ComponentName cls = intent.getComponent(); 857 if (info.targetActivity != null) { 858 cls = new ComponentName(info.packageName, info.targetActivity); 859 } 860 final int userId = UserHandle.getUserId(info.applicationInfo.uid); 861 boolean isDocument = intent != null & intent.isDocument(); 862 // If documentData is non-null then it must match the existing task data. 863 Uri documentData = isDocument ? intent.getData() : null; 864 865 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + target + " in " + this); 866 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 867 final TaskRecord task = mTaskHistory.get(taskNdx); 868 if (task.voiceSession != null) { 869 // We never match voice sessions; those always run independently. 870 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": voice session"); 871 continue; 872 } 873 if (task.userId != userId) { 874 // Looking for a different task. 875 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": different user"); 876 continue; 877 } 878 final ActivityRecord r = task.getTopActivity(); 879 if (r == null || r.finishing || r.userId != userId || 880 r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) { 881 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": mismatch root " + r); 882 continue; 883 } 884 if (r.mActivityType != target.mActivityType) { 885 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": mismatch activity type"); 886 continue; 887 } 888 889 final Intent taskIntent = task.intent; 890 final Intent affinityIntent = task.affinityIntent; 891 final boolean taskIsDocument; 892 final Uri taskDocumentData; 893 if (taskIntent != null && taskIntent.isDocument()) { 894 taskIsDocument = true; 895 taskDocumentData = taskIntent.getData(); 896 } else if (affinityIntent != null && affinityIntent.isDocument()) { 897 taskIsDocument = true; 898 taskDocumentData = affinityIntent.getData(); 899 } else { 900 taskIsDocument = false; 901 taskDocumentData = null; 902 } 903 904 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Comparing existing cls=" 905 + taskIntent.getComponent().flattenToShortString() 906 + "/aff=" + r.task.rootAffinity + " to new cls=" 907 + intent.getComponent().flattenToShortString() + "/aff=" + info.taskAffinity); 908 // TODO Refactor to remove duplications. Check if logic can be simplified. 909 if (taskIntent != null && taskIntent.getComponent() != null && 910 taskIntent.getComponent().compareTo(cls) == 0 && 911 Objects.equals(documentData, taskDocumentData)) { 912 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!"); 913 //dump(); 914 if (DEBUG_TASKS) Slog.d(TAG_TASKS, 915 "For Intent " + intent + " bringing to top: " + r.intent); 916 result.r = r; 917 result.matchedByRootAffinity = false; 918 break; 919 } else if (affinityIntent != null && affinityIntent.getComponent() != null && 920 affinityIntent.getComponent().compareTo(cls) == 0 && 921 Objects.equals(documentData, taskDocumentData)) { 922 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!"); 923 //dump(); 924 if (DEBUG_TASKS) Slog.d(TAG_TASKS, 925 "For Intent " + intent + " bringing to top: " + r.intent); 926 result.r = r; 927 result.matchedByRootAffinity = false; 928 break; 929 } else if (!isDocument && !taskIsDocument 930 && result.r == null && task.canMatchRootAffinity()) { 931 if (task.rootAffinity.equals(target.taskAffinity)) { 932 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching affinity candidate!"); 933 // It is possible for multiple tasks to have the same root affinity especially 934 // if they are in separate stacks. We save off this candidate, but keep looking 935 // to see if there is a better candidate. 936 result.r = r; 937 result.matchedByRootAffinity = true; 938 } 939 } else if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Not a match: " + task); 940 } 941 } 942 943 /** 944 * Returns the first activity (starting from the top of the stack) that 945 * is the same as the given activity. Returns null if no such activity 946 * is found. 947 */ 948 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info, 949 boolean compareIntentFilters) { 950 ComponentName cls = intent.getComponent(); 951 if (info.targetActivity != null) { 952 cls = new ComponentName(info.packageName, info.targetActivity); 953 } 954 final int userId = UserHandle.getUserId(info.applicationInfo.uid); 955 956 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 957 final TaskRecord task = mTaskHistory.get(taskNdx); 958 final ArrayList<ActivityRecord> activities = task.mActivities; 959 960 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 961 ActivityRecord r = activities.get(activityNdx); 962 if (!r.okToShowLocked()) { 963 continue; 964 } 965 if (!r.finishing && r.userId == userId) { 966 if (compareIntentFilters) { 967 if (r.intent.filterEquals(intent)) { 968 return r; 969 } 970 } else { 971 if (r.intent.getComponent().equals(cls)) { 972 return r; 973 } 974 } 975 } 976 } 977 } 978 979 return null; 980 } 981 982 /* 983 * Move the activities around in the stack to bring a user to the foreground. 984 */ 985 final void switchUserLocked(int userId) { 986 if (mCurrentUser == userId) { 987 return; 988 } 989 mCurrentUser = userId; 990 991 // Move userId's tasks to the top. 992 int index = mTaskHistory.size(); 993 for (int i = 0; i < index; ) { 994 final TaskRecord task = mTaskHistory.get(i); 995 996 if (task.okToShowLocked()) { 997 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "switchUserLocked: stack=" + getStackId() + 998 " moving " + task + " to top"); 999 mTaskHistory.remove(i); 1000 mTaskHistory.add(task); 1001 --index; 1002 // Use same value for i. 1003 } else { 1004 ++i; 1005 } 1006 } 1007 } 1008 1009 void minimalResumeActivityLocked(ActivityRecord r) { 1010 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + r + " (starting new instance)" 1011 + " callers=" + Debug.getCallers(5)); 1012 setResumedActivityLocked(r, "minimalResumeActivityLocked"); 1013 r.completeResumeLocked(); 1014 setLaunchTime(r); 1015 if (DEBUG_SAVED_STATE) Slog.i(TAG_SAVED_STATE, 1016 "Launch completed; removing icicle of " + r.icicle); 1017 } 1018 1019 void addRecentActivityLocked(ActivityRecord r) { 1020 if (r != null) { 1021 mRecentTasks.addLocked(r.task); 1022 r.task.touchActiveTime(); 1023 } 1024 } 1025 1026 private void startLaunchTraces(String packageName) { 1027 if (mFullyDrawnStartTime != 0) { 1028 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0); 1029 } 1030 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching: " + packageName, 0); 1031 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0); 1032 } 1033 1034 private void stopFullyDrawnTraceIfNeeded() { 1035 if (mFullyDrawnStartTime != 0 && mLaunchStartTime == 0) { 1036 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0); 1037 mFullyDrawnStartTime = 0; 1038 } 1039 } 1040 1041 void setLaunchTime(ActivityRecord r) { 1042 if (r.displayStartTime == 0) { 1043 r.fullyDrawnStartTime = r.displayStartTime = SystemClock.uptimeMillis(); 1044 if (mLaunchStartTime == 0) { 1045 startLaunchTraces(r.packageName); 1046 mLaunchStartTime = mFullyDrawnStartTime = r.displayStartTime; 1047 } 1048 } else if (mLaunchStartTime == 0) { 1049 startLaunchTraces(r.packageName); 1050 mLaunchStartTime = mFullyDrawnStartTime = SystemClock.uptimeMillis(); 1051 } 1052 } 1053 1054 private void clearLaunchTime(ActivityRecord r) { 1055 // Make sure that there is no activity waiting for this to launch. 1056 if (mStackSupervisor.mWaitingActivityLaunched.isEmpty()) { 1057 r.displayStartTime = r.fullyDrawnStartTime = 0; 1058 } else { 1059 mStackSupervisor.removeTimeoutsForActivityLocked(r); 1060 mStackSupervisor.scheduleIdleTimeoutLocked(r); 1061 } 1062 } 1063 1064 void awakeFromSleepingLocked() { 1065 // Ensure activities are no longer sleeping. 1066 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1067 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 1068 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1069 activities.get(activityNdx).setSleeping(false); 1070 } 1071 } 1072 if (mPausingActivity != null) { 1073 Slog.d(TAG, "awakeFromSleepingLocked: previously pausing activity didn't pause"); 1074 activityPausedLocked(mPausingActivity.appToken, true); 1075 } 1076 } 1077 1078 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) { 1079 final String packageName = aInfo.packageName; 1080 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1081 final List<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 1082 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1083 if (packageName.equals(activities.get(activityNdx).packageName)) { 1084 activities.get(activityNdx).info.applicationInfo = aInfo; 1085 } 1086 } 1087 } 1088 } 1089 1090 /** 1091 * @return true if something must be done before going to sleep. 1092 */ 1093 boolean checkReadyForSleepLocked() { 1094 if (mResumedActivity != null) { 1095 // Still have something resumed; can't sleep until it is paused. 1096 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep needs to pause " + mResumedActivity); 1097 if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING, 1098 "Sleep => pause with userLeaving=false"); 1099 startPausingLocked(false, true, null, false); 1100 return true; 1101 } 1102 if (mPausingActivity != null) { 1103 // Still waiting for something to pause; can't sleep yet. 1104 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still waiting to pause " + mPausingActivity); 1105 return true; 1106 } 1107 1108 if (hasVisibleBehindActivity()) { 1109 // Stop visible behind activity before going to sleep. 1110 final ActivityRecord r = getVisibleBehindActivity(); 1111 mStackSupervisor.mStoppingActivities.add(r); 1112 if (DEBUG_STATES) Slog.v(TAG_STATES, "Sleep still waiting to stop visible behind " + r); 1113 return true; 1114 } 1115 1116 return false; 1117 } 1118 1119 void goToSleep() { 1120 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 1121 1122 // Make sure any paused or stopped but visible activities are now sleeping. 1123 // This ensures that the activity's onStop() is called. 1124 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1125 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 1126 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1127 final ActivityRecord r = activities.get(activityNdx); 1128 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED 1129 || r.state == ActivityState.PAUSED || r.state == ActivityState.PAUSING) { 1130 r.setSleeping(true); 1131 } 1132 } 1133 } 1134 } 1135 1136 /** 1137 * Start pausing the currently resumed activity. It is an error to call this if there 1138 * is already an activity being paused or there is no resumed activity. 1139 * 1140 * @param userLeaving True if this should result in an onUserLeaving to the current activity. 1141 * @param uiSleeping True if this is happening with the user interface going to sleep (the 1142 * screen turning off). 1143 * @param resuming The activity we are currently trying to resume or null if this is not being 1144 * called as part of resuming the top activity, so we shouldn't try to instigate 1145 * a resume here if not null. 1146 * @param dontWait True if the caller does not want to wait for the pause to complete. If 1147 * set to true, we will immediately complete the pause here before returning. 1148 * @return Returns true if an activity now is in the PAUSING state, and we are waiting for 1149 * it to tell us when it is done. 1150 */ 1151 final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, 1152 ActivityRecord resuming, boolean dontWait) { 1153 if (mPausingActivity != null) { 1154 Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity 1155 + " state=" + mPausingActivity.state); 1156 if (!mService.isSleepingLocked()) { 1157 // Avoid recursion among check for sleep and complete pause during sleeping. 1158 // Because activity will be paused immediately after resume, just let pause 1159 // be completed by the order of activity paused from clients. 1160 completePauseLocked(false, resuming); 1161 } 1162 } 1163 ActivityRecord prev = mResumedActivity; 1164 if (prev == null) { 1165 if (resuming == null) { 1166 Slog.wtf(TAG, "Trying to pause when nothing is resumed"); 1167 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 1168 } 1169 return false; 1170 } 1171 1172 if (mActivityContainer.mParentActivity == null) { 1173 // Top level stack, not a child. Look for child stacks. 1174 mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait); 1175 } 1176 1177 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSING: " + prev); 1178 else if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Start pausing: " + prev); 1179 mResumedActivity = null; 1180 mPausingActivity = prev; 1181 mLastPausedActivity = prev; 1182 mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0 1183 || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null; 1184 prev.state = ActivityState.PAUSING; 1185 prev.task.touchActiveTime(); 1186 clearLaunchTime(prev); 1187 final ActivityRecord next = mStackSupervisor.topRunningActivityLocked(); 1188 if (mService.mHasRecents 1189 && (next == null || next.noDisplay || next.task != prev.task || uiSleeping)) { 1190 prev.mUpdateTaskThumbnailWhenHidden = true; 1191 } 1192 stopFullyDrawnTraceIfNeeded(); 1193 1194 mService.updateCpuStats(); 1195 1196 if (prev.app != null && prev.app.thread != null) { 1197 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev); 1198 try { 1199 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY, 1200 prev.userId, System.identityHashCode(prev), 1201 prev.shortComponentName); 1202 mService.updateUsageStats(prev, false); 1203 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing, 1204 userLeaving, prev.configChangeFlags, dontWait); 1205 } catch (Exception e) { 1206 // Ignore exception, if process died other code will cleanup. 1207 Slog.w(TAG, "Exception thrown during pause", e); 1208 mPausingActivity = null; 1209 mLastPausedActivity = null; 1210 mLastNoHistoryActivity = null; 1211 } 1212 } else { 1213 mPausingActivity = null; 1214 mLastPausedActivity = null; 1215 mLastNoHistoryActivity = null; 1216 } 1217 1218 // If we are not going to sleep, we want to ensure the device is 1219 // awake until the next activity is started. 1220 if (!uiSleeping && !mService.isSleepingOrShuttingDownLocked()) { 1221 mStackSupervisor.acquireLaunchWakelock(); 1222 } 1223 1224 if (mPausingActivity != null) { 1225 // Have the window manager pause its key dispatching until the new 1226 // activity has started. If we're pausing the activity just because 1227 // the screen is being turned off and the UI is sleeping, don't interrupt 1228 // key dispatch; the same activity will pick it up again on wakeup. 1229 if (!uiSleeping) { 1230 prev.pauseKeyDispatchingLocked(); 1231 } else if (DEBUG_PAUSE) { 1232 Slog.v(TAG_PAUSE, "Key dispatch not paused for screen off"); 1233 } 1234 1235 if (dontWait) { 1236 // If the caller said they don't want to wait for the pause, then complete 1237 // the pause now. 1238 completePauseLocked(false, resuming); 1239 return false; 1240 1241 } else { 1242 // Schedule a pause timeout in case the app doesn't respond. 1243 // We don't give it much time because this directly impacts the 1244 // responsiveness seen by the user. 1245 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG); 1246 msg.obj = prev; 1247 prev.pauseTime = SystemClock.uptimeMillis(); 1248 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT); 1249 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Waiting for pause to complete..."); 1250 return true; 1251 } 1252 1253 } else { 1254 // This activity failed to schedule the 1255 // pause, so just treat it as being paused now. 1256 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Activity not running, resuming next."); 1257 if (resuming == null) { 1258 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 1259 } 1260 return false; 1261 } 1262 } 1263 1264 final void activityPausedLocked(IBinder token, boolean timeout) { 1265 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, 1266 "Activity paused: token=" + token + ", timeout=" + timeout); 1267 1268 final ActivityRecord r = isInStackLocked(token); 1269 if (r != null) { 1270 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 1271 if (mPausingActivity == r) { 1272 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r 1273 + (timeout ? " (due to timeout)" : " (pause complete)")); 1274 mService.mWindowManager.deferSurfaceLayout(); 1275 try { 1276 completePauseLocked(true, null); 1277 } finally { 1278 mService.mWindowManager.continueSurfaceLayout(); 1279 } 1280 return; 1281 } else { 1282 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE, 1283 r.userId, System.identityHashCode(r), r.shortComponentName, 1284 mPausingActivity != null 1285 ? mPausingActivity.shortComponentName : "(none)"); 1286 if (r.state == ActivityState.PAUSING) { 1287 r.state = ActivityState.PAUSED; 1288 if (r.finishing) { 1289 if (DEBUG_PAUSE) Slog.v(TAG, 1290 "Executing finish of failed to pause activity: " + r); 1291 finishCurrentActivityLocked(r, FINISH_AFTER_VISIBLE, false); 1292 } 1293 } 1294 } 1295 } 1296 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 1297 } 1298 1299 private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) { 1300 ActivityRecord prev = mPausingActivity; 1301 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Complete pause: " + prev); 1302 1303 if (prev != null) { 1304 final boolean wasStopping = prev.state == ActivityState.STOPPING; 1305 prev.state = ActivityState.PAUSED; 1306 if (prev.finishing) { 1307 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Executing finish of activity: " + prev); 1308 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false); 1309 } else if (prev.app != null) { 1310 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueue pending stop if needed: " + prev 1311 + " wasStopping=" + wasStopping + " visible=" + prev.visible); 1312 if (mStackSupervisor.mWaitingVisibleActivities.remove(prev)) { 1313 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG_PAUSE, 1314 "Complete pause, no longer waiting: " + prev); 1315 } 1316 if (prev.deferRelaunchUntilPaused) { 1317 // Complete the deferred relaunch that was waiting for pause to complete. 1318 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Re-launching after pause: " + prev); 1319 prev.relaunchActivityLocked(false /* andResume */, 1320 prev.preserveWindowOnDeferredRelaunch); 1321 } else if (wasStopping) { 1322 // We are also stopping, the stop request must have gone soon after the pause. 1323 // We can't clobber it, because the stop confirmation will not be handled. 1324 // We don't need to schedule another stop, we only need to let it happen. 1325 prev.state = ActivityState.STOPPING; 1326 } else if ((!prev.visible && !hasVisibleBehindActivity()) 1327 || mService.isSleepingOrShuttingDownLocked()) { 1328 // If we were visible then resumeTopActivities will release resources before 1329 // stopping. 1330 addToStopping(prev, true /* immediate */); 1331 } 1332 } else { 1333 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "App died during pause, not stopping: " + prev); 1334 prev = null; 1335 } 1336 // It is possible the activity was freezing the screen before it was paused. 1337 // In that case go ahead and remove the freeze this activity has on the screen 1338 // since it is no longer visible. 1339 if (prev != null) { 1340 prev.stopFreezingScreenLocked(true /*force*/); 1341 } 1342 mPausingActivity = null; 1343 } 1344 1345 if (resumeNext) { 1346 final ActivityStack topStack = mStackSupervisor.getFocusedStack(); 1347 if (!mService.isSleepingOrShuttingDownLocked()) { 1348 mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null); 1349 } else { 1350 mStackSupervisor.checkReadyForSleepLocked(); 1351 ActivityRecord top = topStack.topRunningActivityLocked(); 1352 if (top == null || (prev != null && top != prev)) { 1353 // If there are no more activities available to run, do resume anyway to start 1354 // something. Also if the top activity on the stack is not the just paused 1355 // activity, we need to go ahead and resume it to ensure we complete an 1356 // in-flight app switch. 1357 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 1358 } 1359 } 1360 } 1361 1362 if (prev != null) { 1363 prev.resumeKeyDispatchingLocked(); 1364 1365 if (prev.app != null && prev.cpuTimeAtResume > 0 1366 && mService.mBatteryStatsService.isOnBattery()) { 1367 long diff = mService.mProcessCpuTracker.getCpuTimeForPid(prev.app.pid) 1368 - prev.cpuTimeAtResume; 1369 if (diff > 0) { 1370 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics(); 1371 synchronized (bsi) { 1372 BatteryStatsImpl.Uid.Proc ps = 1373 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid, 1374 prev.info.packageName); 1375 if (ps != null) { 1376 ps.addForegroundTimeLocked(diff); 1377 } 1378 } 1379 } 1380 } 1381 prev.cpuTimeAtResume = 0; // reset it 1382 } 1383 1384 // Notify when the task stack has changed, but only if visibilities changed (not just 1385 // focus). Also if there is an active pinned stack - we always want to notify it about 1386 // task stack changes, because its positioning may depend on it. 1387 if (mStackSupervisor.mAppVisibilitiesChangedSinceLastPause 1388 || mService.mStackSupervisor.getStack(PINNED_STACK_ID) != null) { 1389 mService.mTaskChangeNotificationController.notifyTaskStackChanged(); 1390 mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = false; 1391 } 1392 1393 mStackSupervisor.ensureActivitiesVisibleLocked(resuming, 0, !PRESERVE_WINDOWS); 1394 } 1395 1396 void addToStopping(ActivityRecord r, boolean immediate) { 1397 if (!mStackSupervisor.mStoppingActivities.contains(r)) { 1398 mStackSupervisor.mStoppingActivities.add(r); 1399 } 1400 1401 // If we already have a few activities waiting to stop, then give up 1402 // on things going idle and start clearing them out. Or if r is the 1403 // last of activity of the last task the stack will be empty and must 1404 // be cleared immediately. 1405 boolean forceIdle = mStackSupervisor.mStoppingActivities.size() > MAX_STOPPING_TO_FORCE 1406 || (r.frontOfTask && mTaskHistory.size() <= 1); 1407 1408 if (immediate || forceIdle) { 1409 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Scheduling idle now: forceIdle=" 1410 + forceIdle + "immediate=" + immediate); 1411 mStackSupervisor.scheduleIdleLocked(); 1412 } else { 1413 mStackSupervisor.checkReadyForSleepLocked(); 1414 } 1415 } 1416 1417 // Find the first visible activity above the passed activity and if it is translucent return it 1418 // otherwise return null; 1419 ActivityRecord findNextTranslucentActivity(ActivityRecord r) { 1420 TaskRecord task = r.task; 1421 if (task == null) { 1422 return null; 1423 } 1424 1425 final ActivityStack stack = task.getStack(); 1426 if (stack == null) { 1427 return null; 1428 } 1429 1430 int stackNdx = mStacks.indexOf(stack); 1431 1432 ArrayList<TaskRecord> tasks = stack.mTaskHistory; 1433 int taskNdx = tasks.indexOf(task); 1434 1435 ArrayList<ActivityRecord> activities = task.mActivities; 1436 int activityNdx = activities.indexOf(r) + 1; 1437 1438 final int numStacks = mStacks.size(); 1439 while (stackNdx < numStacks) { 1440 final ActivityStack historyStack = mStacks.get(stackNdx); 1441 tasks = historyStack.mTaskHistory; 1442 final int numTasks = tasks.size(); 1443 while (taskNdx < numTasks) { 1444 final TaskRecord currentTask = tasks.get(taskNdx); 1445 activities = currentTask.mActivities; 1446 final int numActivities = activities.size(); 1447 while (activityNdx < numActivities) { 1448 final ActivityRecord activity = activities.get(activityNdx); 1449 if (!activity.finishing) { 1450 return historyStack.mFullscreen 1451 && currentTask.mFullscreen && activity.fullscreen ? null : activity; 1452 } 1453 ++activityNdx; 1454 } 1455 activityNdx = 0; 1456 ++taskNdx; 1457 } 1458 taskNdx = 0; 1459 ++stackNdx; 1460 } 1461 1462 return null; 1463 } 1464 1465 /** Returns true if the stack contains a fullscreen task. */ 1466 private boolean hasFullscreenTask() { 1467 for (int i = mTaskHistory.size() - 1; i >= 0; --i) { 1468 final TaskRecord task = mTaskHistory.get(i); 1469 if (task.mFullscreen) { 1470 return true; 1471 } 1472 } 1473 return false; 1474 } 1475 1476 /** 1477 * Returns true if the stack is translucent and can have other contents visible behind it if 1478 * needed. A stack is considered translucent if it don't contain a visible or 1479 * starting (about to be visible) activity that is fullscreen (opaque). 1480 * @param starting The currently starting activity or null if there is none. 1481 * @param stackBehindId The id of the stack directly behind this one. 1482 */ 1483 private boolean isStackTranslucent(ActivityRecord starting, int stackBehindId) { 1484 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1485 final TaskRecord task = mTaskHistory.get(taskNdx); 1486 final ArrayList<ActivityRecord> activities = task.mActivities; 1487 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1488 final ActivityRecord r = activities.get(activityNdx); 1489 1490 if (r.finishing) { 1491 // We don't factor in finishing activities when determining translucency since 1492 // they will be gone soon. 1493 continue; 1494 } 1495 1496 if (!r.visible && r != starting) { 1497 // Also ignore invisible activities that are not the currently starting 1498 // activity (about to be visible). 1499 continue; 1500 } 1501 1502 if (r.fullscreen) { 1503 // Stack isn't translucent if it has at least one fullscreen activity 1504 // that is visible. 1505 return false; 1506 } 1507 1508 if (!isHomeOrRecentsStack() && r.frontOfTask 1509 && task.isOverHomeStack() && !StackId.isHomeOrRecentsStack(stackBehindId)) { 1510 // Stack isn't translucent if it's top activity should have the home stack 1511 // behind it and the stack currently behind it isn't the home or recents stack. 1512 return false; 1513 } 1514 } 1515 } 1516 return true; 1517 } 1518 1519 /** 1520 * Returns stack's visibility: {@link #STACK_INVISIBLE}, {@link #STACK_VISIBLE} or 1521 * {@link #STACK_VISIBLE_ACTIVITY_BEHIND}. 1522 * @param starting The currently starting activity or null if there is none. 1523 */ 1524 int getStackVisibilityLocked(ActivityRecord starting) { 1525 if (!isAttached()) { 1526 return STACK_INVISIBLE; 1527 } 1528 1529 if (mStackSupervisor.isFrontStackOnDisplay(this) || mStackSupervisor.isFocusedStack(this)) { 1530 return STACK_VISIBLE; 1531 } 1532 1533 final int stackIndex = mStacks.indexOf(this); 1534 1535 if (stackIndex == mStacks.size() - 1) { 1536 Slog.wtf(TAG, 1537 "Stack=" + this + " isn't front stack but is at the top of the stack list"); 1538 return STACK_INVISIBLE; 1539 } 1540 1541 final ActivityStack focusedStack = mStackSupervisor.getFocusedStack(); 1542 final int focusedStackId = focusedStack.mStackId; 1543 1544 final TaskRecord topFocusedTask = focusedStack.topTask(); 1545 final boolean isOnTopLauncherFocused = topFocusedTask != null && 1546 topFocusedTask.isOnTopLauncher(); 1547 if (isOnTopLauncherFocused) { 1548 // When an on-top launcher is focused, we should find out whether the freeform stack or 1549 // the fullscreen stack appears first underneath and has activities to show, and then 1550 // make it visible. 1551 boolean behindFullscreenOrFreeForm = false; 1552 for (int stackBehindFocusedIndex = mStacks.indexOf(focusedStack) - 1; 1553 stackBehindFocusedIndex >= 0; stackBehindFocusedIndex--) { 1554 ActivityStack stack = mStacks.get(stackBehindFocusedIndex); 1555 if ((stack.mStackId == FREEFORM_WORKSPACE_STACK_ID 1556 || stack.mStackId == FULLSCREEN_WORKSPACE_STACK_ID) 1557 && stack.topRunningActivityLocked() != null) { 1558 if (stackIndex == stackBehindFocusedIndex) { 1559 return !behindFullscreenOrFreeForm ? STACK_VISIBLE : STACK_INVISIBLE; 1560 } 1561 behindFullscreenOrFreeForm = true; 1562 } 1563 } 1564 } 1565 // If an on-top launcher is on the top of the home stack but the home stack is not focused, 1566 // then the whole stack should be invisible. 1567 TaskRecord topTask = topTask(); 1568 if (mStackId != focusedStackId && topTask != null && topTask.isOnTopLauncher()) { 1569 // We're here mostly because the on-top launcher didn't have a chance to move itself to 1570 // back. We should move it to back as soon as possible to avoid other activities 1571 // returning to it or other visibility issues. 1572 moveTaskToBackLocked(topTask.taskId); 1573 return STACK_INVISIBLE; 1574 } 1575 1576 if (mStackId == FULLSCREEN_WORKSPACE_STACK_ID 1577 && hasVisibleBehindActivity() && StackId.isHomeOrRecentsStack(focusedStackId) 1578 && !focusedStack.topActivity().fullscreen) { 1579 // The fullscreen stack should be visible if it has a visible behind activity behind 1580 // the home or recents stack that is translucent. 1581 return STACK_VISIBLE_ACTIVITY_BEHIND; 1582 } 1583 1584 if (mStackId == DOCKED_STACK_ID) { 1585 // Docked stack is always visible, except in the case where the top running activity 1586 // task in the focus stack doesn't support any form of resizing but we show it for the 1587 // home task even though it's not resizable. 1588 final ActivityRecord r = focusedStack.topRunningActivityLocked(); 1589 final TaskRecord task = r != null ? r.task : null; 1590 return task == null || task.supportsSplitScreen() || task.isHomeTask() ? STACK_VISIBLE 1591 : STACK_INVISIBLE; 1592 } 1593 1594 // Find the first stack behind focused stack that actually got something visible. 1595 int stackBehindFocusedIndex = mStacks.indexOf(focusedStack) - 1; 1596 while (stackBehindFocusedIndex >= 0 && 1597 mStacks.get(stackBehindFocusedIndex).topRunningActivityLocked() == null) { 1598 stackBehindFocusedIndex--; 1599 } 1600 if ((focusedStackId == DOCKED_STACK_ID || focusedStackId == PINNED_STACK_ID) 1601 && stackIndex == stackBehindFocusedIndex) { 1602 // Stacks directly behind the docked or pinned stack are always visible. 1603 return STACK_VISIBLE; 1604 } 1605 1606 final int stackBehindFocusedId = (stackBehindFocusedIndex >= 0) 1607 ? mStacks.get(stackBehindFocusedIndex).mStackId : INVALID_STACK_ID; 1608 1609 if (focusedStackId == FULLSCREEN_WORKSPACE_STACK_ID 1610 && focusedStack.isStackTranslucent(starting, stackBehindFocusedId)) { 1611 // Stacks behind the fullscreen stack with a translucent activity are always 1612 // visible so they can act as a backdrop to the translucent activity. 1613 // For example, dialog activities 1614 if (stackIndex == stackBehindFocusedIndex) { 1615 return STACK_VISIBLE; 1616 } 1617 if (stackBehindFocusedIndex >= 0) { 1618 if ((stackBehindFocusedId == DOCKED_STACK_ID 1619 || stackBehindFocusedId == PINNED_STACK_ID) 1620 && stackIndex == (stackBehindFocusedIndex - 1)) { 1621 // The stack behind the docked or pinned stack is also visible so we can have a 1622 // complete backdrop to the translucent activity when the docked stack is up. 1623 return STACK_VISIBLE; 1624 } 1625 } 1626 } 1627 1628 if (StackId.isStaticStack(mStackId)) { 1629 // Visibility of any static stack should have been determined by the conditions above. 1630 return STACK_INVISIBLE; 1631 } 1632 1633 for (int i = stackIndex + 1; i < mStacks.size(); i++) { 1634 final ActivityStack stack = mStacks.get(i); 1635 1636 if (!stack.mFullscreen && !stack.hasFullscreenTask()) { 1637 continue; 1638 } 1639 1640 if (!StackId.isDynamicStacksVisibleBehindAllowed(stack.mStackId)) { 1641 // These stacks can't have any dynamic stacks visible behind them. 1642 return STACK_INVISIBLE; 1643 } 1644 1645 if (!stack.isStackTranslucent(starting, INVALID_STACK_ID)) { 1646 return STACK_INVISIBLE; 1647 } 1648 } 1649 1650 return STACK_VISIBLE; 1651 } 1652 1653 final int rankTaskLayers(int baseLayer) { 1654 int layer = 0; 1655 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1656 final TaskRecord task = mTaskHistory.get(taskNdx); 1657 ActivityRecord r = task.topRunningActivityLocked(); 1658 if (r == null || r.finishing || !r.visible) { 1659 task.mLayerRank = -1; 1660 } else { 1661 task.mLayerRank = baseLayer + layer++; 1662 } 1663 } 1664 return layer; 1665 } 1666 1667 /** 1668 * Make sure that all activities that need to be visible (that is, they 1669 * currently can be seen by the user) actually are. 1670 */ 1671 final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges, 1672 boolean preserveWindows) { 1673 mTopActivityOccludesKeyguard = false; 1674 mTopDismissingKeyguardActivity = null; 1675 mStackSupervisor.mKeyguardController.beginActivityVisibilityUpdate(); 1676 try { 1677 ActivityRecord top = topRunningActivityLocked(); 1678 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "ensureActivitiesVisible behind " + top 1679 + " configChanges=0x" + Integer.toHexString(configChanges)); 1680 if (top != null) { 1681 checkTranslucentActivityWaiting(top); 1682 } 1683 1684 // If the top activity is not fullscreen, then we need to 1685 // make sure any activities under it are now visible. 1686 boolean aboveTop = top != null; 1687 final int stackVisibility = getStackVisibilityLocked(starting); 1688 final boolean stackInvisible = stackVisibility != STACK_VISIBLE; 1689 final boolean stackVisibleBehind = stackVisibility == STACK_VISIBLE_ACTIVITY_BEHIND; 1690 boolean behindFullscreenActivity = stackInvisible; 1691 boolean resumeNextActivity = mStackSupervisor.isFocusedStack(this) 1692 && (isInStackLocked(starting) == null); 1693 boolean behindTranslucentActivity = false; 1694 final ActivityRecord visibleBehind = getVisibleBehindActivity(); 1695 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1696 final TaskRecord task = mTaskHistory.get(taskNdx); 1697 final ArrayList<ActivityRecord> activities = task.mActivities; 1698 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1699 final ActivityRecord r = activities.get(activityNdx); 1700 if (r.finishing) { 1701 // Normally the screenshot will be taken in makeInvisible(). When an activity 1702 // is finishing, we no longer change its visibility, but we still need to take 1703 // the screenshots if startPausingLocked decided it should be taken. 1704 if (r.mUpdateTaskThumbnailWhenHidden) { 1705 r.updateThumbnailLocked(r.screenshotActivityLocked(), 1706 null /* description */); 1707 r.mUpdateTaskThumbnailWhenHidden = false; 1708 } 1709 continue; 1710 } 1711 final boolean isTop = r == top; 1712 if (aboveTop && !isTop) { 1713 continue; 1714 } 1715 aboveTop = false; 1716 1717 // Check whether activity should be visible without Keyguard influence 1718 final boolean visibleIgnoringKeyguard = r.shouldBeVisibleIgnoringKeyguard( 1719 behindTranslucentActivity, stackVisibleBehind, visibleBehind, 1720 behindFullscreenActivity); 1721 r.visibleIgnoringKeyguard = visibleIgnoringKeyguard; 1722 1723 // Now check whether it's really visible depending on Keyguard state. 1724 final boolean reallyVisible = checkKeyguardVisibility(r, 1725 visibleIgnoringKeyguard, isTop); 1726 if (visibleIgnoringKeyguard) { 1727 behindFullscreenActivity = updateBehindFullscreen(stackInvisible, 1728 behindFullscreenActivity, task, r); 1729 if (behindFullscreenActivity && !r.fullscreen) { 1730 behindTranslucentActivity = true; 1731 } 1732 } 1733 if (reallyVisible) { 1734 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Make visible? " + r 1735 + " finishing=" + r.finishing + " state=" + r.state); 1736 // First: if this is not the current activity being started, make 1737 // sure it matches the current configuration. 1738 if (r != starting) { 1739 r.ensureActivityConfigurationLocked(0 /* globalChanges */, preserveWindows); 1740 } 1741 1742 if (r.app == null || r.app.thread == null) { 1743 if (makeVisibleAndRestartIfNeeded(starting, configChanges, isTop, 1744 resumeNextActivity, r)) { 1745 if (activityNdx >= activities.size()) { 1746 // Record may be removed if its process needs to restart. 1747 activityNdx = activities.size() - 1; 1748 } else { 1749 resumeNextActivity = false; 1750 } 1751 } 1752 } else if (r.visible) { 1753 // If this activity is already visible, then there is nothing to do here. 1754 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, 1755 "Skipping: already visible at " + r); 1756 1757 if (r.handleAlreadyVisible()) { 1758 resumeNextActivity = false; 1759 } 1760 } else { 1761 r.makeVisibleIfNeeded(starting); 1762 } 1763 // Aggregate current change flags. 1764 configChanges |= r.configChangeFlags; 1765 } else { 1766 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Make invisible? " + r 1767 + " finishing=" + r.finishing + " state=" + r.state + " stackInvisible=" 1768 + stackInvisible + " behindFullscreenActivity=" 1769 + behindFullscreenActivity + " mLaunchTaskBehind=" 1770 + r.mLaunchTaskBehind); 1771 makeInvisible(r, visibleBehind); 1772 } 1773 } 1774 if (mStackId == FREEFORM_WORKSPACE_STACK_ID) { 1775 // The visibility of tasks and the activities they contain in freeform stack are 1776 // determined individually unlike other stacks where the visibility or fullscreen 1777 // status of an activity in a previous task affects other. 1778 behindFullscreenActivity = stackVisibility == STACK_INVISIBLE; 1779 } else if (mStackId == HOME_STACK_ID) { 1780 if (task.isOnTopLauncher()) { 1781 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "On-top launcher: at " + task 1782 + " stackInvisible=" + stackInvisible 1783 + " behindFullscreenActivity=" + behindFullscreenActivity); 1784 // When an on-top launcher is visible, (e.g. it's on the top of the home stack), 1785 // other tasks in the home stack could be visible if and only if: 1786 // - some app is running in the docked stack; 1787 // - no app is running in either the fullscreen stack or the freefrom stack. 1788 final ActivityStack dockedStack = mStackSupervisor.getStack(DOCKED_STACK_ID); 1789 final ActivityStack fullscreenStack = mStackSupervisor.getStack( 1790 FULLSCREEN_WORKSPACE_STACK_ID); 1791 final ActivityStack freeformStack = mStackSupervisor.getStack( 1792 FREEFORM_WORKSPACE_STACK_ID); 1793 final boolean dockedStackEmpty = dockedStack == null || 1794 dockedStack.topRunningActivityLocked() == null; 1795 final boolean fullscreenStackEmpty = fullscreenStack == null || 1796 fullscreenStack.topRunningActivityLocked() == null; 1797 final boolean freeformStackEmpty = freeformStack == null || 1798 freeformStack.topRunningActivityLocked() == null; 1799 behindFullscreenActivity = dockedStackEmpty || !fullscreenStackEmpty || 1800 !freeformStackEmpty; 1801 } else if (task.isHomeTask()) { 1802 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Home task: at " + task 1803 + " stackInvisible=" + stackInvisible 1804 + " behindFullscreenActivity=" + behindFullscreenActivity); 1805 // No other task in the home stack should be visible behind the home activity. 1806 // Home activities is usually a translucent activity with the wallpaper behind 1807 // them. However, when they don't have the wallpaper behind them, we want to 1808 // show activities in the next application stack behind them vs. another 1809 // task in the home stack like recents. 1810 behindFullscreenActivity = true; 1811 } else if (task.isRecentsTask() 1812 && task.getTaskToReturnTo() == APPLICATION_ACTIVITY_TYPE) { 1813 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, 1814 "Recents task returning to app: at " + task 1815 + " stackInvisible=" + stackInvisible 1816 + " behindFullscreenActivity=" + behindFullscreenActivity); 1817 // We don't want any other tasks in the home stack visible if the recents 1818 // activity is going to be returning to an application activity type. 1819 // We do this to preserve the visible order the user used to get into the 1820 // recents activity. The recents activity is normally translucent and if it 1821 // doesn't have the wallpaper behind it the next activity in the home stack 1822 // shouldn't be visible when the home stack is brought to the front to display 1823 // the recents activity from an app. 1824 behindFullscreenActivity = true; 1825 } 1826 1827 } 1828 } 1829 1830 if (mTranslucentActivityWaiting != null && 1831 mUndrawnActivitiesBelowTopTranslucent.isEmpty()) { 1832 // Nothing is getting drawn or everything was already visible, don't wait for timeout. 1833 notifyActivityDrawnLocked(null); 1834 } 1835 } finally { 1836 mStackSupervisor.mKeyguardController.endActivityVisibilityUpdate(); 1837 } 1838 } 1839 1840 void addStartingWindowsForVisibleActivities(boolean taskSwitch) { 1841 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1842 mTaskHistory.get(taskNdx).addStartingWindowsForVisibleActivities(taskSwitch); 1843 } 1844 } 1845 1846 /** 1847 * @return true if the top visible activity wants to occlude the Keyguard, false otherwise 1848 */ 1849 boolean topActivityOccludesKeyguard() { 1850 return mTopActivityOccludesKeyguard; 1851 } 1852 1853 /** 1854 * @return the top most visible activity that wants to dismiss Keyguard 1855 */ 1856 ActivityRecord getTopDismissingKeyguardActivity() { 1857 return mTopDismissingKeyguardActivity; 1858 } 1859 1860 /** 1861 * Checks whether {@param r} should be visible depending on Keyguard state and updates 1862 * {@link #mTopActivityOccludesKeyguard} and {@link #mTopDismissingKeyguardActivity} if 1863 * necessary. 1864 * 1865 * @return true if {@param r} is visible taken Keyguard state into account, false otherwise 1866 */ 1867 private boolean checkKeyguardVisibility(ActivityRecord r, boolean shouldBeVisible, 1868 boolean isTop) { 1869 final boolean isInPinnedStack = r.getStack().getStackId() == PINNED_STACK_ID; 1870 final boolean keyguardShowing = mStackSupervisor.mKeyguardController.isKeyguardShowing(); 1871 final boolean keyguardLocked = mStackSupervisor.mKeyguardController.isKeyguardLocked(); 1872 final boolean showWhenLocked = r.hasShowWhenLockedWindows() && !isInPinnedStack; 1873 final boolean dismissKeyguard = r.hasDismissKeyguardWindows(); 1874 if (shouldBeVisible) { 1875 if (dismissKeyguard && mTopDismissingKeyguardActivity == null) { 1876 mTopDismissingKeyguardActivity = r; 1877 } 1878 1879 // Only the top activity may control occluded, as we can't occlude the Keyguard if the 1880 // top app doesn't want to occlude it. 1881 if (isTop) { 1882 mTopActivityOccludesKeyguard |= showWhenLocked; 1883 } 1884 } 1885 if (keyguardShowing) { 1886 1887 // If keyguard is showing, nothing is visible, except if we are able to dismiss Keyguard 1888 // right away. 1889 return shouldBeVisible && mStackSupervisor.mKeyguardController 1890 .canShowActivityWhileKeyguardShowing(r, dismissKeyguard); 1891 } else if (keyguardLocked) { 1892 return shouldBeVisible && mStackSupervisor.mKeyguardController.canShowWhileOccluded( 1893 dismissKeyguard, showWhenLocked); 1894 } else { 1895 return shouldBeVisible; 1896 } 1897 } 1898 1899 private void checkTranslucentActivityWaiting(ActivityRecord top) { 1900 if (mTranslucentActivityWaiting != top) { 1901 mUndrawnActivitiesBelowTopTranslucent.clear(); 1902 if (mTranslucentActivityWaiting != null) { 1903 // Call the callback with a timeout indication. 1904 notifyActivityDrawnLocked(null); 1905 mTranslucentActivityWaiting = null; 1906 } 1907 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG); 1908 } 1909 } 1910 1911 private boolean makeVisibleAndRestartIfNeeded(ActivityRecord starting, int configChanges, 1912 boolean isTop, boolean andResume, ActivityRecord r) { 1913 // We need to make sure the app is running if it's the top, or it is just made visible from 1914 // invisible. If the app is already visible, it must have died while it was visible. In this 1915 // case, we'll show the dead window but will not restart the app. Otherwise we could end up 1916 // thrashing. 1917 if (isTop || !r.visible) { 1918 // This activity needs to be visible, but isn't even running... 1919 // get it started and resume if no other stack in this stack is resumed. 1920 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Start and freeze screen for " + r); 1921 if (r != starting) { 1922 r.startFreezingScreenLocked(r.app, configChanges); 1923 } 1924 if (!r.visible || r.mLaunchTaskBehind) { 1925 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Starting and making visible: " + r); 1926 r.setVisible(true); 1927 } 1928 if (r != starting) { 1929 mStackSupervisor.startSpecificActivityLocked(r, andResume, false); 1930 return true; 1931 } 1932 } 1933 return false; 1934 } 1935 1936 private void makeInvisible(ActivityRecord r, ActivityRecord visibleBehind) { 1937 if (!r.visible) { 1938 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Already invisible: " + r); 1939 return; 1940 } 1941 // Now for any activities that aren't visible to the user, make sure they no longer are 1942 // keeping the screen frozen. 1943 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Making invisible: " + r + " " + r.state); 1944 try { 1945 r.setVisible(false); 1946 switch (r.state) { 1947 case STOPPING: 1948 case STOPPED: 1949 if (r.app != null && r.app.thread != null) { 1950 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, 1951 "Scheduling invisibility: " + r); 1952 r.app.thread.scheduleWindowVisibility(r.appToken, false); 1953 } 1954 1955 // Reset the flag indicating that an app can enter picture-in-picture once the 1956 // activity is hidden 1957 r.supportsPictureInPictureWhilePausing = false; 1958 break; 1959 1960 case INITIALIZING: 1961 case RESUMED: 1962 case PAUSING: 1963 case PAUSED: 1964 // This case created for transitioning activities from 1965 // translucent to opaque {@link Activity#convertToOpaque}. 1966 if (visibleBehind == r) { 1967 releaseBackgroundResources(r); 1968 } else { 1969 addToStopping(r, true /* immediate */); 1970 } 1971 break; 1972 1973 default: 1974 break; 1975 } 1976 } catch (Exception e) { 1977 // Just skip on any failure; we'll make it visible when it next restarts. 1978 Slog.w(TAG, "Exception thrown making hidden: " + r.intent.getComponent(), e); 1979 } 1980 } 1981 1982 private boolean updateBehindFullscreen(boolean stackInvisible, boolean behindFullscreenActivity, 1983 TaskRecord task, ActivityRecord r) { 1984 if (r.fullscreen) { 1985 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Fullscreen: at " + r 1986 + " stackInvisible=" + stackInvisible 1987 + " behindFullscreenActivity=" + behindFullscreenActivity); 1988 // At this point, nothing else needs to be shown in this task. 1989 behindFullscreenActivity = true; 1990 } else if (!isHomeOrRecentsStack() && r.frontOfTask && task.isOverHomeStack()) { 1991 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Showing home: at " + r 1992 + " stackInvisible=" + stackInvisible 1993 + " behindFullscreenActivity=" + behindFullscreenActivity); 1994 behindFullscreenActivity = true; 1995 } 1996 return behindFullscreenActivity; 1997 } 1998 1999 void convertActivityToTranslucent(ActivityRecord r) { 2000 mTranslucentActivityWaiting = r; 2001 mUndrawnActivitiesBelowTopTranslucent.clear(); 2002 mHandler.sendEmptyMessageDelayed(TRANSLUCENT_TIMEOUT_MSG, TRANSLUCENT_CONVERSION_TIMEOUT); 2003 } 2004 2005 void clearOtherAppTimeTrackers(AppTimeTracker except) { 2006 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2007 final TaskRecord task = mTaskHistory.get(taskNdx); 2008 final ArrayList<ActivityRecord> activities = task.mActivities; 2009 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2010 final ActivityRecord r = activities.get(activityNdx); 2011 if ( r.appTimeTracker != except) { 2012 r.appTimeTracker = null; 2013 } 2014 } 2015 } 2016 } 2017 2018 /** 2019 * Called as activities below the top translucent activity are redrawn. When the last one is 2020 * redrawn notify the top activity by calling 2021 * {@link Activity#onTranslucentConversionComplete}. 2022 * 2023 * @param r The most recent background activity to be drawn. Or, if r is null then a timeout 2024 * occurred and the activity will be notified immediately. 2025 */ 2026 void notifyActivityDrawnLocked(ActivityRecord r) { 2027 mActivityContainer.setDrawn(); 2028 if ((r == null) 2029 || (mUndrawnActivitiesBelowTopTranslucent.remove(r) && 2030 mUndrawnActivitiesBelowTopTranslucent.isEmpty())) { 2031 // The last undrawn activity below the top has just been drawn. If there is an 2032 // opaque activity at the top, notify it that it can become translucent safely now. 2033 final ActivityRecord waitingActivity = mTranslucentActivityWaiting; 2034 mTranslucentActivityWaiting = null; 2035 mUndrawnActivitiesBelowTopTranslucent.clear(); 2036 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG); 2037 2038 if (waitingActivity != null) { 2039 mWindowManager.setWindowOpaque(waitingActivity.appToken, false); 2040 if (waitingActivity.app != null && waitingActivity.app.thread != null) { 2041 try { 2042 waitingActivity.app.thread.scheduleTranslucentConversionComplete( 2043 waitingActivity.appToken, r != null); 2044 } catch (RemoteException e) { 2045 } 2046 } 2047 } 2048 } 2049 } 2050 2051 /** If any activities below the top running one are in the INITIALIZING state and they have a 2052 * starting window displayed then remove that starting window. It is possible that the activity 2053 * in this state will never resumed in which case that starting window will be orphaned. */ 2054 void cancelInitializingActivities() { 2055 final ActivityRecord topActivity = topRunningActivityLocked(); 2056 boolean aboveTop = true; 2057 // We don't want to clear starting window for activities that aren't behind fullscreen 2058 // activities as we need to display their starting window until they are done initializing. 2059 boolean behindFullscreenActivity = false; 2060 2061 if (getStackVisibilityLocked(null) == STACK_INVISIBLE) { 2062 // The stack is not visible, so no activity in it should be displaying a starting 2063 // window. Mark all activities below top and behind fullscreen. 2064 aboveTop = false; 2065 behindFullscreenActivity = true; 2066 } 2067 2068 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2069 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 2070 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2071 final ActivityRecord r = activities.get(activityNdx); 2072 if (aboveTop) { 2073 if (r == topActivity) { 2074 aboveTop = false; 2075 } 2076 behindFullscreenActivity |= r.fullscreen; 2077 continue; 2078 } 2079 2080 r.removeOrphanedStartingWindow(behindFullscreenActivity); 2081 behindFullscreenActivity |= r.fullscreen; 2082 } 2083 } 2084 } 2085 2086 /** 2087 * Ensure that the top activity in the stack is resumed. 2088 * 2089 * @param prev The previously resumed activity, for when in the process 2090 * of pausing; can be null to call from elsewhere. 2091 * @param options Activity options. 2092 * 2093 * @return Returns true if something is being resumed, or false if 2094 * nothing happened. 2095 * 2096 * NOTE: It is not safe to call this method directly as it can cause an activity in a 2097 * non-focused stack to be resumed. 2098 * Use {@link ActivityStackSupervisor#resumeFocusedStackTopActivityLocked} to resume the 2099 * right activity for the current system state. 2100 */ 2101 boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) { 2102 if (mStackSupervisor.inResumeTopActivity) { 2103 // Don't even start recursing. 2104 return false; 2105 } 2106 2107 boolean result = false; 2108 try { 2109 // Protect against recursion. 2110 mStackSupervisor.inResumeTopActivity = true; 2111 result = resumeTopActivityInnerLocked(prev, options); 2112 } finally { 2113 mStackSupervisor.inResumeTopActivity = false; 2114 } 2115 return result; 2116 } 2117 2118 void setResumedActivityLocked(ActivityRecord r, String reason) { 2119 // TODO: move mResumedActivity to stack supervisor, 2120 // there should only be 1 global copy of resumed activity. 2121 mResumedActivity = r; 2122 r.state = ActivityState.RESUMED; 2123 mService.setResumedActivityUncheckLocked(r, reason); 2124 r.task.touchActiveTime(); 2125 mRecentTasks.addLocked(r.task); 2126 } 2127 2128 private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) { 2129 if (!mService.mBooting && !mService.mBooted) { 2130 // Not ready yet! 2131 return false; 2132 } 2133 2134 // Find the topmost activity in this stack that is not finishing. 2135 final ActivityRecord next = topRunningActivityLocked(); 2136 2137 final boolean hasRunningActivity = next != null; 2138 2139 final ActivityRecord parent = mActivityContainer.mParentActivity; 2140 final boolean isParentNotResumed = parent != null && parent.state != ActivityState.RESUMED; 2141 if (hasRunningActivity 2142 && (isParentNotResumed || !mActivityContainer.isAttachedLocked())) { 2143 // Do not resume this stack if its parent is not resumed. 2144 // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st. 2145 return false; 2146 } 2147 2148 mStackSupervisor.cancelInitializingActivities(); 2149 2150 // Remember how we'll process this pause/resume situation, and ensure 2151 // that the state is reset however we wind up proceeding. 2152 final boolean userLeaving = mStackSupervisor.mUserLeaving; 2153 mStackSupervisor.mUserLeaving = false; 2154 2155 if (!hasRunningActivity) { 2156 // There are no activities left in the stack, let's look somewhere else. 2157 return resumeTopActivityInNextFocusableStack(prev, options, "noMoreActivities"); 2158 } 2159 2160 next.delayedResume = false; 2161 2162 // If the top activity is the resumed one, nothing to do. 2163 if (mResumedActivity == next && next.state == ActivityState.RESUMED && 2164 mStackSupervisor.allResumedActivitiesComplete()) { 2165 // Make sure we have executed any pending transitions, since there 2166 // should be nothing left to do at this point. 2167 executeAppTransition(options); 2168 if (DEBUG_STATES) Slog.d(TAG_STATES, 2169 "resumeTopActivityLocked: Top activity resumed " + next); 2170 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2171 return false; 2172 } 2173 2174 final TaskRecord nextTask = next.task; 2175 final TaskRecord prevTask = prev != null ? prev.task : null; 2176 if (prevTask != null && prevTask.getStack() == this && 2177 prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) { 2178 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2179 if (prevTask == nextTask) { 2180 prevTask.setFrontOfTask(); 2181 } else if (prevTask != topTask()) { 2182 // This task is going away but it was supposed to return to the home stack. 2183 // Now the task above it has to return to the home task instead. 2184 final int taskNdx = mTaskHistory.indexOf(prevTask) + 1; 2185 mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE); 2186 } else if (!isOnHomeDisplay()) { 2187 return false; 2188 } else if (!isHomeStack()){ 2189 if (DEBUG_STATES) Slog.d(TAG_STATES, 2190 "resumeTopActivityLocked: Launching home next"); 2191 return isOnHomeDisplay() && 2192 mStackSupervisor.resumeHomeStackTask(prev, "prevFinished"); 2193 } 2194 } 2195 2196 // If we are sleeping, and there is no resumed activity, and the top 2197 // activity is paused, well that is the state we want. 2198 if (mService.isSleepingOrShuttingDownLocked() 2199 && mLastPausedActivity == next 2200 && mStackSupervisor.allPausedActivitiesComplete()) { 2201 // Make sure we have executed any pending transitions, since there 2202 // should be nothing left to do at this point. 2203 executeAppTransition(options); 2204 if (DEBUG_STATES) Slog.d(TAG_STATES, 2205 "resumeTopActivityLocked: Going to sleep and all paused"); 2206 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2207 return false; 2208 } 2209 2210 // Make sure that the user who owns this activity is started. If not, 2211 // we will just leave it as is because someone should be bringing 2212 // another user's activities to the top of the stack. 2213 if (!mService.mUserController.hasStartedUserState(next.userId)) { 2214 Slog.w(TAG, "Skipping resume of top activity " + next 2215 + ": user " + next.userId + " is stopped"); 2216 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2217 return false; 2218 } 2219 2220 // The activity may be waiting for stop, but that is no longer 2221 // appropriate for it. 2222 mStackSupervisor.mStoppingActivities.remove(next); 2223 mStackSupervisor.mGoingToSleepActivities.remove(next); 2224 next.sleeping = false; 2225 mStackSupervisor.mWaitingVisibleActivities.remove(next); 2226 2227 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resuming " + next); 2228 2229 // If we are currently pausing an activity, then don't do anything until that is done. 2230 if (!mStackSupervisor.allPausedActivitiesComplete()) { 2231 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE, 2232 "resumeTopActivityLocked: Skip resume: some activity pausing."); 2233 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2234 return false; 2235 } 2236 2237 mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid); 2238 2239 // If the flag RESUME_WHILE_PAUSING is set, then continue to schedule the previous activity 2240 // to be paused, while at the same time resuming the new resume activity 2241 final boolean resumeWhilePausing = (next.info.flags & FLAG_RESUME_WHILE_PAUSING) != 0; 2242 boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false); 2243 if (mResumedActivity != null) { 2244 if (DEBUG_STATES) Slog.d(TAG_STATES, 2245 "resumeTopActivityLocked: Pausing " + mResumedActivity); 2246 pausing |= startPausingLocked(userLeaving, false, next, false); 2247 } 2248 if (pausing && !resumeWhilePausing) { 2249 if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG_STATES, 2250 "resumeTopActivityLocked: Skip resume: need to start pausing"); 2251 // At this point we want to put the upcoming activity's process 2252 // at the top of the LRU list, since we know we will be needing it 2253 // very soon and it would be a waste to let it get killed if it 2254 // happens to be sitting towards the end. 2255 if (next.app != null && next.app.thread != null) { 2256 mService.updateLruProcessLocked(next.app, true, null); 2257 } 2258 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2259 return true; 2260 } else if (mResumedActivity == next && next.state == ActivityState.RESUMED && 2261 mStackSupervisor.allResumedActivitiesComplete()) { 2262 // It is possible for the activity to be resumed when we paused back stacks above if the 2263 // next activity doesn't have to wait for pause to complete. 2264 // So, nothing else to-do except: 2265 // Make sure we have executed any pending transitions, since there 2266 // should be nothing left to do at this point. 2267 executeAppTransition(options); 2268 if (DEBUG_STATES) Slog.d(TAG_STATES, 2269 "resumeTopActivityLocked: Top activity resumed (dontWaitForPause) " + next); 2270 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2271 return true; 2272 } 2273 2274 // If the most recent activity was noHistory but was only stopped rather 2275 // than stopped+finished because the device went to sleep, we need to make 2276 // sure to finish it as we're making a new activity topmost. 2277 if (mService.isSleepingLocked() && mLastNoHistoryActivity != null && 2278 !mLastNoHistoryActivity.finishing) { 2279 if (DEBUG_STATES) Slog.d(TAG_STATES, 2280 "no-history finish of " + mLastNoHistoryActivity + " on new resume"); 2281 requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED, 2282 null, "resume-no-history", false); 2283 mLastNoHistoryActivity = null; 2284 } 2285 2286 if (prev != null && prev != next) { 2287 if (!mStackSupervisor.mWaitingVisibleActivities.contains(prev) 2288 && next != null && !next.nowVisible) { 2289 mStackSupervisor.mWaitingVisibleActivities.add(prev); 2290 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, 2291 "Resuming top, waiting visible to hide: " + prev); 2292 } else { 2293 // The next activity is already visible, so hide the previous 2294 // activity's windows right now so we can show the new one ASAP. 2295 // We only do this if the previous is finishing, which should mean 2296 // it is on top of the one being resumed so hiding it quickly 2297 // is good. Otherwise, we want to do the normal route of allowing 2298 // the resumed activity to be shown so we can decide if the 2299 // previous should actually be hidden depending on whether the 2300 // new one is found to be full-screen or not. 2301 if (prev.finishing) { 2302 prev.setVisibility(false); 2303 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, 2304 "Not waiting for visible to hide: " + prev + ", waitingVisible=" 2305 + mStackSupervisor.mWaitingVisibleActivities.contains(prev) 2306 + ", nowVisible=" + next.nowVisible); 2307 } else { 2308 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, 2309 "Previous already visible but still waiting to hide: " + prev 2310 + ", waitingVisible=" 2311 + mStackSupervisor.mWaitingVisibleActivities.contains(prev) 2312 + ", nowVisible=" + next.nowVisible); 2313 } 2314 } 2315 } 2316 2317 // Launching this app's activity, make sure the app is no longer 2318 // considered stopped. 2319 try { 2320 AppGlobals.getPackageManager().setPackageStoppedState( 2321 next.packageName, false, next.userId); /* TODO: Verify if correct userid */ 2322 } catch (RemoteException e1) { 2323 } catch (IllegalArgumentException e) { 2324 Slog.w(TAG, "Failed trying to unstop package " 2325 + next.packageName + ": " + e); 2326 } 2327 2328 // We are starting up the next activity, so tell the window manager 2329 // that the previous one will be hidden soon. This way it can know 2330 // to ignore it when computing the desired screen orientation. 2331 boolean anim = true; 2332 if (prev != null) { 2333 if (prev.finishing) { 2334 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, 2335 "Prepare close transition: prev=" + prev); 2336 if (mNoAnimActivities.contains(prev)) { 2337 anim = false; 2338 mWindowManager.prepareAppTransition(TRANSIT_NONE, false); 2339 } else { 2340 mWindowManager.prepareAppTransition(prev.task == next.task 2341 ? TRANSIT_ACTIVITY_CLOSE 2342 : TRANSIT_TASK_CLOSE, false); 2343 } 2344 prev.setVisibility(false); 2345 } else { 2346 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, 2347 "Prepare open transition: prev=" + prev); 2348 if (mNoAnimActivities.contains(next)) { 2349 anim = false; 2350 mWindowManager.prepareAppTransition(TRANSIT_NONE, false); 2351 } else { 2352 mWindowManager.prepareAppTransition(prev.task == next.task 2353 ? TRANSIT_ACTIVITY_OPEN 2354 : next.mLaunchTaskBehind 2355 ? TRANSIT_TASK_OPEN_BEHIND 2356 : TRANSIT_TASK_OPEN, false); 2357 } 2358 } 2359 } else { 2360 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare open transition: no previous"); 2361 if (mNoAnimActivities.contains(next)) { 2362 anim = false; 2363 mWindowManager.prepareAppTransition(TRANSIT_NONE, false); 2364 } else { 2365 mWindowManager.prepareAppTransition(TRANSIT_ACTIVITY_OPEN, false); 2366 } 2367 } 2368 2369 Bundle resumeAnimOptions = null; 2370 if (anim) { 2371 ActivityOptions opts = next.getOptionsForTargetActivityLocked(); 2372 if (opts != null) { 2373 resumeAnimOptions = opts.toBundle(); 2374 } 2375 next.applyOptionsLocked(); 2376 } else { 2377 next.clearOptionsLocked(); 2378 } 2379 2380 ActivityStack lastStack = mStackSupervisor.getLastStack(); 2381 if (next.app != null && next.app.thread != null) { 2382 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resume running: " + next 2383 + " stopped=" + next.stopped + " visible=" + next.visible); 2384 2385 // If the previous activity is translucent, force a visibility update of 2386 // the next activity, so that it's added to WM's opening app list, and 2387 // transition animation can be set up properly. 2388 // For example, pressing Home button with a translucent activity in focus. 2389 // Launcher is already visible in this case. If we don't add it to opening 2390 // apps, maybeUpdateTransitToWallpaper() will fail to identify this as a 2391 // TRANSIT_WALLPAPER_OPEN animation, and run some funny animation. 2392 final boolean lastActivityTranslucent = lastStack != null 2393 && (!lastStack.mFullscreen 2394 || (lastStack.mLastPausedActivity != null 2395 && !lastStack.mLastPausedActivity.fullscreen)); 2396 2397 // This activity is now becoming visible. 2398 if (!next.visible || next.stopped || lastActivityTranslucent) { 2399 next.setVisibility(true); 2400 } 2401 2402 // schedule launch ticks to collect information about slow apps. 2403 next.startLaunchTickingLocked(); 2404 2405 ActivityRecord lastResumedActivity = 2406 lastStack == null ? null :lastStack.mResumedActivity; 2407 ActivityState lastState = next.state; 2408 2409 mService.updateCpuStats(); 2410 2411 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + next + " (in existing)"); 2412 2413 setResumedActivityLocked(next, "resumeTopActivityInnerLocked"); 2414 2415 mService.updateLruProcessLocked(next.app, true, null); 2416 updateLRUListLocked(next); 2417 mService.updateOomAdjLocked(); 2418 2419 // Have the window manager re-evaluate the orientation of 2420 // the screen based on the new activity order. 2421 boolean notUpdated = true; 2422 if (mStackSupervisor.isFocusedStack(this)) { 2423 final Configuration config = mWindowManager.updateOrientationFromAppTokens( 2424 mStackSupervisor.getDisplayOverrideConfiguration(mDisplayId), 2425 next.mayFreezeScreenLocked(next.app) ? next.appToken : null, mDisplayId); 2426 if (config != null) { 2427 next.frozenBeforeDestroy = true; 2428 } 2429 notUpdated = !mService.updateDisplayOverrideConfigurationLocked(config, next, 2430 false /* deferResume */, mDisplayId); 2431 } 2432 2433 if (notUpdated) { 2434 // The configuration update wasn't able to keep the existing 2435 // instance of the activity, and instead started a new one. 2436 // We should be all done, but let's just make sure our activity 2437 // is still at the top and schedule another run if something 2438 // weird happened. 2439 ActivityRecord nextNext = topRunningActivityLocked(); 2440 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_STATES, 2441 "Activity config changed during resume: " + next 2442 + ", new next: " + nextNext); 2443 if (nextNext != next) { 2444 // Do over! 2445 mStackSupervisor.scheduleResumeTopActivities(); 2446 } 2447 if (!next.visible || next.stopped) { 2448 next.setVisibility(true); 2449 } 2450 next.completeResumeLocked(); 2451 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2452 return true; 2453 } 2454 2455 try { 2456 // Deliver all pending results. 2457 ArrayList<ResultInfo> a = next.results; 2458 if (a != null) { 2459 final int N = a.size(); 2460 if (!next.finishing && N > 0) { 2461 if (DEBUG_RESULTS) Slog.v(TAG_RESULTS, 2462 "Delivering results to " + next + ": " + a); 2463 next.app.thread.scheduleSendResult(next.appToken, a); 2464 } 2465 } 2466 2467 boolean allowSavedSurface = true; 2468 if (next.newIntents != null) { 2469 // Restrict saved surface to launcher start, or there is no intent at all 2470 // (eg. task being brought to front). If the intent is something else, 2471 // likely the app is going to show some specific page or view, instead of 2472 // what's left last time. 2473 for (int i = next.newIntents.size() - 1; i >= 0; i--) { 2474 final Intent intent = next.newIntents.get(i); 2475 if (intent != null && !ActivityRecord.isMainIntent(intent)) { 2476 allowSavedSurface = false; 2477 break; 2478 } 2479 } 2480 next.app.thread.scheduleNewIntent( 2481 next.newIntents, next.appToken, false /* andPause */); 2482 } 2483 2484 // Well the app will no longer be stopped. 2485 // Clear app token stopped state in window manager if needed. 2486 next.notifyAppResumed(next.stopped, allowSavedSurface); 2487 2488 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, next.userId, 2489 System.identityHashCode(next), next.task.taskId, next.shortComponentName); 2490 2491 next.sleeping = false; 2492 mService.showUnsupportedZoomDialogIfNeededLocked(next); 2493 mService.showAskCompatModeDialogLocked(next); 2494 next.app.pendingUiClean = true; 2495 next.app.forceProcessStateUpTo(mService.mTopProcessState); 2496 next.clearOptionsLocked(); 2497 next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState, 2498 mService.isNextTransitionForward(), resumeAnimOptions); 2499 2500 if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Resumed " + next); 2501 } catch (Exception e) { 2502 // Whoops, need to restart this activity! 2503 if (DEBUG_STATES) Slog.v(TAG_STATES, "Resume failed; resetting state to " 2504 + lastState + ": " + next); 2505 next.state = lastState; 2506 if (lastStack != null) { 2507 lastStack.mResumedActivity = lastResumedActivity; 2508 } 2509 Slog.i(TAG, "Restarting because process died: " + next); 2510 if (!next.hasBeenLaunched) { 2511 next.hasBeenLaunched = true; 2512 } else if (SHOW_APP_STARTING_PREVIEW && lastStack != null && 2513 mStackSupervisor.isFrontStack(lastStack)) { 2514 next.showStartingWindow(null /* prev */, false /* newTask */, 2515 false /* taskSwitch */); 2516 } 2517 mStackSupervisor.startSpecificActivityLocked(next, true, false); 2518 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2519 return true; 2520 } 2521 2522 // From this point on, if something goes wrong there is no way 2523 // to recover the activity. 2524 try { 2525 next.completeResumeLocked(); 2526 } catch (Exception e) { 2527 // If any exception gets thrown, toss away this 2528 // activity and try the next one. 2529 Slog.w(TAG, "Exception thrown during resume of " + next, e); 2530 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null, 2531 "resume-exception", true); 2532 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2533 return true; 2534 } 2535 } else { 2536 // Whoops, need to restart this activity! 2537 if (!next.hasBeenLaunched) { 2538 next.hasBeenLaunched = true; 2539 } else { 2540 if (SHOW_APP_STARTING_PREVIEW) { 2541 next.showStartingWindow(null /* prev */, false /* newTask */, 2542 false /* taskSwich */); 2543 } 2544 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next); 2545 } 2546 if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next); 2547 mStackSupervisor.startSpecificActivityLocked(next, true, true); 2548 } 2549 2550 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2551 return true; 2552 } 2553 2554 private boolean resumeTopActivityInNextFocusableStack(ActivityRecord prev, 2555 ActivityOptions options, String reason) { 2556 if ((!mFullscreen || !isOnHomeDisplay()) 2557 && adjustFocusToNextFocusableStackLocked(reason)) { 2558 // Try to move focus to the next visible stack with a running activity if this 2559 // stack is not covering the entire screen or is on a secondary display (with no home 2560 // stack). 2561 return mStackSupervisor.resumeFocusedStackTopActivityLocked( 2562 mStackSupervisor.getFocusedStack(), prev, null); 2563 } 2564 2565 // Let's just start up the Launcher... 2566 ActivityOptions.abort(options); 2567 if (DEBUG_STATES) Slog.d(TAG_STATES, 2568 "resumeTopActivityInNextFocusableStack: " + reason + ", go home"); 2569 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 2570 // Only resume home if on home display 2571 return isOnHomeDisplay() && 2572 mStackSupervisor.resumeHomeStackTask(prev, reason); 2573 } 2574 2575 private TaskRecord getNextTask(TaskRecord targetTask) { 2576 final int index = mTaskHistory.indexOf(targetTask); 2577 if (index >= 0) { 2578 final int numTasks = mTaskHistory.size(); 2579 for (int i = index + 1; i < numTasks; ++i) { 2580 TaskRecord task = mTaskHistory.get(i); 2581 if (task.userId == targetTask.userId) { 2582 return task; 2583 } 2584 } 2585 } 2586 return null; 2587 } 2588 2589 /** Returns the position the input task should be placed in this stack. */ 2590 int getAdjustedPositionForTask(TaskRecord task, int suggestedPosition, 2591 ActivityRecord starting) { 2592 2593 int maxPosition = mTaskHistory.size(); 2594 if ((starting != null && starting.okToShowLocked()) 2595 || (starting == null && task.okToShowLocked())) { 2596 // If the task or starting activity can be shown, then whatever position is okay. 2597 return Math.min(suggestedPosition, maxPosition); 2598 } 2599 2600 // The task can't be shown, put non-current user tasks below current user tasks. 2601 while (maxPosition > 0) { 2602 final TaskRecord tmpTask = mTaskHistory.get(maxPosition - 1); 2603 if (!mStackSupervisor.isCurrentProfileLocked(tmpTask.userId) 2604 || tmpTask.topRunningActivityLocked() == null) { 2605 break; 2606 } 2607 maxPosition--; 2608 } 2609 2610 return Math.min(suggestedPosition, maxPosition); 2611 } 2612 2613 /** 2614 * Used from {@link ActivityStack#positionTask(TaskRecord, int)}. 2615 * @see ActivityManagerService#positionTaskInStack(int, int, int). 2616 */ 2617 private void insertTaskAtPosition(TaskRecord task, int position) { 2618 if (position >= mTaskHistory.size()) { 2619 insertTaskAtTop(task, null); 2620 return; 2621 } 2622 position = getAdjustedPositionForTask(task, position, null /* starting */); 2623 mTaskHistory.remove(task); 2624 mTaskHistory.add(position, task); 2625 mWindowContainerController.positionChildAt(task.getWindowContainerController(), position, 2626 task.mBounds, task.getOverrideConfiguration()); 2627 updateTaskMovement(task, true); 2628 } 2629 2630 private void insertTaskAtTop(TaskRecord task, ActivityRecord starting) { 2631 updateTaskReturnToForTopInsertion(task); 2632 // TODO: Better place to put all the code below...may be addTask... 2633 mTaskHistory.remove(task); 2634 // Now put task at top. 2635 final int position = getAdjustedPositionForTask(task, mTaskHistory.size(), starting); 2636 mTaskHistory.add(position, task); 2637 updateTaskMovement(task, true); 2638 mWindowContainerController.positionChildAtTop(task.getWindowContainerController(), 2639 true /* includingParents */); 2640 } 2641 2642 private void updateTaskReturnToForTopInsertion(TaskRecord task) { 2643 boolean isLastTaskOverHome = false; 2644 // If the moving task is over home stack, transfer its return type to next task 2645 if (task.isOverHomeStack()) { 2646 final TaskRecord nextTask = getNextTask(task); 2647 if (nextTask != null) { 2648 nextTask.setTaskToReturnTo(task.getTaskToReturnTo()); 2649 } else { 2650 isLastTaskOverHome = true; 2651 } 2652 } 2653 2654 // If this is being moved to the top by another activity or being launched from the home 2655 // activity, set mTaskToReturnTo accordingly. 2656 if (isOnHomeDisplay()) { 2657 ActivityStack lastStack = mStackSupervisor.getLastStack(); 2658 final boolean fromHomeOrRecents = lastStack.isHomeOrRecentsStack(); 2659 final TaskRecord topTask = lastStack.topTask(); 2660 final boolean fromOnTopLauncher = topTask != null && topTask.isOnTopLauncher(); 2661 if (fromOnTopLauncher) { 2662 // Since an on-top launcher will is moved to back when tasks are launched from it, 2663 // those tasks should first try to return to a non-home activity. 2664 // This also makes sure that non-home activities are visible under a transparent 2665 // non-home activity. 2666 task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE); 2667 } else if (!isHomeOrRecentsStack() && (fromHomeOrRecents || topTask() != task)) { 2668 // If it's a last task over home - we default to keep its return to type not to 2669 // make underlying task focused when this one will be finished. 2670 int returnToType = isLastTaskOverHome 2671 ? task.getTaskToReturnTo() : APPLICATION_ACTIVITY_TYPE; 2672 if (fromHomeOrRecents && StackId.allowTopTaskToReturnHome(mStackId)) { 2673 returnToType = topTask == null ? HOME_ACTIVITY_TYPE : topTask.taskType; 2674 } 2675 task.setTaskToReturnTo(returnToType); 2676 } 2677 } else { 2678 task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE); 2679 } 2680 } 2681 2682 final void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity, 2683 boolean newTask, boolean keepCurTransition, ActivityOptions options) { 2684 TaskRecord rTask = r.task; 2685 final int taskId = rTask.taskId; 2686 // mLaunchTaskBehind tasks get placed at the back of the task stack. 2687 if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) { 2688 // Last activity in task had been removed or ActivityManagerService is reusing task. 2689 // Insert or replace. 2690 // Might not even be in. 2691 insertTaskAtTop(rTask, r); 2692 } 2693 TaskRecord task = null; 2694 if (!newTask) { 2695 // If starting in an existing task, find where that is... 2696 boolean startIt = true; 2697 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2698 task = mTaskHistory.get(taskNdx); 2699 if (task.getTopActivity() == null) { 2700 // All activities in task are finishing. 2701 continue; 2702 } 2703 if (task == r.task) { 2704 // Here it is! Now, if this is not yet visible to the 2705 // user, then just add it without starting; it will 2706 // get started when the user navigates back to it. 2707 if (!startIt) { 2708 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task " 2709 + task, new RuntimeException("here").fillInStackTrace()); 2710 r.createWindowContainer(); 2711 ActivityOptions.abort(options); 2712 return; 2713 } 2714 break; 2715 } else if (task.numFullscreen > 0) { 2716 startIt = false; 2717 } 2718 } 2719 } 2720 2721 // Place a new activity at top of stack, so it is next to interact with the user. 2722 2723 // If we are not placing the new activity frontmost, we do not want to deliver the 2724 // onUserLeaving callback to the actual frontmost activity 2725 if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) { 2726 mStackSupervisor.mUserLeaving = false; 2727 if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING, 2728 "startActivity() behind front, mUserLeaving=false"); 2729 } 2730 2731 task = r.task; 2732 2733 // Slot the activity into the history stack and proceed 2734 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task, 2735 new RuntimeException("here").fillInStackTrace()); 2736 r.createWindowContainer(); 2737 task.setFrontOfTask(); 2738 2739 if (!isHomeOrRecentsStack() || numActivities() > 0) { 2740 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, 2741 "Prepare open transition: starting " + r); 2742 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 2743 mWindowManager.prepareAppTransition(TRANSIT_NONE, keepCurTransition); 2744 mNoAnimActivities.add(r); 2745 } else { 2746 int transit = TRANSIT_ACTIVITY_OPEN; 2747 if (newTask) { 2748 if (r.mLaunchTaskBehind) { 2749 transit = TRANSIT_TASK_OPEN_BEHIND; 2750 } else { 2751 // If a new task is being launched, then mark the existing top activity as 2752 // supporting picture-in-picture while pausing 2753 if (focusedTopActivity != null) { 2754 focusedTopActivity.supportsPictureInPictureWhilePausing = true; 2755 } 2756 transit = TRANSIT_TASK_OPEN; 2757 } 2758 } 2759 mWindowManager.prepareAppTransition(transit, keepCurTransition); 2760 mNoAnimActivities.remove(r); 2761 } 2762 boolean doShow = true; 2763 if (newTask) { 2764 // Even though this activity is starting fresh, we still need 2765 // to reset it to make sure we apply affinities to move any 2766 // existing activities from other tasks in to it. 2767 // If the caller has requested that the target task be 2768 // reset, then do so. 2769 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) { 2770 resetTaskIfNeededLocked(r, r); 2771 doShow = topRunningNonDelayedActivityLocked(null) == r; 2772 } 2773 } else if (options != null && options.getAnimationType() 2774 == ActivityOptions.ANIM_SCENE_TRANSITION) { 2775 doShow = false; 2776 } 2777 if (r.mLaunchTaskBehind) { 2778 // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we 2779 // tell WindowManager that r is visible even though it is at the back of the stack. 2780 r.setVisibility(true); 2781 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 2782 } else if (SHOW_APP_STARTING_PREVIEW && doShow) { 2783 // Figure out if we are transitioning from another activity that is 2784 // "has the same starting icon" as the next one. This allows the 2785 // window manager to keep the previous window it had previously 2786 // created, if it still had one. 2787 ActivityRecord prev = r.task.topRunningActivityWithStartingWindowLocked(); 2788 if (prev != null) { 2789 // We don't want to reuse the previous starting preview if: 2790 // (1) The current activity is in a different task. 2791 if (prev.task != r.task) { 2792 prev = null; 2793 } 2794 // (2) The current activity is already displayed. 2795 else if (prev.nowVisible) { 2796 prev = null; 2797 } 2798 } 2799 r.showStartingWindow(prev, newTask, isTaskSwitch(r, focusedTopActivity)); 2800 } 2801 } else { 2802 // If this is the first activity, don't do any fancy animations, 2803 // because there is nothing for it to animate on top of. 2804 ActivityOptions.abort(options); 2805 } 2806 } 2807 2808 private boolean isTaskSwitch(ActivityRecord r, 2809 ActivityRecord topFocusedActivity) { 2810 return topFocusedActivity != null && r.task != topFocusedActivity.task; 2811 } 2812 2813 /** 2814 * Perform a reset of the given task, if needed as part of launching it. 2815 * Returns the new HistoryRecord at the top of the task. 2816 */ 2817 /** 2818 * Helper method for #resetTaskIfNeededLocked. 2819 * We are inside of the task being reset... we'll either finish this activity, push it out 2820 * for another task, or leave it as-is. 2821 * @param task The task containing the Activity (taskTop) that might be reset. 2822 * @param forceReset 2823 * @return An ActivityOptions that needs to be processed. 2824 */ 2825 private ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task, boolean forceReset) { 2826 ActivityOptions topOptions = null; 2827 2828 int replyChainEnd = -1; 2829 boolean canMoveOptions = true; 2830 2831 // We only do this for activities that are not the root of the task (since if we finish 2832 // the root, we may no longer have the task!). 2833 final ArrayList<ActivityRecord> activities = task.mActivities; 2834 final int numActivities = activities.size(); 2835 final int rootActivityNdx = task.findEffectiveRootIndex(); 2836 for (int i = numActivities - 1; i > rootActivityNdx; --i ) { 2837 ActivityRecord target = activities.get(i); 2838 if (target.frontOfTask) 2839 break; 2840 2841 final int flags = target.info.flags; 2842 final boolean finishOnTaskLaunch = 2843 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; 2844 final boolean allowTaskReparenting = 2845 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; 2846 final boolean clearWhenTaskReset = 2847 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0; 2848 2849 if (!finishOnTaskLaunch 2850 && !clearWhenTaskReset 2851 && target.resultTo != null) { 2852 // If this activity is sending a reply to a previous 2853 // activity, we can't do anything with it now until 2854 // we reach the start of the reply chain. 2855 // XXX note that we are assuming the result is always 2856 // to the previous activity, which is almost always 2857 // the case but we really shouldn't count on. 2858 if (replyChainEnd < 0) { 2859 replyChainEnd = i; 2860 } 2861 } else if (!finishOnTaskLaunch 2862 && !clearWhenTaskReset 2863 && allowTaskReparenting 2864 && target.taskAffinity != null 2865 && !target.taskAffinity.equals(task.affinity)) { 2866 // If this activity has an affinity for another 2867 // task, then we need to move it out of here. We will 2868 // move it as far out of the way as possible, to the 2869 // bottom of the activity stack. This also keeps it 2870 // correctly ordered with any activities we previously 2871 // moved. 2872 final TaskRecord targetTask; 2873 final ActivityRecord bottom = 2874 !mTaskHistory.isEmpty() && !mTaskHistory.get(0).mActivities.isEmpty() ? 2875 mTaskHistory.get(0).mActivities.get(0) : null; 2876 if (bottom != null && target.taskAffinity != null 2877 && target.taskAffinity.equals(bottom.task.affinity)) { 2878 // If the activity currently at the bottom has the 2879 // same task affinity as the one we are moving, 2880 // then merge it into the same task. 2881 targetTask = bottom.task; 2882 if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Start pushing activity " + target 2883 + " out to bottom task " + bottom.task); 2884 } else { 2885 targetTask = createTaskRecord( 2886 mStackSupervisor.getNextTaskIdForUserLocked(target.userId), 2887 target.info, null, null, null, false, target.mActivityType); 2888 targetTask.affinityIntent = target.intent; 2889 if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Start pushing activity " + target 2890 + " out to new task " + target.task); 2891 } 2892 2893 boolean noOptions = canMoveOptions; 2894 final int start = replyChainEnd < 0 ? i : replyChainEnd; 2895 for (int srcPos = start; srcPos >= i; --srcPos) { 2896 final ActivityRecord p = activities.get(srcPos); 2897 if (p.finishing) { 2898 continue; 2899 } 2900 2901 canMoveOptions = false; 2902 if (noOptions && topOptions == null) { 2903 topOptions = p.takeOptionsLocked(); 2904 if (topOptions != null) { 2905 noOptions = false; 2906 } 2907 } 2908 if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE, 2909 "Removing activity " + p + " from task=" + task + " adding to task=" 2910 + targetTask + " Callers=" + Debug.getCallers(4)); 2911 if (DEBUG_TASKS) Slog.v(TAG_TASKS, 2912 "Pushing next activity " + p + " out to target's task " + target.task); 2913 p.setTask(targetTask, null); 2914 targetTask.addActivityAtBottom(p); 2915 } 2916 2917 mWindowContainerController.positionChildAtBottom( 2918 targetTask.getWindowContainerController()); 2919 replyChainEnd = -1; 2920 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) { 2921 // If the activity should just be removed -- either 2922 // because it asks for it, or the task should be 2923 // cleared -- then finish it and anything that is 2924 // part of its reply chain. 2925 int end; 2926 if (clearWhenTaskReset) { 2927 // In this case, we want to finish this activity 2928 // and everything above it, so be sneaky and pretend 2929 // like these are all in the reply chain. 2930 end = activities.size() - 1; 2931 } else if (replyChainEnd < 0) { 2932 end = i; 2933 } else { 2934 end = replyChainEnd; 2935 } 2936 boolean noOptions = canMoveOptions; 2937 for (int srcPos = i; srcPos <= end; srcPos++) { 2938 ActivityRecord p = activities.get(srcPos); 2939 if (p.finishing) { 2940 continue; 2941 } 2942 canMoveOptions = false; 2943 if (noOptions && topOptions == null) { 2944 topOptions = p.takeOptionsLocked(); 2945 if (topOptions != null) { 2946 noOptions = false; 2947 } 2948 } 2949 if (DEBUG_TASKS) Slog.w(TAG_TASKS, 2950 "resetTaskIntendedTask: calling finishActivity on " + p); 2951 if (finishActivityLocked( 2952 p, Activity.RESULT_CANCELED, null, "reset-task", false)) { 2953 end--; 2954 srcPos--; 2955 } 2956 } 2957 replyChainEnd = -1; 2958 } else { 2959 // If we were in the middle of a chain, well the 2960 // activity that started it all doesn't want anything 2961 // special, so leave it all as-is. 2962 replyChainEnd = -1; 2963 } 2964 } 2965 2966 return topOptions; 2967 } 2968 2969 /** 2970 * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given 2971 * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop. 2972 * @param affinityTask The task we are looking for an affinity to. 2973 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to. 2974 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked. 2975 * @param forceReset Flag passed in to resetTaskIfNeededLocked. 2976 */ 2977 private int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task, 2978 boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) { 2979 int replyChainEnd = -1; 2980 final int taskId = task.taskId; 2981 final String taskAffinity = task.affinity; 2982 2983 final ArrayList<ActivityRecord> activities = affinityTask.mActivities; 2984 final int numActivities = activities.size(); 2985 final int rootActivityNdx = affinityTask.findEffectiveRootIndex(); 2986 2987 // Do not operate on or below the effective root Activity. 2988 for (int i = numActivities - 1; i > rootActivityNdx; --i) { 2989 ActivityRecord target = activities.get(i); 2990 if (target.frontOfTask) 2991 break; 2992 2993 final int flags = target.info.flags; 2994 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; 2995 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; 2996 2997 if (target.resultTo != null) { 2998 // If this activity is sending a reply to a previous 2999 // activity, we can't do anything with it now until 3000 // we reach the start of the reply chain. 3001 // XXX note that we are assuming the result is always 3002 // to the previous activity, which is almost always 3003 // the case but we really shouldn't count on. 3004 if (replyChainEnd < 0) { 3005 replyChainEnd = i; 3006 } 3007 } else if (topTaskIsHigher 3008 && allowTaskReparenting 3009 && taskAffinity != null 3010 && taskAffinity.equals(target.taskAffinity)) { 3011 // This activity has an affinity for our task. Either remove it if we are 3012 // clearing or move it over to our task. Note that 3013 // we currently punt on the case where we are resetting a 3014 // task that is not at the top but who has activities above 3015 // with an affinity to it... this is really not a normal 3016 // case, and we will need to later pull that task to the front 3017 // and usually at that point we will do the reset and pick 3018 // up those remaining activities. (This only happens if 3019 // someone starts an activity in a new task from an activity 3020 // in a task that is not currently on top.) 3021 if (forceReset || finishOnTaskLaunch) { 3022 final int start = replyChainEnd >= 0 ? replyChainEnd : i; 3023 if (DEBUG_TASKS) Slog.v(TAG_TASKS, 3024 "Finishing task at index " + start + " to " + i); 3025 for (int srcPos = start; srcPos >= i; --srcPos) { 3026 final ActivityRecord p = activities.get(srcPos); 3027 if (p.finishing) { 3028 continue; 3029 } 3030 finishActivityLocked( 3031 p, Activity.RESULT_CANCELED, null, "move-affinity", false); 3032 } 3033 } else { 3034 if (taskInsertionPoint < 0) { 3035 taskInsertionPoint = task.mActivities.size(); 3036 3037 } 3038 3039 final int start = replyChainEnd >= 0 ? replyChainEnd : i; 3040 if (DEBUG_TASKS) Slog.v(TAG_TASKS, 3041 "Reparenting from task=" + affinityTask + ":" + start + "-" + i 3042 + " to task=" + task + ":" + taskInsertionPoint); 3043 for (int srcPos = start; srcPos >= i; --srcPos) { 3044 final ActivityRecord p = activities.get(srcPos); 3045 p.setTask(task, null); 3046 task.addActivityAtIndex(taskInsertionPoint, p); 3047 3048 if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE, 3049 "Removing and adding activity " + p + " to stack at " + task 3050 + " callers=" + Debug.getCallers(3)); 3051 if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Pulling activity " + p 3052 + " from " + srcPos + " in to resetting task " + task); 3053 } 3054 mWindowContainerController.positionChildAtTop( 3055 task.getWindowContainerController(), true /* includingParents */); 3056 3057 // Now we've moved it in to place... but what if this is 3058 // a singleTop activity and we have put it on top of another 3059 // instance of the same activity? Then we drop the instance 3060 // below so it remains singleTop. 3061 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { 3062 ArrayList<ActivityRecord> taskActivities = task.mActivities; 3063 int targetNdx = taskActivities.indexOf(target); 3064 if (targetNdx > 0) { 3065 ActivityRecord p = taskActivities.get(targetNdx - 1); 3066 if (p.intent.getComponent().equals(target.intent.getComponent())) { 3067 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace", 3068 false); 3069 } 3070 } 3071 } 3072 } 3073 3074 replyChainEnd = -1; 3075 } 3076 } 3077 return taskInsertionPoint; 3078 } 3079 3080 final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop, 3081 ActivityRecord newActivity) { 3082 boolean forceReset = 3083 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0; 3084 if (ACTIVITY_INACTIVE_RESET_TIME > 0 3085 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) { 3086 if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) { 3087 forceReset = true; 3088 } 3089 } 3090 3091 final TaskRecord task = taskTop.task; 3092 3093 /** False until we evaluate the TaskRecord associated with taskTop. Switches to true 3094 * for remaining tasks. Used for later tasks to reparent to task. */ 3095 boolean taskFound = false; 3096 3097 /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */ 3098 ActivityOptions topOptions = null; 3099 3100 // Preserve the location for reparenting in the new task. 3101 int reparentInsertionPoint = -1; 3102 3103 for (int i = mTaskHistory.size() - 1; i >= 0; --i) { 3104 final TaskRecord targetTask = mTaskHistory.get(i); 3105 3106 if (targetTask == task) { 3107 topOptions = resetTargetTaskIfNeededLocked(task, forceReset); 3108 taskFound = true; 3109 } else { 3110 reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task, 3111 taskFound, forceReset, reparentInsertionPoint); 3112 } 3113 } 3114 3115 int taskNdx = mTaskHistory.indexOf(task); 3116 if (taskNdx >= 0) { 3117 do { 3118 taskTop = mTaskHistory.get(taskNdx--).getTopActivity(); 3119 } while (taskTop == null && taskNdx >= 0); 3120 } 3121 3122 if (topOptions != null) { 3123 // If we got some ActivityOptions from an activity on top that 3124 // was removed from the task, propagate them to the new real top. 3125 if (taskTop != null) { 3126 taskTop.updateOptionsLocked(topOptions); 3127 } else { 3128 topOptions.abort(); 3129 } 3130 } 3131 3132 return taskTop; 3133 } 3134 3135 void sendActivityResultLocked(int callingUid, ActivityRecord r, 3136 String resultWho, int requestCode, int resultCode, Intent data) { 3137 3138 if (callingUid > 0) { 3139 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName, 3140 data, r.getUriPermissionsLocked(), r.userId); 3141 } 3142 3143 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r 3144 + " : who=" + resultWho + " req=" + requestCode 3145 + " res=" + resultCode + " data=" + data); 3146 if (mResumedActivity == r && r.app != null && r.app.thread != null) { 3147 try { 3148 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>(); 3149 list.add(new ResultInfo(resultWho, requestCode, 3150 resultCode, data)); 3151 r.app.thread.scheduleSendResult(r.appToken, list); 3152 return; 3153 } catch (Exception e) { 3154 Slog.w(TAG, "Exception thrown sending result to " + r, e); 3155 } 3156 } 3157 3158 r.addResultLocked(null, resultWho, requestCode, resultCode, data); 3159 } 3160 3161 private void adjustFocusedActivityStackLocked(ActivityRecord r, String reason) { 3162 if (!mStackSupervisor.isFocusedStack(this) || mResumedActivity != r) { 3163 return; 3164 } 3165 3166 final ActivityRecord next = topRunningActivityLocked(); 3167 final String myReason = reason + " adjustFocus"; 3168 if (next != r) { 3169 if (next != null && StackId.keepFocusInStackIfPossible(mStackId) && isFocusable()) { 3170 // For freeform, docked, and pinned stacks we always keep the focus within the 3171 // stack as long as there is a running activity. 3172 return; 3173 } else { 3174 final TaskRecord task = r.task; 3175 if (r.frontOfTask && task == topTask() && task.isOverHomeStack()) { 3176 // For non-fullscreen stack, we want to move the focus to the next visible 3177 // stack to prevent the home screen from moving to the top and obscuring 3178 // other visible stacks. 3179 if (!mFullscreen 3180 && adjustFocusToNextFocusableStackLocked(myReason)) { 3181 return; 3182 } 3183 // Move the home stack to the top if this stack is fullscreen or there is no 3184 // other visible stack. 3185 if (mStackSupervisor.moveHomeStackTaskToTop(myReason)) { 3186 // Activity focus was already adjusted. Nothing else to do... 3187 return; 3188 } 3189 } 3190 } 3191 } 3192 3193 mStackSupervisor.moveFocusableActivityStackToFrontLocked( 3194 mStackSupervisor.topRunningActivityLocked(), myReason); 3195 } 3196 3197 private boolean adjustFocusToNextFocusableStackLocked(String reason) { 3198 final ActivityStack stack = mStackSupervisor.getNextFocusableStackLocked(this); 3199 final String myReason = reason + " adjustFocusToNextFocusableStack"; 3200 if (stack == null) { 3201 return false; 3202 } 3203 3204 final ActivityRecord top = stack.topRunningActivityLocked(); 3205 3206 if (stack.isHomeOrRecentsStack() && (top == null || !top.visible)) { 3207 // If we will be focusing on the home stack next and its current top activity isn't 3208 // visible, then use the task return to value to determine the home task to display next. 3209 return mStackSupervisor.moveHomeStackTaskToTop(reason); 3210 } 3211 3212 stack.moveToFront(myReason); 3213 return true; 3214 } 3215 3216 final void stopActivityLocked(ActivityRecord r) { 3217 if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, "Stopping: " + r); 3218 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0 3219 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) { 3220 if (!r.finishing) { 3221 if (!mService.isSleepingLocked()) { 3222 if (DEBUG_STATES) Slog.d(TAG_STATES, "no-history finish of " + r); 3223 if (requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null, 3224 "stop-no-history", false)) { 3225 // Activity was finished, no need to continue trying to schedule stop. 3226 adjustFocusedActivityStackLocked(r, "stopActivityFinished"); 3227 r.resumeKeyDispatchingLocked(); 3228 return; 3229 } 3230 } else { 3231 if (DEBUG_STATES) Slog.d(TAG_STATES, "Not finishing noHistory " + r 3232 + " on stop because we're just sleeping"); 3233 } 3234 } 3235 } 3236 3237 if (r.app != null && r.app.thread != null) { 3238 adjustFocusedActivityStackLocked(r, "stopActivity"); 3239 r.resumeKeyDispatchingLocked(); 3240 try { 3241 r.stopped = false; 3242 if (DEBUG_STATES) Slog.v(TAG_STATES, 3243 "Moving to STOPPING: " + r + " (stop requested)"); 3244 r.state = ActivityState.STOPPING; 3245 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, 3246 "Stopping visible=" + r.visible + " for " + r); 3247 if (!r.visible) { 3248 r.setVisibility(false); 3249 } 3250 EventLogTags.writeAmStopActivity( 3251 r.userId, System.identityHashCode(r), r.shortComponentName); 3252 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags); 3253 if (mService.isSleepingOrShuttingDownLocked()) { 3254 r.setSleeping(true); 3255 } 3256 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r); 3257 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT); 3258 } catch (Exception e) { 3259 // Maybe just ignore exceptions here... if the process 3260 // has crashed, our death notification will clean things 3261 // up. 3262 Slog.w(TAG, "Exception thrown during pause", e); 3263 // Just in case, assume it to be stopped. 3264 r.stopped = true; 3265 if (DEBUG_STATES) Slog.v(TAG_STATES, "Stop failed; moving to STOPPED: " + r); 3266 r.state = ActivityState.STOPPED; 3267 if (r.deferRelaunchUntilPaused) { 3268 destroyActivityLocked(r, true, "stop-except"); 3269 } 3270 } 3271 } 3272 } 3273 3274 /** 3275 * @return Returns true if the activity is being finished, false if for 3276 * some reason it is being left as-is. 3277 */ 3278 final boolean requestFinishActivityLocked(IBinder token, int resultCode, 3279 Intent resultData, String reason, boolean oomAdj) { 3280 ActivityRecord r = isInStackLocked(token); 3281 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(TAG_STATES, 3282 "Finishing activity token=" + token + " r=" 3283 + ", result=" + resultCode + ", data=" + resultData 3284 + ", reason=" + reason); 3285 if (r == null) { 3286 return false; 3287 } 3288 3289 finishActivityLocked(r, resultCode, resultData, reason, oomAdj); 3290 return true; 3291 } 3292 3293 final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) { 3294 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3295 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3296 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3297 ActivityRecord r = activities.get(activityNdx); 3298 if (r.resultTo == self && r.requestCode == requestCode) { 3299 if ((r.resultWho == null && resultWho == null) || 3300 (r.resultWho != null && r.resultWho.equals(resultWho))) { 3301 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub", 3302 false); 3303 } 3304 } 3305 } 3306 } 3307 mService.updateOomAdjLocked(); 3308 } 3309 3310 final TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) { 3311 ActivityRecord r = topRunningActivityLocked(); 3312 TaskRecord finishedTask = null; 3313 if (r == null || r.app != app) { 3314 return null; 3315 } 3316 Slog.w(TAG, " Force finishing activity " 3317 + r.intent.getComponent().flattenToShortString()); 3318 int taskNdx = mTaskHistory.indexOf(r.task); 3319 int activityNdx = r.task.mActivities.indexOf(r); 3320 finishActivityLocked(r, Activity.RESULT_CANCELED, null, reason, false); 3321 finishedTask = r.task; 3322 // Also terminate any activities below it that aren't yet 3323 // stopped, to avoid a situation where one will get 3324 // re-start our crashing activity once it gets resumed again. 3325 --activityNdx; 3326 if (activityNdx < 0) { 3327 do { 3328 --taskNdx; 3329 if (taskNdx < 0) { 3330 break; 3331 } 3332 activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1; 3333 } while (activityNdx < 0); 3334 } 3335 if (activityNdx >= 0) { 3336 r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx); 3337 if (r.state == ActivityState.RESUMED 3338 || r.state == ActivityState.PAUSING 3339 || r.state == ActivityState.PAUSED) { 3340 if (!r.isHomeActivity() || mService.mHomeProcess != r.app) { 3341 Slog.w(TAG, " Force finishing activity " 3342 + r.intent.getComponent().flattenToShortString()); 3343 finishActivityLocked(r, Activity.RESULT_CANCELED, null, reason, false); 3344 } 3345 } 3346 } 3347 return finishedTask; 3348 } 3349 3350 final void finishVoiceTask(IVoiceInteractionSession session) { 3351 IBinder sessionBinder = session.asBinder(); 3352 boolean didOne = false; 3353 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3354 TaskRecord tr = mTaskHistory.get(taskNdx); 3355 if (tr.voiceSession != null && tr.voiceSession.asBinder() == sessionBinder) { 3356 for (int activityNdx = tr.mActivities.size() - 1; activityNdx >= 0; --activityNdx) { 3357 ActivityRecord r = tr.mActivities.get(activityNdx); 3358 if (!r.finishing) { 3359 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "finish-voice", 3360 false); 3361 didOne = true; 3362 } 3363 } 3364 } else { 3365 // Check if any of the activities are using voice 3366 for (int activityNdx = tr.mActivities.size() - 1; activityNdx >= 0; --activityNdx) { 3367 ActivityRecord r = tr.mActivities.get(activityNdx); 3368 if (r.voiceSession != null 3369 && r.voiceSession.asBinder() == sessionBinder) { 3370 // Inform of cancellation 3371 r.clearVoiceSessionLocked(); 3372 try { 3373 r.app.thread.scheduleLocalVoiceInteractionStarted((IBinder) r.appToken, 3374 null); 3375 } catch (RemoteException re) { 3376 // Ok 3377 } 3378 mService.finishRunningVoiceLocked(); 3379 break; 3380 } 3381 } 3382 } 3383 } 3384 3385 if (didOne) { 3386 mService.updateOomAdjLocked(); 3387 } 3388 } 3389 3390 final boolean finishActivityAffinityLocked(ActivityRecord r) { 3391 ArrayList<ActivityRecord> activities = r.task.mActivities; 3392 for (int index = activities.indexOf(r); index >= 0; --index) { 3393 ActivityRecord cur = activities.get(index); 3394 if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) { 3395 break; 3396 } 3397 finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true); 3398 } 3399 return true; 3400 } 3401 3402 private void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) { 3403 // send the result 3404 ActivityRecord resultTo = r.resultTo; 3405 if (resultTo != null) { 3406 if (DEBUG_RESULTS) Slog.v(TAG_RESULTS, "Adding result to " + resultTo 3407 + " who=" + r.resultWho + " req=" + r.requestCode 3408 + " res=" + resultCode + " data=" + resultData); 3409 if (resultTo.userId != r.userId) { 3410 if (resultData != null) { 3411 resultData.prepareToLeaveUser(r.userId); 3412 } 3413 } 3414 if (r.info.applicationInfo.uid > 0) { 3415 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid, 3416 resultTo.packageName, resultData, 3417 resultTo.getUriPermissionsLocked(), resultTo.userId); 3418 } 3419 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode, 3420 resultData); 3421 r.resultTo = null; 3422 } 3423 else if (DEBUG_RESULTS) Slog.v(TAG_RESULTS, "No result destination from " + r); 3424 3425 // Make sure this HistoryRecord is not holding on to other resources, 3426 // because clients have remote IPC references to this object so we 3427 // can't assume that will go away and want to avoid circular IPC refs. 3428 r.results = null; 3429 r.pendingResults = null; 3430 r.newIntents = null; 3431 r.icicle = null; 3432 } 3433 3434 /** 3435 * @return Returns true if this activity has been removed from the history 3436 * list, or false if it is still in the list and will be removed later. 3437 */ 3438 final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData, 3439 String reason, boolean oomAdj) { 3440 if (r.finishing) { 3441 Slog.w(TAG, "Duplicate finish request for " + r); 3442 return false; 3443 } 3444 3445 mWindowManager.deferSurfaceLayout(); 3446 try { 3447 r.makeFinishingLocked(); 3448 final TaskRecord task = r.task; 3449 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, 3450 r.userId, System.identityHashCode(r), 3451 task.taskId, r.shortComponentName, reason); 3452 final ArrayList<ActivityRecord> activities = task.mActivities; 3453 final int index = activities.indexOf(r); 3454 if (index < (activities.size() - 1)) { 3455 task.setFrontOfTask(); 3456 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) { 3457 // If the caller asked that this activity (and all above it) 3458 // be cleared when the task is reset, don't lose that information, 3459 // but propagate it up to the next activity. 3460 ActivityRecord next = activities.get(index+1); 3461 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 3462 } 3463 } 3464 3465 r.pauseKeyDispatchingLocked(); 3466 3467 adjustFocusedActivityStackLocked(r, "finishActivity"); 3468 3469 finishActivityResultsLocked(r, resultCode, resultData); 3470 3471 final boolean endTask = index <= 0; 3472 final int transit = endTask ? TRANSIT_TASK_CLOSE : TRANSIT_ACTIVITY_CLOSE; 3473 if (mResumedActivity == r) { 3474 if (DEBUG_VISIBILITY || DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, 3475 "Prepare close transition: finishing " + r); 3476 if (endTask) { 3477 mService.mTaskChangeNotificationController.notifyTaskRemovalStarted(task.taskId); 3478 } 3479 mWindowManager.prepareAppTransition(transit, false); 3480 3481 // Tell window manager to prepare for this one to be removed. 3482 r.setVisibility(false); 3483 3484 if (mPausingActivity == null) { 3485 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Finish needs to pause: " + r); 3486 if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING, 3487 "finish() => pause with userLeaving=false"); 3488 startPausingLocked(false, false, null, false); 3489 } 3490 3491 if (endTask) { 3492 mStackSupervisor.removeLockedTaskLocked(task); 3493 } 3494 } else if (r.state != ActivityState.PAUSING) { 3495 // If the activity is PAUSING, we will complete the finish once 3496 // it is done pausing; else we can just directly finish it here. 3497 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Finish not pausing: " + r); 3498 if (r.visible) { 3499 mWindowManager.prepareAppTransition(transit, false); 3500 r.setVisibility(false); 3501 mWindowManager.executeAppTransition(); 3502 if (!mStackSupervisor.mWaitingVisibleActivities.contains(r)) { 3503 mStackSupervisor.mWaitingVisibleActivities.add(r); 3504 } 3505 } 3506 return finishCurrentActivityLocked(r, (r.visible || r.nowVisible) ? 3507 FINISH_AFTER_VISIBLE : FINISH_AFTER_PAUSE, oomAdj) == null; 3508 } else { 3509 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Finish waiting for pause of: " + r); 3510 } 3511 3512 return false; 3513 } finally { 3514 mWindowManager.continueSurfaceLayout(); 3515 } 3516 } 3517 3518 static final int FINISH_IMMEDIATELY = 0; 3519 static final int FINISH_AFTER_PAUSE = 1; 3520 static final int FINISH_AFTER_VISIBLE = 2; 3521 3522 final ActivityRecord finishCurrentActivityLocked(ActivityRecord r, int mode, boolean oomAdj) { 3523 // First things first: if this activity is currently visible, 3524 // and the resumed activity is not yet visible, then hold off on 3525 // finishing until the resumed one becomes visible. 3526 3527 final ActivityRecord next = mStackSupervisor.topRunningActivityLocked(); 3528 3529 if (mode == FINISH_AFTER_VISIBLE && (r.visible || r.nowVisible) 3530 && next != null && !next.nowVisible) { 3531 if (!mStackSupervisor.mStoppingActivities.contains(r)) { 3532 addToStopping(r, false /* immediate */); 3533 } 3534 if (DEBUG_STATES) Slog.v(TAG_STATES, 3535 "Moving to STOPPING: "+ r + " (finish requested)"); 3536 r.state = ActivityState.STOPPING; 3537 if (oomAdj) { 3538 mService.updateOomAdjLocked(); 3539 } 3540 return r; 3541 } 3542 3543 // make sure the record is cleaned out of other places. 3544 mStackSupervisor.mStoppingActivities.remove(r); 3545 mStackSupervisor.mGoingToSleepActivities.remove(r); 3546 mStackSupervisor.mWaitingVisibleActivities.remove(r); 3547 if (mResumedActivity == r) { 3548 mResumedActivity = null; 3549 } 3550 final ActivityState prevState = r.state; 3551 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to FINISHING: " + r); 3552 r.state = ActivityState.FINISHING; 3553 final boolean finishingActivityInNonFocusedStack 3554 = r.getStack() != mStackSupervisor.getFocusedStack() 3555 && prevState == ActivityState.PAUSED && mode == FINISH_AFTER_VISIBLE; 3556 3557 if (mode == FINISH_IMMEDIATELY 3558 || (prevState == ActivityState.PAUSED 3559 && (mode == FINISH_AFTER_PAUSE || mStackId == PINNED_STACK_ID)) 3560 || finishingActivityInNonFocusedStack 3561 || prevState == ActivityState.STOPPED 3562 || prevState == ActivityState.INITIALIZING) { 3563 r.makeFinishingLocked(); 3564 boolean activityRemoved = destroyActivityLocked(r, true, "finish-imm"); 3565 3566 if (finishingActivityInNonFocusedStack) { 3567 // Finishing activity that was in paused state and it was in not currently focused 3568 // stack, need to make something visible in its place. 3569 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 3570 } 3571 if (activityRemoved) { 3572 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 3573 } 3574 if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS, 3575 "destroyActivityLocked: finishCurrentActivityLocked r=" + r + 3576 " destroy returned removed=" + activityRemoved); 3577 return activityRemoved ? null : r; 3578 } 3579 3580 // Need to go through the full pause cycle to get this 3581 // activity into the stopped state and then finish it. 3582 if (DEBUG_ALL) Slog.v(TAG, "Enqueueing pending finish: " + r); 3583 mStackSupervisor.mFinishingActivities.add(r); 3584 r.resumeKeyDispatchingLocked(); 3585 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 3586 return r; 3587 } 3588 3589 void finishAllActivitiesLocked(boolean immediately) { 3590 boolean noActivitiesInStack = true; 3591 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3592 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3593 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3594 final ActivityRecord r = activities.get(activityNdx); 3595 noActivitiesInStack = false; 3596 if (r.finishing && !immediately) { 3597 continue; 3598 } 3599 Slog.d(TAG, "finishAllActivitiesLocked: finishing " + r + " immediately"); 3600 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false); 3601 } 3602 } 3603 if (noActivitiesInStack) { 3604 mActivityContainer.onTaskListEmptyLocked(); 3605 } 3606 } 3607 3608 final boolean shouldUpRecreateTaskLocked(ActivityRecord srec, String destAffinity) { 3609 // Basic case: for simple app-centric recents, we need to recreate 3610 // the task if the affinity has changed. 3611 if (srec == null || srec.task.affinity == null || 3612 !srec.task.affinity.equals(destAffinity)) { 3613 return true; 3614 } 3615 // Document-centric case: an app may be split in to multiple documents; 3616 // they need to re-create their task if this current activity is the root 3617 // of a document, unless simply finishing it will return them to the the 3618 // correct app behind. 3619 if (srec.frontOfTask && srec.task != null && srec.task.getBaseIntent() != null 3620 && srec.task.getBaseIntent().isDocument()) { 3621 // Okay, this activity is at the root of its task. What to do, what to do... 3622 if (srec.task.getTaskToReturnTo() != ActivityRecord.APPLICATION_ACTIVITY_TYPE) { 3623 // Finishing won't return to an application, so we need to recreate. 3624 return true; 3625 } 3626 // We now need to get the task below it to determine what to do. 3627 int taskIdx = mTaskHistory.indexOf(srec.task); 3628 if (taskIdx <= 0) { 3629 Slog.w(TAG, "shouldUpRecreateTask: task not in history for " + srec); 3630 return false; 3631 } 3632 if (taskIdx == 0) { 3633 // At the bottom of the stack, nothing to go back to. 3634 return true; 3635 } 3636 TaskRecord prevTask = mTaskHistory.get(taskIdx); 3637 if (!srec.task.affinity.equals(prevTask.affinity)) { 3638 // These are different apps, so need to recreate. 3639 return true; 3640 } 3641 } 3642 return false; 3643 } 3644 3645 final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode, 3646 Intent resultData) { 3647 final TaskRecord task = srec.task; 3648 final ArrayList<ActivityRecord> activities = task.mActivities; 3649 final int start = activities.indexOf(srec); 3650 if (!mTaskHistory.contains(task) || (start < 0)) { 3651 return false; 3652 } 3653 int finishTo = start - 1; 3654 ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo); 3655 boolean foundParentInTask = false; 3656 final ComponentName dest = destIntent.getComponent(); 3657 if (start > 0 && dest != null) { 3658 for (int i = finishTo; i >= 0; i--) { 3659 ActivityRecord r = activities.get(i); 3660 if (r.info.packageName.equals(dest.getPackageName()) && 3661 r.info.name.equals(dest.getClassName())) { 3662 finishTo = i; 3663 parent = r; 3664 foundParentInTask = true; 3665 break; 3666 } 3667 } 3668 } 3669 3670 IActivityController controller = mService.mController; 3671 if (controller != null) { 3672 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0); 3673 if (next != null) { 3674 // ask watcher if this is allowed 3675 boolean resumeOK = true; 3676 try { 3677 resumeOK = controller.activityResuming(next.packageName); 3678 } catch (RemoteException e) { 3679 mService.mController = null; 3680 Watchdog.getInstance().setActivityController(null); 3681 } 3682 3683 if (!resumeOK) { 3684 return false; 3685 } 3686 } 3687 } 3688 final long origId = Binder.clearCallingIdentity(); 3689 for (int i = start; i > finishTo; i--) { 3690 ActivityRecord r = activities.get(i); 3691 requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true); 3692 // Only return the supplied result for the first activity finished 3693 resultCode = Activity.RESULT_CANCELED; 3694 resultData = null; 3695 } 3696 3697 if (parent != null && foundParentInTask) { 3698 final int parentLaunchMode = parent.info.launchMode; 3699 final int destIntentFlags = destIntent.getFlags(); 3700 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE || 3701 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK || 3702 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP || 3703 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) { 3704 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent, 3705 srec.packageName); 3706 } else { 3707 try { 3708 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo( 3709 destIntent.getComponent(), 0, srec.userId); 3710 int res = mService.mActivityStarter.startActivityLocked(srec.app.thread, 3711 destIntent, null /*ephemeralIntent*/, null, aInfo, null /*rInfo*/, null, 3712 null, parent.appToken, null, 0, -1, parent.launchedFromUid, 3713 parent.launchedFromPackage, -1, parent.launchedFromUid, 0, null, 3714 false, true, null, null, null); 3715 foundParentInTask = res == ActivityManager.START_SUCCESS; 3716 } catch (RemoteException e) { 3717 foundParentInTask = false; 3718 } 3719 requestFinishActivityLocked(parent.appToken, resultCode, 3720 resultData, "navigate-top", true); 3721 } 3722 } 3723 Binder.restoreCallingIdentity(origId); 3724 return foundParentInTask; 3725 } 3726 /** 3727 * Perform the common clean-up of an activity record. This is called both 3728 * as part of destroyActivityLocked() (when destroying the client-side 3729 * representation) and cleaning things up as a result of its hosting 3730 * processing going away, in which case there is no remaining client-side 3731 * state to destroy so only the cleanup here is needed. 3732 * 3733 * Note: Call before #removeActivityFromHistoryLocked. 3734 */ 3735 private void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices, boolean setState) { 3736 if (mResumedActivity == r) { 3737 mResumedActivity = null; 3738 } 3739 if (mPausingActivity == r) { 3740 mPausingActivity = null; 3741 } 3742 3743 r.deferRelaunchUntilPaused = false; 3744 r.frozenBeforeDestroy = false; 3745 3746 if (setState) { 3747 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to DESTROYED: " + r + " (cleaning up)"); 3748 r.state = ActivityState.DESTROYED; 3749 if (DEBUG_APP) Slog.v(TAG_APP, "Clearing app during cleanUp for activity " + r); 3750 r.app = null; 3751 } 3752 3753 // Make sure this record is no longer in the pending finishes list. 3754 // This could happen, for example, if we are trimming activities 3755 // down to the max limit while they are still waiting to finish. 3756 mStackSupervisor.mFinishingActivities.remove(r); 3757 mStackSupervisor.mWaitingVisibleActivities.remove(r); 3758 3759 // Remove any pending results. 3760 if (r.finishing && r.pendingResults != null) { 3761 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) { 3762 PendingIntentRecord rec = apr.get(); 3763 if (rec != null) { 3764 mService.cancelIntentSenderLocked(rec, false); 3765 } 3766 } 3767 r.pendingResults = null; 3768 } 3769 3770 if (cleanServices) { 3771 cleanUpActivityServicesLocked(r); 3772 } 3773 3774 // Get rid of any pending idle timeouts. 3775 removeTimeoutsForActivityLocked(r); 3776 if (getVisibleBehindActivity() == r) { 3777 mStackSupervisor.requestVisibleBehindLocked(r, false); 3778 } 3779 3780 // Clean-up activities are no longer relaunching (e.g. app process died). Notify window 3781 // manager so it can update its bookkeeping. 3782 mWindowManager.notifyAppRelaunchesCleared(r.appToken); 3783 } 3784 3785 private void removeTimeoutsForActivityLocked(ActivityRecord r) { 3786 mStackSupervisor.removeTimeoutsForActivityLocked(r); 3787 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 3788 mHandler.removeMessages(STOP_TIMEOUT_MSG, r); 3789 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r); 3790 r.finishLaunchTickingLocked(); 3791 } 3792 3793 private void removeActivityFromHistoryLocked(ActivityRecord r, String reason) { 3794 mStackSupervisor.removeChildActivityContainers(r); 3795 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null); 3796 r.makeFinishingLocked(); 3797 if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE, 3798 "Removing activity " + r + " from stack callers=" + Debug.getCallers(5)); 3799 3800 r.takeFromHistory(); 3801 removeTimeoutsForActivityLocked(r); 3802 if (DEBUG_STATES) Slog.v(TAG_STATES, 3803 "Moving to DESTROYED: " + r + " (removed from history)"); 3804 r.state = ActivityState.DESTROYED; 3805 if (DEBUG_APP) Slog.v(TAG_APP, "Clearing app during remove for activity " + r); 3806 r.app = null; 3807 r.removeWindowContainer(); 3808 final TaskRecord task = r.task; 3809 if (task != null && task.removeActivity(r)) { 3810 if (DEBUG_STACK) Slog.i(TAG_STACK, 3811 "removeActivityFromHistoryLocked: last activity removed from " + this); 3812 if (mStackSupervisor.isFocusedStack(this) && task == topTask() && 3813 task.isOverHomeStack()) { 3814 mStackSupervisor.moveHomeStackTaskToTop(reason); 3815 } 3816 removeTask(task, reason); 3817 } 3818 cleanUpActivityServicesLocked(r); 3819 r.removeUriPermissionsLocked(); 3820 } 3821 3822 /** 3823 * Perform clean-up of service connections in an activity record. 3824 */ 3825 private void cleanUpActivityServicesLocked(ActivityRecord r) { 3826 // Throw away any services that have been bound by this activity. 3827 if (r.connections != null) { 3828 Iterator<ConnectionRecord> it = r.connections.iterator(); 3829 while (it.hasNext()) { 3830 ConnectionRecord c = it.next(); 3831 mService.mServices.removeConnectionLocked(c, null, r); 3832 } 3833 r.connections = null; 3834 } 3835 } 3836 3837 final void scheduleDestroyActivities(ProcessRecord owner, String reason) { 3838 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG); 3839 msg.obj = new ScheduleDestroyArgs(owner, reason); 3840 mHandler.sendMessage(msg); 3841 } 3842 3843 private void destroyActivitiesLocked(ProcessRecord owner, String reason) { 3844 boolean lastIsOpaque = false; 3845 boolean activityRemoved = false; 3846 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3847 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3848 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3849 final ActivityRecord r = activities.get(activityNdx); 3850 if (r.finishing) { 3851 continue; 3852 } 3853 if (r.fullscreen) { 3854 lastIsOpaque = true; 3855 } 3856 if (owner != null && r.app != owner) { 3857 continue; 3858 } 3859 if (!lastIsOpaque) { 3860 continue; 3861 } 3862 if (r.isDestroyable()) { 3863 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Destroying " + r + " in state " + r.state 3864 + " resumed=" + mResumedActivity 3865 + " pausing=" + mPausingActivity + " for reason " + reason); 3866 if (destroyActivityLocked(r, true, reason)) { 3867 activityRemoved = true; 3868 } 3869 } 3870 } 3871 } 3872 if (activityRemoved) { 3873 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 3874 } 3875 } 3876 3877 final boolean safelyDestroyActivityLocked(ActivityRecord r, String reason) { 3878 if (r.isDestroyable()) { 3879 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, 3880 "Destroying " + r + " in state " + r.state + " resumed=" + mResumedActivity 3881 + " pausing=" + mPausingActivity + " for reason " + reason); 3882 return destroyActivityLocked(r, true, reason); 3883 } 3884 return false; 3885 } 3886 3887 final int releaseSomeActivitiesLocked(ProcessRecord app, ArraySet<TaskRecord> tasks, 3888 String reason) { 3889 // Iterate over tasks starting at the back (oldest) first. 3890 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app); 3891 int maxTasks = tasks.size() / 4; 3892 if (maxTasks < 1) { 3893 maxTasks = 1; 3894 } 3895 int numReleased = 0; 3896 for (int taskNdx = 0; taskNdx < mTaskHistory.size() && maxTasks > 0; taskNdx++) { 3897 final TaskRecord task = mTaskHistory.get(taskNdx); 3898 if (!tasks.contains(task)) { 3899 continue; 3900 } 3901 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Looking for activities to release in " + task); 3902 int curNum = 0; 3903 final ArrayList<ActivityRecord> activities = task.mActivities; 3904 for (int actNdx = 0; actNdx < activities.size(); actNdx++) { 3905 final ActivityRecord activity = activities.get(actNdx); 3906 if (activity.app == app && activity.isDestroyable()) { 3907 if (DEBUG_RELEASE) Slog.v(TAG_RELEASE, "Destroying " + activity 3908 + " in state " + activity.state + " resumed=" + mResumedActivity 3909 + " pausing=" + mPausingActivity + " for reason " + reason); 3910 destroyActivityLocked(activity, true, reason); 3911 if (activities.get(actNdx) != activity) { 3912 // Was removed from list, back up so we don't miss the next one. 3913 actNdx--; 3914 } 3915 curNum++; 3916 } 3917 } 3918 if (curNum > 0) { 3919 numReleased += curNum; 3920 maxTasks--; 3921 if (mTaskHistory.get(taskNdx) != task) { 3922 // The entire task got removed, back up so we don't miss the next one. 3923 taskNdx--; 3924 } 3925 } 3926 } 3927 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, 3928 "Done releasing: did " + numReleased + " activities"); 3929 return numReleased; 3930 } 3931 3932 /** 3933 * Destroy the current CLIENT SIDE instance of an activity. This may be 3934 * called both when actually finishing an activity, or when performing 3935 * a configuration switch where we destroy the current client-side object 3936 * but then create a new client-side object for this same HistoryRecord. 3937 */ 3938 final boolean destroyActivityLocked(ActivityRecord r, boolean removeFromApp, String reason) { 3939 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(TAG_SWITCH, 3940 "Removing activity from " + reason + ": token=" + r 3941 + ", app=" + (r.app != null ? r.app.processName : "(null)")); 3942 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY, 3943 r.userId, System.identityHashCode(r), 3944 r.task.taskId, r.shortComponentName, reason); 3945 3946 boolean removedFromHistory = false; 3947 3948 cleanUpActivityLocked(r, false, false); 3949 3950 final boolean hadApp = r.app != null; 3951 3952 if (hadApp) { 3953 if (removeFromApp) { 3954 r.app.activities.remove(r); 3955 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) { 3956 mService.mHeavyWeightProcess = null; 3957 mService.mHandler.sendEmptyMessage( 3958 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG); 3959 } 3960 if (r.app.activities.isEmpty()) { 3961 // Update any services we are bound to that might care about whether 3962 // their client may have activities. 3963 mService.mServices.updateServiceConnectionActivitiesLocked(r.app); 3964 // No longer have activities, so update LRU list and oom adj. 3965 mService.updateLruProcessLocked(r.app, false, null); 3966 mService.updateOomAdjLocked(); 3967 } 3968 } 3969 3970 boolean skipDestroy = false; 3971 3972 try { 3973 if (DEBUG_SWITCH) Slog.i(TAG_SWITCH, "Destroying: " + r); 3974 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing, 3975 r.configChangeFlags); 3976 } catch (Exception e) { 3977 // We can just ignore exceptions here... if the process 3978 // has crashed, our death notification will clean things 3979 // up. 3980 //Slog.w(TAG, "Exception thrown during finish", e); 3981 if (r.finishing) { 3982 removeActivityFromHistoryLocked(r, reason + " exceptionInScheduleDestroy"); 3983 removedFromHistory = true; 3984 skipDestroy = true; 3985 } 3986 } 3987 3988 r.nowVisible = false; 3989 3990 // If the activity is finishing, we need to wait on removing it 3991 // from the list to give it a chance to do its cleanup. During 3992 // that time it may make calls back with its token so we need to 3993 // be able to find it on the list and so we don't want to remove 3994 // it from the list yet. Otherwise, we can just immediately put 3995 // it in the destroyed state since we are not removing it from the 3996 // list. 3997 if (r.finishing && !skipDestroy) { 3998 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to DESTROYING: " + r 3999 + " (destroy requested)"); 4000 r.state = ActivityState.DESTROYING; 4001 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r); 4002 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT); 4003 } else { 4004 if (DEBUG_STATES) Slog.v(TAG_STATES, 4005 "Moving to DESTROYED: " + r + " (destroy skipped)"); 4006 r.state = ActivityState.DESTROYED; 4007 if (DEBUG_APP) Slog.v(TAG_APP, "Clearing app during destroy for activity " + r); 4008 r.app = null; 4009 } 4010 } else { 4011 // remove this record from the history. 4012 if (r.finishing) { 4013 removeActivityFromHistoryLocked(r, reason + " hadNoApp"); 4014 removedFromHistory = true; 4015 } else { 4016 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to DESTROYED: " + r + " (no app)"); 4017 r.state = ActivityState.DESTROYED; 4018 if (DEBUG_APP) Slog.v(TAG_APP, "Clearing app during destroy for activity " + r); 4019 r.app = null; 4020 } 4021 } 4022 4023 r.configChangeFlags = 0; 4024 4025 if (!mLRUActivities.remove(r) && hadApp) { 4026 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list"); 4027 } 4028 4029 return removedFromHistory; 4030 } 4031 4032 final void activityDestroyedLocked(IBinder token, String reason) { 4033 final long origId = Binder.clearCallingIdentity(); 4034 try { 4035 ActivityRecord r = ActivityRecord.forTokenLocked(token); 4036 if (r != null) { 4037 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r); 4038 } 4039 if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS, "activityDestroyedLocked: r=" + r); 4040 4041 if (isInStackLocked(r) != null) { 4042 if (r.state == ActivityState.DESTROYING) { 4043 cleanUpActivityLocked(r, true, false); 4044 removeActivityFromHistoryLocked(r, reason); 4045 } 4046 } 4047 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 4048 } finally { 4049 Binder.restoreCallingIdentity(origId); 4050 } 4051 } 4052 4053 void releaseBackgroundResources(ActivityRecord r) { 4054 if (hasVisibleBehindActivity() && 4055 !mHandler.hasMessages(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG)) { 4056 if (r == topRunningActivityLocked() 4057 && getStackVisibilityLocked(null) == STACK_VISIBLE) { 4058 // Don't release the top activity if it has requested to run behind the next 4059 // activity and the stack is currently visible. 4060 return; 4061 } 4062 if (DEBUG_STATES) Slog.d(TAG_STATES, "releaseBackgroundResources activtyDisplay=" + 4063 mActivityContainer.mActivityDisplay + " visibleBehind=" + r + " app=" + r.app + 4064 " thread=" + r.app.thread); 4065 if (r != null && r.app != null && r.app.thread != null) { 4066 try { 4067 r.app.thread.scheduleCancelVisibleBehind(r.appToken); 4068 } catch (RemoteException e) { 4069 } 4070 mHandler.sendEmptyMessageDelayed(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG, 500); 4071 } else { 4072 Slog.e(TAG, "releaseBackgroundResources: activity " + r + " no longer running"); 4073 backgroundResourcesReleased(); 4074 } 4075 } 4076 } 4077 4078 final void backgroundResourcesReleased() { 4079 mHandler.removeMessages(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG); 4080 final ActivityRecord r = getVisibleBehindActivity(); 4081 if (r != null) { 4082 mStackSupervisor.mStoppingActivities.add(r); 4083 setVisibleBehindActivity(null); 4084 mStackSupervisor.scheduleIdleTimeoutLocked(null); 4085 } 4086 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 4087 } 4088 4089 boolean hasVisibleBehindActivity() { 4090 return isAttached() && mActivityContainer.mActivityDisplay.hasVisibleBehindActivity(); 4091 } 4092 4093 void setVisibleBehindActivity(ActivityRecord r) { 4094 if (isAttached()) { 4095 mActivityContainer.mActivityDisplay.setVisibleBehindActivity(r); 4096 } 4097 } 4098 4099 ActivityRecord getVisibleBehindActivity() { 4100 return isAttached() ? mActivityContainer.mActivityDisplay.mVisibleBehindActivity : null; 4101 } 4102 4103 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list, 4104 ProcessRecord app, String listName) { 4105 int i = list.size(); 4106 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 4107 "Removing app " + app + " from list " + listName + " with " + i + " entries"); 4108 while (i > 0) { 4109 i--; 4110 ActivityRecord r = list.get(i); 4111 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "Record #" + i + " " + r); 4112 if (r.app == app) { 4113 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "---> REMOVING this entry!"); 4114 list.remove(i); 4115 removeTimeoutsForActivityLocked(r); 4116 } 4117 } 4118 } 4119 4120 private boolean removeHistoryRecordsForAppLocked(ProcessRecord app) { 4121 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities"); 4122 removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app, 4123 "mStoppingActivities"); 4124 removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app, 4125 "mGoingToSleepActivities"); 4126 removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app, 4127 "mWaitingVisibleActivities"); 4128 removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app, 4129 "mFinishingActivities"); 4130 4131 boolean hasVisibleActivities = false; 4132 4133 // Clean out the history list. 4134 int i = numActivities(); 4135 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 4136 "Removing app " + app + " from history with " + i + " entries"); 4137 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4138 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 4139 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 4140 final ActivityRecord r = activities.get(activityNdx); 4141 --i; 4142 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 4143 "Record #" + i + " " + r + ": app=" + r.app); 4144 if (r.app == app) { 4145 if (r.visible) { 4146 hasVisibleActivities = true; 4147 } 4148 final boolean remove; 4149 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) { 4150 // Don't currently have state for the activity, or 4151 // it is finishing -- always remove it. 4152 remove = true; 4153 } else if (!r.visible && r.launchCount > 2 && 4154 r.lastLaunchTime > (SystemClock.uptimeMillis() - 60000)) { 4155 // We have launched this activity too many times since it was 4156 // able to run, so give up and remove it. 4157 // (Note if the activity is visible, we don't remove the record. 4158 // We leave the dead window on the screen but the process will 4159 // not be restarted unless user explicitly tap on it.) 4160 remove = true; 4161 } else { 4162 // The process may be gone, but the activity lives on! 4163 remove = false; 4164 } 4165 if (remove) { 4166 if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) Slog.i(TAG_ADD_REMOVE, 4167 "Removing activity " + r + " from stack at " + i 4168 + ": haveState=" + r.haveState 4169 + " stateNotNeeded=" + r.stateNotNeeded 4170 + " finishing=" + r.finishing 4171 + " state=" + r.state + " callers=" + Debug.getCallers(5)); 4172 if (!r.finishing) { 4173 Slog.w(TAG, "Force removing " + r + ": app died, no saved state"); 4174 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, 4175 r.userId, System.identityHashCode(r), 4176 r.task.taskId, r.shortComponentName, 4177 "proc died without state saved"); 4178 if (r.state == ActivityState.RESUMED) { 4179 mService.updateUsageStats(r, false); 4180 } 4181 } 4182 } else { 4183 // We have the current state for this activity, so 4184 // it can be restarted later when needed. 4185 if (DEBUG_ALL) Slog.v(TAG, "Keeping entry, setting app to null"); 4186 if (DEBUG_APP) Slog.v(TAG_APP, 4187 "Clearing app during removeHistory for activity " + r); 4188 r.app = null; 4189 // Set nowVisible to previous visible state. If the app was visible while 4190 // it died, we leave the dead window on screen so it's basically visible. 4191 // This is needed when user later tap on the dead window, we need to stop 4192 // other apps when user transfers focus to the restarted activity. 4193 r.nowVisible = r.visible; 4194 if (!r.haveState) { 4195 if (DEBUG_SAVED_STATE) Slog.i(TAG_SAVED_STATE, 4196 "App died, clearing saved state of " + r); 4197 r.icicle = null; 4198 } 4199 } 4200 cleanUpActivityLocked(r, true, true); 4201 if (remove) { 4202 removeActivityFromHistoryLocked(r, "appDied"); 4203 } 4204 } 4205 } 4206 } 4207 4208 return hasVisibleActivities; 4209 } 4210 4211 private void updateTransitLocked(int transit, ActivityOptions options) { 4212 if (options != null) { 4213 ActivityRecord r = topRunningActivityLocked(); 4214 if (r != null && r.state != ActivityState.RESUMED) { 4215 r.updateOptionsLocked(options); 4216 } else { 4217 ActivityOptions.abort(options); 4218 } 4219 } 4220 mWindowManager.prepareAppTransition(transit, false); 4221 } 4222 4223 private void updateTaskMovement(TaskRecord task, boolean toFront) { 4224 if (task.isPersistable) { 4225 task.mLastTimeMoved = System.currentTimeMillis(); 4226 // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most 4227 // recently will be most negative, tasks sent to the bottom before that will be less 4228 // negative. Similarly for recent tasks moved to the top which will be most positive. 4229 if (!toFront) { 4230 task.mLastTimeMoved *= -1; 4231 } 4232 } 4233 mStackSupervisor.invalidateTaskLayers(); 4234 } 4235 4236 void moveHomeStackTaskToTop() { 4237 final int top = mTaskHistory.size() - 1; 4238 for (int taskNdx = top; taskNdx >= 0; --taskNdx) { 4239 final TaskRecord task = mTaskHistory.get(taskNdx); 4240 if (task.taskType == HOME_ACTIVITY_TYPE) { 4241 if (DEBUG_TASKS || DEBUG_STACK) Slog.d(TAG_STACK, 4242 "moveHomeStackTaskToTop: moving " + task); 4243 mTaskHistory.remove(taskNdx); 4244 mTaskHistory.add(top, task); 4245 updateTaskMovement(task, true); 4246 return; 4247 } 4248 } 4249 } 4250 4251 final void moveTaskToFrontLocked(TaskRecord tr, boolean noAnimation, ActivityOptions options, 4252 AppTimeTracker timeTracker, String reason) { 4253 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "moveTaskToFront: " + tr); 4254 4255 final ActivityRecord focusedTopActivity = mStackSupervisor.getFocusedStack() != null 4256 ? mStackSupervisor.getFocusedStack().topActivity() : null; 4257 final int numTasks = mTaskHistory.size(); 4258 final int index = mTaskHistory.indexOf(tr); 4259 if (numTasks == 0 || index < 0) { 4260 // nothing to do! 4261 if (noAnimation) { 4262 ActivityOptions.abort(options); 4263 } else { 4264 updateTransitLocked(TRANSIT_TASK_TO_FRONT, options); 4265 } 4266 return; 4267 } 4268 4269 if (timeTracker != null) { 4270 // The caller wants a time tracker associated with this task. 4271 for (int i = tr.mActivities.size() - 1; i >= 0; i--) { 4272 tr.mActivities.get(i).appTimeTracker = timeTracker; 4273 } 4274 } 4275 4276 // Shift all activities with this task up to the top 4277 // of the stack, keeping them in the same internal order. 4278 insertTaskAtTop(tr, null); 4279 4280 // Don't refocus if invisible to current user 4281 ActivityRecord top = tr.getTopActivity(); 4282 if (top == null || !top.okToShowLocked()) { 4283 addRecentActivityLocked(top); 4284 ActivityOptions.abort(options); 4285 return; 4286 } 4287 4288 // Set focus to the top running activity of this stack. 4289 ActivityRecord r = topRunningActivityLocked(); 4290 mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, reason); 4291 4292 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to front transition: task=" + tr); 4293 if (noAnimation) { 4294 mWindowManager.prepareAppTransition(TRANSIT_NONE, false); 4295 if (r != null) { 4296 mNoAnimActivities.add(r); 4297 } 4298 ActivityOptions.abort(options); 4299 } else { 4300 updateTransitLocked(TRANSIT_TASK_TO_FRONT, options); 4301 } 4302 // If a new task is moved to the front, then mark the existing top activity as supporting 4303 // picture-in-picture while paused 4304 if (focusedTopActivity != null) { 4305 focusedTopActivity.supportsPictureInPictureWhilePausing = true; 4306 } 4307 4308 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 4309 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId); 4310 4311 mService.mTaskChangeNotificationController.notifyTaskMovedToFront(tr.taskId); 4312 } 4313 4314 /** 4315 * Worker method for rearranging history stack. Implements the function of moving all 4316 * activities for a specific task (gathering them if disjoint) into a single group at the 4317 * bottom of the stack. 4318 * 4319 * If a watcher is installed, the action is preflighted and the watcher has an opportunity 4320 * to premeptively cancel the move. 4321 * 4322 * @param taskId The taskId to collect and move to the bottom. 4323 * @return Returns true if the move completed, false if not. 4324 */ 4325 final boolean moveTaskToBackLocked(int taskId) { 4326 final TaskRecord tr = taskForIdLocked(taskId); 4327 if (tr == null) { 4328 Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId); 4329 return false; 4330 } 4331 4332 Slog.i(TAG, "moveTaskToBack: " + tr); 4333 mStackSupervisor.removeLockedTaskLocked(tr); 4334 4335 // If we have a watcher, preflight the move before committing to it. First check 4336 // for *other* available tasks, but if none are available, then try again allowing the 4337 // current task to be selected. 4338 if (mStackSupervisor.isFrontStack(this) && mService.mController != null) { 4339 ActivityRecord next = topRunningActivityLocked(null, taskId); 4340 if (next == null) { 4341 next = topRunningActivityLocked(null, 0); 4342 } 4343 if (next != null) { 4344 // ask watcher if this is allowed 4345 boolean moveOK = true; 4346 try { 4347 moveOK = mService.mController.activityResuming(next.packageName); 4348 } catch (RemoteException e) { 4349 mService.mController = null; 4350 Watchdog.getInstance().setActivityController(null); 4351 } 4352 if (!moveOK) { 4353 return false; 4354 } 4355 } 4356 } 4357 4358 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to back transition: task=" + taskId); 4359 4360 if (mStackId == HOME_STACK_ID && topTask().isHomeTask()) { 4361 if (topTask().isOnTopLauncher()) { 4362 // An on-top launcher doesn't affect the visibility of activities on other stacks 4363 // behind it. So if we're moving an on-top launcher to the back, we want to move the 4364 // focus to the next focusable stack and resume an activity there. 4365 // Besides, when the docked stack is visible, we should also move the home stack to 4366 // the back to avoid the recents pops up on top of a fullscreen or freeform 4367 // activity. 4368 4369 // Move the home stack to back. 4370 moveToBack(topTask()); 4371 4372 // Resume an activity in the next focusable stack. 4373 adjustFocusToNextFocusableStackLocked("moveTaskToBack"); 4374 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 4375 return true; 4376 } 4377 4378 // For the case where we are moving the home task back and there is an activity visible 4379 // behind it on the fullscreen stack, we want to move the focus to the visible behind 4380 // activity to maintain order with what the user is seeing. 4381 final ActivityStack fullscreenStack = 4382 mStackSupervisor.getStack(FULLSCREEN_WORKSPACE_STACK_ID); 4383 if (fullscreenStack != null && fullscreenStack.hasVisibleBehindActivity()) { 4384 final ActivityRecord visibleBehind = fullscreenStack.getVisibleBehindActivity(); 4385 mStackSupervisor.moveFocusableActivityStackToFrontLocked(visibleBehind, "moveTaskToBack"); 4386 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 4387 return true; 4388 } 4389 } 4390 4391 boolean prevIsHome = false; 4392 4393 // If true, we should resume the home activity next if the task we are moving to the 4394 // back is over the home stack. We force to false if the task we are moving to back 4395 // is the home task and we don't want it resumed after moving to the back. 4396 final boolean canGoHome = !tr.isHomeTask() && tr.isOverHomeStack(); 4397 if (canGoHome) { 4398 final TaskRecord nextTask = getNextTask(tr); 4399 if (nextTask != null) { 4400 nextTask.setTaskToReturnTo(tr.getTaskToReturnTo()); 4401 } else { 4402 prevIsHome = true; 4403 } 4404 } 4405 mTaskHistory.remove(tr); 4406 mTaskHistory.add(0, tr); 4407 updateTaskMovement(tr, false); 4408 4409 // There is an assumption that moving a task to the back moves it behind the home activity. 4410 // We make sure here that some activity in the stack will launch home. 4411 int numTasks = mTaskHistory.size(); 4412 for (int taskNdx = numTasks - 1; taskNdx >= 1; --taskNdx) { 4413 final TaskRecord task = mTaskHistory.get(taskNdx); 4414 if (task.isOverHomeStack()) { 4415 break; 4416 } 4417 if (taskNdx == 1) { 4418 // Set the last task before tr to go to home. 4419 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE); 4420 } 4421 } 4422 4423 mWindowManager.prepareAppTransition(TRANSIT_TASK_TO_BACK, false); 4424 mWindowContainerController.positionChildAtBottom(tr.getWindowContainerController()); 4425 4426 final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null; 4427 if (prevIsHome || (task == tr && canGoHome) || (numTasks <= 1 && isOnHomeDisplay())) { 4428 if (!mService.mBooting && !mService.mBooted) { 4429 // Not ready yet! 4430 return false; 4431 } 4432 tr.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE); 4433 return mStackSupervisor.resumeHomeStackTask(null, "moveTaskToBack"); 4434 } 4435 4436 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 4437 return true; 4438 } 4439 4440 static void logStartActivity(int tag, ActivityRecord r, TaskRecord task) { 4441 final Uri data = r.intent.getData(); 4442 final String strData = data != null ? data.toSafeString() : null; 4443 4444 EventLog.writeEvent(tag, 4445 r.userId, System.identityHashCode(r), task.taskId, 4446 r.shortComponentName, r.intent.getAction(), 4447 r.intent.getType(), strData, r.intent.getFlags()); 4448 } 4449 4450 /** 4451 * Ensures all visible activities at or below the input activity have the right configuration. 4452 */ 4453 void ensureVisibleActivitiesConfigurationLocked(ActivityRecord start, boolean preserveWindow) { 4454 if (start == null || !start.visible) { 4455 return; 4456 } 4457 4458 final TaskRecord startTask = start.task; 4459 boolean behindFullscreen = false; 4460 boolean updatedConfig = false; 4461 4462 for (int taskIndex = mTaskHistory.indexOf(startTask); taskIndex >= 0; --taskIndex) { 4463 final TaskRecord task = mTaskHistory.get(taskIndex); 4464 final ArrayList<ActivityRecord> activities = task.mActivities; 4465 int activityIndex = 4466 (start.task == task) ? activities.indexOf(start) : activities.size() - 1; 4467 for (; activityIndex >= 0; --activityIndex) { 4468 final ActivityRecord r = activities.get(activityIndex); 4469 updatedConfig |= r.ensureActivityConfigurationLocked(0 /* globalChanges */, 4470 preserveWindow); 4471 if (r.fullscreen) { 4472 behindFullscreen = true; 4473 break; 4474 } 4475 } 4476 if (behindFullscreen) { 4477 break; 4478 } 4479 } 4480 if (updatedConfig) { 4481 // Ensure the resumed state of the focus activity if we updated the configuration of 4482 // any activity. 4483 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 4484 } 4485 } 4486 4487 // TODO: Figure-out a way to consolidate with resize() method below. 4488 @Override 4489 public void requestResize(Rect bounds) { 4490 mService.resizeStack(mStackId, bounds, true /* allowResizeInDockedMode */, 4491 false /* preserveWindows */, false /* animate */, -1 /* animationDuration */); 4492 } 4493 4494 // TODO: Can only be called from special methods in ActivityStackSupervisor. 4495 // Need to consolidate those calls points into this resize method so anyone can call directly. 4496 void resize(Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds) { 4497 bounds = TaskRecord.validateBounds(bounds); 4498 4499 if (!updateBoundsAllowed(bounds, tempTaskBounds, tempTaskInsetBounds)) { 4500 return; 4501 } 4502 4503 // Update override configurations of all tasks in the stack. 4504 final Rect taskBounds = tempTaskBounds != null ? tempTaskBounds : bounds; 4505 final Rect insetBounds = tempTaskInsetBounds != null ? tempTaskInsetBounds : taskBounds; 4506 4507 mTmpBounds.clear(); 4508 mTmpConfigs.clear(); 4509 mTmpInsetBounds.clear(); 4510 4511 for (int i = mTaskHistory.size() - 1; i >= 0; i--) { 4512 final TaskRecord task = mTaskHistory.get(i); 4513 if (task.isResizeable()) { 4514 if (mStackId == FREEFORM_WORKSPACE_STACK_ID) { 4515 // For freeform stack we don't adjust the size of the tasks to match that 4516 // of the stack, but we do try to make sure the tasks are still contained 4517 // with the bounds of the stack. 4518 mTmpRect2.set(task.mBounds); 4519 fitWithinBounds(mTmpRect2, bounds); 4520 task.updateOverrideConfiguration(mTmpRect2); 4521 } else { 4522 task.updateOverrideConfiguration(taskBounds, insetBounds); 4523 } 4524 } 4525 4526 mTmpConfigs.put(task.taskId, task.getOverrideConfiguration()); 4527 mTmpBounds.put(task.taskId, task.mBounds); 4528 if (tempTaskInsetBounds != null) { 4529 mTmpInsetBounds.put(task.taskId, tempTaskInsetBounds); 4530 } 4531 } 4532 4533 mFullscreen = mWindowContainerController.resize(bounds, mTmpConfigs, mTmpBounds, 4534 mTmpInsetBounds); 4535 setBounds(bounds); 4536 } 4537 4538 4539 /** 4540 * Adjust bounds to stay within stack bounds. 4541 * 4542 * Since bounds might be outside of stack bounds, this method tries to move the bounds in a way 4543 * that keep them unchanged, but be contained within the stack bounds. 4544 * 4545 * @param bounds Bounds to be adjusted. 4546 * @param stackBounds Bounds within which the other bounds should remain. 4547 */ 4548 private static void fitWithinBounds(Rect bounds, Rect stackBounds) { 4549 if (stackBounds == null || stackBounds.contains(bounds)) { 4550 return; 4551 } 4552 4553 if (bounds.left < stackBounds.left || bounds.right > stackBounds.right) { 4554 final int maxRight = stackBounds.right 4555 - (stackBounds.width() / FIT_WITHIN_BOUNDS_DIVIDER); 4556 int horizontalDiff = stackBounds.left - bounds.left; 4557 if ((horizontalDiff < 0 && bounds.left >= maxRight) 4558 || (bounds.left + horizontalDiff >= maxRight)) { 4559 horizontalDiff = maxRight - bounds.left; 4560 } 4561 bounds.left += horizontalDiff; 4562 bounds.right += horizontalDiff; 4563 } 4564 4565 if (bounds.top < stackBounds.top || bounds.bottom > stackBounds.bottom) { 4566 final int maxBottom = stackBounds.bottom 4567 - (stackBounds.height() / FIT_WITHIN_BOUNDS_DIVIDER); 4568 int verticalDiff = stackBounds.top - bounds.top; 4569 if ((verticalDiff < 0 && bounds.top >= maxBottom) 4570 || (bounds.top + verticalDiff >= maxBottom)) { 4571 verticalDiff = maxBottom - bounds.top; 4572 } 4573 bounds.top += verticalDiff; 4574 bounds.bottom += verticalDiff; 4575 } 4576 } 4577 4578 boolean willActivityBeVisibleLocked(IBinder token) { 4579 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4580 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 4581 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 4582 final ActivityRecord r = activities.get(activityNdx); 4583 if (r.appToken == token) { 4584 return true; 4585 } 4586 if (r.fullscreen && !r.finishing) { 4587 return false; 4588 } 4589 } 4590 } 4591 final ActivityRecord r = ActivityRecord.forTokenLocked(token); 4592 if (r == null) { 4593 return false; 4594 } 4595 if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false," 4596 + " would have returned true for r=" + r); 4597 return !r.finishing; 4598 } 4599 4600 void closeSystemDialogsLocked() { 4601 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4602 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 4603 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 4604 final ActivityRecord r = activities.get(activityNdx); 4605 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) { 4606 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true); 4607 } 4608 } 4609 } 4610 } 4611 4612 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses, 4613 boolean doit, boolean evenPersistent, int userId) { 4614 boolean didSomething = false; 4615 TaskRecord lastTask = null; 4616 ComponentName homeActivity = null; 4617 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4618 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 4619 int numActivities = activities.size(); 4620 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) { 4621 ActivityRecord r = activities.get(activityNdx); 4622 final boolean sameComponent = 4623 (r.packageName.equals(packageName) && (filterByClasses == null 4624 || filterByClasses.contains(r.realActivity.getClassName()))) 4625 || (packageName == null && r.userId == userId); 4626 if ((userId == UserHandle.USER_ALL || r.userId == userId) 4627 && (sameComponent || r.task == lastTask) 4628 && (r.app == null || evenPersistent || !r.app.persistent)) { 4629 if (!doit) { 4630 if (r.finishing) { 4631 // If this activity is just finishing, then it is not 4632 // interesting as far as something to stop. 4633 continue; 4634 } 4635 return true; 4636 } 4637 if (r.isHomeActivity()) { 4638 if (homeActivity != null && homeActivity.equals(r.realActivity)) { 4639 Slog.i(TAG, "Skip force-stop again " + r); 4640 continue; 4641 } else { 4642 homeActivity = r.realActivity; 4643 } 4644 } 4645 didSomething = true; 4646 Slog.i(TAG, " Force finishing activity " + r); 4647 if (sameComponent) { 4648 if (r.app != null) { 4649 r.app.removed = true; 4650 } 4651 r.app = null; 4652 } 4653 lastTask = r.task; 4654 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop", 4655 true)) { 4656 // r has been deleted from mActivities, accommodate. 4657 --numActivities; 4658 --activityNdx; 4659 } 4660 } 4661 } 4662 } 4663 return didSomething; 4664 } 4665 4666 void getTasksLocked(List<RunningTaskInfo> list, int callingUid, boolean allowed) { 4667 boolean focusedStack = mStackSupervisor.getFocusedStack() == this; 4668 boolean topTask = true; 4669 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4670 final TaskRecord task = mTaskHistory.get(taskNdx); 4671 if (task.getTopActivity() == null) { 4672 continue; 4673 } 4674 ActivityRecord r = null; 4675 ActivityRecord top = null; 4676 ActivityRecord tmp; 4677 int numActivities = 0; 4678 int numRunning = 0; 4679 final ArrayList<ActivityRecord> activities = task.mActivities; 4680 if (!allowed && !task.isHomeTask() && task.effectiveUid != callingUid) { 4681 continue; 4682 } 4683 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 4684 tmp = activities.get(activityNdx); 4685 if (tmp.finishing) { 4686 continue; 4687 } 4688 r = tmp; 4689 4690 // Initialize state for next task if needed. 4691 if (top == null || (top.state == ActivityState.INITIALIZING)) { 4692 top = r; 4693 numActivities = numRunning = 0; 4694 } 4695 4696 // Add 'r' into the current task. 4697 numActivities++; 4698 if (r.app != null && r.app.thread != null) { 4699 numRunning++; 4700 } 4701 4702 if (DEBUG_ALL) Slog.v( 4703 TAG, r.intent.getComponent().flattenToShortString() 4704 + ": task=" + r.task); 4705 } 4706 4707 RunningTaskInfo ci = new RunningTaskInfo(); 4708 ci.id = task.taskId; 4709 ci.stackId = mStackId; 4710 ci.baseActivity = r.intent.getComponent(); 4711 ci.topActivity = top.intent.getComponent(); 4712 ci.lastActiveTime = task.lastActiveTime; 4713 if (focusedStack && topTask) { 4714 // Give the latest time to ensure foreground task can be sorted 4715 // at the first, because lastActiveTime of creating task is 0. 4716 ci.lastActiveTime = System.currentTimeMillis(); 4717 topTask = false; 4718 } 4719 4720 if (top.task != null) { 4721 ci.description = top.task.lastDescription; 4722 } 4723 ci.numActivities = numActivities; 4724 ci.numRunning = numRunning; 4725 ci.supportsSplitScreenMultiWindow = task.supportsSplitScreen(); 4726 ci.resizeMode = task.mResizeMode; 4727 list.add(ci); 4728 } 4729 } 4730 4731 void unhandledBackLocked() { 4732 final int top = mTaskHistory.size() - 1; 4733 if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, "Performing unhandledBack(): top activity at " + top); 4734 if (top >= 0) { 4735 final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities; 4736 int activityTop = activities.size() - 1; 4737 if (activityTop >= 0) { 4738 finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null, 4739 "unhandled-back", true); 4740 } 4741 } 4742 } 4743 4744 /** 4745 * Reset local parameters because an app's activity died. 4746 * @param app The app of the activity that died. 4747 * @return result from removeHistoryRecordsForAppLocked. 4748 */ 4749 boolean handleAppDiedLocked(ProcessRecord app) { 4750 if (mPausingActivity != null && mPausingActivity.app == app) { 4751 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG_PAUSE, 4752 "App died while pausing: " + mPausingActivity); 4753 mPausingActivity = null; 4754 } 4755 if (mLastPausedActivity != null && mLastPausedActivity.app == app) { 4756 mLastPausedActivity = null; 4757 mLastNoHistoryActivity = null; 4758 } 4759 4760 return removeHistoryRecordsForAppLocked(app); 4761 } 4762 4763 void handleAppCrashLocked(ProcessRecord app) { 4764 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4765 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 4766 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 4767 final ActivityRecord r = activities.get(activityNdx); 4768 if (r.app == app) { 4769 Slog.w(TAG, " Force finishing activity " 4770 + r.intent.getComponent().flattenToShortString()); 4771 // Force the destroy to skip right to removal. 4772 r.app = null; 4773 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false); 4774 } 4775 } 4776 } 4777 } 4778 4779 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll, 4780 boolean dumpClient, String dumpPackage, boolean needSep, String header) { 4781 boolean printed = false; 4782 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4783 final TaskRecord task = mTaskHistory.get(taskNdx); 4784 printed |= ActivityStackSupervisor.dumpHistoryList(fd, pw, 4785 mTaskHistory.get(taskNdx).mActivities, " ", "Hist", true, !dumpAll, 4786 dumpClient, dumpPackage, needSep, header, 4787 " Task id #" + task.taskId + "\n" + 4788 " mFullscreen=" + task.mFullscreen + "\n" + 4789 " mBounds=" + task.mBounds + "\n" + 4790 " mMinWidth=" + task.mMinWidth + "\n" + 4791 " mMinHeight=" + task.mMinHeight + "\n" + 4792 " mLastNonFullscreenBounds=" + task.mLastNonFullscreenBounds); 4793 if (printed) { 4794 header = null; 4795 } 4796 } 4797 return printed; 4798 } 4799 4800 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) { 4801 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(); 4802 4803 if ("all".equals(name)) { 4804 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4805 activities.addAll(mTaskHistory.get(taskNdx).mActivities); 4806 } 4807 } else if ("top".equals(name)) { 4808 final int top = mTaskHistory.size() - 1; 4809 if (top >= 0) { 4810 final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities; 4811 int listTop = list.size() - 1; 4812 if (listTop >= 0) { 4813 activities.add(list.get(listTop)); 4814 } 4815 } 4816 } else { 4817 ItemMatcher matcher = new ItemMatcher(); 4818 matcher.build(name); 4819 4820 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4821 for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) { 4822 if (matcher.match(r1, r1.intent.getComponent())) { 4823 activities.add(r1); 4824 } 4825 } 4826 } 4827 } 4828 4829 return activities; 4830 } 4831 4832 ActivityRecord restartPackage(String packageName) { 4833 ActivityRecord starting = topRunningActivityLocked(); 4834 4835 // All activities that came from the package must be 4836 // restarted as if there was a config change. 4837 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 4838 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 4839 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 4840 final ActivityRecord a = activities.get(activityNdx); 4841 if (a.info.packageName.equals(packageName)) { 4842 a.forceNewConfig = true; 4843 if (starting != null && a == starting && a.visible) { 4844 a.startFreezingScreenLocked(starting.app, 4845 CONFIG_SCREEN_LAYOUT); 4846 } 4847 } 4848 } 4849 } 4850 4851 return starting; 4852 } 4853 4854 void removeTask(TaskRecord task, String reason) { 4855 removeTask(task, reason, REMOVE_TASK_MODE_DESTROYING); 4856 } 4857 4858 /** 4859 * Removes the input task from this stack. 4860 * @param task to remove. 4861 * @param reason for removal. 4862 * @param mode task removal mode. Either {@link #REMOVE_TASK_MODE_DESTROYING}, 4863 * {@link #REMOVE_TASK_MODE_MOVING}, {@link #REMOVE_TASK_MODE_MOVING_TO_TOP}. 4864 */ 4865 void removeTask(TaskRecord task, String reason, int mode) { 4866 if (mode == REMOVE_TASK_MODE_DESTROYING) { 4867 task.removeWindowContainer(); 4868 } 4869 4870 final ActivityRecord r = mResumedActivity; 4871 if (r != null && r.task == task) { 4872 mResumedActivity = null; 4873 } 4874 4875 final int taskNdx = mTaskHistory.indexOf(task); 4876 final int topTaskNdx = mTaskHistory.size() - 1; 4877 if (task.isOverHomeStack() && taskNdx < topTaskNdx) { 4878 final TaskRecord nextTask = mTaskHistory.get(taskNdx + 1); 4879 if (!nextTask.isOverHomeStack()) { 4880 nextTask.setTaskToReturnTo(HOME_ACTIVITY_TYPE); 4881 } 4882 } 4883 mTaskHistory.remove(task); 4884 updateTaskMovement(task, true); 4885 4886 if (mode == REMOVE_TASK_MODE_DESTROYING && task.mActivities.isEmpty()) { 4887 // TODO: VI what about activity? 4888 final boolean isVoiceSession = task.voiceSession != null; 4889 if (isVoiceSession) { 4890 try { 4891 task.voiceSession.taskFinished(task.intent, task.taskId); 4892 } catch (RemoteException e) { 4893 } 4894 } 4895 if (task.autoRemoveFromRecents() || isVoiceSession) { 4896 // Task creator asked to remove this when done, or this task was a voice 4897 // interaction, so it should not remain on the recent tasks list. 4898 mRecentTasks.remove(task); 4899 task.removedFromRecents(); 4900 } 4901 } 4902 4903 if (mTaskHistory.isEmpty()) { 4904 if (DEBUG_STACK) Slog.i(TAG_STACK, "removeTask: removing stack=" + this); 4905 // We only need to adjust focused stack if this stack is in focus and we are not in the 4906 // process of moving the task to the top of the stack that will be focused. 4907 if (isOnHomeDisplay() && mode != REMOVE_TASK_MODE_MOVING_TO_TOP 4908 && mStackSupervisor.isFocusedStack(this)) { 4909 String myReason = reason + " leftTaskHistoryEmpty"; 4910 if (mFullscreen || !adjustFocusToNextFocusableStackLocked(myReason)) { 4911 mStackSupervisor.moveHomeStackToFront(myReason); 4912 } 4913 } 4914 if (mStacks != null) { 4915 mStacks.remove(this); 4916 mStacks.add(0, this); 4917 } 4918 if (!isHomeOrRecentsStack()) { 4919 mActivityContainer.onTaskListEmptyLocked(); 4920 } 4921 } 4922 4923 task.setStack(null); 4924 } 4925 4926 TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent, 4927 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, 4928 boolean toTop, int type) { 4929 TaskRecord task = new TaskRecord(mService, taskId, info, intent, voiceSession, 4930 voiceInteractor, type); 4931 // add the task to stack first, mTaskPositioner might need the stack association 4932 addTask(task, toTop, "createTaskRecord"); 4933 final boolean isLockscreenShown = 4934 mService.mStackSupervisor.mKeyguardController.isKeyguardShowing(); 4935 if (!layoutTaskInStack(task, info.windowLayout) && mBounds != null && task.isResizeable() 4936 && !isLockscreenShown) { 4937 task.updateOverrideConfiguration(mBounds); 4938 } 4939 task.createWindowContainer(toTop, (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0); 4940 return task; 4941 } 4942 4943 boolean layoutTaskInStack(TaskRecord task, ActivityInfo.WindowLayout windowLayout) { 4944 if (mTaskPositioner == null) { 4945 return false; 4946 } 4947 mTaskPositioner.updateDefaultBounds(task, mTaskHistory, windowLayout); 4948 return true; 4949 } 4950 4951 ArrayList<TaskRecord> getAllTasks() { 4952 return new ArrayList<>(mTaskHistory); 4953 } 4954 4955 void addTask(final TaskRecord task, final boolean toTop, String reason) { 4956 addTask(task, toTop ? MAX_VALUE : 0, reason); 4957 if (toTop) { 4958 // TODO: figure-out a way to remove this call. 4959 mWindowContainerController.positionChildAtTop(task.getWindowContainerController(), 4960 true /* includingParents */); 4961 } 4962 } 4963 4964 // TODO: This shouldn't allow automatic reparenting. Remove the call to preAddTask and deal 4965 // with the fall-out... 4966 void addTask(final TaskRecord task, int position, String reason) { 4967 // TODO: Is this remove really needed? Need to look into the call path for the other addTask 4968 mTaskHistory.remove(task); 4969 position = getAdjustedPositionForTask(task, position, null /* starting */); 4970 final boolean toTop = position >= mTaskHistory.size(); 4971 final ActivityStack prevStack = preAddTask(task, reason, toTop); 4972 4973 mTaskHistory.add(position, task); 4974 task.setStack(this); 4975 4976 if (toTop) { 4977 updateTaskReturnToForTopInsertion(task); 4978 } 4979 4980 updateTaskMovement(task, toTop); 4981 4982 postAddTask(task, prevStack); 4983 } 4984 4985 void positionChildAt(TaskRecord task, int index) { 4986 4987 if (task.getStack() != this) { 4988 throw new IllegalArgumentException("AS.positionChildAt: task=" + task 4989 + " is not a child of stack=" + this + " current parent=" + task.getStack()); 4990 } 4991 4992 task.updateOverrideConfigurationForStack(this); 4993 4994 final ActivityRecord topRunningActivity = task.topRunningActivityLocked(); 4995 final boolean wasResumed = topRunningActivity == task.getStack().mResumedActivity; 4996 insertTaskAtPosition(task, index); 4997 task.setStack(this); 4998 postAddTask(task, null /* prevStack */); 4999 5000 if (wasResumed) { 5001 if (mResumedActivity != null) { 5002 Log.wtf(TAG, "mResumedActivity was already set when moving mResumedActivity from" 5003 + " other stack to this stack mResumedActivity=" + mResumedActivity 5004 + " other mResumedActivity=" + topRunningActivity); 5005 } 5006 mResumedActivity = topRunningActivity; 5007 } 5008 5009 // The task might have already been running and its visibility needs to be synchronized with 5010 // the visibility of the stack / windows. 5011 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 5012 mStackSupervisor.resumeFocusedStackTopActivityLocked(); 5013 } 5014 5015 private ActivityStack preAddTask(TaskRecord task, String reason, boolean toTop) { 5016 final ActivityStack prevStack = task.getStack(); 5017 if (prevStack != null && prevStack != this) { 5018 prevStack.removeTask(task, reason, 5019 toTop ? REMOVE_TASK_MODE_MOVING_TO_TOP : REMOVE_TASK_MODE_MOVING); 5020 } 5021 return prevStack; 5022 } 5023 5024 private void postAddTask(TaskRecord task, ActivityStack prevStack) { 5025 if (prevStack != null) { 5026 mStackSupervisor.scheduleReportPictureInPictureModeChangedIfNeeded(task, prevStack); 5027 } else if (task.voiceSession != null) { 5028 try { 5029 task.voiceSession.taskStarted(task.intent, task.taskId); 5030 } catch (RemoteException e) { 5031 } 5032 } 5033 } 5034 5035 void moveToFrontAndResumeStateIfNeeded(ActivityRecord r, boolean moveToFront, boolean setResume, 5036 boolean setPause, String reason) { 5037 if (!moveToFront) { 5038 return; 5039 } 5040 5041 // If the activity owns the last resumed activity, transfer that together, 5042 // so that we don't resume the same activity again in the new stack. 5043 // Apps may depend on onResume()/onPause() being called in pairs. 5044 if (setResume) { 5045 mResumedActivity = r; 5046 } 5047 // If the activity was previously pausing, then ensure we transfer that as well 5048 if (setPause) { 5049 mPausingActivity = r; 5050 } 5051 // Move the stack in which we are placing the activity to the front. The call will also 5052 // make sure the activity focus is set. 5053 moveToFront(reason); 5054 } 5055 5056 /** 5057 * Moves the input activity from its current stack to this one. 5058 * NOTE: The current task of the activity isn't moved to this stack. Instead a new task is 5059 * created on this stack which the activity is added to. 5060 * */ 5061 void moveActivityToStack(ActivityRecord r) { 5062 final ActivityStack prevStack = r.getStack(); 5063 if (prevStack.mStackId == mStackId) { 5064 // You are already in the right stack silly... 5065 return; 5066 } 5067 5068 final boolean wasFocused = mStackSupervisor.isFocusedStack(prevStack) 5069 && (mStackSupervisor.topRunningActivityLocked() == r); 5070 final boolean wasResumed = wasFocused && (prevStack.mResumedActivity == r); 5071 final boolean wasPaused = prevStack.mPausingActivity == r; 5072 5073 final TaskRecord task = createTaskRecord( 5074 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), 5075 r.info, r.intent, null, null, true, r.mActivityType); 5076 r.setTask(task, null); 5077 task.addActivityToTop(r); 5078 mStackSupervisor.scheduleReportPictureInPictureModeChangedIfNeeded(task, prevStack); 5079 moveToFrontAndResumeStateIfNeeded(r, wasFocused, wasResumed, wasPaused, 5080 "moveActivityToStack"); 5081 if (wasResumed) { 5082 prevStack.mResumedActivity = null; 5083 } 5084 if (wasPaused) { 5085 prevStack.mPausingActivity = null; 5086 } 5087 } 5088 5089 public int getStackId() { 5090 return mStackId; 5091 } 5092 5093 @Override 5094 public String toString() { 5095 return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this)) 5096 + " stackId=" + mStackId + ", " + mTaskHistory.size() + " tasks}"; 5097 } 5098 5099 void onLockTaskPackagesUpdatedLocked() { 5100 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 5101 mTaskHistory.get(taskNdx).setLockTaskAuth(); 5102 } 5103 } 5104 5105 void executeAppTransition(ActivityOptions options) { 5106 mWindowManager.executeAppTransition(); 5107 mNoAnimActivities.clear(); 5108 ActivityOptions.abort(options); 5109 } 5110} 5111