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