ActivityStack.java revision 9d4e9bcebbd97ad51daa0ef15cfba5aabb399bbb
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 com.android.server.am.ActivityManagerService.TAG; 20import static com.android.server.am.ActivityManagerService.localLOGV; 21import static com.android.server.am.ActivityManagerService.DEBUG_CLEANUP; 22import static com.android.server.am.ActivityManagerService.DEBUG_CONFIGURATION; 23import static com.android.server.am.ActivityManagerService.DEBUG_PAUSE; 24import static com.android.server.am.ActivityManagerService.DEBUG_RESULTS; 25import static com.android.server.am.ActivityManagerService.DEBUG_STACK; 26import static com.android.server.am.ActivityManagerService.DEBUG_SWITCH; 27import static com.android.server.am.ActivityManagerService.DEBUG_TASKS; 28import static com.android.server.am.ActivityManagerService.DEBUG_TRANSITION; 29import static com.android.server.am.ActivityManagerService.DEBUG_USER_LEAVING; 30import static com.android.server.am.ActivityManagerService.DEBUG_VISBILITY; 31import static com.android.server.am.ActivityManagerService.VALIDATE_TOKENS; 32 33import static com.android.server.am.ActivityStackSupervisor.DEBUG_ADD_REMOVE; 34import static com.android.server.am.ActivityStackSupervisor.DEBUG_APP; 35import static com.android.server.am.ActivityStackSupervisor.DEBUG_CONTAINERS; 36import static com.android.server.am.ActivityStackSupervisor.DEBUG_SAVED_STATE; 37import static com.android.server.am.ActivityStackSupervisor.DEBUG_SCREENSHOTS; 38import static com.android.server.am.ActivityStackSupervisor.DEBUG_STATES; 39import static com.android.server.am.ActivityStackSupervisor.HOME_STACK_ID; 40 41import com.android.internal.app.IVoiceInteractor; 42import com.android.internal.os.BatteryStatsImpl; 43import com.android.server.Watchdog; 44import com.android.server.am.ActivityManagerService.ItemMatcher; 45import com.android.server.am.ActivityStackSupervisor.ActivityContainer; 46import com.android.server.wm.AppTransition; 47import com.android.server.wm.TaskGroup; 48import com.android.server.wm.WindowManagerService; 49 50import android.app.Activity; 51import android.app.ActivityManager; 52import android.app.ActivityOptions; 53import android.app.AppGlobals; 54import android.app.IActivityController; 55import android.app.ResultInfo; 56import android.app.ActivityManager.RunningTaskInfo; 57import android.content.ComponentName; 58import android.content.Intent; 59import android.content.pm.ActivityInfo; 60import android.content.pm.PackageManager; 61import android.content.res.Configuration; 62import android.content.res.Resources; 63import android.graphics.Bitmap; 64import android.net.Uri; 65import android.os.Binder; 66import android.os.Bundle; 67import android.os.Debug; 68import android.os.Handler; 69import android.os.IBinder; 70import android.os.Looper; 71import android.os.Message; 72import android.os.PersistableBundle; 73import android.os.RemoteException; 74import android.os.SystemClock; 75import android.os.Trace; 76import android.os.UserHandle; 77import android.service.voice.IVoiceInteractionSession; 78import android.util.EventLog; 79import android.util.Slog; 80import android.view.Display; 81 82import java.io.FileDescriptor; 83import java.io.PrintWriter; 84import java.lang.ref.WeakReference; 85import java.util.ArrayList; 86import java.util.Iterator; 87import java.util.List; 88import java.util.Objects; 89 90/** 91 * State and management of a single stack of activities. 92 */ 93final class ActivityStack { 94 95 // Ticks during which we check progress while waiting for an app to launch. 96 static final int LAUNCH_TICK = 500; 97 98 // How long we wait until giving up on the last activity to pause. This 99 // is short because it directly impacts the responsiveness of starting the 100 // next activity. 101 static final int PAUSE_TIMEOUT = 500; 102 103 // How long we wait for the activity to tell us it has stopped before 104 // giving up. This is a good amount of time because we really need this 105 // from the application in order to get its saved state. 106 static final int STOP_TIMEOUT = 10*1000; 107 108 // How long we wait until giving up on an activity telling us it has 109 // finished destroying itself. 110 static final int DESTROY_TIMEOUT = 10*1000; 111 112 // How long until we reset a task when the user returns to it. Currently 113 // disabled. 114 static final long ACTIVITY_INACTIVE_RESET_TIME = 0; 115 116 // How long between activity launches that we consider safe to not warn 117 // the user about an unexpected activity being launched on top. 118 static final long START_WARN_TIME = 5*1000; 119 120 // Set to false to disable the preview that is shown while a new activity 121 // is being started. 122 static final boolean SHOW_APP_STARTING_PREVIEW = true; 123 124 // How long to wait for all background Activities to redraw following a call to 125 // convertToTranslucent(). 126 static final long TRANSLUCENT_CONVERSION_TIMEOUT = 2000; 127 128 static final boolean SCREENSHOT_FORCE_565 = ActivityManager.isLowRamDeviceStatic(); 129 130 enum ActivityState { 131 INITIALIZING, 132 RESUMED, 133 PAUSING, 134 PAUSED, 135 STOPPING, 136 STOPPED, 137 FINISHING, 138 DESTROYING, 139 DESTROYED 140 } 141 142 final ActivityManagerService mService; 143 final WindowManagerService mWindowManager; 144 145 /** 146 * The back history of all previous (and possibly still 147 * running) activities. It contains #TaskRecord objects. 148 */ 149 private ArrayList<TaskRecord> mTaskHistory = new ArrayList<TaskRecord>(); 150 151 /** 152 * Used for validating app tokens with window manager. 153 */ 154 final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>(); 155 156 /** 157 * List of running activities, sorted by recent usage. 158 * The first entry in the list is the least recently used. 159 * It contains HistoryRecord objects. 160 */ 161 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>(); 162 163 /** 164 * Animations that for the current transition have requested not to 165 * be considered for the transition animation. 166 */ 167 final ArrayList<ActivityRecord> mNoAnimActivities = new ArrayList<ActivityRecord>(); 168 169 /** 170 * When we are in the process of pausing an activity, before starting the 171 * next one, this variable holds the activity that is currently being paused. 172 */ 173 ActivityRecord mPausingActivity = null; 174 175 /** 176 * This is the last activity that we put into the paused state. This is 177 * used to determine if we need to do an activity transition while sleeping, 178 * when we normally hold the top activity paused. 179 */ 180 ActivityRecord mLastPausedActivity = null; 181 182 /** 183 * Activities that specify No History must be removed once the user navigates away from them. 184 * If the device goes to sleep with such an activity in the paused state then we save it here 185 * and finish it later if another activity replaces it on wakeup. 186 */ 187 ActivityRecord mLastNoHistoryActivity = null; 188 189 /** 190 * Current activity that is resumed, or null if there is none. 191 */ 192 ActivityRecord mResumedActivity = null; 193 194 /** 195 * This is the last activity that has been started. It is only used to 196 * identify when multiple activities are started at once so that the user 197 * can be warned they may not be in the activity they think they are. 198 */ 199 ActivityRecord mLastStartedActivity = null; 200 201 // The topmost Activity passed to convertToTranslucent(). When non-null it means we are 202 // waiting for all Activities in mUndrawnActivitiesBelowTopTranslucent to be removed as they 203 // are drawn. When the last member of mUndrawnActivitiesBelowTopTranslucent is removed the 204 // Activity in mTranslucentActivityWaiting is notified via 205 // Activity.onTranslucentConversionComplete(false). If a timeout occurs prior to the last 206 // background activity being drawn then the same call will be made with a true value. 207 ActivityRecord mTranslucentActivityWaiting = null; 208 ArrayList<ActivityRecord> mUndrawnActivitiesBelowTopTranslucent = 209 new ArrayList<ActivityRecord>(); 210 // Options passed from the caller of the convertToTranslucent to the activity that will 211 // appear below it. 212 ActivityOptions mReturningActivityOptions = null; 213 214 /** 215 * Set when we know we are going to be calling updateConfiguration() 216 * soon, so want to skip intermediate config checks. 217 */ 218 boolean mConfigWillChange; 219 220 long mLaunchStartTime = 0; 221 long mFullyDrawnStartTime = 0; 222 223 /** 224 * Save the most recent screenshot for reuse. This keeps Recents from taking two identical 225 * screenshots, one for the Recents thumbnail and one for the pauseActivity thumbnail. 226 */ 227 private ActivityRecord mLastScreenshotActivity = null; 228 private Bitmap mLastScreenshotBitmap = null; 229 230 int mThumbnailWidth = -1; 231 int mThumbnailHeight = -1; 232 233 int mCurrentUser; 234 235 final int mStackId; 236 final ActivityContainer mActivityContainer; 237 /** The other stacks, in order, on the attached display. Updated at attach/detach time. */ 238 ArrayList<ActivityStack> mStacks; 239 /** The attached Display's unique identifier, or -1 if detached */ 240 int mDisplayId; 241 242 /** Run all ActivityStacks through this */ 243 final ActivityStackSupervisor mStackSupervisor; 244 245 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1; 246 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2; 247 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3; 248 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4; 249 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5; 250 static final int TRANSLUCENT_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6; 251 252 static class ScheduleDestroyArgs { 253 final ProcessRecord mOwner; 254 final boolean mOomAdj; 255 final String mReason; 256 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) { 257 mOwner = owner; 258 mOomAdj = oomAdj; 259 mReason = reason; 260 } 261 } 262 263 final Handler mHandler; 264 265 final class ActivityStackHandler extends Handler { 266 //public Handler() { 267 // if (localLOGV) Slog.v(TAG, "Handler started!"); 268 //} 269 ActivityStackHandler(Looper looper) { 270 super(looper); 271 } 272 273 @Override 274 public void handleMessage(Message msg) { 275 switch (msg.what) { 276 case PAUSE_TIMEOUT_MSG: { 277 ActivityRecord r = (ActivityRecord)msg.obj; 278 // We don't at this point know if the activity is fullscreen, 279 // so we need to be conservative and assume it isn't. 280 Slog.w(TAG, "Activity pause timeout for " + r); 281 synchronized (mService) { 282 if (r.app != null) { 283 mService.logAppTooSlow(r.app, r.pauseTime, "pausing " + r); 284 } 285 activityPausedLocked(r.appToken, true, r.persistentState); 286 } 287 } break; 288 case LAUNCH_TICK_MSG: { 289 ActivityRecord r = (ActivityRecord)msg.obj; 290 synchronized (mService) { 291 if (r.continueLaunchTickingLocked()) { 292 mService.logAppTooSlow(r.app, r.launchTickTime, "launching " + r); 293 } 294 } 295 } break; 296 case DESTROY_TIMEOUT_MSG: { 297 ActivityRecord r = (ActivityRecord)msg.obj; 298 // We don't at this point know if the activity is fullscreen, 299 // so we need to be conservative and assume it isn't. 300 Slog.w(TAG, "Activity destroy timeout for " + r); 301 synchronized (mService) { 302 activityDestroyedLocked(r != null ? r.appToken : null); 303 } 304 } break; 305 case STOP_TIMEOUT_MSG: { 306 ActivityRecord r = (ActivityRecord)msg.obj; 307 // We don't at this point know if the activity is fullscreen, 308 // so we need to be conservative and assume it isn't. 309 Slog.w(TAG, "Activity stop timeout for " + r); 310 synchronized (mService) { 311 if (r.isInHistory()) { 312 activityStoppedLocked(r, null, null, null); 313 } 314 } 315 } break; 316 case DESTROY_ACTIVITIES_MSG: { 317 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj; 318 synchronized (mService) { 319 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason); 320 } 321 } break; 322 case TRANSLUCENT_TIMEOUT_MSG: { 323 synchronized (mService) { 324 notifyActivityDrawnLocked(null); 325 } 326 } break; 327 } 328 } 329 } 330 331 int numActivities() { 332 int count = 0; 333 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 334 count += mTaskHistory.get(taskNdx).mActivities.size(); 335 } 336 return count; 337 } 338 339 ActivityStack(ActivityStackSupervisor.ActivityContainer activityContainer) { 340 mActivityContainer = activityContainer; 341 mStackSupervisor = activityContainer.getOuter(); 342 mService = mStackSupervisor.mService; 343 mHandler = new ActivityStackHandler(mService.mHandler.getLooper()); 344 mWindowManager = mService.mWindowManager; 345 mStackId = activityContainer.mStackId; 346 mCurrentUser = mService.mCurrentUserId; 347 // Get the activity screenshot thumbnail dimensions 348 Resources res = mService.mContext.getResources(); 349 mThumbnailWidth = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width); 350 mThumbnailHeight = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height); 351 } 352 353 /** 354 * Checks whether the userid is a profile of the current user. 355 */ 356 private boolean isCurrentProfileLocked(int userId) { 357 if (userId == mCurrentUser) return true; 358 for (int i = 0; i < mService.mCurrentProfileIds.length; i++) { 359 if (mService.mCurrentProfileIds[i] == userId) return true; 360 } 361 return false; 362 } 363 364 boolean okToShowLocked(ActivityRecord r) { 365 return isCurrentProfileLocked(r.userId) 366 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0; 367 } 368 369 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) { 370 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 371 ActivityRecord r = mTaskHistory.get(taskNdx).topRunningActivityLocked(notTop); 372 if (r != null) { 373 return r; 374 } 375 } 376 return null; 377 } 378 379 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) { 380 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 381 final TaskRecord task = mTaskHistory.get(taskNdx); 382 final ArrayList<ActivityRecord> activities = task.mActivities; 383 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 384 ActivityRecord r = activities.get(activityNdx); 385 if (!r.finishing && !r.delayedResume && r != notTop && okToShowLocked(r)) { 386 return r; 387 } 388 } 389 } 390 return null; 391 } 392 393 /** 394 * This is a simplified version of topRunningActivityLocked that provides a number of 395 * optional skip-over modes. It is intended for use with the ActivityController hook only. 396 * 397 * @param token If non-null, any history records matching this token will be skipped. 398 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID. 399 * 400 * @return Returns the HistoryRecord of the next activity on the stack. 401 */ 402 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) { 403 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 404 TaskRecord task = mTaskHistory.get(taskNdx); 405 if (task.taskId == taskId) { 406 continue; 407 } 408 ArrayList<ActivityRecord> activities = task.mActivities; 409 for (int i = activities.size() - 1; i >= 0; --i) { 410 final ActivityRecord r = activities.get(i); 411 // Note: the taskId check depends on real taskId fields being non-zero 412 if (!r.finishing && (token != r.appToken) && okToShowLocked(r)) { 413 return r; 414 } 415 } 416 } 417 return null; 418 } 419 420 final ActivityRecord topActivity() { 421 // Iterate to find the first non-empty task stack. Note that this code can 422 // be simplified once we stop storing tasks with empty mActivities lists. 423 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 424 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 425 final int topActivityNdx = activities.size() - 1; 426 if (topActivityNdx >= 0) { 427 return activities.get(topActivityNdx); 428 } 429 } 430 return null; 431 } 432 433 final TaskRecord topTask() { 434 final int size = mTaskHistory.size(); 435 if (size > 0) { 436 return mTaskHistory.get(size - 1); 437 } 438 return null; 439 } 440 441 TaskRecord taskForIdLocked(int id) { 442 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 443 final TaskRecord task = mTaskHistory.get(taskNdx); 444 if (task.taskId == id) { 445 return task; 446 } 447 } 448 return null; 449 } 450 451 ActivityRecord isInStackLocked(IBinder token) { 452 final ActivityRecord r = ActivityRecord.forToken(token); 453 if (r != null) { 454 final TaskRecord task = r.task; 455 if (task.mActivities.contains(r) && mTaskHistory.contains(task)) { 456 if (task.stack != this) Slog.w(TAG, 457 "Illegal state! task does not point to stack it is in."); 458 return r; 459 } 460 } 461 return null; 462 } 463 464 final boolean updateLRUListLocked(ActivityRecord r) { 465 final boolean hadit = mLRUActivities.remove(r); 466 mLRUActivities.add(r); 467 return hadit; 468 } 469 470 final boolean isHomeStack() { 471 return mStackId == HOME_STACK_ID; 472 } 473 474 final boolean isOnHomeDisplay() { 475 return isAttached() && 476 mActivityContainer.mActivityDisplay.mDisplayId == Display.DEFAULT_DISPLAY; 477 } 478 479 final void moveToFront() { 480 if (isAttached()) { 481 if (isOnHomeDisplay()) { 482 mStackSupervisor.moveHomeStack(isHomeStack()); 483 } 484 mStacks.remove(this); 485 mStacks.add(this); 486 } 487 } 488 489 final boolean isAttached() { 490 return mStacks != null; 491 } 492 493 /** 494 * Returns the top activity in any existing task matching the given 495 * Intent. Returns null if no such task is found. 496 */ 497 ActivityRecord findTaskLocked(ActivityRecord target) { 498 Intent intent = target.intent; 499 ActivityInfo info = target.info; 500 ComponentName cls = intent.getComponent(); 501 if (info.targetActivity != null) { 502 cls = new ComponentName(info.packageName, info.targetActivity); 503 } 504 final int userId = UserHandle.getUserId(info.applicationInfo.uid); 505 boolean isDocument = intent != null & intent.isDocument(); 506 // If documentData is non-null then it must match the existing task data. 507 Uri documentData = isDocument ? intent.getData() : null; 508 509 if (DEBUG_TASKS) Slog.d(TAG, "Looking for task of " + target + " in " + this); 510 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 511 final TaskRecord task = mTaskHistory.get(taskNdx); 512 if (task.voiceSession != null) { 513 // We never match voice sessions; those always run independently. 514 if (DEBUG_TASKS) Slog.d(TAG, "Skipping " + task + ": voice session"); 515 continue; 516 } 517 if (task.userId != userId) { 518 // Looking for a different task. 519 if (DEBUG_TASKS) Slog.d(TAG, "Skipping " + task + ": different user"); 520 continue; 521 } 522 final ActivityRecord r = task.getTopActivity(); 523 if (r == null || r.finishing || r.userId != userId || 524 r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) { 525 if (DEBUG_TASKS) Slog.d(TAG, "Skipping " + task + ": mismatch root " + r); 526 continue; 527 } 528 529 final Intent taskIntent = task.intent; 530 final Intent affinityIntent = task.affinityIntent; 531 final boolean taskIsDocument; 532 final Uri taskDocumentData; 533 if (taskIntent != null && taskIntent.isDocument()) { 534 taskIsDocument = true; 535 taskDocumentData = taskIntent.getData(); 536 } else if (affinityIntent != null && affinityIntent.isDocument()) { 537 taskIsDocument = true; 538 taskDocumentData = affinityIntent.getData(); 539 } else { 540 taskIsDocument = false; 541 taskDocumentData = null; 542 } 543 544 if (DEBUG_TASKS) Slog.d(TAG, "Comparing existing cls=" 545 + taskIntent.getComponent().flattenToShortString() 546 + "/aff=" + r.task.affinity + " to new cls=" 547 + intent.getComponent().flattenToShortString() + "/aff=" + info.taskAffinity); 548 if (!isDocument && !taskIsDocument && task.affinity != null) { 549 if (task.affinity.equals(target.taskAffinity)) { 550 if (DEBUG_TASKS) Slog.d(TAG, "Found matching affinity!"); 551 return r; 552 } 553 } else if (taskIntent != null && taskIntent.getComponent() != null && 554 taskIntent.getComponent().compareTo(cls) == 0 && 555 Objects.equals(documentData, taskDocumentData)) { 556 if (DEBUG_TASKS) Slog.d(TAG, "Found matching class!"); 557 //dump(); 558 if (DEBUG_TASKS) Slog.d(TAG, "For Intent " + intent + " bringing to top: " 559 + r.intent); 560 return r; 561 } else if (affinityIntent != null && affinityIntent.getComponent() != null && 562 affinityIntent.getComponent().compareTo(cls) == 0 && 563 Objects.equals(documentData, taskDocumentData)) { 564 if (DEBUG_TASKS) Slog.d(TAG, "Found matching class!"); 565 //dump(); 566 if (DEBUG_TASKS) Slog.d(TAG, "For Intent " + intent + " bringing to top: " 567 + r.intent); 568 return r; 569 } else if (DEBUG_TASKS) { 570 Slog.d(TAG, "Not a match: " + task); 571 } 572 } 573 574 return null; 575 } 576 577 /** 578 * Returns the first activity (starting from the top of the stack) that 579 * is the same as the given activity. Returns null if no such activity 580 * is found. 581 */ 582 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) { 583 ComponentName cls = intent.getComponent(); 584 if (info.targetActivity != null) { 585 cls = new ComponentName(info.packageName, info.targetActivity); 586 } 587 final int userId = UserHandle.getUserId(info.applicationInfo.uid); 588 589 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 590 TaskRecord task = mTaskHistory.get(taskNdx); 591 if (!isCurrentProfileLocked(task.userId)) { 592 return null; 593 } 594 final ArrayList<ActivityRecord> activities = task.mActivities; 595 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 596 ActivityRecord r = activities.get(activityNdx); 597 if (!r.finishing && r.intent.getComponent().equals(cls) && r.userId == userId) { 598 //Slog.i(TAG, "Found matching class!"); 599 //dump(); 600 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent); 601 return r; 602 } 603 } 604 } 605 606 return null; 607 } 608 609 /* 610 * Move the activities around in the stack to bring a user to the foreground. 611 */ 612 final void switchUserLocked(int userId) { 613 if (mCurrentUser == userId) { 614 return; 615 } 616 mCurrentUser = userId; 617 618 // Move userId's tasks to the top. 619 int index = mTaskHistory.size(); 620 for (int i = 0; i < index; ) { 621 TaskRecord task = mTaskHistory.get(i); 622 if (isCurrentProfileLocked(task.userId)) { 623 if (DEBUG_TASKS) Slog.d(TAG, "switchUserLocked: stack=" + getStackId() + 624 " moving " + task + " to top"); 625 mTaskHistory.remove(i); 626 mTaskHistory.add(task); 627 --index; 628 // Use same value for i. 629 } else { 630 ++i; 631 } 632 } 633 if (VALIDATE_TOKENS) { 634 validateAppTokensLocked(); 635 } 636 } 637 638 void minimalResumeActivityLocked(ActivityRecord r) { 639 r.state = ActivityState.RESUMED; 640 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r 641 + " (starting new instance)"); 642 r.stopped = false; 643 mResumedActivity = r; 644 r.task.touchActiveTime(); 645 mService.addRecentTaskLocked(r.task); 646 completeResumeLocked(r); 647 mStackSupervisor.checkReadyForSleepLocked(); 648 setLaunchTime(r); 649 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle); 650 } 651 652 private void startLaunchTraces() { 653 if (mFullyDrawnStartTime != 0) { 654 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0); 655 } 656 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching", 0); 657 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0); 658 } 659 660 private void stopFullyDrawnTraceIfNeeded() { 661 if (mFullyDrawnStartTime != 0 && mLaunchStartTime == 0) { 662 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0); 663 mFullyDrawnStartTime = 0; 664 } 665 } 666 667 void setLaunchTime(ActivityRecord r) { 668 if (r.displayStartTime == 0) { 669 r.fullyDrawnStartTime = r.displayStartTime = SystemClock.uptimeMillis(); 670 if (mLaunchStartTime == 0) { 671 startLaunchTraces(); 672 mLaunchStartTime = mFullyDrawnStartTime = r.displayStartTime; 673 } 674 } else if (mLaunchStartTime == 0) { 675 startLaunchTraces(); 676 mLaunchStartTime = mFullyDrawnStartTime = SystemClock.uptimeMillis(); 677 } 678 } 679 680 void clearLaunchTime(ActivityRecord r) { 681 // Make sure that there is no activity waiting for this to launch. 682 if (mStackSupervisor.mWaitingActivityLaunched.isEmpty()) { 683 r.displayStartTime = r.fullyDrawnStartTime = 0; 684 } else { 685 mStackSupervisor.removeTimeoutsForActivityLocked(r); 686 mStackSupervisor.scheduleIdleTimeoutLocked(r); 687 } 688 } 689 690 void awakeFromSleepingLocked() { 691 // Ensure activities are no longer sleeping. 692 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 693 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 694 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 695 activities.get(activityNdx).setSleeping(false); 696 } 697 } 698 } 699 700 /** 701 * @return true if something must be done before going to sleep. 702 */ 703 boolean checkReadyForSleepLocked() { 704 if (mResumedActivity != null) { 705 // Still have something resumed; can't sleep until it is paused. 706 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity); 707 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false"); 708 startPausingLocked(false, true); 709 return true; 710 } 711 if (mPausingActivity != null) { 712 // Still waiting for something to pause; can't sleep yet. 713 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity); 714 return true; 715 } 716 717 return false; 718 } 719 720 void goToSleep() { 721 ensureActivitiesVisibleLocked(null, 0); 722 723 // Make sure any stopped but visible activities are now sleeping. 724 // This ensures that the activity's onStop() is called. 725 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 726 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 727 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 728 final ActivityRecord r = activities.get(activityNdx); 729 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) { 730 r.setSleeping(true); 731 } 732 } 733 } 734 } 735 736 /** 737 * This resets the saved state from the last screenshot, forcing a new screenshot to be taken 738 * again when requested. 739 */ 740 private void invalidateLastScreenshot() { 741 mLastScreenshotActivity = null; 742 if (mLastScreenshotBitmap != null) { 743 mLastScreenshotBitmap.recycle(); 744 } 745 mLastScreenshotBitmap = null; 746 } 747 748 public final Bitmap screenshotActivities(ActivityRecord who) { 749 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "screenshotActivities: " + who); 750 if (who.noDisplay) { 751 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tNo display"); 752 return null; 753 } 754 755 TaskRecord tr = who.task; 756 if (mService.getMostRecentTask() != tr || isHomeStack()) { 757 // This is an optimization -- since we never show Home or Recents within Recents itself, 758 // we can just go ahead and skip taking the screenshot if this is the home stack. In 759 // the case where the most recent task is not the task that was supplied, then the stack 760 // has changed, so invalidate the last screenshot(). 761 invalidateLastScreenshot(); 762 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tIs Home stack? " + isHomeStack()); 763 return null; 764 } 765 766 int w = mThumbnailWidth; 767 int h = mThumbnailHeight; 768 if (w > 0) { 769 if (who != mLastScreenshotActivity || mLastScreenshotBitmap == null 770 || mLastScreenshotActivity.state == ActivityState.RESUMED 771 || mLastScreenshotBitmap.getWidth() != w 772 || mLastScreenshotBitmap.getHeight() != h) { 773 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tUpdating screenshot"); 774 mLastScreenshotActivity = who; 775 mLastScreenshotBitmap = mWindowManager.screenshotApplications( 776 who.appToken, Display.DEFAULT_DISPLAY, w, h, SCREENSHOT_FORCE_565); 777 } 778 if (mLastScreenshotBitmap != null) { 779 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tReusing last screenshot"); 780 return mLastScreenshotBitmap.copy(mLastScreenshotBitmap.getConfig(), true); 781 } 782 } 783 Slog.e(TAG, "Invalid thumbnail dimensions: " + w + "x" + h); 784 return null; 785 } 786 787 final void startPausingLocked(boolean userLeaving, boolean uiSleeping) { 788 if (mPausingActivity != null) { 789 Slog.e(TAG, "Trying to pause when pause is already pending for " 790 + mPausingActivity, new RuntimeException("here").fillInStackTrace()); 791 } 792 ActivityRecord prev = mResumedActivity; 793 if (prev == null) { 794 Slog.e(TAG, "Trying to pause when nothing is resumed", 795 new RuntimeException("here").fillInStackTrace()); 796 mStackSupervisor.resumeTopActivitiesLocked(); 797 return; 798 } 799 800 if (mActivityContainer.mParentActivity == null) { 801 // Top level stack, not a child. Look for child stacks. 802 mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping); 803 } 804 805 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev); 806 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev); 807 mResumedActivity = null; 808 mPausingActivity = prev; 809 mLastPausedActivity = prev; 810 mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0 811 || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null; 812 prev.state = ActivityState.PAUSING; 813 prev.task.touchActiveTime(); 814 clearLaunchTime(prev); 815 final ActivityRecord next = mStackSupervisor.topRunningActivityLocked(); 816 if (next == null || next.noDisplay || next.task != prev.task) { 817 prev.updateThumbnail(screenshotActivities(prev), null); 818 } 819 stopFullyDrawnTraceIfNeeded(); 820 821 mService.updateCpuStats(); 822 823 if (prev.app != null && prev.app.thread != null) { 824 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev); 825 try { 826 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY, 827 prev.userId, System.identityHashCode(prev), 828 prev.shortComponentName); 829 mService.updateUsageStats(prev, false); 830 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing, 831 userLeaving, prev.configChangeFlags); 832 } catch (Exception e) { 833 // Ignore exception, if process died other code will cleanup. 834 Slog.w(TAG, "Exception thrown during pause", e); 835 mPausingActivity = null; 836 mLastPausedActivity = null; 837 mLastNoHistoryActivity = null; 838 } 839 } else { 840 mPausingActivity = null; 841 mLastPausedActivity = null; 842 mLastNoHistoryActivity = null; 843 } 844 845 // If we are not going to sleep, we want to ensure the device is 846 // awake until the next activity is started. 847 if (!mService.isSleepingOrShuttingDown()) { 848 mStackSupervisor.acquireLaunchWakelock(); 849 } 850 851 if (mPausingActivity != null) { 852 // Have the window manager pause its key dispatching until the new 853 // activity has started. If we're pausing the activity just because 854 // the screen is being turned off and the UI is sleeping, don't interrupt 855 // key dispatch; the same activity will pick it up again on wakeup. 856 if (!uiSleeping) { 857 prev.pauseKeyDispatchingLocked(); 858 } else { 859 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off"); 860 } 861 862 // Schedule a pause timeout in case the app doesn't respond. 863 // We don't give it much time because this directly impacts the 864 // responsiveness seen by the user. 865 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG); 866 msg.obj = prev; 867 prev.pauseTime = SystemClock.uptimeMillis(); 868 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT); 869 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete..."); 870 } else { 871 // This activity failed to schedule the 872 // pause, so just treat it as being paused now. 873 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next."); 874 mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null); 875 } 876 } 877 878 final void activityPausedLocked(IBinder token, boolean timeout, 879 PersistableBundle persistentState) { 880 if (DEBUG_PAUSE) Slog.v( 881 TAG, "Activity paused: token=" + token + ", timeout=" + timeout); 882 883 final ActivityRecord r = isInStackLocked(token); 884 if (r != null) { 885 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 886 if (persistentState != null) { 887 r.persistentState = persistentState; 888 mService.notifyTaskPersisterLocked(r.task, false); 889 } 890 if (mPausingActivity == r) { 891 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r 892 + (timeout ? " (due to timeout)" : " (pause complete)")); 893 r.state = ActivityState.PAUSED; 894 completePauseLocked(); 895 } else { 896 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE, 897 r.userId, System.identityHashCode(r), r.shortComponentName, 898 mPausingActivity != null 899 ? mPausingActivity.shortComponentName : "(none)"); 900 } 901 } 902 } 903 904 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, 905 PersistableBundle persistentState, CharSequence description) { 906 if (r.state != ActivityState.STOPPING) { 907 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r); 908 mHandler.removeMessages(STOP_TIMEOUT_MSG, r); 909 return; 910 } 911 if (persistentState != null) { 912 r.persistentState = persistentState; 913 mService.notifyTaskPersisterLocked(r.task, false); 914 } 915 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle); 916 if (icicle != null) { 917 // If icicle is null, this is happening due to a timeout, so we 918 // haven't really saved the state. 919 r.icicle = icicle; 920 r.haveState = true; 921 r.launchCount = 0; 922 r.updateThumbnail(null, description); 923 } 924 if (!r.stopped) { 925 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)"); 926 mHandler.removeMessages(STOP_TIMEOUT_MSG, r); 927 r.stopped = true; 928 r.state = ActivityState.STOPPED; 929 if (r.finishing) { 930 r.clearOptionsLocked(); 931 } else { 932 if (r.configDestroy) { 933 destroyActivityLocked(r, true, false, "stop-config"); 934 mStackSupervisor.resumeTopActivitiesLocked(); 935 } else { 936 mStackSupervisor.updatePreviousProcessLocked(r); 937 } 938 } 939 } 940 } 941 942 private void completePauseLocked() { 943 ActivityRecord prev = mPausingActivity; 944 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev); 945 946 if (prev != null) { 947 if (prev.finishing) { 948 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev); 949 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false); 950 } else if (prev.app != null) { 951 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev); 952 if (prev.waitingVisible) { 953 prev.waitingVisible = false; 954 mStackSupervisor.mWaitingVisibleActivities.remove(prev); 955 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v( 956 TAG, "Complete pause, no longer waiting: " + prev); 957 } 958 if (prev.configDestroy) { 959 // The previous is being paused because the configuration 960 // is changing, which means it is actually stopping... 961 // To juggle the fact that we are also starting a new 962 // instance right now, we need to first completely stop 963 // the current instance before starting the new one. 964 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev); 965 destroyActivityLocked(prev, true, false, "pause-config"); 966 } else { 967 mStackSupervisor.mStoppingActivities.add(prev); 968 if (mStackSupervisor.mStoppingActivities.size() > 3 || 969 prev.frontOfTask && mTaskHistory.size() <= 1) { 970 // If we already have a few activities waiting to stop, 971 // then give up on things going idle and start clearing 972 // them out. Or if r is the last of activity of the last task the stack 973 // will be empty and must be cleared immediately. 974 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle"); 975 mStackSupervisor.scheduleIdleLocked(); 976 } else { 977 mStackSupervisor.checkReadyForSleepLocked(); 978 } 979 } 980 } else { 981 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev); 982 prev = null; 983 } 984 mPausingActivity = null; 985 } 986 987 final ActivityStack topStack = mStackSupervisor.getFocusedStack(); 988 if (!mService.isSleepingOrShuttingDown()) { 989 mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null); 990 } else { 991 mStackSupervisor.checkReadyForSleepLocked(); 992 ActivityRecord top = topStack.topRunningActivityLocked(null); 993 if (top == null || (prev != null && top != prev)) { 994 // If there are no more activities available to run, 995 // do resume anyway to start something. Also if the top 996 // activity on the stack is not the just paused activity, 997 // we need to go ahead and resume it to ensure we complete 998 // an in-flight app switch. 999 mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null); 1000 } 1001 } 1002 1003 if (prev != null) { 1004 prev.resumeKeyDispatchingLocked(); 1005 1006 if (prev.app != null && prev.cpuTimeAtResume > 0 1007 && mService.mBatteryStatsService.isOnBattery()) { 1008 long diff; 1009 synchronized (mService.mProcessCpuThread) { 1010 diff = mService.mProcessCpuTracker.getCpuTimeForPid(prev.app.pid) 1011 - prev.cpuTimeAtResume; 1012 } 1013 if (diff > 0) { 1014 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics(); 1015 synchronized (bsi) { 1016 BatteryStatsImpl.Uid.Proc ps = 1017 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid, 1018 prev.info.packageName); 1019 if (ps != null) { 1020 ps.addForegroundTimeLocked(diff); 1021 } 1022 } 1023 } 1024 } 1025 prev.cpuTimeAtResume = 0; // reset it 1026 } 1027 } 1028 1029 /** 1030 * Once we know that we have asked an application to put an activity in 1031 * the resumed state (either by launching it or explicitly telling it), 1032 * this function updates the rest of our state to match that fact. 1033 */ 1034 private void completeResumeLocked(ActivityRecord next) { 1035 next.idle = false; 1036 next.results = null; 1037 next.newIntents = null; 1038 if (next.nowVisible) { 1039 // We won't get a call to reportActivityVisibleLocked() so dismiss lockscreen now. 1040 mStackSupervisor.dismissKeyguard(); 1041 } 1042 1043 // schedule an idle timeout in case the app doesn't do it for us. 1044 mStackSupervisor.scheduleIdleTimeoutLocked(next); 1045 1046 mStackSupervisor.reportResumedActivityLocked(next); 1047 1048 next.resumeKeyDispatchingLocked(); 1049 mNoAnimActivities.clear(); 1050 1051 // Mark the point when the activity is resuming 1052 // TODO: To be more accurate, the mark should be before the onCreate, 1053 // not after the onResume. But for subsequent starts, onResume is fine. 1054 if (next.app != null) { 1055 synchronized (mService.mProcessCpuThread) { 1056 next.cpuTimeAtResume = mService.mProcessCpuTracker.getCpuTimeForPid(next.app.pid); 1057 } 1058 } else { 1059 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process 1060 } 1061 1062 // If we are resuming the activity that we had last screenshotted, then we know it will be 1063 // updated, so invalidate the last screenshot to ensure we take a fresh one when requested 1064 if (next == mLastScreenshotActivity) { 1065 invalidateLastScreenshot(); 1066 } 1067 } 1068 1069 private void setVisibile(ActivityRecord r, boolean visible) { 1070 r.visible = visible; 1071 mWindowManager.setAppVisibility(r.appToken, visible); 1072 final ArrayList<ActivityContainer> containers = r.mChildContainers; 1073 for (int containerNdx = containers.size() - 1; containerNdx >= 0; --containerNdx) { 1074 ActivityContainer container = containers.get(containerNdx); 1075 container.setVisible(visible); 1076 } 1077 } 1078 1079 // Checks if any of the stacks above this one has a fullscreen activity behind it. 1080 // If so, this stack is hidden, otherwise it is visible. 1081 private boolean isStackVisible() { 1082 if (!isAttached()) { 1083 return false; 1084 } 1085 1086 if (mStackSupervisor.isFrontStack(this)) { 1087 return true; 1088 } 1089 1090 /** 1091 * Start at the task above this one and go up, looking for a visible 1092 * fullscreen activity, or a translucent activity that requested the 1093 * wallpaper to be shown behind it. 1094 */ 1095 for (int i = mStacks.indexOf(this) + 1; i < mStacks.size(); i++) { 1096 final ArrayList<TaskRecord> tasks = mStacks.get(i).getAllTasks(); 1097 for (int taskNdx = 0; taskNdx < tasks.size(); taskNdx++) { 1098 final ArrayList<ActivityRecord> activities = tasks.get(taskNdx).mActivities; 1099 for (int activityNdx = 0; activityNdx < activities.size(); activityNdx++) { 1100 final ActivityRecord r = activities.get(activityNdx); 1101 1102 // Conditions for an activity to obscure the stack we're 1103 // examining: 1104 // 1. Not Finishing AND Visible AND: 1105 // 2. Either: 1106 // - Full Screen Activity OR 1107 // - On top of Home and our stack is NOT home 1108 if (!r.finishing && r.visible && (r.fullscreen || 1109 (!isHomeStack() && r.frontOfTask && tasks.get(taskNdx).mOnTopOfHome))) { 1110 return false; 1111 } 1112 } 1113 } 1114 } 1115 1116 return true; 1117 } 1118 1119 final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges) { 1120 ActivityRecord r = topRunningActivityLocked(null); 1121 if (r != null) { 1122 ensureActivitiesVisibleLocked(r, starting, null, configChanges); 1123 } 1124 } 1125 1126 /** 1127 * Make sure that all activities that need to be visible (that is, they 1128 * currently can be seen by the user) actually are. 1129 */ 1130 final void ensureActivitiesVisibleLocked(ActivityRecord top, ActivityRecord starting, 1131 String onlyThisProcess, int configChanges) { 1132 if (DEBUG_VISBILITY) Slog.v( 1133 TAG, "ensureActivitiesVisible behind " + top 1134 + " configChanges=0x" + Integer.toHexString(configChanges)); 1135 1136 if (mTranslucentActivityWaiting != top) { 1137 mUndrawnActivitiesBelowTopTranslucent.clear(); 1138 if (mTranslucentActivityWaiting != null) { 1139 // Call the callback with a timeout indication. 1140 notifyActivityDrawnLocked(null); 1141 mTranslucentActivityWaiting = null; 1142 } 1143 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG); 1144 } 1145 1146 // If the top activity is not fullscreen, then we need to 1147 // make sure any activities under it are now visible. 1148 boolean aboveTop = true; 1149 boolean behindFullscreen = !isStackVisible(); 1150 1151 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1152 final TaskRecord task = mTaskHistory.get(taskNdx); 1153 final ArrayList<ActivityRecord> activities = task.mActivities; 1154 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1155 final ActivityRecord r = activities.get(activityNdx); 1156 if (r.finishing) { 1157 continue; 1158 } 1159 if (aboveTop && r != top) { 1160 continue; 1161 } 1162 aboveTop = false; 1163 if (!behindFullscreen) { 1164 if (DEBUG_VISBILITY) Slog.v( 1165 TAG, "Make visible? " + r + " finishing=" + r.finishing 1166 + " state=" + r.state); 1167 1168 final boolean doThisProcess = onlyThisProcess == null 1169 || onlyThisProcess.equals(r.processName); 1170 1171 // First: if this is not the current activity being started, make 1172 // sure it matches the current configuration. 1173 if (r != starting && doThisProcess) { 1174 ensureActivityConfigurationLocked(r, 0); 1175 } 1176 1177 if (r.app == null || r.app.thread == null) { 1178 if (onlyThisProcess == null || onlyThisProcess.equals(r.processName)) { 1179 // This activity needs to be visible, but isn't even 1180 // running... get it started, but don't resume it 1181 // at this point. 1182 if (DEBUG_VISBILITY) Slog.v(TAG, "Start and freeze screen for " + r); 1183 if (r != starting) { 1184 r.startFreezingScreenLocked(r.app, configChanges); 1185 } 1186 if (!r.visible) { 1187 if (DEBUG_VISBILITY) Slog.v( 1188 TAG, "Starting and making visible: " + r); 1189 setVisibile(r, true); 1190 } 1191 if (r != starting) { 1192 mStackSupervisor.startSpecificActivityLocked(r, false, false); 1193 } 1194 } 1195 1196 } else if (r.visible) { 1197 // If this activity is already visible, then there is nothing 1198 // else to do here. 1199 if (DEBUG_VISBILITY) Slog.v(TAG, "Skipping: already visible at " + r); 1200 r.stopFreezingScreenLocked(false); 1201 1202 } else if (onlyThisProcess == null) { 1203 // This activity is not currently visible, but is running. 1204 // Tell it to become visible. 1205 r.visible = true; 1206 if (r.state != ActivityState.RESUMED && r != starting) { 1207 // If this activity is paused, tell it 1208 // to now show its window. 1209 if (DEBUG_VISBILITY) Slog.v( 1210 TAG, "Making visible and scheduling visibility: " + r); 1211 try { 1212 if (mTranslucentActivityWaiting != null) { 1213 r.updateOptionsLocked(mReturningActivityOptions); 1214 mUndrawnActivitiesBelowTopTranslucent.add(r); 1215 } 1216 setVisibile(r, true); 1217 r.sleeping = false; 1218 r.app.pendingUiClean = true; 1219 r.app.thread.scheduleWindowVisibility(r.appToken, true); 1220 r.stopFreezingScreenLocked(false); 1221 } catch (Exception e) { 1222 // Just skip on any failure; we'll make it 1223 // visible when it next restarts. 1224 Slog.w(TAG, "Exception thrown making visibile: " 1225 + r.intent.getComponent(), e); 1226 } 1227 } 1228 } 1229 1230 // Aggregate current change flags. 1231 configChanges |= r.configChangeFlags; 1232 1233 if (r.fullscreen) { 1234 // At this point, nothing else needs to be shown 1235 if (DEBUG_VISBILITY) Slog.v(TAG, "Fullscreen: at " + r); 1236 behindFullscreen = true; 1237 } else if (!isHomeStack() && r.frontOfTask && task.mOnTopOfHome) { 1238 if (DEBUG_VISBILITY) Slog.v(TAG, "Showing home: at " + r); 1239 behindFullscreen = true; 1240 } 1241 } else { 1242 if (DEBUG_VISBILITY) Slog.v( 1243 TAG, "Make invisible? " + r + " finishing=" + r.finishing 1244 + " state=" + r.state 1245 + " behindFullscreen=" + behindFullscreen); 1246 // Now for any activities that aren't visible to the user, make 1247 // sure they no longer are keeping the screen frozen. 1248 if (r.visible) { 1249 if (DEBUG_VISBILITY) Slog.v(TAG, "Making invisible: " + r); 1250 try { 1251 setVisibile(r, false); 1252 switch (r.state) { 1253 case STOPPING: 1254 case STOPPED: 1255 if (r.app != null && r.app.thread != null) { 1256 if (DEBUG_VISBILITY) Slog.v( 1257 TAG, "Scheduling invisibility: " + r); 1258 r.app.thread.scheduleWindowVisibility(r.appToken, false); 1259 } 1260 break; 1261 1262 case INITIALIZING: 1263 case RESUMED: 1264 case PAUSING: 1265 case PAUSED: 1266 // This case created for transitioning activities from 1267 // translucent to opaque {@link Activity#convertToOpaque}. 1268 if (!mStackSupervisor.mStoppingActivities.contains(r)) { 1269 mStackSupervisor.mStoppingActivities.add(r); 1270 } 1271 mStackSupervisor.scheduleIdleLocked(); 1272 break; 1273 1274 default: 1275 break; 1276 } 1277 } catch (Exception e) { 1278 // Just skip on any failure; we'll make it 1279 // visible when it next restarts. 1280 Slog.w(TAG, "Exception thrown making hidden: " 1281 + r.intent.getComponent(), e); 1282 } 1283 } else { 1284 if (DEBUG_VISBILITY) Slog.v(TAG, "Already invisible: " + r); 1285 } 1286 } 1287 } 1288 } 1289 } 1290 1291 void convertToTranslucent(ActivityRecord r, ActivityOptions options) { 1292 mTranslucentActivityWaiting = r; 1293 mUndrawnActivitiesBelowTopTranslucent.clear(); 1294 mReturningActivityOptions = options; 1295 mHandler.sendEmptyMessageDelayed(TRANSLUCENT_TIMEOUT_MSG, TRANSLUCENT_CONVERSION_TIMEOUT); 1296 } 1297 1298 /** 1299 * Called as activities below the top translucent activity are redrawn. When the last one is 1300 * redrawn notify the top activity by calling 1301 * {@link Activity#onTranslucentConversionComplete}. 1302 * 1303 * @param r The most recent background activity to be drawn. Or, if r is null then a timeout 1304 * occurred and the activity will be notified immediately. 1305 */ 1306 void notifyActivityDrawnLocked(ActivityRecord r) { 1307 mActivityContainer.setDrawn(); 1308 if ((r == null) 1309 || (mUndrawnActivitiesBelowTopTranslucent.remove(r) && 1310 mUndrawnActivitiesBelowTopTranslucent.isEmpty())) { 1311 // The last undrawn activity below the top has just been drawn. If there is an 1312 // opaque activity at the top, notify it that it can become translucent safely now. 1313 final ActivityRecord waitingActivity = mTranslucentActivityWaiting; 1314 mTranslucentActivityWaiting = null; 1315 mUndrawnActivitiesBelowTopTranslucent.clear(); 1316 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG); 1317 1318 if (waitingActivity != null) { 1319 mWindowManager.setWindowOpaque(waitingActivity.appToken, false); 1320 if (waitingActivity.app != null && waitingActivity.app.thread != null) { 1321 try { 1322 waitingActivity.app.thread.scheduleTranslucentConversionComplete( 1323 waitingActivity.appToken, r != null); 1324 } catch (RemoteException e) { 1325 } 1326 } 1327 } 1328 } 1329 } 1330 1331 /** If any activities below the top running one are in the INITIALIZING state and they have a 1332 * starting window displayed then remove that starting window. It is possible that the activity 1333 * in this state will never resumed in which case that starting window will be orphaned. */ 1334 void cancelInitializingActivities() { 1335 final ActivityRecord topActivity = topRunningActivityLocked(null); 1336 boolean aboveTop = true; 1337 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1338 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 1339 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1340 final ActivityRecord r = activities.get(activityNdx); 1341 if (aboveTop) { 1342 if (r == topActivity) { 1343 aboveTop = false; 1344 } 1345 continue; 1346 } 1347 1348 if (r.state == ActivityState.INITIALIZING && r.mStartingWindowShown) { 1349 if (DEBUG_VISBILITY) Slog.w(TAG, "Found orphaned starting window " + r); 1350 r.mStartingWindowShown = false; 1351 mWindowManager.removeAppStartingWindow(r.appToken); 1352 } 1353 } 1354 } 1355 } 1356 1357 /** 1358 * Ensure that the top activity in the stack is resumed. 1359 * 1360 * @param prev The previously resumed activity, for when in the process 1361 * of pausing; can be null to call from elsewhere. 1362 * 1363 * @return Returns true if something is being resumed, or false if 1364 * nothing happened. 1365 */ 1366 final boolean resumeTopActivityLocked(ActivityRecord prev) { 1367 return resumeTopActivityLocked(prev, null); 1368 } 1369 1370 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) { 1371 if (ActivityManagerService.DEBUG_LOCKSCREEN) mService.logLockScreen(""); 1372 1373 ActivityRecord parent = mActivityContainer.mParentActivity; 1374 if ((parent != null && parent.state != ActivityState.RESUMED) || 1375 !mActivityContainer.isAttachedLocked()) { 1376 // Do not resume this stack if its parent is not resumed. 1377 // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st. 1378 return false; 1379 } 1380 1381 cancelInitializingActivities(); 1382 1383 // Find the first activity that is not finishing. 1384 ActivityRecord next = topRunningActivityLocked(null); 1385 1386 // Remember how we'll process this pause/resume situation, and ensure 1387 // that the state is reset however we wind up proceeding. 1388 final boolean userLeaving = mStackSupervisor.mUserLeaving; 1389 mStackSupervisor.mUserLeaving = false; 1390 1391 if (next == null) { 1392 // There are no more activities! Let's just start up the 1393 // Launcher... 1394 ActivityOptions.abort(options); 1395 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: No more activities go home"); 1396 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1397 // Only resume home if on home display 1398 return isOnHomeDisplay() && mStackSupervisor.resumeHomeActivity(prev); 1399 } 1400 1401 next.delayedResume = false; 1402 1403 // If the top activity is the resumed one, nothing to do. 1404 if (mResumedActivity == next && next.state == ActivityState.RESUMED && 1405 mStackSupervisor.allResumedActivitiesComplete()) { 1406 // Make sure we have executed any pending transitions, since there 1407 // should be nothing left to do at this point. 1408 mWindowManager.executeAppTransition(); 1409 mNoAnimActivities.clear(); 1410 ActivityOptions.abort(options); 1411 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Top activity resumed " + next); 1412 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1413 return false; 1414 } 1415 1416 final TaskRecord nextTask = next.task; 1417 final TaskRecord prevTask = prev != null ? prev.task : null; 1418 if (prevTask != null && prevTask.stack == this && 1419 prevTask.mOnTopOfHome && prev.finishing && prev.frontOfTask) { 1420 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1421 if (prevTask == nextTask) { 1422 prevTask.setFrontOfTask(); 1423 } else if (prevTask != topTask()) { 1424 // This task is going away but it was supposed to return to the home task. 1425 // Now the task above it has to return to the home task instead. 1426 final int taskNdx = mTaskHistory.indexOf(prevTask) + 1; 1427 mTaskHistory.get(taskNdx).mOnTopOfHome = true; 1428 } else { 1429 if (DEBUG_STATES && isOnHomeDisplay()) Slog.d(TAG, 1430 "resumeTopActivityLocked: Launching home next"); 1431 // Only resume home if on home display 1432 return isOnHomeDisplay() && mStackSupervisor.resumeHomeActivity(prev); 1433 } 1434 } 1435 1436 // If we are sleeping, and there is no resumed activity, and the top 1437 // activity is paused, well that is the state we want. 1438 if (mService.isSleepingOrShuttingDown() 1439 && mLastPausedActivity == next 1440 && mStackSupervisor.allPausedActivitiesComplete()) { 1441 // Make sure we have executed any pending transitions, since there 1442 // should be nothing left to do at this point. 1443 mWindowManager.executeAppTransition(); 1444 mNoAnimActivities.clear(); 1445 ActivityOptions.abort(options); 1446 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Going to sleep and all paused"); 1447 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1448 return false; 1449 } 1450 1451 // Make sure that the user who owns this activity is started. If not, 1452 // we will just leave it as is because someone should be bringing 1453 // another user's activities to the top of the stack. 1454 if (mService.mStartedUsers.get(next.userId) == null) { 1455 Slog.w(TAG, "Skipping resume of top activity " + next 1456 + ": user " + next.userId + " is stopped"); 1457 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1458 return false; 1459 } 1460 1461 // The activity may be waiting for stop, but that is no longer 1462 // appropriate for it. 1463 mStackSupervisor.mStoppingActivities.remove(next); 1464 mStackSupervisor.mGoingToSleepActivities.remove(next); 1465 next.sleeping = false; 1466 mStackSupervisor.mWaitingVisibleActivities.remove(next); 1467 1468 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next); 1469 1470 // If we are currently pausing an activity, then don't do anything 1471 // until that is done. 1472 if (!mStackSupervisor.allPausedActivitiesComplete()) { 1473 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG, 1474 "resumeTopActivityLocked: Skip resume: some activity pausing."); 1475 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1476 return false; 1477 } 1478 1479 // Okay we are now going to start a switch, to 'next'. We may first 1480 // have to pause the current activity, but this is an important point 1481 // where we have decided to go to 'next' so keep track of that. 1482 // XXX "App Redirected" dialog is getting too many false positives 1483 // at this point, so turn off for now. 1484 if (false) { 1485 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) { 1486 long now = SystemClock.uptimeMillis(); 1487 final boolean inTime = mLastStartedActivity.startTime != 0 1488 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now; 1489 final int lastUid = mLastStartedActivity.info.applicationInfo.uid; 1490 final int nextUid = next.info.applicationInfo.uid; 1491 if (inTime && lastUid != nextUid 1492 && lastUid != next.launchedFromUid 1493 && mService.checkPermission( 1494 android.Manifest.permission.STOP_APP_SWITCHES, 1495 -1, next.launchedFromUid) 1496 != PackageManager.PERMISSION_GRANTED) { 1497 mService.showLaunchWarningLocked(mLastStartedActivity, next); 1498 } else { 1499 next.startTime = now; 1500 mLastStartedActivity = next; 1501 } 1502 } else { 1503 next.startTime = SystemClock.uptimeMillis(); 1504 mLastStartedActivity = next; 1505 } 1506 } 1507 1508 // We need to start pausing the current activity so the top one 1509 // can be resumed... 1510 boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving); 1511 if (mResumedActivity != null) { 1512 pausing = true; 1513 startPausingLocked(userLeaving, false); 1514 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Pausing " + mResumedActivity); 1515 } 1516 if (pausing) { 1517 if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG, 1518 "resumeTopActivityLocked: Skip resume: need to start pausing"); 1519 // At this point we want to put the upcoming activity's process 1520 // at the top of the LRU list, since we know we will be needing it 1521 // very soon and it would be a waste to let it get killed if it 1522 // happens to be sitting towards the end. 1523 if (next.app != null && next.app.thread != null) { 1524 // No reason to do full oom adj update here; we'll let that 1525 // happen whenever it needs to later. 1526 mService.updateLruProcessLocked(next.app, true, null); 1527 } 1528 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1529 return true; 1530 } 1531 1532 // If the most recent activity was noHistory but was only stopped rather 1533 // than stopped+finished because the device went to sleep, we need to make 1534 // sure to finish it as we're making a new activity topmost. 1535 if (mService.isSleeping() && mLastNoHistoryActivity != null && 1536 !mLastNoHistoryActivity.finishing) { 1537 if (DEBUG_STATES) Slog.d(TAG, "no-history finish of " + mLastNoHistoryActivity + 1538 " on new resume"); 1539 requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED, 1540 null, "no-history", false); 1541 mLastNoHistoryActivity = null; 1542 } 1543 1544 if (prev != null && prev != next) { 1545 if (!prev.waitingVisible && next != null && !next.nowVisible) { 1546 prev.waitingVisible = true; 1547 mStackSupervisor.mWaitingVisibleActivities.add(prev); 1548 if (DEBUG_SWITCH) Slog.v( 1549 TAG, "Resuming top, waiting visible to hide: " + prev); 1550 } else { 1551 // The next activity is already visible, so hide the previous 1552 // activity's windows right now so we can show the new one ASAP. 1553 // We only do this if the previous is finishing, which should mean 1554 // it is on top of the one being resumed so hiding it quickly 1555 // is good. Otherwise, we want to do the normal route of allowing 1556 // the resumed activity to be shown so we can decide if the 1557 // previous should actually be hidden depending on whether the 1558 // new one is found to be full-screen or not. 1559 if (prev.finishing) { 1560 mWindowManager.setAppVisibility(prev.appToken, false); 1561 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: " 1562 + prev + ", waitingVisible=" 1563 + (prev != null ? prev.waitingVisible : null) 1564 + ", nowVisible=" + next.nowVisible); 1565 } else { 1566 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: " 1567 + prev + ", waitingVisible=" 1568 + (prev != null ? prev.waitingVisible : null) 1569 + ", nowVisible=" + next.nowVisible); 1570 } 1571 } 1572 } 1573 1574 // Launching this app's activity, make sure the app is no longer 1575 // considered stopped. 1576 try { 1577 AppGlobals.getPackageManager().setPackageStoppedState( 1578 next.packageName, false, next.userId); /* TODO: Verify if correct userid */ 1579 } catch (RemoteException e1) { 1580 } catch (IllegalArgumentException e) { 1581 Slog.w(TAG, "Failed trying to unstop package " 1582 + next.packageName + ": " + e); 1583 } 1584 1585 // We are starting up the next activity, so tell the window manager 1586 // that the previous one will be hidden soon. This way it can know 1587 // to ignore it when computing the desired screen orientation. 1588 boolean anim = true; 1589 if (prev != null) { 1590 if (prev.finishing) { 1591 if (DEBUG_TRANSITION) Slog.v(TAG, 1592 "Prepare close transition: prev=" + prev); 1593 if (mNoAnimActivities.contains(prev)) { 1594 anim = false; 1595 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 1596 } else { 1597 mWindowManager.prepareAppTransition(prev.task == next.task 1598 ? AppTransition.TRANSIT_ACTIVITY_CLOSE 1599 : AppTransition.TRANSIT_TASK_CLOSE, false); 1600 } 1601 mWindowManager.setAppWillBeHidden(prev.appToken); 1602 mWindowManager.setAppVisibility(prev.appToken, false); 1603 } else { 1604 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: prev=" + prev); 1605 if (mNoAnimActivities.contains(next)) { 1606 anim = false; 1607 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 1608 } else { 1609 mWindowManager.prepareAppTransition(prev.task == next.task 1610 ? AppTransition.TRANSIT_ACTIVITY_OPEN 1611 : AppTransition.TRANSIT_TASK_OPEN, false); 1612 } 1613 } 1614 if (false) { 1615 mWindowManager.setAppWillBeHidden(prev.appToken); 1616 mWindowManager.setAppVisibility(prev.appToken, false); 1617 } 1618 } else { 1619 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: no previous"); 1620 if (mNoAnimActivities.contains(next)) { 1621 anim = false; 1622 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 1623 } else { 1624 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_ACTIVITY_OPEN, false); 1625 } 1626 } 1627 1628 Bundle resumeAnimOptions = null; 1629 if (anim) { 1630 ActivityOptions opts = next.getOptionsForTargetActivityLocked(); 1631 if (opts != null) { 1632 resumeAnimOptions = opts.toBundle(); 1633 } 1634 next.applyOptionsLocked(); 1635 } else { 1636 next.clearOptionsLocked(); 1637 } 1638 1639 ActivityStack lastStack = mStackSupervisor.getLastStack(); 1640 if (next.app != null && next.app.thread != null) { 1641 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next); 1642 1643 // This activity is now becoming visible. 1644 mWindowManager.setAppVisibility(next.appToken, true); 1645 1646 // schedule launch ticks to collect information about slow apps. 1647 next.startLaunchTickingLocked(); 1648 1649 ActivityRecord lastResumedActivity = 1650 lastStack == null ? null :lastStack.mResumedActivity; 1651 ActivityState lastState = next.state; 1652 1653 mService.updateCpuStats(); 1654 1655 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)"); 1656 next.state = ActivityState.RESUMED; 1657 mResumedActivity = next; 1658 next.task.touchActiveTime(); 1659 mService.addRecentTaskLocked(next.task); 1660 mService.updateLruProcessLocked(next.app, true, null); 1661 updateLRUListLocked(next); 1662 mService.updateOomAdjLocked(); 1663 1664 // Have the window manager re-evaluate the orientation of 1665 // the screen based on the new activity order. 1666 boolean notUpdated = true; 1667 if (mStackSupervisor.isFrontStack(this)) { 1668 Configuration config = mWindowManager.updateOrientationFromAppTokens( 1669 mService.mConfiguration, 1670 next.mayFreezeScreenLocked(next.app) ? next.appToken : null); 1671 if (config != null) { 1672 next.frozenBeforeDestroy = true; 1673 } 1674 notUpdated = !mService.updateConfigurationLocked(config, next, false, false); 1675 } 1676 1677 if (notUpdated) { 1678 // The configuration update wasn't able to keep the existing 1679 // instance of the activity, and instead started a new one. 1680 // We should be all done, but let's just make sure our activity 1681 // is still at the top and schedule another run if something 1682 // weird happened. 1683 ActivityRecord nextNext = topRunningActivityLocked(null); 1684 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, 1685 "Activity config changed during resume: " + next 1686 + ", new next: " + nextNext); 1687 if (nextNext != next) { 1688 // Do over! 1689 mStackSupervisor.scheduleResumeTopActivities(); 1690 } 1691 if (mStackSupervisor.reportResumedActivityLocked(next)) { 1692 mNoAnimActivities.clear(); 1693 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1694 return true; 1695 } 1696 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1697 return false; 1698 } 1699 1700 try { 1701 // Deliver all pending results. 1702 ArrayList<ResultInfo> a = next.results; 1703 if (a != null) { 1704 final int N = a.size(); 1705 if (!next.finishing && N > 0) { 1706 if (DEBUG_RESULTS) Slog.v( 1707 TAG, "Delivering results to " + next 1708 + ": " + a); 1709 next.app.thread.scheduleSendResult(next.appToken, a); 1710 } 1711 } 1712 1713 if (next.newIntents != null) { 1714 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken); 1715 } 1716 1717 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, 1718 next.userId, System.identityHashCode(next), 1719 next.task.taskId, next.shortComponentName); 1720 1721 next.sleeping = false; 1722 mService.showAskCompatModeDialogLocked(next); 1723 next.app.pendingUiClean = true; 1724 next.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_TOP); 1725 next.clearOptionsLocked(); 1726 next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState, 1727 mService.isNextTransitionForward(), resumeAnimOptions); 1728 1729 mStackSupervisor.checkReadyForSleepLocked(); 1730 1731 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Resumed " + next); 1732 } catch (Exception e) { 1733 // Whoops, need to restart this activity! 1734 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to " 1735 + lastState + ": " + next); 1736 next.state = lastState; 1737 if (lastStack != null) { 1738 lastStack.mResumedActivity = lastResumedActivity; 1739 } 1740 Slog.i(TAG, "Restarting because process died: " + next); 1741 if (!next.hasBeenLaunched) { 1742 next.hasBeenLaunched = true; 1743 } else if (SHOW_APP_STARTING_PREVIEW && lastStack != null && 1744 mStackSupervisor.isFrontStack(lastStack)) { 1745 mWindowManager.setAppStartingWindow( 1746 next.appToken, next.packageName, next.theme, 1747 mService.compatibilityInfoForPackageLocked(next.info.applicationInfo), 1748 next.nonLocalizedLabel, next.labelRes, next.icon, next.logo, 1749 next.windowFlags, null, true); 1750 } 1751 mStackSupervisor.startSpecificActivityLocked(next, true, false); 1752 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1753 return true; 1754 } 1755 1756 // From this point on, if something goes wrong there is no way 1757 // to recover the activity. 1758 try { 1759 next.visible = true; 1760 completeResumeLocked(next); 1761 } catch (Exception e) { 1762 // If any exception gets thrown, toss away this 1763 // activity and try the next one. 1764 Slog.w(TAG, "Exception thrown during resume of " + next, e); 1765 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null, 1766 "resume-exception", true); 1767 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1768 return true; 1769 } 1770 next.stopped = false; 1771 1772 } else { 1773 // Whoops, need to restart this activity! 1774 if (!next.hasBeenLaunched) { 1775 next.hasBeenLaunched = true; 1776 } else { 1777 if (SHOW_APP_STARTING_PREVIEW) { 1778 mWindowManager.setAppStartingWindow( 1779 next.appToken, next.packageName, next.theme, 1780 mService.compatibilityInfoForPackageLocked( 1781 next.info.applicationInfo), 1782 next.nonLocalizedLabel, 1783 next.labelRes, next.icon, next.logo, next.windowFlags, 1784 null, true); 1785 } 1786 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next); 1787 } 1788 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Restarting " + next); 1789 mStackSupervisor.startSpecificActivityLocked(next, true, true); 1790 } 1791 1792 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1793 return true; 1794 } 1795 1796 private void insertTaskAtTop(TaskRecord task) { 1797 // If this is being moved to the top by another activity or being launched from the home 1798 // activity, set mOnTopOfHome accordingly. 1799 if (isOnHomeDisplay()) { 1800 ActivityStack lastStack = mStackSupervisor.getLastStack(); 1801 final boolean fromHome = lastStack.isHomeStack(); 1802 if (!isHomeStack() && (fromHome || topTask() != task)) { 1803 task.mOnTopOfHome = fromHome; 1804 } 1805 } else { 1806 task.mOnTopOfHome = false; 1807 } 1808 1809 mTaskHistory.remove(task); 1810 // Now put task at top. 1811 int stackNdx = mTaskHistory.size(); 1812 if (!isCurrentProfileLocked(task.userId)) { 1813 // Put non-current user tasks below current user tasks. 1814 while (--stackNdx >= 0) { 1815 if (!isCurrentProfileLocked(mTaskHistory.get(stackNdx).userId)) { 1816 break; 1817 } 1818 } 1819 ++stackNdx; 1820 } 1821 mTaskHistory.add(stackNdx, task); 1822 updateTaskMovement(task, true); 1823 } 1824 1825 final void startActivityLocked(ActivityRecord r, boolean newTask, 1826 boolean doResume, boolean keepCurTransition, Bundle options) { 1827 TaskRecord rTask = r.task; 1828 final int taskId = rTask.taskId; 1829 if (taskForIdLocked(taskId) == null || newTask) { 1830 // Last activity in task had been removed or ActivityManagerService is reusing task. 1831 // Insert or replace. 1832 // Might not even be in. 1833 insertTaskAtTop(rTask); 1834 mWindowManager.moveTaskToTop(taskId); 1835 } 1836 TaskRecord task = null; 1837 if (!newTask) { 1838 // If starting in an existing task, find where that is... 1839 boolean startIt = true; 1840 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1841 task = mTaskHistory.get(taskNdx); 1842 if (task == r.task) { 1843 // Here it is! Now, if this is not yet visible to the 1844 // user, then just add it without starting; it will 1845 // get started when the user navigates back to it. 1846 if (!startIt) { 1847 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task " 1848 + task, new RuntimeException("here").fillInStackTrace()); 1849 task.addActivityToTop(r); 1850 r.putInHistory(); 1851 mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken, 1852 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, 1853 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, 1854 r.userId, r.info.configChanges, task.voiceSession != null); 1855 if (VALIDATE_TOKENS) { 1856 validateAppTokensLocked(); 1857 } 1858 ActivityOptions.abort(options); 1859 return; 1860 } 1861 break; 1862 } else if (task.numFullscreen > 0) { 1863 startIt = false; 1864 } 1865 } 1866 } 1867 1868 // Place a new activity at top of stack, so it is next to interact 1869 // with the user. 1870 1871 // If we are not placing the new activity frontmost, we do not want 1872 // to deliver the onUserLeaving callback to the actual frontmost 1873 // activity 1874 if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) { 1875 mStackSupervisor.mUserLeaving = false; 1876 if (DEBUG_USER_LEAVING) Slog.v(TAG, 1877 "startActivity() behind front, mUserLeaving=false"); 1878 } 1879 1880 task = r.task; 1881 1882 // Slot the activity into the history stack and proceed 1883 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task, 1884 new RuntimeException("here").fillInStackTrace()); 1885 task.addActivityToTop(r); 1886 task.setFrontOfTask(); 1887 1888 r.putInHistory(); 1889 if (!isHomeStack() || numActivities() > 0) { 1890 // We want to show the starting preview window if we are 1891 // switching to a new task, or the next activity's process is 1892 // not currently running. 1893 boolean showStartingIcon = newTask; 1894 ProcessRecord proc = r.app; 1895 if (proc == null) { 1896 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid); 1897 } 1898 if (proc == null || proc.thread == null) { 1899 showStartingIcon = true; 1900 } 1901 if (DEBUG_TRANSITION) Slog.v(TAG, 1902 "Prepare open transition: starting " + r); 1903 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 1904 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition); 1905 mNoAnimActivities.add(r); 1906 } else { 1907 mWindowManager.prepareAppTransition(newTask 1908 ? AppTransition.TRANSIT_TASK_OPEN 1909 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition); 1910 mNoAnimActivities.remove(r); 1911 } 1912 mWindowManager.addAppToken(task.mActivities.indexOf(r), 1913 r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, 1914 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId, 1915 r.info.configChanges, task.voiceSession != null); 1916 boolean doShow = true; 1917 if (newTask) { 1918 // Even though this activity is starting fresh, we still need 1919 // to reset it to make sure we apply affinities to move any 1920 // existing activities from other tasks in to it. 1921 // If the caller has requested that the target task be 1922 // reset, then do so. 1923 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) { 1924 resetTaskIfNeededLocked(r, r); 1925 doShow = topRunningNonDelayedActivityLocked(null) == r; 1926 } 1927 } 1928 if (SHOW_APP_STARTING_PREVIEW && doShow) { 1929 // Figure out if we are transitioning from another activity that is 1930 // "has the same starting icon" as the next one. This allows the 1931 // window manager to keep the previous window it had previously 1932 // created, if it still had one. 1933 ActivityRecord prev = mResumedActivity; 1934 if (prev != null) { 1935 // We don't want to reuse the previous starting preview if: 1936 // (1) The current activity is in a different task. 1937 if (prev.task != r.task) { 1938 prev = null; 1939 } 1940 // (2) The current activity is already displayed. 1941 else if (prev.nowVisible) { 1942 prev = null; 1943 } 1944 } 1945 mWindowManager.setAppStartingWindow( 1946 r.appToken, r.packageName, r.theme, 1947 mService.compatibilityInfoForPackageLocked( 1948 r.info.applicationInfo), r.nonLocalizedLabel, 1949 r.labelRes, r.icon, r.logo, r.windowFlags, 1950 prev != null ? prev.appToken : null, showStartingIcon); 1951 r.mStartingWindowShown = true; 1952 } 1953 } else { 1954 // If this is the first activity, don't do any fancy animations, 1955 // because there is nothing for it to animate on top of. 1956 mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken, 1957 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, 1958 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId, 1959 r.info.configChanges, task.voiceSession != null); 1960 ActivityOptions.abort(options); 1961 options = null; 1962 } 1963 if (VALIDATE_TOKENS) { 1964 validateAppTokensLocked(); 1965 } 1966 1967 if (doResume) { 1968 mStackSupervisor.resumeTopActivitiesLocked(this, r, options); 1969 } 1970 } 1971 1972 final void validateAppTokensLocked() { 1973 mValidateAppTokens.clear(); 1974 mValidateAppTokens.ensureCapacity(numActivities()); 1975 final int numTasks = mTaskHistory.size(); 1976 for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) { 1977 TaskRecord task = mTaskHistory.get(taskNdx); 1978 final ArrayList<ActivityRecord> activities = task.mActivities; 1979 if (activities.isEmpty()) { 1980 continue; 1981 } 1982 TaskGroup group = new TaskGroup(); 1983 group.taskId = task.taskId; 1984 mValidateAppTokens.add(group); 1985 final int numActivities = activities.size(); 1986 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) { 1987 final ActivityRecord r = activities.get(activityNdx); 1988 group.tokens.add(r.appToken); 1989 } 1990 } 1991 mWindowManager.validateAppTokens(mStackId, mValidateAppTokens); 1992 } 1993 1994 /** 1995 * Perform a reset of the given task, if needed as part of launching it. 1996 * Returns the new HistoryRecord at the top of the task. 1997 */ 1998 /** 1999 * Helper method for #resetTaskIfNeededLocked. 2000 * We are inside of the task being reset... we'll either finish this activity, push it out 2001 * for another task, or leave it as-is. 2002 * @param task The task containing the Activity (taskTop) that might be reset. 2003 * @param forceReset 2004 * @return An ActivityOptions that needs to be processed. 2005 */ 2006 final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task, boolean forceReset) { 2007 ActivityOptions topOptions = null; 2008 2009 int replyChainEnd = -1; 2010 boolean canMoveOptions = true; 2011 2012 // We only do this for activities that are not the root of the task (since if we finish 2013 // the root, we may no longer have the task!). 2014 final ArrayList<ActivityRecord> activities = task.mActivities; 2015 final int numActivities = activities.size(); 2016 final int rootActivityNdx = task.findEffectiveRootIndex(); 2017 for (int i = numActivities - 1; i > rootActivityNdx; --i ) { 2018 ActivityRecord target = activities.get(i); 2019 2020 final int flags = target.info.flags; 2021 final boolean finishOnTaskLaunch = 2022 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; 2023 final boolean allowTaskReparenting = 2024 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; 2025 final boolean clearWhenTaskReset = 2026 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0; 2027 2028 if (!finishOnTaskLaunch 2029 && !clearWhenTaskReset 2030 && target.resultTo != null) { 2031 // If this activity is sending a reply to a previous 2032 // activity, we can't do anything with it now until 2033 // we reach the start of the reply chain. 2034 // XXX note that we are assuming the result is always 2035 // to the previous activity, which is almost always 2036 // the case but we really shouldn't count on. 2037 if (replyChainEnd < 0) { 2038 replyChainEnd = i; 2039 } 2040 } else if (!finishOnTaskLaunch 2041 && !clearWhenTaskReset 2042 && allowTaskReparenting 2043 && target.taskAffinity != null 2044 && !target.taskAffinity.equals(task.affinity)) { 2045 // If this activity has an affinity for another 2046 // task, then we need to move it out of here. We will 2047 // move it as far out of the way as possible, to the 2048 // bottom of the activity stack. This also keeps it 2049 // correctly ordered with any activities we previously 2050 // moved. 2051 final ThumbnailHolder newThumbHolder; 2052 final TaskRecord targetTask; 2053 final ActivityRecord bottom = 2054 !mTaskHistory.isEmpty() && !mTaskHistory.get(0).mActivities.isEmpty() ? 2055 mTaskHistory.get(0).mActivities.get(0) : null; 2056 if (bottom != null && target.taskAffinity != null 2057 && target.taskAffinity.equals(bottom.task.affinity)) { 2058 // If the activity currently at the bottom has the 2059 // same task affinity as the one we are moving, 2060 // then merge it into the same task. 2061 targetTask = bottom.task; 2062 newThumbHolder = bottom.thumbHolder == null ? targetTask : bottom.thumbHolder; 2063 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target 2064 + " out to bottom task " + bottom.task); 2065 } else { 2066 targetTask = createTaskRecord(mStackSupervisor.getNextTaskId(), target.info, 2067 null, null, null, false); 2068 newThumbHolder = targetTask; 2069 targetTask.affinityIntent = target.intent; 2070 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target 2071 + " out to new task " + target.task); 2072 } 2073 2074 target.thumbHolder = newThumbHolder; 2075 2076 final int targetTaskId = targetTask.taskId; 2077 mWindowManager.setAppGroupId(target.appToken, targetTaskId); 2078 2079 boolean noOptions = canMoveOptions; 2080 final int start = replyChainEnd < 0 ? i : replyChainEnd; 2081 for (int srcPos = start; srcPos >= i; --srcPos) { 2082 final ActivityRecord p = activities.get(srcPos); 2083 if (p.finishing) { 2084 continue; 2085 } 2086 2087 ThumbnailHolder curThumbHolder = p.thumbHolder; 2088 canMoveOptions = false; 2089 if (noOptions && topOptions == null) { 2090 topOptions = p.takeOptionsLocked(); 2091 if (topOptions != null) { 2092 noOptions = false; 2093 } 2094 } 2095 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task=" 2096 + task + " adding to task=" + targetTask 2097 + " Callers=" + Debug.getCallers(4)); 2098 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p 2099 + " out to target's task " + target.task); 2100 p.setTask(targetTask, curThumbHolder, false); 2101 targetTask.addActivityAtBottom(p); 2102 2103 mWindowManager.setAppGroupId(p.appToken, targetTaskId); 2104 } 2105 2106 mWindowManager.moveTaskToBottom(targetTaskId); 2107 if (VALIDATE_TOKENS) { 2108 validateAppTokensLocked(); 2109 } 2110 2111 replyChainEnd = -1; 2112 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) { 2113 // If the activity should just be removed -- either 2114 // because it asks for it, or the task should be 2115 // cleared -- then finish it and anything that is 2116 // part of its reply chain. 2117 int end; 2118 if (clearWhenTaskReset) { 2119 // In this case, we want to finish this activity 2120 // and everything above it, so be sneaky and pretend 2121 // like these are all in the reply chain. 2122 end = numActivities - 1; 2123 } else if (replyChainEnd < 0) { 2124 end = i; 2125 } else { 2126 end = replyChainEnd; 2127 } 2128 boolean noOptions = canMoveOptions; 2129 for (int srcPos = i; srcPos <= end; srcPos++) { 2130 ActivityRecord p = activities.get(srcPos); 2131 if (p.finishing) { 2132 continue; 2133 } 2134 canMoveOptions = false; 2135 if (noOptions && topOptions == null) { 2136 topOptions = p.takeOptionsLocked(); 2137 if (topOptions != null) { 2138 noOptions = false; 2139 } 2140 } 2141 if (DEBUG_TASKS) Slog.w(TAG, 2142 "resetTaskIntendedTask: calling finishActivity on " + p); 2143 if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) { 2144 end--; 2145 srcPos--; 2146 } 2147 } 2148 replyChainEnd = -1; 2149 } else { 2150 // If we were in the middle of a chain, well the 2151 // activity that started it all doesn't want anything 2152 // special, so leave it all as-is. 2153 replyChainEnd = -1; 2154 } 2155 } 2156 2157 return topOptions; 2158 } 2159 2160 /** 2161 * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given 2162 * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop. 2163 * @param affinityTask The task we are looking for an affinity to. 2164 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to. 2165 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked. 2166 * @param forceReset Flag passed in to resetTaskIfNeededLocked. 2167 */ 2168 private int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task, 2169 boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) { 2170 int replyChainEnd = -1; 2171 final int taskId = task.taskId; 2172 final String taskAffinity = task.affinity; 2173 2174 final ArrayList<ActivityRecord> activities = affinityTask.mActivities; 2175 final int numActivities = activities.size(); 2176 final int rootActivityNdx = affinityTask.findEffectiveRootIndex(); 2177 2178 // Do not operate on or below the effective root Activity. 2179 for (int i = numActivities - 1; i > rootActivityNdx; --i) { 2180 ActivityRecord target = activities.get(i); 2181 2182 final int flags = target.info.flags; 2183 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; 2184 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; 2185 2186 if (target.resultTo != null) { 2187 // If this activity is sending a reply to a previous 2188 // activity, we can't do anything with it now until 2189 // we reach the start of the reply chain. 2190 // XXX note that we are assuming the result is always 2191 // to the previous activity, which is almost always 2192 // the case but we really shouldn't count on. 2193 if (replyChainEnd < 0) { 2194 replyChainEnd = i; 2195 } 2196 } else if (topTaskIsHigher 2197 && allowTaskReparenting 2198 && taskAffinity != null 2199 && taskAffinity.equals(target.taskAffinity)) { 2200 // This activity has an affinity for our task. Either remove it if we are 2201 // clearing or move it over to our task. Note that 2202 // we currently punt on the case where we are resetting a 2203 // task that is not at the top but who has activities above 2204 // with an affinity to it... this is really not a normal 2205 // case, and we will need to later pull that task to the front 2206 // and usually at that point we will do the reset and pick 2207 // up those remaining activities. (This only happens if 2208 // someone starts an activity in a new task from an activity 2209 // in a task that is not currently on top.) 2210 if (forceReset || finishOnTaskLaunch) { 2211 final int start = replyChainEnd >= 0 ? replyChainEnd : i; 2212 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i); 2213 for (int srcPos = start; srcPos >= i; --srcPos) { 2214 final ActivityRecord p = activities.get(srcPos); 2215 if (p.finishing) { 2216 continue; 2217 } 2218 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false); 2219 } 2220 } else { 2221 if (taskInsertionPoint < 0) { 2222 taskInsertionPoint = task.mActivities.size(); 2223 2224 } 2225 2226 final int start = replyChainEnd >= 0 ? replyChainEnd : i; 2227 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting from task=" + affinityTask + ":" 2228 + start + "-" + i + " to task=" + task + ":" + taskInsertionPoint); 2229 for (int srcPos = start; srcPos >= i; --srcPos) { 2230 final ActivityRecord p = activities.get(srcPos); 2231 p.setTask(task, null, false); 2232 task.addActivityAtIndex(taskInsertionPoint, p); 2233 2234 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p 2235 + " to stack at " + task, 2236 new RuntimeException("here").fillInStackTrace()); 2237 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos 2238 + " in to resetting task " + task); 2239 mWindowManager.setAppGroupId(p.appToken, taskId); 2240 } 2241 mWindowManager.moveTaskToTop(taskId); 2242 if (VALIDATE_TOKENS) { 2243 validateAppTokensLocked(); 2244 } 2245 2246 // Now we've moved it in to place... but what if this is 2247 // a singleTop activity and we have put it on top of another 2248 // instance of the same activity? Then we drop the instance 2249 // below so it remains singleTop. 2250 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { 2251 ArrayList<ActivityRecord> taskActivities = task.mActivities; 2252 int targetNdx = taskActivities.indexOf(target); 2253 if (targetNdx > 0) { 2254 ActivityRecord p = taskActivities.get(targetNdx - 1); 2255 if (p.intent.getComponent().equals(target.intent.getComponent())) { 2256 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace", 2257 false); 2258 } 2259 } 2260 } 2261 } 2262 2263 replyChainEnd = -1; 2264 } 2265 } 2266 return taskInsertionPoint; 2267 } 2268 2269 final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop, 2270 ActivityRecord newActivity) { 2271 boolean forceReset = 2272 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0; 2273 if (ACTIVITY_INACTIVE_RESET_TIME > 0 2274 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) { 2275 if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) { 2276 forceReset = true; 2277 } 2278 } 2279 2280 final TaskRecord task = taskTop.task; 2281 2282 /** False until we evaluate the TaskRecord associated with taskTop. Switches to true 2283 * for remaining tasks. Used for later tasks to reparent to task. */ 2284 boolean taskFound = false; 2285 2286 /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */ 2287 ActivityOptions topOptions = null; 2288 2289 // Preserve the location for reparenting in the new task. 2290 int reparentInsertionPoint = -1; 2291 2292 for (int i = mTaskHistory.size() - 1; i >= 0; --i) { 2293 final TaskRecord targetTask = mTaskHistory.get(i); 2294 2295 if (targetTask == task) { 2296 topOptions = resetTargetTaskIfNeededLocked(task, forceReset); 2297 taskFound = true; 2298 } else { 2299 reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task, 2300 taskFound, forceReset, reparentInsertionPoint); 2301 } 2302 } 2303 2304 int taskNdx = mTaskHistory.indexOf(task); 2305 do { 2306 taskTop = mTaskHistory.get(taskNdx--).getTopActivity(); 2307 } while (taskTop == null && taskNdx >= 0); 2308 2309 if (topOptions != null) { 2310 // If we got some ActivityOptions from an activity on top that 2311 // was removed from the task, propagate them to the new real top. 2312 if (taskTop != null) { 2313 taskTop.updateOptionsLocked(topOptions); 2314 } else { 2315 topOptions.abort(); 2316 } 2317 } 2318 2319 return taskTop; 2320 } 2321 2322 void sendActivityResultLocked(int callingUid, ActivityRecord r, 2323 String resultWho, int requestCode, int resultCode, Intent data) { 2324 2325 if (callingUid > 0) { 2326 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName, 2327 data, r.getUriPermissionsLocked(), r.userId); 2328 } 2329 2330 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r 2331 + " : who=" + resultWho + " req=" + requestCode 2332 + " res=" + resultCode + " data=" + data); 2333 if (mResumedActivity == r && r.app != null && r.app.thread != null) { 2334 try { 2335 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>(); 2336 list.add(new ResultInfo(resultWho, requestCode, 2337 resultCode, data)); 2338 r.app.thread.scheduleSendResult(r.appToken, list); 2339 return; 2340 } catch (Exception e) { 2341 Slog.w(TAG, "Exception thrown sending result to " + r, e); 2342 } 2343 } 2344 2345 r.addResultLocked(null, resultWho, requestCode, resultCode, data); 2346 } 2347 2348 private void adjustFocusedActivityLocked(ActivityRecord r) { 2349 if (mStackSupervisor.isFrontStack(this) && mService.mFocusedActivity == r) { 2350 ActivityRecord next = topRunningActivityLocked(null); 2351 if (next != r) { 2352 final TaskRecord task = r.task; 2353 if (r.frontOfTask && task == topTask() && task.mOnTopOfHome) { 2354 mStackSupervisor.moveHomeToTop(); 2355 } 2356 } 2357 ActivityRecord top = mStackSupervisor.topRunningActivityLocked(); 2358 if (top != null) { 2359 mService.setFocusedActivityLocked(top); 2360 } 2361 } 2362 } 2363 2364 final void stopActivityLocked(ActivityRecord r) { 2365 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r); 2366 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0 2367 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) { 2368 if (!r.finishing) { 2369 if (!mService.isSleeping()) { 2370 if (DEBUG_STATES) { 2371 Slog.d(TAG, "no-history finish of " + r); 2372 } 2373 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null, 2374 "no-history", false); 2375 } else { 2376 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r 2377 + " on stop because we're just sleeping"); 2378 } 2379 } 2380 } 2381 2382 if (r.app != null && r.app.thread != null) { 2383 adjustFocusedActivityLocked(r); 2384 r.resumeKeyDispatchingLocked(); 2385 try { 2386 r.stopped = false; 2387 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r 2388 + " (stop requested)"); 2389 r.state = ActivityState.STOPPING; 2390 if (DEBUG_VISBILITY) Slog.v( 2391 TAG, "Stopping visible=" + r.visible + " for " + r); 2392 if (!r.visible) { 2393 mWindowManager.setAppVisibility(r.appToken, false); 2394 } 2395 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags); 2396 if (mService.isSleepingOrShuttingDown()) { 2397 r.setSleeping(true); 2398 } 2399 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r); 2400 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT); 2401 } catch (Exception e) { 2402 // Maybe just ignore exceptions here... if the process 2403 // has crashed, our death notification will clean things 2404 // up. 2405 Slog.w(TAG, "Exception thrown during pause", e); 2406 // Just in case, assume it to be stopped. 2407 r.stopped = true; 2408 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r); 2409 r.state = ActivityState.STOPPED; 2410 if (r.configDestroy) { 2411 destroyActivityLocked(r, true, false, "stop-except"); 2412 } 2413 } 2414 } 2415 } 2416 2417 /** 2418 * @return Returns true if the activity is being finished, false if for 2419 * some reason it is being left as-is. 2420 */ 2421 final boolean requestFinishActivityLocked(IBinder token, int resultCode, 2422 Intent resultData, String reason, boolean oomAdj) { 2423 ActivityRecord r = isInStackLocked(token); 2424 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v( 2425 TAG, "Finishing activity token=" + token + " r=" 2426 + ", result=" + resultCode + ", data=" + resultData 2427 + ", reason=" + reason); 2428 if (r == null) { 2429 return false; 2430 } 2431 2432 finishActivityLocked(r, resultCode, resultData, reason, oomAdj); 2433 return true; 2434 } 2435 2436 final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) { 2437 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2438 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 2439 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2440 ActivityRecord r = activities.get(activityNdx); 2441 if (r.resultTo == self && r.requestCode == requestCode) { 2442 if ((r.resultWho == null && resultWho == null) || 2443 (r.resultWho != null && r.resultWho.equals(resultWho))) { 2444 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub", 2445 false); 2446 } 2447 } 2448 } 2449 } 2450 mService.updateOomAdjLocked(); 2451 } 2452 2453 final void finishTopRunningActivityLocked(ProcessRecord app) { 2454 ActivityRecord r = topRunningActivityLocked(null); 2455 if (r != null && r.app == app) { 2456 // If the top running activity is from this crashing 2457 // process, then terminate it to avoid getting in a loop. 2458 Slog.w(TAG, " Force finishing activity " 2459 + r.intent.getComponent().flattenToShortString()); 2460 int taskNdx = mTaskHistory.indexOf(r.task); 2461 int activityNdx = r.task.mActivities.indexOf(r); 2462 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false); 2463 // Also terminate any activities below it that aren't yet 2464 // stopped, to avoid a situation where one will get 2465 // re-start our crashing activity once it gets resumed again. 2466 --activityNdx; 2467 if (activityNdx < 0) { 2468 do { 2469 --taskNdx; 2470 if (taskNdx < 0) { 2471 break; 2472 } 2473 activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1; 2474 } while (activityNdx < 0); 2475 } 2476 if (activityNdx >= 0) { 2477 r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx); 2478 if (r.state == ActivityState.RESUMED 2479 || r.state == ActivityState.PAUSING 2480 || r.state == ActivityState.PAUSED) { 2481 if (!r.isHomeActivity() || mService.mHomeProcess != r.app) { 2482 Slog.w(TAG, " Force finishing activity " 2483 + r.intent.getComponent().flattenToShortString()); 2484 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false); 2485 } 2486 } 2487 } 2488 } 2489 } 2490 2491 final boolean finishActivityAffinityLocked(ActivityRecord r) { 2492 ArrayList<ActivityRecord> activities = r.task.mActivities; 2493 for (int index = activities.indexOf(r); index >= 0; --index) { 2494 ActivityRecord cur = activities.get(index); 2495 if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) { 2496 break; 2497 } 2498 finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true); 2499 } 2500 return true; 2501 } 2502 2503 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) { 2504 // send the result 2505 ActivityRecord resultTo = r.resultTo; 2506 if (resultTo != null) { 2507 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo 2508 + " who=" + r.resultWho + " req=" + r.requestCode 2509 + " res=" + resultCode + " data=" + resultData); 2510 if (resultTo.userId != r.userId) { 2511 if (resultData != null) { 2512 resultData.prepareToLeaveUser(r.userId); 2513 } 2514 } 2515 if (r.info.applicationInfo.uid > 0) { 2516 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid, 2517 resultTo.packageName, resultData, 2518 resultTo.getUriPermissionsLocked(), resultTo.userId); 2519 } 2520 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode, 2521 resultData); 2522 r.resultTo = null; 2523 } 2524 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r); 2525 2526 // Make sure this HistoryRecord is not holding on to other resources, 2527 // because clients have remote IPC references to this object so we 2528 // can't assume that will go away and want to avoid circular IPC refs. 2529 r.results = null; 2530 r.pendingResults = null; 2531 r.newIntents = null; 2532 r.icicle = null; 2533 } 2534 2535 /** 2536 * @return Returns true if this activity has been removed from the history 2537 * list, or false if it is still in the list and will be removed later. 2538 */ 2539 final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData, 2540 String reason, boolean oomAdj) { 2541 if (r.finishing) { 2542 Slog.w(TAG, "Duplicate finish request for " + r); 2543 return false; 2544 } 2545 2546 r.makeFinishing(); 2547 final TaskRecord task = r.task; 2548 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, 2549 r.userId, System.identityHashCode(r), 2550 task.taskId, r.shortComponentName, reason); 2551 final ArrayList<ActivityRecord> activities = task.mActivities; 2552 final int index = activities.indexOf(r); 2553 if (index < (activities.size() - 1)) { 2554 task.setFrontOfTask(); 2555 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) { 2556 // If the caller asked that this activity (and all above it) 2557 // be cleared when the task is reset, don't lose that information, 2558 // but propagate it up to the next activity. 2559 ActivityRecord next = activities.get(index+1); 2560 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 2561 } 2562 } 2563 2564 r.pauseKeyDispatchingLocked(); 2565 2566 adjustFocusedActivityLocked(r); 2567 2568 finishActivityResultsLocked(r, resultCode, resultData); 2569 2570 if (mResumedActivity == r) { 2571 boolean endTask = index <= 0; 2572 if (DEBUG_VISBILITY || DEBUG_TRANSITION) Slog.v(TAG, 2573 "Prepare close transition: finishing " + r); 2574 mWindowManager.prepareAppTransition(endTask 2575 ? AppTransition.TRANSIT_TASK_CLOSE 2576 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false); 2577 2578 // Tell window manager to prepare for this one to be removed. 2579 mWindowManager.setAppVisibility(r.appToken, false); 2580 2581 if (mPausingActivity == null) { 2582 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r); 2583 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false"); 2584 startPausingLocked(false, false); 2585 } 2586 2587 if (endTask) { 2588 mStackSupervisor.endLockTaskModeIfTaskEnding(task); 2589 } 2590 } else if (r.state != ActivityState.PAUSING) { 2591 // If the activity is PAUSING, we will complete the finish once 2592 // it is done pausing; else we can just directly finish it here. 2593 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r); 2594 return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null; 2595 } else { 2596 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r); 2597 } 2598 2599 return false; 2600 } 2601 2602 static final int FINISH_IMMEDIATELY = 0; 2603 static final int FINISH_AFTER_PAUSE = 1; 2604 static final int FINISH_AFTER_VISIBLE = 2; 2605 2606 final ActivityRecord finishCurrentActivityLocked(ActivityRecord r, int mode, boolean oomAdj) { 2607 // First things first: if this activity is currently visible, 2608 // and the resumed activity is not yet visible, then hold off on 2609 // finishing until the resumed one becomes visible. 2610 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) { 2611 if (!mStackSupervisor.mStoppingActivities.contains(r)) { 2612 mStackSupervisor.mStoppingActivities.add(r); 2613 if (mStackSupervisor.mStoppingActivities.size() > 3 2614 || r.frontOfTask && mTaskHistory.size() <= 1) { 2615 // If we already have a few activities waiting to stop, 2616 // then give up on things going idle and start clearing 2617 // them out. Or if r is the last of activity of the last task the stack 2618 // will be empty and must be cleared immediately. 2619 mStackSupervisor.scheduleIdleLocked(); 2620 } else { 2621 mStackSupervisor.checkReadyForSleepLocked(); 2622 } 2623 } 2624 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r 2625 + " (finish requested)"); 2626 r.state = ActivityState.STOPPING; 2627 if (oomAdj) { 2628 mService.updateOomAdjLocked(); 2629 } 2630 return r; 2631 } 2632 2633 // make sure the record is cleaned out of other places. 2634 mStackSupervisor.mStoppingActivities.remove(r); 2635 mStackSupervisor.mGoingToSleepActivities.remove(r); 2636 mStackSupervisor.mWaitingVisibleActivities.remove(r); 2637 if (mResumedActivity == r) { 2638 mResumedActivity = null; 2639 } 2640 final ActivityState prevState = r.state; 2641 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r); 2642 r.state = ActivityState.FINISHING; 2643 2644 if (mode == FINISH_IMMEDIATELY 2645 || prevState == ActivityState.STOPPED 2646 || prevState == ActivityState.INITIALIZING) { 2647 // If this activity is already stopped, we can just finish 2648 // it right now. 2649 r.makeFinishing(); 2650 boolean activityRemoved = destroyActivityLocked(r, true, oomAdj, "finish-imm"); 2651 if (activityRemoved) { 2652 mStackSupervisor.resumeTopActivitiesLocked(); 2653 } 2654 if (DEBUG_CONTAINERS) Slog.d(TAG, 2655 "destroyActivityLocked: finishCurrentActivityLocked r=" + r + 2656 " destroy returned removed=" + activityRemoved); 2657 return activityRemoved ? null : r; 2658 } 2659 2660 // Need to go through the full pause cycle to get this 2661 // activity into the stopped state and then finish it. 2662 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r); 2663 mStackSupervisor.mFinishingActivities.add(r); 2664 r.resumeKeyDispatchingLocked(); 2665 mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null); 2666 return r; 2667 } 2668 2669 void finishAllActivitiesLocked() { 2670 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2671 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 2672 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2673 final ActivityRecord r = activities.get(activityNdx); 2674 if (r.finishing) { 2675 continue; 2676 } 2677 Slog.d(TAG, "finishAllActivitiesLocked: finishing " + r); 2678 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false); 2679 } 2680 } 2681 } 2682 2683 final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode, 2684 Intent resultData) { 2685 final ActivityRecord srec = ActivityRecord.forToken(token); 2686 final TaskRecord task = srec.task; 2687 final ArrayList<ActivityRecord> activities = task.mActivities; 2688 final int start = activities.indexOf(srec); 2689 if (!mTaskHistory.contains(task) || (start < 0)) { 2690 return false; 2691 } 2692 int finishTo = start - 1; 2693 ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo); 2694 boolean foundParentInTask = false; 2695 final ComponentName dest = destIntent.getComponent(); 2696 if (start > 0 && dest != null) { 2697 for (int i = finishTo; i >= 0; i--) { 2698 ActivityRecord r = activities.get(i); 2699 if (r.info.packageName.equals(dest.getPackageName()) && 2700 r.info.name.equals(dest.getClassName())) { 2701 finishTo = i; 2702 parent = r; 2703 foundParentInTask = true; 2704 break; 2705 } 2706 } 2707 } 2708 2709 IActivityController controller = mService.mController; 2710 if (controller != null) { 2711 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0); 2712 if (next != null) { 2713 // ask watcher if this is allowed 2714 boolean resumeOK = true; 2715 try { 2716 resumeOK = controller.activityResuming(next.packageName); 2717 } catch (RemoteException e) { 2718 mService.mController = null; 2719 Watchdog.getInstance().setActivityController(null); 2720 } 2721 2722 if (!resumeOK) { 2723 return false; 2724 } 2725 } 2726 } 2727 final long origId = Binder.clearCallingIdentity(); 2728 for (int i = start; i > finishTo; i--) { 2729 ActivityRecord r = activities.get(i); 2730 requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true); 2731 // Only return the supplied result for the first activity finished 2732 resultCode = Activity.RESULT_CANCELED; 2733 resultData = null; 2734 } 2735 2736 if (parent != null && foundParentInTask) { 2737 final int parentLaunchMode = parent.info.launchMode; 2738 final int destIntentFlags = destIntent.getFlags(); 2739 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE || 2740 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK || 2741 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP || 2742 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) { 2743 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent); 2744 } else { 2745 try { 2746 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo( 2747 destIntent.getComponent(), 0, srec.userId); 2748 int res = mStackSupervisor.startActivityLocked(srec.app.thread, destIntent, 2749 null, aInfo, null, null, parent.appToken, null, 2750 0, -1, parent.launchedFromUid, parent.launchedFromPackage, 2751 0, null, true, null, null); 2752 foundParentInTask = res == ActivityManager.START_SUCCESS; 2753 } catch (RemoteException e) { 2754 foundParentInTask = false; 2755 } 2756 requestFinishActivityLocked(parent.appToken, resultCode, 2757 resultData, "navigate-up", true); 2758 } 2759 } 2760 Binder.restoreCallingIdentity(origId); 2761 return foundParentInTask; 2762 } 2763 /** 2764 * Perform the common clean-up of an activity record. This is called both 2765 * as part of destroyActivityLocked() (when destroying the client-side 2766 * representation) and cleaning things up as a result of its hosting 2767 * processing going away, in which case there is no remaining client-side 2768 * state to destroy so only the cleanup here is needed. 2769 */ 2770 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices, 2771 boolean setState) { 2772 if (mResumedActivity == r) { 2773 mResumedActivity = null; 2774 } 2775 if (mPausingActivity == r) { 2776 mPausingActivity = null; 2777 } 2778 mService.clearFocusedActivity(r); 2779 2780 r.configDestroy = false; 2781 r.frozenBeforeDestroy = false; 2782 2783 if (setState) { 2784 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)"); 2785 r.state = ActivityState.DESTROYED; 2786 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r); 2787 r.app = null; 2788 } 2789 2790 // Make sure this record is no longer in the pending finishes list. 2791 // This could happen, for example, if we are trimming activities 2792 // down to the max limit while they are still waiting to finish. 2793 mStackSupervisor.mFinishingActivities.remove(r); 2794 mStackSupervisor.mWaitingVisibleActivities.remove(r); 2795 2796 // Remove any pending results. 2797 if (r.finishing && r.pendingResults != null) { 2798 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) { 2799 PendingIntentRecord rec = apr.get(); 2800 if (rec != null) { 2801 mService.cancelIntentSenderLocked(rec, false); 2802 } 2803 } 2804 r.pendingResults = null; 2805 } 2806 2807 if (cleanServices) { 2808 cleanUpActivityServicesLocked(r); 2809 } 2810 2811 // Get rid of any pending idle timeouts. 2812 removeTimeoutsForActivityLocked(r); 2813 } 2814 2815 private void removeTimeoutsForActivityLocked(ActivityRecord r) { 2816 mStackSupervisor.removeTimeoutsForActivityLocked(r); 2817 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 2818 mHandler.removeMessages(STOP_TIMEOUT_MSG, r); 2819 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r); 2820 r.finishLaunchTickingLocked(); 2821 } 2822 2823 private void removeActivityFromHistoryLocked(ActivityRecord r) { 2824 mStackSupervisor.removeChildActivityContainers(r); 2825 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null); 2826 r.makeFinishing(); 2827 if (DEBUG_ADD_REMOVE) { 2828 RuntimeException here = new RuntimeException("here"); 2829 here.fillInStackTrace(); 2830 Slog.i(TAG, "Removing activity " + r + " from stack"); 2831 } 2832 r.takeFromHistory(); 2833 removeTimeoutsForActivityLocked(r); 2834 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)"); 2835 r.state = ActivityState.DESTROYED; 2836 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r); 2837 r.app = null; 2838 mWindowManager.removeAppToken(r.appToken); 2839 if (VALIDATE_TOKENS) { 2840 validateAppTokensLocked(); 2841 } 2842 final TaskRecord task = r.task; 2843 if (task != null && task.removeActivity(r)) { 2844 if (DEBUG_STACK) Slog.i(TAG, 2845 "removeActivityFromHistoryLocked: last activity removed from " + this); 2846 if (mStackSupervisor.isFrontStack(this) && task == topTask() && task.mOnTopOfHome) { 2847 mStackSupervisor.moveHomeToTop(); 2848 } 2849 removeTask(task); 2850 } 2851 cleanUpActivityServicesLocked(r); 2852 r.removeUriPermissionsLocked(); 2853 } 2854 2855 /** 2856 * Perform clean-up of service connections in an activity record. 2857 */ 2858 final void cleanUpActivityServicesLocked(ActivityRecord r) { 2859 // Throw away any services that have been bound by this activity. 2860 if (r.connections != null) { 2861 Iterator<ConnectionRecord> it = r.connections.iterator(); 2862 while (it.hasNext()) { 2863 ConnectionRecord c = it.next(); 2864 mService.mServices.removeConnectionLocked(c, null, r); 2865 } 2866 r.connections = null; 2867 } 2868 } 2869 2870 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) { 2871 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG); 2872 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason); 2873 mHandler.sendMessage(msg); 2874 } 2875 2876 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) { 2877 boolean lastIsOpaque = false; 2878 boolean activityRemoved = false; 2879 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2880 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 2881 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2882 final ActivityRecord r = activities.get(activityNdx); 2883 if (r.finishing) { 2884 continue; 2885 } 2886 if (r.fullscreen) { 2887 lastIsOpaque = true; 2888 } 2889 if (owner != null && r.app != owner) { 2890 continue; 2891 } 2892 if (!lastIsOpaque) { 2893 continue; 2894 } 2895 // We can destroy this one if we have its icicle saved and 2896 // it is not in the process of pausing/stopping/finishing. 2897 if (r.app != null && r != mResumedActivity && r != mPausingActivity 2898 && r.haveState && !r.visible && r.stopped 2899 && r.state != ActivityState.DESTROYING 2900 && r.state != ActivityState.DESTROYED) { 2901 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state 2902 + " resumed=" + mResumedActivity 2903 + " pausing=" + mPausingActivity); 2904 if (destroyActivityLocked(r, true, oomAdj, reason)) { 2905 activityRemoved = true; 2906 } 2907 } 2908 } 2909 } 2910 if (activityRemoved) { 2911 mStackSupervisor.resumeTopActivitiesLocked(); 2912 } 2913 } 2914 2915 /** 2916 * Destroy the current CLIENT SIDE instance of an activity. This may be 2917 * called both when actually finishing an activity, or when performing 2918 * a configuration switch where we destroy the current client-side object 2919 * but then create a new client-side object for this same HistoryRecord. 2920 */ 2921 final boolean destroyActivityLocked(ActivityRecord r, 2922 boolean removeFromApp, boolean oomAdj, String reason) { 2923 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v( 2924 TAG, "Removing activity from " + reason + ": token=" + r 2925 + ", app=" + (r.app != null ? r.app.processName : "(null)")); 2926 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY, 2927 r.userId, System.identityHashCode(r), 2928 r.task.taskId, r.shortComponentName, reason); 2929 2930 boolean removedFromHistory = false; 2931 2932 cleanUpActivityLocked(r, false, false); 2933 2934 final boolean hadApp = r.app != null; 2935 2936 if (hadApp) { 2937 if (removeFromApp) { 2938 r.app.activities.remove(r); 2939 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) { 2940 mService.mHeavyWeightProcess = null; 2941 mService.mHandler.sendEmptyMessage( 2942 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG); 2943 } 2944 if (r.app.activities.isEmpty()) { 2945 // No longer have activities, so update LRU list and oom adj. 2946 mService.updateLruProcessLocked(r.app, false, null); 2947 mService.updateOomAdjLocked(); 2948 } 2949 } 2950 2951 boolean skipDestroy = false; 2952 2953 try { 2954 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r); 2955 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing, 2956 r.configChangeFlags); 2957 } catch (Exception e) { 2958 // We can just ignore exceptions here... if the process 2959 // has crashed, our death notification will clean things 2960 // up. 2961 //Slog.w(TAG, "Exception thrown during finish", e); 2962 if (r.finishing) { 2963 removeActivityFromHistoryLocked(r); 2964 removedFromHistory = true; 2965 skipDestroy = true; 2966 } 2967 } 2968 2969 r.nowVisible = false; 2970 2971 // If the activity is finishing, we need to wait on removing it 2972 // from the list to give it a chance to do its cleanup. During 2973 // that time it may make calls back with its token so we need to 2974 // be able to find it on the list and so we don't want to remove 2975 // it from the list yet. Otherwise, we can just immediately put 2976 // it in the destroyed state since we are not removing it from the 2977 // list. 2978 if (r.finishing && !skipDestroy) { 2979 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r 2980 + " (destroy requested)"); 2981 r.state = ActivityState.DESTROYING; 2982 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r); 2983 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT); 2984 } else { 2985 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (destroy skipped)"); 2986 r.state = ActivityState.DESTROYED; 2987 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r); 2988 r.app = null; 2989 } 2990 } else { 2991 // remove this record from the history. 2992 if (r.finishing) { 2993 removeActivityFromHistoryLocked(r); 2994 removedFromHistory = true; 2995 } else { 2996 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (no app)"); 2997 r.state = ActivityState.DESTROYED; 2998 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r); 2999 r.app = null; 3000 } 3001 } 3002 3003 r.configChangeFlags = 0; 3004 3005 if (!mLRUActivities.remove(r) && hadApp) { 3006 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list"); 3007 } 3008 3009 return removedFromHistory; 3010 } 3011 3012 final void activityDestroyedLocked(IBinder token) { 3013 final long origId = Binder.clearCallingIdentity(); 3014 try { 3015 ActivityRecord r = ActivityRecord.forToken(token); 3016 if (r != null) { 3017 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r); 3018 } 3019 if (DEBUG_CONTAINERS) Slog.d(TAG, "activityDestroyedLocked: r=" + r); 3020 3021 if (isInStackLocked(token) != null) { 3022 if (r.state == ActivityState.DESTROYING) { 3023 cleanUpActivityLocked(r, true, false); 3024 removeActivityFromHistoryLocked(r); 3025 } 3026 } 3027 mStackSupervisor.resumeTopActivitiesLocked(); 3028 } finally { 3029 Binder.restoreCallingIdentity(origId); 3030 } 3031 } 3032 3033 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list, 3034 ProcessRecord app, String listName) { 3035 int i = list.size(); 3036 if (DEBUG_CLEANUP) Slog.v( 3037 TAG, "Removing app " + app + " from list " + listName 3038 + " with " + i + " entries"); 3039 while (i > 0) { 3040 i--; 3041 ActivityRecord r = list.get(i); 3042 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r); 3043 if (r.app == app) { 3044 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!"); 3045 list.remove(i); 3046 removeTimeoutsForActivityLocked(r); 3047 } 3048 } 3049 } 3050 3051 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) { 3052 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities"); 3053 removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app, 3054 "mStoppingActivities"); 3055 removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app, 3056 "mGoingToSleepActivities"); 3057 removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app, 3058 "mWaitingVisibleActivities"); 3059 removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app, 3060 "mFinishingActivities"); 3061 3062 boolean hasVisibleActivities = false; 3063 3064 // Clean out the history list. 3065 int i = numActivities(); 3066 if (DEBUG_CLEANUP) Slog.v( 3067 TAG, "Removing app " + app + " from history with " + i + " entries"); 3068 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3069 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3070 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3071 final ActivityRecord r = activities.get(activityNdx); 3072 --i; 3073 if (DEBUG_CLEANUP) Slog.v( 3074 TAG, "Record #" + i + " " + r + ": app=" + r.app); 3075 if (r.app == app) { 3076 boolean remove; 3077 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) { 3078 // Don't currently have state for the activity, or 3079 // it is finishing -- always remove it. 3080 remove = true; 3081 } else if (r.launchCount > 2 && 3082 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) { 3083 // We have launched this activity too many times since it was 3084 // able to run, so give up and remove it. 3085 remove = true; 3086 } else { 3087 // The process may be gone, but the activity lives on! 3088 remove = false; 3089 } 3090 if (remove) { 3091 if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) { 3092 RuntimeException here = new RuntimeException("here"); 3093 here.fillInStackTrace(); 3094 Slog.i(TAG, "Removing activity " + r + " from stack at " + i 3095 + ": haveState=" + r.haveState 3096 + " stateNotNeeded=" + r.stateNotNeeded 3097 + " finishing=" + r.finishing 3098 + " state=" + r.state, here); 3099 } 3100 if (!r.finishing) { 3101 Slog.w(TAG, "Force removing " + r + ": app died, no saved state"); 3102 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, 3103 r.userId, System.identityHashCode(r), 3104 r.task.taskId, r.shortComponentName, 3105 "proc died without state saved"); 3106 if (r.state == ActivityState.RESUMED) { 3107 mService.updateUsageStats(r, false); 3108 } 3109 } 3110 removeActivityFromHistoryLocked(r); 3111 3112 } else { 3113 // We have the current state for this activity, so 3114 // it can be restarted later when needed. 3115 if (localLOGV) Slog.v( 3116 TAG, "Keeping entry, setting app to null"); 3117 if (r.visible) { 3118 hasVisibleActivities = true; 3119 } 3120 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity " 3121 + r); 3122 r.app = null; 3123 r.nowVisible = false; 3124 if (!r.haveState) { 3125 if (DEBUG_SAVED_STATE) Slog.i(TAG, 3126 "App died, clearing saved state of " + r); 3127 r.icicle = null; 3128 } 3129 } 3130 3131 cleanUpActivityLocked(r, true, true); 3132 } 3133 } 3134 } 3135 3136 return hasVisibleActivities; 3137 } 3138 3139 final void updateTransitLocked(int transit, Bundle options) { 3140 if (options != null) { 3141 ActivityRecord r = topRunningActivityLocked(null); 3142 if (r != null && r.state != ActivityState.RESUMED) { 3143 r.updateOptionsLocked(options); 3144 } else { 3145 ActivityOptions.abort(options); 3146 } 3147 } 3148 mWindowManager.prepareAppTransition(transit, false); 3149 } 3150 3151 void updateTaskMovement(TaskRecord task, boolean toFront) { 3152 if (task.isPersistable) { 3153 task.mLastTimeMoved = System.currentTimeMillis(); 3154 // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most 3155 // recently will be most negative, tasks sent to the bottom before that will be less 3156 // negative. Similarly for recent tasks moved to the top which will be most positive. 3157 if (!toFront) { 3158 task.mLastTimeMoved *= -1; 3159 } 3160 } 3161 } 3162 3163 void moveHomeTaskToTop() { 3164 final int top = mTaskHistory.size() - 1; 3165 for (int taskNdx = top; taskNdx >= 0; --taskNdx) { 3166 final TaskRecord task = mTaskHistory.get(taskNdx); 3167 if (task.isHomeTask()) { 3168 if (DEBUG_TASKS || DEBUG_STACK) Slog.d(TAG, "moveHomeTaskToTop: moving " + task); 3169 mTaskHistory.remove(taskNdx); 3170 mTaskHistory.add(top, task); 3171 updateTaskMovement(task, true); 3172 mWindowManager.moveTaskToTop(task.taskId); 3173 return; 3174 } 3175 } 3176 } 3177 3178 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) { 3179 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr); 3180 3181 final int numTasks = mTaskHistory.size(); 3182 final int index = mTaskHistory.indexOf(tr); 3183 if (numTasks == 0 || index < 0) { 3184 // nothing to do! 3185 if (reason != null && 3186 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 3187 ActivityOptions.abort(options); 3188 } else { 3189 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options); 3190 } 3191 return; 3192 } 3193 3194 moveToFront(); 3195 3196 // Shift all activities with this task up to the top 3197 // of the stack, keeping them in the same internal order. 3198 insertTaskAtTop(tr); 3199 3200 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr); 3201 if (reason != null && 3202 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 3203 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 3204 ActivityRecord r = topRunningActivityLocked(null); 3205 if (r != null) { 3206 mNoAnimActivities.add(r); 3207 } 3208 ActivityOptions.abort(options); 3209 } else { 3210 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options); 3211 } 3212 3213 mWindowManager.moveTaskToTop(tr.taskId); 3214 3215 mStackSupervisor.resumeTopActivitiesLocked(); 3216 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId); 3217 3218 if (VALIDATE_TOKENS) { 3219 validateAppTokensLocked(); 3220 } 3221 } 3222 3223 /** 3224 * Worker method for rearranging history stack. Implements the function of moving all 3225 * activities for a specific task (gathering them if disjoint) into a single group at the 3226 * bottom of the stack. 3227 * 3228 * If a watcher is installed, the action is preflighted and the watcher has an opportunity 3229 * to premeptively cancel the move. 3230 * 3231 * @param taskId The taskId to collect and move to the bottom. 3232 * @return Returns true if the move completed, false if not. 3233 */ 3234 final boolean moveTaskToBackLocked(int taskId, ActivityRecord reason) { 3235 final TaskRecord tr = taskForIdLocked(taskId); 3236 if (tr == null) { 3237 Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId); 3238 return false; 3239 } 3240 3241 Slog.i(TAG, "moveTaskToBack: " + tr); 3242 3243 mStackSupervisor.endLockTaskModeIfTaskEnding(tr); 3244 3245 // If we have a watcher, preflight the move before committing to it. First check 3246 // for *other* available tasks, but if none are available, then try again allowing the 3247 // current task to be selected. 3248 if (mStackSupervisor.isFrontStack(this) && mService.mController != null) { 3249 ActivityRecord next = topRunningActivityLocked(null, taskId); 3250 if (next == null) { 3251 next = topRunningActivityLocked(null, 0); 3252 } 3253 if (next != null) { 3254 // ask watcher if this is allowed 3255 boolean moveOK = true; 3256 try { 3257 moveOK = mService.mController.activityResuming(next.packageName); 3258 } catch (RemoteException e) { 3259 mService.mController = null; 3260 Watchdog.getInstance().setActivityController(null); 3261 } 3262 if (!moveOK) { 3263 return false; 3264 } 3265 } 3266 } 3267 3268 if (DEBUG_TRANSITION) Slog.v(TAG, 3269 "Prepare to back transition: task=" + taskId); 3270 3271 mTaskHistory.remove(tr); 3272 mTaskHistory.add(0, tr); 3273 updateTaskMovement(tr, false); 3274 3275 // There is an assumption that moving a task to the back moves it behind the home activity. 3276 // We make sure here that some activity in the stack will launch home. 3277 int numTasks = mTaskHistory.size(); 3278 for (int taskNdx = numTasks - 1; taskNdx >= 1; --taskNdx) { 3279 final TaskRecord task = mTaskHistory.get(taskNdx); 3280 if (task.mOnTopOfHome) { 3281 break; 3282 } 3283 if (taskNdx == 1) { 3284 // Set the last task before tr to go to home. 3285 task.mOnTopOfHome = true; 3286 } 3287 } 3288 3289 if (reason != null && 3290 (reason.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 3291 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 3292 ActivityRecord r = topRunningActivityLocked(null); 3293 if (r != null) { 3294 mNoAnimActivities.add(r); 3295 } 3296 } else { 3297 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_TASK_TO_BACK, false); 3298 } 3299 mWindowManager.moveTaskToBottom(taskId); 3300 3301 if (VALIDATE_TOKENS) { 3302 validateAppTokensLocked(); 3303 } 3304 3305 final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null; 3306 if (task == tr && tr.mOnTopOfHome || numTasks <= 1 && isOnHomeDisplay()) { 3307 tr.mOnTopOfHome = false; 3308 return mStackSupervisor.resumeHomeActivity(null); 3309 } 3310 3311 mStackSupervisor.resumeTopActivitiesLocked(); 3312 return true; 3313 } 3314 3315 static final void logStartActivity(int tag, ActivityRecord r, 3316 TaskRecord task) { 3317 final Uri data = r.intent.getData(); 3318 final String strData = data != null ? data.toSafeString() : null; 3319 3320 EventLog.writeEvent(tag, 3321 r.userId, System.identityHashCode(r), task.taskId, 3322 r.shortComponentName, r.intent.getAction(), 3323 r.intent.getType(), strData, r.intent.getFlags()); 3324 } 3325 3326 /** 3327 * Make sure the given activity matches the current configuration. Returns 3328 * false if the activity had to be destroyed. Returns true if the 3329 * configuration is the same, or the activity will remain running as-is 3330 * for whatever reason. Ensures the HistoryRecord is updated with the 3331 * correct configuration and all other bookkeeping is handled. 3332 */ 3333 final boolean ensureActivityConfigurationLocked(ActivityRecord r, 3334 int globalChanges) { 3335 if (mConfigWillChange) { 3336 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3337 "Skipping config check (will change): " + r); 3338 return true; 3339 } 3340 3341 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3342 "Ensuring correct configuration: " + r); 3343 3344 // Short circuit: if the two configurations are the exact same 3345 // object (the common case), then there is nothing to do. 3346 Configuration newConfig = mService.mConfiguration; 3347 if (r.configuration == newConfig && !r.forceNewConfig) { 3348 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3349 "Configuration unchanged in " + r); 3350 return true; 3351 } 3352 3353 // We don't worry about activities that are finishing. 3354 if (r.finishing) { 3355 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3356 "Configuration doesn't matter in finishing " + r); 3357 r.stopFreezingScreenLocked(false); 3358 return true; 3359 } 3360 3361 // Okay we now are going to make this activity have the new config. 3362 // But then we need to figure out how it needs to deal with that. 3363 Configuration oldConfig = r.configuration; 3364 r.configuration = newConfig; 3365 3366 // Determine what has changed. May be nothing, if this is a config 3367 // that has come back from the app after going idle. In that case 3368 // we just want to leave the official config object now in the 3369 // activity and do nothing else. 3370 final int changes = oldConfig.diff(newConfig); 3371 if (changes == 0 && !r.forceNewConfig) { 3372 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3373 "Configuration no differences in " + r); 3374 return true; 3375 } 3376 3377 // If the activity isn't currently running, just leave the new 3378 // configuration and it will pick that up next time it starts. 3379 if (r.app == null || r.app.thread == null) { 3380 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3381 "Configuration doesn't matter not running " + r); 3382 r.stopFreezingScreenLocked(false); 3383 r.forceNewConfig = false; 3384 return true; 3385 } 3386 3387 // Figure out how to handle the changes between the configurations. 3388 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) { 3389 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x" 3390 + Integer.toHexString(changes) + ", handles=0x" 3391 + Integer.toHexString(r.info.getRealConfigChanged()) 3392 + ", newConfig=" + newConfig); 3393 } 3394 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) { 3395 // Aha, the activity isn't handling the change, so DIE DIE DIE. 3396 r.configChangeFlags |= changes; 3397 r.startFreezingScreenLocked(r.app, globalChanges); 3398 r.forceNewConfig = false; 3399 if (r.app == null || r.app.thread == null) { 3400 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3401 "Config is destroying non-running " + r); 3402 destroyActivityLocked(r, true, false, "config"); 3403 } else if (r.state == ActivityState.PAUSING) { 3404 // A little annoying: we are waiting for this activity to 3405 // finish pausing. Let's not do anything now, but just 3406 // flag that it needs to be restarted when done pausing. 3407 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3408 "Config is skipping already pausing " + r); 3409 r.configDestroy = true; 3410 return true; 3411 } else if (r.state == ActivityState.RESUMED) { 3412 // Try to optimize this case: the configuration is changing 3413 // and we need to restart the top, resumed activity. 3414 // Instead of doing the normal handshaking, just say 3415 // "restart!". 3416 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3417 "Config is relaunching resumed " + r); 3418 relaunchActivityLocked(r, r.configChangeFlags, true); 3419 r.configChangeFlags = 0; 3420 } else { 3421 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3422 "Config is relaunching non-resumed " + r); 3423 relaunchActivityLocked(r, r.configChangeFlags, false); 3424 r.configChangeFlags = 0; 3425 } 3426 3427 // All done... tell the caller we weren't able to keep this 3428 // activity around. 3429 return false; 3430 } 3431 3432 // Default case: the activity can handle this new configuration, so 3433 // hand it over. Note that we don't need to give it the new 3434 // configuration, since we always send configuration changes to all 3435 // process when they happen so it can just use whatever configuration 3436 // it last got. 3437 if (r.app != null && r.app.thread != null) { 3438 try { 3439 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r); 3440 r.app.thread.scheduleActivityConfigurationChanged(r.appToken); 3441 } catch (RemoteException e) { 3442 // If process died, whatever. 3443 } 3444 } 3445 r.stopFreezingScreenLocked(false); 3446 3447 return true; 3448 } 3449 3450 private boolean relaunchActivityLocked(ActivityRecord r, 3451 int changes, boolean andResume) { 3452 List<ResultInfo> results = null; 3453 List<Intent> newIntents = null; 3454 if (andResume) { 3455 results = r.results; 3456 newIntents = r.newIntents; 3457 } 3458 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r 3459 + " with results=" + results + " newIntents=" + newIntents 3460 + " andResume=" + andResume); 3461 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY 3462 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r), 3463 r.task.taskId, r.shortComponentName); 3464 3465 r.startFreezingScreenLocked(r.app, 0); 3466 3467 mStackSupervisor.removeChildActivityContainers(r); 3468 3469 try { 3470 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, 3471 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ") 3472 + r); 3473 r.forceNewConfig = false; 3474 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents, 3475 changes, !andResume, new Configuration(mService.mConfiguration)); 3476 // Note: don't need to call pauseIfSleepingLocked() here, because 3477 // the caller will only pass in 'andResume' if this activity is 3478 // currently resumed, which implies we aren't sleeping. 3479 } catch (RemoteException e) { 3480 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e); 3481 } 3482 3483 if (andResume) { 3484 r.results = null; 3485 r.newIntents = null; 3486 r.state = ActivityState.RESUMED; 3487 } else { 3488 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 3489 r.state = ActivityState.PAUSED; 3490 } 3491 3492 return true; 3493 } 3494 3495 boolean willActivityBeVisibleLocked(IBinder token) { 3496 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3497 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3498 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3499 final ActivityRecord r = activities.get(activityNdx); 3500 if (r.appToken == token) { 3501 return true; 3502 } 3503 if (r.fullscreen && !r.finishing) { 3504 return false; 3505 } 3506 } 3507 } 3508 final ActivityRecord r = ActivityRecord.forToken(token); 3509 if (r == null) { 3510 return false; 3511 } 3512 if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false," 3513 + " would have returned true for r=" + r); 3514 return !r.finishing; 3515 } 3516 3517 void closeSystemDialogsLocked() { 3518 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3519 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3520 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3521 final ActivityRecord r = activities.get(activityNdx); 3522 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) { 3523 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true); 3524 } 3525 } 3526 } 3527 } 3528 3529 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) { 3530 boolean didSomething = false; 3531 TaskRecord lastTask = null; 3532 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3533 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3534 int numActivities = activities.size(); 3535 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) { 3536 ActivityRecord r = activities.get(activityNdx); 3537 final boolean samePackage = r.packageName.equals(name) 3538 || (name == null && r.userId == userId); 3539 if ((userId == UserHandle.USER_ALL || r.userId == userId) 3540 && (samePackage || r.task == lastTask) 3541 && (r.app == null || evenPersistent || !r.app.persistent)) { 3542 if (!doit) { 3543 if (r.finishing) { 3544 // If this activity is just finishing, then it is not 3545 // interesting as far as something to stop. 3546 continue; 3547 } 3548 return true; 3549 } 3550 didSomething = true; 3551 Slog.i(TAG, " Force finishing activity " + r); 3552 if (samePackage) { 3553 if (r.app != null) { 3554 r.app.removed = true; 3555 } 3556 r.app = null; 3557 } 3558 lastTask = r.task; 3559 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop", 3560 true)) { 3561 // r has been deleted from mActivities, accommodate. 3562 --numActivities; 3563 --activityNdx; 3564 } 3565 } 3566 } 3567 } 3568 return didSomething; 3569 } 3570 3571 void getTasksLocked(List<RunningTaskInfo> list, int callingUid, boolean allowed) { 3572 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3573 final TaskRecord task = mTaskHistory.get(taskNdx); 3574 ActivityRecord r = null; 3575 ActivityRecord top = null; 3576 int numActivities = 0; 3577 int numRunning = 0; 3578 final ArrayList<ActivityRecord> activities = task.mActivities; 3579 if (activities.isEmpty()) { 3580 continue; 3581 } 3582 if (!allowed && !task.isHomeTask() && task.creatorUid != callingUid) { 3583 continue; 3584 } 3585 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3586 r = activities.get(activityNdx); 3587 3588 // Initialize state for next task if needed. 3589 if (top == null || (top.state == ActivityState.INITIALIZING)) { 3590 top = r; 3591 numActivities = numRunning = 0; 3592 } 3593 3594 // Add 'r' into the current task. 3595 numActivities++; 3596 if (r.app != null && r.app.thread != null) { 3597 numRunning++; 3598 } 3599 3600 if (localLOGV) Slog.v( 3601 TAG, r.intent.getComponent().flattenToShortString() 3602 + ": task=" + r.task); 3603 } 3604 3605 RunningTaskInfo ci = new RunningTaskInfo(); 3606 ci.id = task.taskId; 3607 ci.baseActivity = r.intent.getComponent(); 3608 ci.topActivity = top.intent.getComponent(); 3609 ci.lastActiveTime = task.lastActiveTime; 3610 3611 if (top.thumbHolder != null) { 3612 ci.description = top.thumbHolder.lastDescription; 3613 } 3614 ci.numActivities = numActivities; 3615 ci.numRunning = numRunning; 3616 //System.out.println( 3617 // "#" + maxNum + ": " + " descr=" + ci.description); 3618 list.add(ci); 3619 } 3620 } 3621 3622 public void unhandledBackLocked() { 3623 final int top = mTaskHistory.size() - 1; 3624 if (DEBUG_SWITCH) Slog.d( 3625 TAG, "Performing unhandledBack(): top activity at " + top); 3626 if (top >= 0) { 3627 final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities; 3628 int activityTop = activities.size() - 1; 3629 if (activityTop > 0) { 3630 finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null, 3631 "unhandled-back", true); 3632 } 3633 } 3634 } 3635 3636 /** 3637 * Reset local parameters because an app's activity died. 3638 * @param app The app of the activity that died. 3639 * @return result from removeHistoryRecordsForAppLocked. 3640 */ 3641 boolean handleAppDiedLocked(ProcessRecord app) { 3642 if (mPausingActivity != null && mPausingActivity.app == app) { 3643 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG, 3644 "App died while pausing: " + mPausingActivity); 3645 mPausingActivity = null; 3646 } 3647 if (mLastPausedActivity != null && mLastPausedActivity.app == app) { 3648 mLastPausedActivity = null; 3649 mLastNoHistoryActivity = null; 3650 } 3651 3652 return removeHistoryRecordsForAppLocked(app); 3653 } 3654 3655 void handleAppCrashLocked(ProcessRecord app) { 3656 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3657 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3658 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3659 final ActivityRecord r = activities.get(activityNdx); 3660 if (r.app == app) { 3661 Slog.w(TAG, " Force finishing activity " 3662 + r.intent.getComponent().flattenToShortString()); 3663 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false); 3664 } 3665 } 3666 } 3667 } 3668 3669 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll, 3670 boolean dumpClient, String dumpPackage, boolean needSep, String header) { 3671 boolean printed = false; 3672 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3673 final TaskRecord task = mTaskHistory.get(taskNdx); 3674 printed |= ActivityStackSupervisor.dumpHistoryList(fd, pw, 3675 mTaskHistory.get(taskNdx).mActivities, " ", "Hist", true, !dumpAll, 3676 dumpClient, dumpPackage, needSep, header, 3677 " Task id #" + task.taskId); 3678 if (printed) { 3679 header = null; 3680 } 3681 } 3682 return printed; 3683 } 3684 3685 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) { 3686 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(); 3687 3688 if ("all".equals(name)) { 3689 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3690 activities.addAll(mTaskHistory.get(taskNdx).mActivities); 3691 } 3692 } else if ("top".equals(name)) { 3693 final int top = mTaskHistory.size() - 1; 3694 if (top >= 0) { 3695 final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities; 3696 int listTop = list.size() - 1; 3697 if (listTop >= 0) { 3698 activities.add(list.get(listTop)); 3699 } 3700 } 3701 } else { 3702 ItemMatcher matcher = new ItemMatcher(); 3703 matcher.build(name); 3704 3705 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3706 for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) { 3707 if (matcher.match(r1, r1.intent.getComponent())) { 3708 activities.add(r1); 3709 } 3710 } 3711 } 3712 } 3713 3714 return activities; 3715 } 3716 3717 ActivityRecord restartPackage(String packageName) { 3718 ActivityRecord starting = topRunningActivityLocked(null); 3719 3720 // All activities that came from the package must be 3721 // restarted as if there was a config change. 3722 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3723 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3724 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3725 final ActivityRecord a = activities.get(activityNdx); 3726 if (a.info.packageName.equals(packageName)) { 3727 a.forceNewConfig = true; 3728 if (starting != null && a == starting && a.visible) { 3729 a.startFreezingScreenLocked(starting.app, 3730 ActivityInfo.CONFIG_SCREEN_LAYOUT); 3731 } 3732 } 3733 } 3734 } 3735 3736 return starting; 3737 } 3738 3739 void removeTask(TaskRecord task) { 3740 mStackSupervisor.endLockTaskModeIfTaskEnding(task); 3741 mWindowManager.removeTask(task.taskId); 3742 final ActivityRecord r = mResumedActivity; 3743 if (r != null && r.task == task) { 3744 mResumedActivity = null; 3745 } 3746 3747 final int taskNdx = mTaskHistory.indexOf(task); 3748 final int topTaskNdx = mTaskHistory.size() - 1; 3749 if (task.mOnTopOfHome && taskNdx < topTaskNdx) { 3750 mTaskHistory.get(taskNdx + 1).mOnTopOfHome = true; 3751 } 3752 mTaskHistory.remove(task); 3753 updateTaskMovement(task, true); 3754 3755 if (task.mActivities.isEmpty()) { 3756 final boolean isVoiceSession = task.voiceSession != null; 3757 if (isVoiceSession) { 3758 try { 3759 task.voiceSession.taskFinished(task.intent, task.taskId); 3760 } catch (RemoteException e) { 3761 } 3762 } 3763 if (task.autoRemoveFromRecents() || isVoiceSession) { 3764 // Task creator asked to remove this when done, or this task was a voice 3765 // interaction, so it should not remain on the recent tasks list. 3766 mService.mRecentTasks.remove(task); 3767 } 3768 } 3769 3770 if (mTaskHistory.isEmpty()) { 3771 if (DEBUG_STACK) Slog.i(TAG, "removeTask: moving to back stack=" + this); 3772 if (isOnHomeDisplay()) { 3773 mStackSupervisor.moveHomeStack(!isHomeStack()); 3774 } 3775 if (mStacks != null) { 3776 mStacks.remove(this); 3777 mStacks.add(0, this); 3778 } 3779 mActivityContainer.onTaskListEmptyLocked(); 3780 } 3781 } 3782 3783 TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent, 3784 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, 3785 boolean toTop) { 3786 TaskRecord task = new TaskRecord(mService, taskId, info, intent, voiceSession, 3787 voiceInteractor); 3788 addTask(task, toTop, false); 3789 return task; 3790 } 3791 3792 ArrayList<TaskRecord> getAllTasks() { 3793 return new ArrayList<TaskRecord>(mTaskHistory); 3794 } 3795 3796 void addTask(final TaskRecord task, final boolean toTop, boolean moving) { 3797 task.stack = this; 3798 if (toTop) { 3799 insertTaskAtTop(task); 3800 } else { 3801 mTaskHistory.add(0, task); 3802 updateTaskMovement(task, false); 3803 } 3804 if (!moving && task.voiceSession != null) { 3805 try { 3806 task.voiceSession.taskStarted(task.intent, task.taskId); 3807 } catch (RemoteException e) { 3808 } 3809 } 3810 } 3811 3812 public int getStackId() { 3813 return mStackId; 3814 } 3815 3816 @Override 3817 public String toString() { 3818 return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this)) 3819 + " stackId=" + mStackId + ", " + mTaskHistory.size() + " tasks}"; 3820 } 3821} 3822