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