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