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