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