ActivityStack.java revision d163e751895930a1c8d8d6c3d7e0a37177dbbf19
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 /** 1070 * Determine if home should be visible below the passed record. 1071 * @param record activity we are querying for. 1072 * @return true if home is visible below the passed activity, false otherwise. 1073 */ 1074 boolean isActivityOverHome(ActivityRecord record) { 1075 // Start at record and go down, look for either home or a visible fullscreen activity. 1076 final TaskRecord recordTask = record.task; 1077 for (int taskNdx = mTaskHistory.indexOf(recordTask); taskNdx >= 0; --taskNdx) { 1078 TaskRecord task = mTaskHistory.get(taskNdx); 1079 final ArrayList<ActivityRecord> activities = task.mActivities; 1080 final int startNdx = 1081 task == recordTask ? activities.indexOf(record) : activities.size() - 1; 1082 for (int activityNdx = startNdx; activityNdx >= 0; --activityNdx) { 1083 final ActivityRecord r = activities.get(activityNdx); 1084 if (r.isHomeActivity()) { 1085 return true; 1086 } 1087 if (!r.finishing && r.fullscreen) { 1088 // Passed activity is over a fullscreen activity. 1089 return false; 1090 } 1091 } 1092 if (task.mOnTopOfHome) { 1093 // Got to the bottom of a task on top of home without finding a visible fullscreen 1094 // activity. Home is visible. 1095 return true; 1096 } 1097 } 1098 // Got to the bottom of this stack and still don't know. If this is over the home stack 1099 // then record is over home. May not work if we ever get more than two layers. 1100 return mStackSupervisor.isFrontStack(this); 1101 } 1102 1103 private void setVisibile(ActivityRecord r, boolean visible) { 1104 r.visible = visible; 1105 mWindowManager.setAppVisibility(r.appToken, visible); 1106 final ArrayList<ActivityContainer> containers = r.mChildContainers; 1107 for (int containerNdx = containers.size() - 1; containerNdx >= 0; --containerNdx) { 1108 ActivityContainer container = containers.get(containerNdx); 1109 container.setVisible(visible); 1110 } 1111 } 1112 1113 // Checks if any of the stacks above this one has a fullscreen activity behind it. 1114 // If so, this stack is hidden, otherwise it is visible. 1115 private boolean isStackVisible() { 1116 if (!isAttached()) { 1117 return false; 1118 } 1119 1120 if (mStackSupervisor.isFrontStack(this)) { 1121 return true; 1122 } 1123 1124 /** 1125 * Start at the task above this one and go up, looking for a visible 1126 * fullscreen activity, or a translucent activity that requested the 1127 * wallpaper to be shown behind it. 1128 */ 1129 for (int i = mStacks.indexOf(this) + 1; i < mStacks.size(); i++) { 1130 final ArrayList<TaskRecord> tasks = mStacks.get(i).getAllTasks(); 1131 for (int taskNdx = 0; taskNdx < tasks.size(); taskNdx++) { 1132 final ArrayList<ActivityRecord> activities = tasks.get(taskNdx).mActivities; 1133 for (int activityNdx = 0; activityNdx < activities.size(); activityNdx++) { 1134 final ActivityRecord r = activities.get(activityNdx); 1135 1136 // Conditions for an activity to obscure the stack we're 1137 // examining: 1138 // 1. Not Finishing AND Visible AND: 1139 // 2. Either: 1140 // - Full Screen Activity OR 1141 // - On top of Home and our stack is NOT home 1142 if (!r.finishing && r.visible && (r.fullscreen || 1143 (!isHomeStack() && r.frontOfTask && tasks.get(taskNdx).mOnTopOfHome))) { 1144 return false; 1145 } 1146 } 1147 } 1148 } 1149 1150 return true; 1151 } 1152 1153 final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges) { 1154 ActivityRecord r = topRunningActivityLocked(null); 1155 if (r != null) { 1156 ensureActivitiesVisibleLocked(r, starting, null, configChanges); 1157 } 1158 } 1159 1160 /** 1161 * Make sure that all activities that need to be visible (that is, they 1162 * currently can be seen by the user) actually are. 1163 */ 1164 final void ensureActivitiesVisibleLocked(ActivityRecord top, ActivityRecord starting, 1165 String onlyThisProcess, int configChanges) { 1166 if (DEBUG_VISBILITY) Slog.v( 1167 TAG, "ensureActivitiesVisible behind " + top 1168 + " configChanges=0x" + Integer.toHexString(configChanges)); 1169 1170 if (mTranslucentActivityWaiting != top) { 1171 mUndrawnActivitiesBelowTopTranslucent.clear(); 1172 if (mTranslucentActivityWaiting != null) { 1173 // Call the callback with a timeout indication. 1174 notifyActivityDrawnLocked(null); 1175 mTranslucentActivityWaiting = null; 1176 } 1177 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG); 1178 } 1179 1180 // If the top activity is not fullscreen, then we need to 1181 // make sure any activities under it are now visible. 1182 boolean aboveTop = true; 1183 boolean behindFullscreen = !isStackVisible(); 1184 1185 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1186 final TaskRecord task = mTaskHistory.get(taskNdx); 1187 final ArrayList<ActivityRecord> activities = task.mActivities; 1188 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1189 final ActivityRecord r = activities.get(activityNdx); 1190 if (r.finishing) { 1191 continue; 1192 } 1193 if (aboveTop && r != top) { 1194 continue; 1195 } 1196 aboveTop = false; 1197 if (!behindFullscreen) { 1198 if (DEBUG_VISBILITY) Slog.v( 1199 TAG, "Make visible? " + r + " finishing=" + r.finishing 1200 + " state=" + r.state); 1201 1202 final boolean doThisProcess = onlyThisProcess == null 1203 || onlyThisProcess.equals(r.processName); 1204 1205 // First: if this is not the current activity being started, make 1206 // sure it matches the current configuration. 1207 if (r != starting && doThisProcess) { 1208 ensureActivityConfigurationLocked(r, 0); 1209 } 1210 1211 if (r.app == null || r.app.thread == null) { 1212 if (onlyThisProcess == null || onlyThisProcess.equals(r.processName)) { 1213 // This activity needs to be visible, but isn't even 1214 // running... get it started, but don't resume it 1215 // at this point. 1216 if (DEBUG_VISBILITY) Slog.v(TAG, "Start and freeze screen for " + r); 1217 if (r != starting) { 1218 r.startFreezingScreenLocked(r.app, configChanges); 1219 } 1220 if (!r.visible) { 1221 if (DEBUG_VISBILITY) Slog.v( 1222 TAG, "Starting and making visible: " + r); 1223 setVisibile(r, true); 1224 } 1225 if (r != starting) { 1226 mStackSupervisor.startSpecificActivityLocked(r, false, false); 1227 } 1228 } 1229 1230 } else if (r.visible) { 1231 // If this activity is already visible, then there is nothing 1232 // else to do here. 1233 if (DEBUG_VISBILITY) Slog.v(TAG, "Skipping: already visible at " + r); 1234 r.stopFreezingScreenLocked(false); 1235 1236 } else if (onlyThisProcess == null) { 1237 // This activity is not currently visible, but is running. 1238 // Tell it to become visible. 1239 r.visible = true; 1240 if (r.state != ActivityState.RESUMED && r != starting) { 1241 // If this activity is paused, tell it 1242 // to now show its window. 1243 if (DEBUG_VISBILITY) Slog.v( 1244 TAG, "Making visible and scheduling visibility: " + r); 1245 try { 1246 if (mTranslucentActivityWaiting != null) { 1247 r.updateOptionsLocked(mReturningActivityOptions); 1248 mUndrawnActivitiesBelowTopTranslucent.add(r); 1249 } 1250 setVisibile(r, true); 1251 r.sleeping = false; 1252 r.app.pendingUiClean = true; 1253 r.app.thread.scheduleWindowVisibility(r.appToken, true); 1254 r.stopFreezingScreenLocked(false); 1255 } catch (Exception e) { 1256 // Just skip on any failure; we'll make it 1257 // visible when it next restarts. 1258 Slog.w(TAG, "Exception thrown making visibile: " 1259 + r.intent.getComponent(), e); 1260 } 1261 } 1262 } 1263 1264 // Aggregate current change flags. 1265 configChanges |= r.configChangeFlags; 1266 1267 if (r.fullscreen) { 1268 // At this point, nothing else needs to be shown 1269 if (DEBUG_VISBILITY) Slog.v(TAG, "Fullscreen: at " + r); 1270 behindFullscreen = true; 1271 } else if (!isHomeStack() && r.frontOfTask && task.mOnTopOfHome) { 1272 if (DEBUG_VISBILITY) Slog.v(TAG, "Showing home: at " + r); 1273 behindFullscreen = true; 1274 } 1275 } else { 1276 if (DEBUG_VISBILITY) Slog.v( 1277 TAG, "Make invisible? " + r + " finishing=" + r.finishing 1278 + " state=" + r.state 1279 + " behindFullscreen=" + behindFullscreen); 1280 // Now for any activities that aren't visible to the user, make 1281 // sure they no longer are keeping the screen frozen. 1282 if (r.visible) { 1283 if (DEBUG_VISBILITY) Slog.v(TAG, "Making invisible: " + r); 1284 try { 1285 setVisibile(r, false); 1286 switch (r.state) { 1287 case STOPPING: 1288 case STOPPED: 1289 if (r.app != null && r.app.thread != null) { 1290 if (DEBUG_VISBILITY) Slog.v( 1291 TAG, "Scheduling invisibility: " + r); 1292 r.app.thread.scheduleWindowVisibility(r.appToken, false); 1293 } 1294 break; 1295 1296 case INITIALIZING: 1297 case RESUMED: 1298 case PAUSING: 1299 case PAUSED: 1300 // This case created for transitioning activities from 1301 // translucent to opaque {@link Activity#convertToOpaque}. 1302 if (!mStackSupervisor.mStoppingActivities.contains(r)) { 1303 mStackSupervisor.mStoppingActivities.add(r); 1304 } 1305 mStackSupervisor.scheduleIdleLocked(); 1306 break; 1307 1308 default: 1309 break; 1310 } 1311 } catch (Exception e) { 1312 // Just skip on any failure; we'll make it 1313 // visible when it next restarts. 1314 Slog.w(TAG, "Exception thrown making hidden: " 1315 + r.intent.getComponent(), e); 1316 } 1317 } else { 1318 if (DEBUG_VISBILITY) Slog.v(TAG, "Already invisible: " + r); 1319 } 1320 } 1321 } 1322 } 1323 } 1324 1325 void convertToTranslucent(ActivityRecord r, ActivityOptions options) { 1326 mTranslucentActivityWaiting = r; 1327 mUndrawnActivitiesBelowTopTranslucent.clear(); 1328 mReturningActivityOptions = options; 1329 mHandler.sendEmptyMessageDelayed(TRANSLUCENT_TIMEOUT_MSG, TRANSLUCENT_CONVERSION_TIMEOUT); 1330 } 1331 1332 /** 1333 * Called as activities below the top translucent activity are redrawn. When the last one is 1334 * redrawn notify the top activity by calling 1335 * {@link Activity#onTranslucentConversionComplete}. 1336 * 1337 * @param r The most recent background activity to be drawn. Or, if r is null then a timeout 1338 * occurred and the activity will be notified immediately. 1339 */ 1340 void notifyActivityDrawnLocked(ActivityRecord r) { 1341 mActivityContainer.setDrawn(); 1342 if ((r == null) 1343 || (mUndrawnActivitiesBelowTopTranslucent.remove(r) && 1344 mUndrawnActivitiesBelowTopTranslucent.isEmpty())) { 1345 // The last undrawn activity below the top has just been drawn. If there is an 1346 // opaque activity at the top, notify it that it can become translucent safely now. 1347 final ActivityRecord waitingActivity = mTranslucentActivityWaiting; 1348 mTranslucentActivityWaiting = null; 1349 mUndrawnActivitiesBelowTopTranslucent.clear(); 1350 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG); 1351 1352 if (waitingActivity != null) { 1353 mWindowManager.setWindowOpaque(waitingActivity.appToken, false); 1354 if (waitingActivity.app != null && waitingActivity.app.thread != null) { 1355 try { 1356 waitingActivity.app.thread.scheduleTranslucentConversionComplete( 1357 waitingActivity.appToken, r != null); 1358 } catch (RemoteException e) { 1359 } 1360 } 1361 } 1362 } 1363 } 1364 1365 /** If any activities below the top running one are in the INITIALIZING state and they have a 1366 * starting window displayed then remove that starting window. It is possible that the activity 1367 * in this state will never resumed in which case that starting window will be orphaned. */ 1368 void cancelInitializingActivities() { 1369 final ActivityRecord topActivity = topRunningActivityLocked(null); 1370 boolean aboveTop = true; 1371 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1372 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 1373 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1374 final ActivityRecord r = activities.get(activityNdx); 1375 if (aboveTop) { 1376 if (r == topActivity) { 1377 aboveTop = false; 1378 } 1379 continue; 1380 } 1381 1382 if (r.state == ActivityState.INITIALIZING && r.mStartingWindowShown) { 1383 if (DEBUG_VISBILITY) Slog.w(TAG, "Found orphaned starting window " + r); 1384 r.mStartingWindowShown = false; 1385 mWindowManager.removeAppStartingWindow(r.appToken); 1386 } 1387 } 1388 } 1389 } 1390 1391 /** 1392 * Ensure that the top activity in the stack is resumed. 1393 * 1394 * @param prev The previously resumed activity, for when in the process 1395 * of pausing; can be null to call from elsewhere. 1396 * 1397 * @return Returns true if something is being resumed, or false if 1398 * nothing happened. 1399 */ 1400 final boolean resumeTopActivityLocked(ActivityRecord prev) { 1401 return resumeTopActivityLocked(prev, null); 1402 } 1403 1404 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) { 1405 if (ActivityManagerService.DEBUG_LOCKSCREEN) mService.logLockScreen(""); 1406 1407 ActivityRecord parent = mActivityContainer.mParentActivity; 1408 if ((parent != null && parent.state != ActivityState.RESUMED) || 1409 !mActivityContainer.isAttachedLocked()) { 1410 // Do not resume this stack if its parent is not resumed. 1411 // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st. 1412 return false; 1413 } 1414 1415 cancelInitializingActivities(); 1416 1417 // Find the first activity that is not finishing. 1418 ActivityRecord next = topRunningActivityLocked(null); 1419 1420 // Remember how we'll process this pause/resume situation, and ensure 1421 // that the state is reset however we wind up proceeding. 1422 final boolean userLeaving = mStackSupervisor.mUserLeaving; 1423 mStackSupervisor.mUserLeaving = false; 1424 1425 if (next == null) { 1426 // There are no more activities! Let's just start up the 1427 // Launcher... 1428 ActivityOptions.abort(options); 1429 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: No more activities go home"); 1430 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1431 // Only resume home if on home display 1432 return isOnHomeDisplay() && mStackSupervisor.resumeHomeActivity(prev); 1433 } 1434 1435 next.delayedResume = false; 1436 1437 // If the top activity is the resumed one, nothing to do. 1438 if (mResumedActivity == next && next.state == ActivityState.RESUMED && 1439 mStackSupervisor.allResumedActivitiesComplete()) { 1440 // Make sure we have executed any pending transitions, since there 1441 // should be nothing left to do at this point. 1442 mWindowManager.executeAppTransition(); 1443 mNoAnimActivities.clear(); 1444 ActivityOptions.abort(options); 1445 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Top activity resumed " + next); 1446 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1447 return false; 1448 } 1449 1450 final TaskRecord nextTask = next.task; 1451 final TaskRecord prevTask = prev != null ? prev.task : null; 1452 if (prevTask != null && prevTask.stack == this && 1453 prevTask.mOnTopOfHome && prev.finishing && prev.frontOfTask) { 1454 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1455 if (prevTask == nextTask) { 1456 prevTask.setFrontOfTask(); 1457 } else if (prevTask != topTask()) { 1458 // This task is going away but it was supposed to return to the home task. 1459 // Now the task above it has to return to the home task instead. 1460 final int taskNdx = mTaskHistory.indexOf(prevTask) + 1; 1461 mTaskHistory.get(taskNdx).mOnTopOfHome = true; 1462 } else { 1463 if (DEBUG_STATES && isOnHomeDisplay()) Slog.d(TAG, 1464 "resumeTopActivityLocked: Launching home next"); 1465 // Only resume home if on home display 1466 return isOnHomeDisplay() && mStackSupervisor.resumeHomeActivity(prev); 1467 } 1468 } 1469 1470 // If we are sleeping, and there is no resumed activity, and the top 1471 // activity is paused, well that is the state we want. 1472 if (mService.isSleepingOrShuttingDown() 1473 && mLastPausedActivity == next 1474 && mStackSupervisor.allPausedActivitiesComplete()) { 1475 // Make sure we have executed any pending transitions, since there 1476 // should be nothing left to do at this point. 1477 mWindowManager.executeAppTransition(); 1478 mNoAnimActivities.clear(); 1479 ActivityOptions.abort(options); 1480 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Going to sleep and all paused"); 1481 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1482 return false; 1483 } 1484 1485 // Make sure that the user who owns this activity is started. If not, 1486 // we will just leave it as is because someone should be bringing 1487 // another user's activities to the top of the stack. 1488 if (mService.mStartedUsers.get(next.userId) == null) { 1489 Slog.w(TAG, "Skipping resume of top activity " + next 1490 + ": user " + next.userId + " is stopped"); 1491 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1492 return false; 1493 } 1494 1495 // The activity may be waiting for stop, but that is no longer 1496 // appropriate for it. 1497 mStackSupervisor.mStoppingActivities.remove(next); 1498 mStackSupervisor.mGoingToSleepActivities.remove(next); 1499 next.sleeping = false; 1500 mStackSupervisor.mWaitingVisibleActivities.remove(next); 1501 1502 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next); 1503 1504 // If we are currently pausing an activity, then don't do anything 1505 // until that is done. 1506 if (!mStackSupervisor.allPausedActivitiesComplete()) { 1507 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG, 1508 "resumeTopActivityLocked: Skip resume: some activity pausing."); 1509 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1510 return false; 1511 } 1512 1513 // Okay we are now going to start a switch, to 'next'. We may first 1514 // have to pause the current activity, but this is an important point 1515 // where we have decided to go to 'next' so keep track of that. 1516 // XXX "App Redirected" dialog is getting too many false positives 1517 // at this point, so turn off for now. 1518 if (false) { 1519 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) { 1520 long now = SystemClock.uptimeMillis(); 1521 final boolean inTime = mLastStartedActivity.startTime != 0 1522 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now; 1523 final int lastUid = mLastStartedActivity.info.applicationInfo.uid; 1524 final int nextUid = next.info.applicationInfo.uid; 1525 if (inTime && lastUid != nextUid 1526 && lastUid != next.launchedFromUid 1527 && mService.checkPermission( 1528 android.Manifest.permission.STOP_APP_SWITCHES, 1529 -1, next.launchedFromUid) 1530 != PackageManager.PERMISSION_GRANTED) { 1531 mService.showLaunchWarningLocked(mLastStartedActivity, next); 1532 } else { 1533 next.startTime = now; 1534 mLastStartedActivity = next; 1535 } 1536 } else { 1537 next.startTime = SystemClock.uptimeMillis(); 1538 mLastStartedActivity = next; 1539 } 1540 } 1541 1542 // We need to start pausing the current activity so the top one 1543 // can be resumed... 1544 boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving); 1545 if (mResumedActivity != null) { 1546 pausing = true; 1547 startPausingLocked(userLeaving, false); 1548 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Pausing " + mResumedActivity); 1549 } 1550 if (pausing) { 1551 if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG, 1552 "resumeTopActivityLocked: Skip resume: need to start pausing"); 1553 // At this point we want to put the upcoming activity's process 1554 // at the top of the LRU list, since we know we will be needing it 1555 // very soon and it would be a waste to let it get killed if it 1556 // happens to be sitting towards the end. 1557 if (next.app != null && next.app.thread != null) { 1558 // No reason to do full oom adj update here; we'll let that 1559 // happen whenever it needs to later. 1560 mService.updateLruProcessLocked(next.app, true, null); 1561 } 1562 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1563 return true; 1564 } 1565 1566 // If the most recent activity was noHistory but was only stopped rather 1567 // than stopped+finished because the device went to sleep, we need to make 1568 // sure to finish it as we're making a new activity topmost. 1569 if (mService.isSleeping() && mLastNoHistoryActivity != null && 1570 !mLastNoHistoryActivity.finishing) { 1571 if (DEBUG_STATES) Slog.d(TAG, "no-history finish of " + mLastNoHistoryActivity + 1572 " on new resume"); 1573 requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED, 1574 null, "no-history", false); 1575 mLastNoHistoryActivity = null; 1576 } 1577 1578 if (prev != null && prev != next) { 1579 if (!prev.waitingVisible && next != null && !next.nowVisible) { 1580 prev.waitingVisible = true; 1581 mStackSupervisor.mWaitingVisibleActivities.add(prev); 1582 if (DEBUG_SWITCH) Slog.v( 1583 TAG, "Resuming top, waiting visible to hide: " + prev); 1584 } else { 1585 // The next activity is already visible, so hide the previous 1586 // activity's windows right now so we can show the new one ASAP. 1587 // We only do this if the previous is finishing, which should mean 1588 // it is on top of the one being resumed so hiding it quickly 1589 // is good. Otherwise, we want to do the normal route of allowing 1590 // the resumed activity to be shown so we can decide if the 1591 // previous should actually be hidden depending on whether the 1592 // new one is found to be full-screen or not. 1593 if (prev.finishing) { 1594 mWindowManager.setAppVisibility(prev.appToken, false); 1595 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: " 1596 + prev + ", waitingVisible=" 1597 + (prev != null ? prev.waitingVisible : null) 1598 + ", nowVisible=" + next.nowVisible); 1599 } else { 1600 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: " 1601 + prev + ", waitingVisible=" 1602 + (prev != null ? prev.waitingVisible : null) 1603 + ", nowVisible=" + next.nowVisible); 1604 } 1605 } 1606 } 1607 1608 // Launching this app's activity, make sure the app is no longer 1609 // considered stopped. 1610 try { 1611 AppGlobals.getPackageManager().setPackageStoppedState( 1612 next.packageName, false, next.userId); /* TODO: Verify if correct userid */ 1613 } catch (RemoteException e1) { 1614 } catch (IllegalArgumentException e) { 1615 Slog.w(TAG, "Failed trying to unstop package " 1616 + next.packageName + ": " + e); 1617 } 1618 1619 // We are starting up the next activity, so tell the window manager 1620 // that the previous one will be hidden soon. This way it can know 1621 // to ignore it when computing the desired screen orientation. 1622 boolean anim = true; 1623 if (prev != null) { 1624 if (prev.finishing) { 1625 if (DEBUG_TRANSITION) Slog.v(TAG, 1626 "Prepare close transition: prev=" + prev); 1627 if (mNoAnimActivities.contains(prev)) { 1628 anim = false; 1629 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 1630 } else { 1631 mWindowManager.prepareAppTransition(prev.task == next.task 1632 ? AppTransition.TRANSIT_ACTIVITY_CLOSE 1633 : AppTransition.TRANSIT_TASK_CLOSE, false); 1634 } 1635 mWindowManager.setAppWillBeHidden(prev.appToken); 1636 mWindowManager.setAppVisibility(prev.appToken, false); 1637 } else { 1638 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: prev=" + prev); 1639 if (mNoAnimActivities.contains(next)) { 1640 anim = false; 1641 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 1642 } else { 1643 mWindowManager.prepareAppTransition(prev.task == next.task 1644 ? AppTransition.TRANSIT_ACTIVITY_OPEN 1645 : AppTransition.TRANSIT_TASK_OPEN, false); 1646 } 1647 } 1648 if (false) { 1649 mWindowManager.setAppWillBeHidden(prev.appToken); 1650 mWindowManager.setAppVisibility(prev.appToken, false); 1651 } 1652 } else { 1653 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: no previous"); 1654 if (mNoAnimActivities.contains(next)) { 1655 anim = false; 1656 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 1657 } else { 1658 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_ACTIVITY_OPEN, false); 1659 } 1660 } 1661 1662 Bundle resumeAnimOptions = null; 1663 if (anim) { 1664 ActivityOptions opts = next.getOptionsForTargetActivityLocked(); 1665 if (opts != null) { 1666 resumeAnimOptions = opts.toBundle(); 1667 } 1668 next.applyOptionsLocked(); 1669 } else { 1670 next.clearOptionsLocked(); 1671 } 1672 1673 ActivityStack lastStack = mStackSupervisor.getLastStack(); 1674 if (next.app != null && next.app.thread != null) { 1675 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next); 1676 1677 // This activity is now becoming visible. 1678 mWindowManager.setAppVisibility(next.appToken, true); 1679 1680 // schedule launch ticks to collect information about slow apps. 1681 next.startLaunchTickingLocked(); 1682 1683 ActivityRecord lastResumedActivity = 1684 lastStack == null ? null :lastStack.mResumedActivity; 1685 ActivityState lastState = next.state; 1686 1687 mService.updateCpuStats(); 1688 1689 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)"); 1690 next.state = ActivityState.RESUMED; 1691 mResumedActivity = next; 1692 next.task.touchActiveTime(); 1693 mService.addRecentTaskLocked(next.task); 1694 mService.updateLruProcessLocked(next.app, true, null); 1695 updateLRUListLocked(next); 1696 mService.updateOomAdjLocked(); 1697 1698 // Have the window manager re-evaluate the orientation of 1699 // the screen based on the new activity order. 1700 boolean notUpdated = true; 1701 if (mStackSupervisor.isFrontStack(this)) { 1702 Configuration config = mWindowManager.updateOrientationFromAppTokens( 1703 mService.mConfiguration, 1704 next.mayFreezeScreenLocked(next.app) ? next.appToken : null); 1705 if (config != null) { 1706 next.frozenBeforeDestroy = true; 1707 } 1708 notUpdated = !mService.updateConfigurationLocked(config, next, false, false); 1709 } 1710 1711 if (notUpdated) { 1712 // The configuration update wasn't able to keep the existing 1713 // instance of the activity, and instead started a new one. 1714 // We should be all done, but let's just make sure our activity 1715 // is still at the top and schedule another run if something 1716 // weird happened. 1717 ActivityRecord nextNext = topRunningActivityLocked(null); 1718 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, 1719 "Activity config changed during resume: " + next 1720 + ", new next: " + nextNext); 1721 if (nextNext != next) { 1722 // Do over! 1723 mStackSupervisor.scheduleResumeTopActivities(); 1724 } 1725 if (mStackSupervisor.reportResumedActivityLocked(next)) { 1726 mNoAnimActivities.clear(); 1727 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1728 return true; 1729 } 1730 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1731 return false; 1732 } 1733 1734 try { 1735 // Deliver all pending results. 1736 ArrayList<ResultInfo> a = next.results; 1737 if (a != null) { 1738 final int N = a.size(); 1739 if (!next.finishing && N > 0) { 1740 if (DEBUG_RESULTS) Slog.v( 1741 TAG, "Delivering results to " + next 1742 + ": " + a); 1743 next.app.thread.scheduleSendResult(next.appToken, a); 1744 } 1745 } 1746 1747 if (next.newIntents != null) { 1748 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken); 1749 } 1750 1751 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, 1752 next.userId, System.identityHashCode(next), 1753 next.task.taskId, next.shortComponentName); 1754 1755 next.sleeping = false; 1756 mService.showAskCompatModeDialogLocked(next); 1757 next.app.pendingUiClean = true; 1758 next.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_TOP); 1759 next.clearOptionsLocked(); 1760 next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState, 1761 mService.isNextTransitionForward(), resumeAnimOptions); 1762 1763 mStackSupervisor.checkReadyForSleepLocked(); 1764 1765 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Resumed " + next); 1766 } catch (Exception e) { 1767 // Whoops, need to restart this activity! 1768 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to " 1769 + lastState + ": " + next); 1770 next.state = lastState; 1771 if (lastStack != null) { 1772 lastStack.mResumedActivity = lastResumedActivity; 1773 } 1774 Slog.i(TAG, "Restarting because process died: " + next); 1775 if (!next.hasBeenLaunched) { 1776 next.hasBeenLaunched = true; 1777 } else if (SHOW_APP_STARTING_PREVIEW && lastStack != null && 1778 mStackSupervisor.isFrontStack(lastStack)) { 1779 mWindowManager.setAppStartingWindow( 1780 next.appToken, next.packageName, next.theme, 1781 mService.compatibilityInfoForPackageLocked(next.info.applicationInfo), 1782 next.nonLocalizedLabel, next.labelRes, next.icon, next.logo, 1783 next.windowFlags, null, true); 1784 } 1785 mStackSupervisor.startSpecificActivityLocked(next, true, false); 1786 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1787 return true; 1788 } 1789 1790 // From this point on, if something goes wrong there is no way 1791 // to recover the activity. 1792 try { 1793 next.visible = true; 1794 completeResumeLocked(next); 1795 } catch (Exception e) { 1796 // If any exception gets thrown, toss away this 1797 // activity and try the next one. 1798 Slog.w(TAG, "Exception thrown during resume of " + next, e); 1799 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null, 1800 "resume-exception", true); 1801 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1802 return true; 1803 } 1804 next.stopped = false; 1805 1806 } else { 1807 // Whoops, need to restart this activity! 1808 if (!next.hasBeenLaunched) { 1809 next.hasBeenLaunched = true; 1810 } else { 1811 if (SHOW_APP_STARTING_PREVIEW) { 1812 mWindowManager.setAppStartingWindow( 1813 next.appToken, next.packageName, next.theme, 1814 mService.compatibilityInfoForPackageLocked( 1815 next.info.applicationInfo), 1816 next.nonLocalizedLabel, 1817 next.labelRes, next.icon, next.logo, next.windowFlags, 1818 null, true); 1819 } 1820 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next); 1821 } 1822 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Restarting " + next); 1823 mStackSupervisor.startSpecificActivityLocked(next, true, true); 1824 } 1825 1826 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); 1827 return true; 1828 } 1829 1830 private void insertTaskAtTop(TaskRecord task) { 1831 // If this is being moved to the top by another activity or being launched from the home 1832 // activity, set mOnTopOfHome accordingly. 1833 if (isOnHomeDisplay()) { 1834 ActivityStack lastStack = mStackSupervisor.getLastStack(); 1835 final boolean fromHome = lastStack.isHomeStack(); 1836 if (!isHomeStack() && (fromHome || topTask() != task)) { 1837 task.mOnTopOfHome = fromHome; 1838 } 1839 } else { 1840 task.mOnTopOfHome = false; 1841 } 1842 1843 mTaskHistory.remove(task); 1844 // Now put task at top. 1845 int stackNdx = mTaskHistory.size(); 1846 if (!isCurrentProfileLocked(task.userId)) { 1847 // Put non-current user tasks below current user tasks. 1848 while (--stackNdx >= 0) { 1849 if (!isCurrentProfileLocked(mTaskHistory.get(stackNdx).userId)) { 1850 break; 1851 } 1852 } 1853 ++stackNdx; 1854 } 1855 mTaskHistory.add(stackNdx, task); 1856 updateTaskMovement(task, true); 1857 } 1858 1859 final void startActivityLocked(ActivityRecord r, boolean newTask, 1860 boolean doResume, boolean keepCurTransition, Bundle options) { 1861 TaskRecord rTask = r.task; 1862 final int taskId = rTask.taskId; 1863 if (taskForIdLocked(taskId) == null || newTask) { 1864 // Last activity in task had been removed or ActivityManagerService is reusing task. 1865 // Insert or replace. 1866 // Might not even be in. 1867 insertTaskAtTop(rTask); 1868 mWindowManager.moveTaskToTop(taskId); 1869 } 1870 TaskRecord task = null; 1871 if (!newTask) { 1872 // If starting in an existing task, find where that is... 1873 boolean startIt = true; 1874 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 1875 task = mTaskHistory.get(taskNdx); 1876 if (task == r.task) { 1877 // Here it is! Now, if this is not yet visible to the 1878 // user, then just add it without starting; it will 1879 // get started when the user navigates back to it. 1880 if (!startIt) { 1881 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task " 1882 + task, new RuntimeException("here").fillInStackTrace()); 1883 task.addActivityToTop(r); 1884 r.putInHistory(); 1885 mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken, 1886 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, 1887 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, 1888 r.userId, r.info.configChanges, task.voiceSession != null); 1889 if (VALIDATE_TOKENS) { 1890 validateAppTokensLocked(); 1891 } 1892 ActivityOptions.abort(options); 1893 return; 1894 } 1895 break; 1896 } else if (task.numFullscreen > 0) { 1897 startIt = false; 1898 } 1899 } 1900 } 1901 1902 // Place a new activity at top of stack, so it is next to interact 1903 // with the user. 1904 1905 // If we are not placing the new activity frontmost, we do not want 1906 // to deliver the onUserLeaving callback to the actual frontmost 1907 // activity 1908 if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) { 1909 mStackSupervisor.mUserLeaving = false; 1910 if (DEBUG_USER_LEAVING) Slog.v(TAG, 1911 "startActivity() behind front, mUserLeaving=false"); 1912 } 1913 1914 task = r.task; 1915 1916 // Slot the activity into the history stack and proceed 1917 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task, 1918 new RuntimeException("here").fillInStackTrace()); 1919 task.addActivityToTop(r); 1920 task.setFrontOfTask(); 1921 1922 r.putInHistory(); 1923 if (!isHomeStack() || numActivities() > 0) { 1924 // We want to show the starting preview window if we are 1925 // switching to a new task, or the next activity's process is 1926 // not currently running. 1927 boolean showStartingIcon = newTask; 1928 ProcessRecord proc = r.app; 1929 if (proc == null) { 1930 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid); 1931 } 1932 if (proc == null || proc.thread == null) { 1933 showStartingIcon = true; 1934 } 1935 if (DEBUG_TRANSITION) Slog.v(TAG, 1936 "Prepare open transition: starting " + r); 1937 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 1938 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition); 1939 mNoAnimActivities.add(r); 1940 } else { 1941 mWindowManager.prepareAppTransition(newTask 1942 ? AppTransition.TRANSIT_TASK_OPEN 1943 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition); 1944 mNoAnimActivities.remove(r); 1945 } 1946 mWindowManager.addAppToken(task.mActivities.indexOf(r), 1947 r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, 1948 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId, 1949 r.info.configChanges, task.voiceSession != null); 1950 boolean doShow = true; 1951 if (newTask) { 1952 // Even though this activity is starting fresh, we still need 1953 // to reset it to make sure we apply affinities to move any 1954 // existing activities from other tasks in to it. 1955 // If the caller has requested that the target task be 1956 // reset, then do so. 1957 if ((r.intent.getFlags() 1958 & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) { 1959 resetTaskIfNeededLocked(r, r); 1960 doShow = topRunningNonDelayedActivityLocked(null) == r; 1961 } 1962 } 1963 if (SHOW_APP_STARTING_PREVIEW && doShow) { 1964 // Figure out if we are transitioning from another activity that is 1965 // "has the same starting icon" as the next one. This allows the 1966 // window manager to keep the previous window it had previously 1967 // created, if it still had one. 1968 ActivityRecord prev = mResumedActivity; 1969 if (prev != null) { 1970 // We don't want to reuse the previous starting preview if: 1971 // (1) The current activity is in a different task. 1972 if (prev.task != r.task) { 1973 prev = null; 1974 } 1975 // (2) The current activity is already displayed. 1976 else if (prev.nowVisible) { 1977 prev = null; 1978 } 1979 } 1980 mWindowManager.setAppStartingWindow( 1981 r.appToken, r.packageName, r.theme, 1982 mService.compatibilityInfoForPackageLocked( 1983 r.info.applicationInfo), r.nonLocalizedLabel, 1984 r.labelRes, r.icon, r.logo, r.windowFlags, 1985 prev != null ? prev.appToken : null, showStartingIcon); 1986 r.mStartingWindowShown = true; 1987 } 1988 } else { 1989 // If this is the first activity, don't do any fancy animations, 1990 // because there is nothing for it to animate on top of. 1991 mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken, 1992 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, 1993 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId, 1994 r.info.configChanges, task.voiceSession != null); 1995 ActivityOptions.abort(options); 1996 options = null; 1997 } 1998 if (VALIDATE_TOKENS) { 1999 validateAppTokensLocked(); 2000 } 2001 2002 if (doResume) { 2003 mStackSupervisor.resumeTopActivitiesLocked(this, r, options); 2004 } 2005 } 2006 2007 final void validateAppTokensLocked() { 2008 mValidateAppTokens.clear(); 2009 mValidateAppTokens.ensureCapacity(numActivities()); 2010 final int numTasks = mTaskHistory.size(); 2011 for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) { 2012 TaskRecord task = mTaskHistory.get(taskNdx); 2013 final ArrayList<ActivityRecord> activities = task.mActivities; 2014 if (activities.isEmpty()) { 2015 continue; 2016 } 2017 TaskGroup group = new TaskGroup(); 2018 group.taskId = task.taskId; 2019 mValidateAppTokens.add(group); 2020 final int numActivities = activities.size(); 2021 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) { 2022 final ActivityRecord r = activities.get(activityNdx); 2023 group.tokens.add(r.appToken); 2024 } 2025 } 2026 mWindowManager.validateAppTokens(mStackId, mValidateAppTokens); 2027 } 2028 2029 /** 2030 * Perform a reset of the given task, if needed as part of launching it. 2031 * Returns the new HistoryRecord at the top of the task. 2032 */ 2033 /** 2034 * Helper method for #resetTaskIfNeededLocked. 2035 * We are inside of the task being reset... we'll either finish this activity, push it out 2036 * for another task, or leave it as-is. 2037 * @param task The task containing the Activity (taskTop) that might be reset. 2038 * @param forceReset 2039 * @return An ActivityOptions that needs to be processed. 2040 */ 2041 final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task, boolean forceReset) { 2042 ActivityOptions topOptions = null; 2043 2044 int replyChainEnd = -1; 2045 boolean canMoveOptions = true; 2046 2047 // We only do this for activities that are not the root of the task (since if we finish 2048 // the root, we may no longer have the task!). 2049 final ArrayList<ActivityRecord> activities = task.mActivities; 2050 final int numActivities = activities.size(); 2051 for (int i = numActivities - 1; i > 0; --i ) { 2052 ActivityRecord target = activities.get(i); 2053 2054 final int flags = target.info.flags; 2055 final boolean finishOnTaskLaunch = 2056 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; 2057 final boolean allowTaskReparenting = 2058 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; 2059 final boolean clearWhenTaskReset = 2060 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0; 2061 2062 if (!finishOnTaskLaunch 2063 && !clearWhenTaskReset 2064 && target.resultTo != null) { 2065 // If this activity is sending a reply to a previous 2066 // activity, we can't do anything with it now until 2067 // we reach the start of the reply chain. 2068 // XXX note that we are assuming the result is always 2069 // to the previous activity, which is almost always 2070 // the case but we really shouldn't count on. 2071 if (replyChainEnd < 0) { 2072 replyChainEnd = i; 2073 } 2074 } else if (!finishOnTaskLaunch 2075 && !clearWhenTaskReset 2076 && allowTaskReparenting 2077 && target.taskAffinity != null 2078 && !target.taskAffinity.equals(task.affinity)) { 2079 // If this activity has an affinity for another 2080 // task, then we need to move it out of here. We will 2081 // move it as far out of the way as possible, to the 2082 // bottom of the activity stack. This also keeps it 2083 // correctly ordered with any activities we previously 2084 // moved. 2085 final ThumbnailHolder newThumbHolder; 2086 final TaskRecord targetTask; 2087 final ActivityRecord bottom = 2088 !mTaskHistory.isEmpty() && !mTaskHistory.get(0).mActivities.isEmpty() ? 2089 mTaskHistory.get(0).mActivities.get(0) : null; 2090 if (bottom != null && target.taskAffinity != null 2091 && target.taskAffinity.equals(bottom.task.affinity)) { 2092 // If the activity currently at the bottom has the 2093 // same task affinity as the one we are moving, 2094 // then merge it into the same task. 2095 targetTask = bottom.task; 2096 newThumbHolder = bottom.thumbHolder == null ? targetTask : bottom.thumbHolder; 2097 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target 2098 + " out to bottom task " + bottom.task); 2099 } else { 2100 targetTask = createTaskRecord(mStackSupervisor.getNextTaskId(), target.info, 2101 null, null, null, false); 2102 newThumbHolder = targetTask; 2103 targetTask.affinityIntent = target.intent; 2104 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target 2105 + " out to new task " + target.task); 2106 } 2107 2108 target.thumbHolder = newThumbHolder; 2109 2110 final int targetTaskId = targetTask.taskId; 2111 mWindowManager.setAppGroupId(target.appToken, targetTaskId); 2112 2113 boolean noOptions = canMoveOptions; 2114 final int start = replyChainEnd < 0 ? i : replyChainEnd; 2115 for (int srcPos = start; srcPos >= i; --srcPos) { 2116 final ActivityRecord p = activities.get(srcPos); 2117 if (p.finishing) { 2118 continue; 2119 } 2120 2121 ThumbnailHolder curThumbHolder = p.thumbHolder; 2122 canMoveOptions = false; 2123 if (noOptions && topOptions == null) { 2124 topOptions = p.takeOptionsLocked(); 2125 if (topOptions != null) { 2126 noOptions = false; 2127 } 2128 } 2129 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task=" 2130 + task + " adding to task=" + targetTask 2131 + " Callers=" + Debug.getCallers(4)); 2132 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p 2133 + " out to target's task " + target.task); 2134 p.setTask(targetTask, curThumbHolder, false); 2135 targetTask.addActivityAtBottom(p); 2136 2137 mWindowManager.setAppGroupId(p.appToken, targetTaskId); 2138 } 2139 2140 mWindowManager.moveTaskToBottom(targetTaskId); 2141 if (VALIDATE_TOKENS) { 2142 validateAppTokensLocked(); 2143 } 2144 2145 replyChainEnd = -1; 2146 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) { 2147 // If the activity should just be removed -- either 2148 // because it asks for it, or the task should be 2149 // cleared -- then finish it and anything that is 2150 // part of its reply chain. 2151 int end; 2152 if (clearWhenTaskReset) { 2153 // In this case, we want to finish this activity 2154 // and everything above it, so be sneaky and pretend 2155 // like these are all in the reply chain. 2156 end = numActivities - 1; 2157 } else if (replyChainEnd < 0) { 2158 end = i; 2159 } else { 2160 end = replyChainEnd; 2161 } 2162 boolean noOptions = canMoveOptions; 2163 for (int srcPos = i; srcPos <= end; srcPos++) { 2164 ActivityRecord p = activities.get(srcPos); 2165 if (p.finishing) { 2166 continue; 2167 } 2168 canMoveOptions = false; 2169 if (noOptions && topOptions == null) { 2170 topOptions = p.takeOptionsLocked(); 2171 if (topOptions != null) { 2172 noOptions = false; 2173 } 2174 } 2175 if (DEBUG_TASKS) Slog.w(TAG, 2176 "resetTaskIntendedTask: calling finishActivity on " + p); 2177 if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) { 2178 end--; 2179 srcPos--; 2180 } 2181 } 2182 replyChainEnd = -1; 2183 } else { 2184 // If we were in the middle of a chain, well the 2185 // activity that started it all doesn't want anything 2186 // special, so leave it all as-is. 2187 replyChainEnd = -1; 2188 } 2189 } 2190 2191 return topOptions; 2192 } 2193 2194 /** 2195 * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given 2196 * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop. 2197 * @param affinityTask The task we are looking for an affinity to. 2198 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to. 2199 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked. 2200 * @param forceReset Flag passed in to resetTaskIfNeededLocked. 2201 */ 2202 private int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task, 2203 boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) { 2204 int replyChainEnd = -1; 2205 final int taskId = task.taskId; 2206 final String taskAffinity = task.affinity; 2207 2208 final ArrayList<ActivityRecord> activities = affinityTask.mActivities; 2209 final int numActivities = activities.size(); 2210 // Do not operate on the root Activity. 2211 for (int i = numActivities - 1; i > 0; --i) { 2212 ActivityRecord target = activities.get(i); 2213 2214 final int flags = target.info.flags; 2215 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; 2216 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; 2217 2218 if (target.resultTo != null) { 2219 // If this activity is sending a reply to a previous 2220 // activity, we can't do anything with it now until 2221 // we reach the start of the reply chain. 2222 // XXX note that we are assuming the result is always 2223 // to the previous activity, which is almost always 2224 // the case but we really shouldn't count on. 2225 if (replyChainEnd < 0) { 2226 replyChainEnd = i; 2227 } 2228 } else if (topTaskIsHigher 2229 && allowTaskReparenting 2230 && taskAffinity != null 2231 && taskAffinity.equals(target.taskAffinity)) { 2232 // This activity has an affinity for our task. Either remove it if we are 2233 // clearing or move it over to our task. Note that 2234 // we currently punt on the case where we are resetting a 2235 // task that is not at the top but who has activities above 2236 // with an affinity to it... this is really not a normal 2237 // case, and we will need to later pull that task to the front 2238 // and usually at that point we will do the reset and pick 2239 // up those remaining activities. (This only happens if 2240 // someone starts an activity in a new task from an activity 2241 // in a task that is not currently on top.) 2242 if (forceReset || finishOnTaskLaunch) { 2243 final int start = replyChainEnd >= 0 ? replyChainEnd : i; 2244 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i); 2245 for (int srcPos = start; srcPos >= i; --srcPos) { 2246 final ActivityRecord p = activities.get(srcPos); 2247 if (p.finishing) { 2248 continue; 2249 } 2250 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false); 2251 } 2252 } else { 2253 if (taskInsertionPoint < 0) { 2254 taskInsertionPoint = task.mActivities.size(); 2255 2256 } 2257 2258 final int start = replyChainEnd >= 0 ? replyChainEnd : i; 2259 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting from task=" + affinityTask + ":" 2260 + start + "-" + i + " to task=" + task + ":" + taskInsertionPoint); 2261 for (int srcPos = start; srcPos >= i; --srcPos) { 2262 final ActivityRecord p = activities.get(srcPos); 2263 p.setTask(task, null, false); 2264 task.addActivityAtIndex(taskInsertionPoint, p); 2265 2266 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p 2267 + " to stack at " + task, 2268 new RuntimeException("here").fillInStackTrace()); 2269 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos 2270 + " in to resetting task " + task); 2271 mWindowManager.setAppGroupId(p.appToken, taskId); 2272 } 2273 mWindowManager.moveTaskToTop(taskId); 2274 if (VALIDATE_TOKENS) { 2275 validateAppTokensLocked(); 2276 } 2277 2278 // Now we've moved it in to place... but what if this is 2279 // a singleTop activity and we have put it on top of another 2280 // instance of the same activity? Then we drop the instance 2281 // below so it remains singleTop. 2282 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { 2283 ArrayList<ActivityRecord> taskActivities = task.mActivities; 2284 int targetNdx = taskActivities.indexOf(target); 2285 if (targetNdx > 0) { 2286 ActivityRecord p = taskActivities.get(targetNdx - 1); 2287 if (p.intent.getComponent().equals(target.intent.getComponent())) { 2288 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace", 2289 false); 2290 } 2291 } 2292 } 2293 } 2294 2295 replyChainEnd = -1; 2296 } 2297 } 2298 return taskInsertionPoint; 2299 } 2300 2301 final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop, 2302 ActivityRecord newActivity) { 2303 boolean forceReset = 2304 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0; 2305 if (ACTIVITY_INACTIVE_RESET_TIME > 0 2306 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) { 2307 if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) { 2308 forceReset = true; 2309 } 2310 } 2311 2312 final TaskRecord task = taskTop.task; 2313 2314 /** False until we evaluate the TaskRecord associated with taskTop. Switches to true 2315 * for remaining tasks. Used for later tasks to reparent to task. */ 2316 boolean taskFound = false; 2317 2318 /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */ 2319 ActivityOptions topOptions = null; 2320 2321 // Preserve the location for reparenting in the new task. 2322 int reparentInsertionPoint = -1; 2323 2324 for (int i = mTaskHistory.size() - 1; i >= 0; --i) { 2325 final TaskRecord targetTask = mTaskHistory.get(i); 2326 2327 if (targetTask == task) { 2328 topOptions = resetTargetTaskIfNeededLocked(task, forceReset); 2329 taskFound = true; 2330 } else { 2331 reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task, 2332 taskFound, forceReset, reparentInsertionPoint); 2333 } 2334 } 2335 2336 int taskNdx = mTaskHistory.indexOf(task); 2337 do { 2338 taskTop = mTaskHistory.get(taskNdx--).getTopActivity(); 2339 } while (taskTop == null && taskNdx >= 0); 2340 2341 if (topOptions != null) { 2342 // If we got some ActivityOptions from an activity on top that 2343 // was removed from the task, propagate them to the new real top. 2344 if (taskTop != null) { 2345 taskTop.updateOptionsLocked(topOptions); 2346 } else { 2347 topOptions.abort(); 2348 } 2349 } 2350 2351 return taskTop; 2352 } 2353 2354 void sendActivityResultLocked(int callingUid, ActivityRecord r, 2355 String resultWho, int requestCode, int resultCode, Intent data) { 2356 2357 if (callingUid > 0) { 2358 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName, 2359 data, r.getUriPermissionsLocked(), r.userId); 2360 } 2361 2362 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r 2363 + " : who=" + resultWho + " req=" + requestCode 2364 + " res=" + resultCode + " data=" + data); 2365 if (mResumedActivity == r && r.app != null && r.app.thread != null) { 2366 try { 2367 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>(); 2368 list.add(new ResultInfo(resultWho, requestCode, 2369 resultCode, data)); 2370 r.app.thread.scheduleSendResult(r.appToken, list); 2371 return; 2372 } catch (Exception e) { 2373 Slog.w(TAG, "Exception thrown sending result to " + r, e); 2374 } 2375 } 2376 2377 r.addResultLocked(null, resultWho, requestCode, resultCode, data); 2378 } 2379 2380 private void adjustFocusedActivityLocked(ActivityRecord r) { 2381 if (mStackSupervisor.isFrontStack(this) && mService.mFocusedActivity == r) { 2382 ActivityRecord next = topRunningActivityLocked(null); 2383 if (next != r) { 2384 final TaskRecord task = r.task; 2385 if (r.frontOfTask && task == topTask() && task.mOnTopOfHome) { 2386 mStackSupervisor.moveHomeToTop(); 2387 } 2388 } 2389 ActivityRecord top = mStackSupervisor.topRunningActivityLocked(); 2390 if (top != null) { 2391 mService.setFocusedActivityLocked(top); 2392 } 2393 } 2394 } 2395 2396 final void stopActivityLocked(ActivityRecord r) { 2397 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r); 2398 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0 2399 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) { 2400 if (!r.finishing) { 2401 if (!mService.isSleeping()) { 2402 if (DEBUG_STATES) { 2403 Slog.d(TAG, "no-history finish of " + r); 2404 } 2405 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null, 2406 "no-history", false); 2407 } else { 2408 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r 2409 + " on stop because we're just sleeping"); 2410 } 2411 } 2412 } 2413 2414 if (r.app != null && r.app.thread != null) { 2415 adjustFocusedActivityLocked(r); 2416 r.resumeKeyDispatchingLocked(); 2417 try { 2418 r.stopped = false; 2419 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r 2420 + " (stop requested)"); 2421 r.state = ActivityState.STOPPING; 2422 if (DEBUG_VISBILITY) Slog.v( 2423 TAG, "Stopping visible=" + r.visible + " for " + r); 2424 if (!r.visible) { 2425 mWindowManager.setAppVisibility(r.appToken, false); 2426 } 2427 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags); 2428 if (mService.isSleepingOrShuttingDown()) { 2429 r.setSleeping(true); 2430 } 2431 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r); 2432 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT); 2433 } catch (Exception e) { 2434 // Maybe just ignore exceptions here... if the process 2435 // has crashed, our death notification will clean things 2436 // up. 2437 Slog.w(TAG, "Exception thrown during pause", e); 2438 // Just in case, assume it to be stopped. 2439 r.stopped = true; 2440 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r); 2441 r.state = ActivityState.STOPPED; 2442 if (r.configDestroy) { 2443 destroyActivityLocked(r, true, false, "stop-except"); 2444 } 2445 } 2446 } 2447 } 2448 2449 /** 2450 * @return Returns true if the activity is being finished, false if for 2451 * some reason it is being left as-is. 2452 */ 2453 final boolean requestFinishActivityLocked(IBinder token, int resultCode, 2454 Intent resultData, String reason, boolean oomAdj) { 2455 ActivityRecord r = isInStackLocked(token); 2456 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v( 2457 TAG, "Finishing activity token=" + token + " r=" 2458 + ", result=" + resultCode + ", data=" + resultData 2459 + ", reason=" + reason); 2460 if (r == null) { 2461 return false; 2462 } 2463 2464 finishActivityLocked(r, resultCode, resultData, reason, oomAdj); 2465 return true; 2466 } 2467 2468 final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) { 2469 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2470 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 2471 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2472 ActivityRecord r = activities.get(activityNdx); 2473 if (r.resultTo == self && r.requestCode == requestCode) { 2474 if ((r.resultWho == null && resultWho == null) || 2475 (r.resultWho != null && r.resultWho.equals(resultWho))) { 2476 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub", 2477 false); 2478 } 2479 } 2480 } 2481 } 2482 mService.updateOomAdjLocked(); 2483 } 2484 2485 final void finishTopRunningActivityLocked(ProcessRecord app) { 2486 ActivityRecord r = topRunningActivityLocked(null); 2487 if (r != null && r.app == app) { 2488 // If the top running activity is from this crashing 2489 // process, then terminate it to avoid getting in a loop. 2490 Slog.w(TAG, " Force finishing activity " 2491 + r.intent.getComponent().flattenToShortString()); 2492 int taskNdx = mTaskHistory.indexOf(r.task); 2493 int activityNdx = r.task.mActivities.indexOf(r); 2494 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false); 2495 // Also terminate any activities below it that aren't yet 2496 // stopped, to avoid a situation where one will get 2497 // re-start our crashing activity once it gets resumed again. 2498 --activityNdx; 2499 if (activityNdx < 0) { 2500 do { 2501 --taskNdx; 2502 if (taskNdx < 0) { 2503 break; 2504 } 2505 activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1; 2506 } while (activityNdx < 0); 2507 } 2508 if (activityNdx >= 0) { 2509 r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx); 2510 if (r.state == ActivityState.RESUMED 2511 || r.state == ActivityState.PAUSING 2512 || r.state == ActivityState.PAUSED) { 2513 if (!r.isHomeActivity() || mService.mHomeProcess != r.app) { 2514 Slog.w(TAG, " Force finishing activity " 2515 + r.intent.getComponent().flattenToShortString()); 2516 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false); 2517 } 2518 } 2519 } 2520 } 2521 } 2522 2523 final boolean finishActivityAffinityLocked(ActivityRecord r) { 2524 ArrayList<ActivityRecord> activities = r.task.mActivities; 2525 for (int index = activities.indexOf(r); index >= 0; --index) { 2526 ActivityRecord cur = activities.get(index); 2527 if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) { 2528 break; 2529 } 2530 finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true); 2531 } 2532 return true; 2533 } 2534 2535 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) { 2536 // send the result 2537 ActivityRecord resultTo = r.resultTo; 2538 if (resultTo != null) { 2539 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo 2540 + " who=" + r.resultWho + " req=" + r.requestCode 2541 + " res=" + resultCode + " data=" + resultData); 2542 if (resultTo.userId != r.userId) { 2543 if (resultData != null) { 2544 resultData.prepareToLeaveUser(r.userId); 2545 } 2546 } 2547 if (r.info.applicationInfo.uid > 0) { 2548 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid, 2549 resultTo.packageName, resultData, 2550 resultTo.getUriPermissionsLocked(), resultTo.userId); 2551 } 2552 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode, 2553 resultData); 2554 r.resultTo = null; 2555 } 2556 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r); 2557 2558 // Make sure this HistoryRecord is not holding on to other resources, 2559 // because clients have remote IPC references to this object so we 2560 // can't assume that will go away and want to avoid circular IPC refs. 2561 r.results = null; 2562 r.pendingResults = null; 2563 r.newIntents = null; 2564 r.icicle = null; 2565 } 2566 2567 /** 2568 * @return Returns true if this activity has been removed from the history 2569 * list, or false if it is still in the list and will be removed later. 2570 */ 2571 final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData, 2572 String reason, boolean oomAdj) { 2573 if (r.finishing) { 2574 Slog.w(TAG, "Duplicate finish request for " + r); 2575 return false; 2576 } 2577 2578 r.makeFinishing(); 2579 final TaskRecord task = r.task; 2580 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, 2581 r.userId, System.identityHashCode(r), 2582 task.taskId, r.shortComponentName, reason); 2583 final ArrayList<ActivityRecord> activities = task.mActivities; 2584 final int index = activities.indexOf(r); 2585 if (index < (activities.size() - 1)) { 2586 task.setFrontOfTask(); 2587 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) { 2588 // If the caller asked that this activity (and all above it) 2589 // be cleared when the task is reset, don't lose that information, 2590 // but propagate it up to the next activity. 2591 ActivityRecord next = activities.get(index+1); 2592 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 2593 } 2594 } 2595 2596 r.pauseKeyDispatchingLocked(); 2597 2598 adjustFocusedActivityLocked(r); 2599 2600 finishActivityResultsLocked(r, resultCode, resultData); 2601 2602 if (mResumedActivity == r) { 2603 boolean endTask = index <= 0; 2604 if (DEBUG_VISBILITY || DEBUG_TRANSITION) Slog.v(TAG, 2605 "Prepare close transition: finishing " + r); 2606 mWindowManager.prepareAppTransition(endTask 2607 ? AppTransition.TRANSIT_TASK_CLOSE 2608 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false); 2609 2610 // Tell window manager to prepare for this one to be removed. 2611 mWindowManager.setAppVisibility(r.appToken, false); 2612 2613 if (mPausingActivity == null) { 2614 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r); 2615 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false"); 2616 startPausingLocked(false, false); 2617 } 2618 2619 if (endTask) { 2620 mStackSupervisor.endLockTaskModeIfTaskEnding(task); 2621 } 2622 } else if (r.state != ActivityState.PAUSING) { 2623 // If the activity is PAUSING, we will complete the finish once 2624 // it is done pausing; else we can just directly finish it here. 2625 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r); 2626 return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null; 2627 } else { 2628 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r); 2629 } 2630 2631 return false; 2632 } 2633 2634 static final int FINISH_IMMEDIATELY = 0; 2635 static final int FINISH_AFTER_PAUSE = 1; 2636 static final int FINISH_AFTER_VISIBLE = 2; 2637 2638 final ActivityRecord finishCurrentActivityLocked(ActivityRecord r, int mode, boolean oomAdj) { 2639 // First things first: if this activity is currently visible, 2640 // and the resumed activity is not yet visible, then hold off on 2641 // finishing until the resumed one becomes visible. 2642 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) { 2643 if (!mStackSupervisor.mStoppingActivities.contains(r)) { 2644 mStackSupervisor.mStoppingActivities.add(r); 2645 if (mStackSupervisor.mStoppingActivities.size() > 3 2646 || r.frontOfTask && mTaskHistory.size() <= 1) { 2647 // If we already have a few activities waiting to stop, 2648 // then give up on things going idle and start clearing 2649 // them out. Or if r is the last of activity of the last task the stack 2650 // will be empty and must be cleared immediately. 2651 mStackSupervisor.scheduleIdleLocked(); 2652 } else { 2653 mStackSupervisor.checkReadyForSleepLocked(); 2654 } 2655 } 2656 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r 2657 + " (finish requested)"); 2658 r.state = ActivityState.STOPPING; 2659 if (oomAdj) { 2660 mService.updateOomAdjLocked(); 2661 } 2662 return r; 2663 } 2664 2665 // make sure the record is cleaned out of other places. 2666 mStackSupervisor.mStoppingActivities.remove(r); 2667 mStackSupervisor.mGoingToSleepActivities.remove(r); 2668 mStackSupervisor.mWaitingVisibleActivities.remove(r); 2669 if (mResumedActivity == r) { 2670 mResumedActivity = null; 2671 } 2672 final ActivityState prevState = r.state; 2673 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r); 2674 r.state = ActivityState.FINISHING; 2675 2676 if (mode == FINISH_IMMEDIATELY 2677 || prevState == ActivityState.STOPPED 2678 || prevState == ActivityState.INITIALIZING) { 2679 // If this activity is already stopped, we can just finish 2680 // it right now. 2681 r.makeFinishing(); 2682 boolean activityRemoved = destroyActivityLocked(r, true, oomAdj, "finish-imm"); 2683 if (activityRemoved) { 2684 mStackSupervisor.resumeTopActivitiesLocked(); 2685 } 2686 if (DEBUG_CONTAINERS) Slog.d(TAG, 2687 "destroyActivityLocked: finishCurrentActivityLocked r=" + r + 2688 " destroy returned removed=" + activityRemoved); 2689 return activityRemoved ? null : r; 2690 } 2691 2692 // Need to go through the full pause cycle to get this 2693 // activity into the stopped state and then finish it. 2694 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r); 2695 mStackSupervisor.mFinishingActivities.add(r); 2696 r.resumeKeyDispatchingLocked(); 2697 mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null); 2698 return r; 2699 } 2700 2701 void finishAllActivitiesLocked() { 2702 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2703 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 2704 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2705 final ActivityRecord r = activities.get(activityNdx); 2706 if (r.finishing) { 2707 continue; 2708 } 2709 Slog.d(TAG, "finishAllActivitiesLocked: finishing " + r); 2710 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false); 2711 } 2712 } 2713 } 2714 2715 final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode, 2716 Intent resultData) { 2717 final ActivityRecord srec = ActivityRecord.forToken(token); 2718 final TaskRecord task = srec.task; 2719 final ArrayList<ActivityRecord> activities = task.mActivities; 2720 final int start = activities.indexOf(srec); 2721 if (!mTaskHistory.contains(task) || (start < 0)) { 2722 return false; 2723 } 2724 int finishTo = start - 1; 2725 ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo); 2726 boolean foundParentInTask = false; 2727 final ComponentName dest = destIntent.getComponent(); 2728 if (start > 0 && dest != null) { 2729 for (int i = finishTo; i >= 0; i--) { 2730 ActivityRecord r = activities.get(i); 2731 if (r.info.packageName.equals(dest.getPackageName()) && 2732 r.info.name.equals(dest.getClassName())) { 2733 finishTo = i; 2734 parent = r; 2735 foundParentInTask = true; 2736 break; 2737 } 2738 } 2739 } 2740 2741 IActivityController controller = mService.mController; 2742 if (controller != null) { 2743 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0); 2744 if (next != null) { 2745 // ask watcher if this is allowed 2746 boolean resumeOK = true; 2747 try { 2748 resumeOK = controller.activityResuming(next.packageName); 2749 } catch (RemoteException e) { 2750 mService.mController = null; 2751 Watchdog.getInstance().setActivityController(null); 2752 } 2753 2754 if (!resumeOK) { 2755 return false; 2756 } 2757 } 2758 } 2759 final long origId = Binder.clearCallingIdentity(); 2760 for (int i = start; i > finishTo; i--) { 2761 ActivityRecord r = activities.get(i); 2762 requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true); 2763 // Only return the supplied result for the first activity finished 2764 resultCode = Activity.RESULT_CANCELED; 2765 resultData = null; 2766 } 2767 2768 if (parent != null && foundParentInTask) { 2769 final int parentLaunchMode = parent.info.launchMode; 2770 final int destIntentFlags = destIntent.getFlags(); 2771 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE || 2772 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK || 2773 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP || 2774 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) { 2775 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent); 2776 } else { 2777 try { 2778 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo( 2779 destIntent.getComponent(), 0, srec.userId); 2780 int res = mStackSupervisor.startActivityLocked(srec.app.thread, destIntent, 2781 null, aInfo, null, null, parent.appToken, null, 2782 0, -1, parent.launchedFromUid, parent.launchedFromPackage, 2783 0, null, true, null, null); 2784 foundParentInTask = res == ActivityManager.START_SUCCESS; 2785 } catch (RemoteException e) { 2786 foundParentInTask = false; 2787 } 2788 requestFinishActivityLocked(parent.appToken, resultCode, 2789 resultData, "navigate-up", true); 2790 } 2791 } 2792 Binder.restoreCallingIdentity(origId); 2793 return foundParentInTask; 2794 } 2795 /** 2796 * Perform the common clean-up of an activity record. This is called both 2797 * as part of destroyActivityLocked() (when destroying the client-side 2798 * representation) and cleaning things up as a result of its hosting 2799 * processing going away, in which case there is no remaining client-side 2800 * state to destroy so only the cleanup here is needed. 2801 */ 2802 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices, 2803 boolean setState) { 2804 if (mResumedActivity == r) { 2805 mResumedActivity = null; 2806 } 2807 if (mPausingActivity == r) { 2808 mPausingActivity = null; 2809 } 2810 mService.clearFocusedActivity(r); 2811 2812 r.configDestroy = false; 2813 r.frozenBeforeDestroy = false; 2814 2815 if (setState) { 2816 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)"); 2817 r.state = ActivityState.DESTROYED; 2818 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r); 2819 r.app = null; 2820 } 2821 2822 // Make sure this record is no longer in the pending finishes list. 2823 // This could happen, for example, if we are trimming activities 2824 // down to the max limit while they are still waiting to finish. 2825 mStackSupervisor.mFinishingActivities.remove(r); 2826 mStackSupervisor.mWaitingVisibleActivities.remove(r); 2827 2828 // Remove any pending results. 2829 if (r.finishing && r.pendingResults != null) { 2830 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) { 2831 PendingIntentRecord rec = apr.get(); 2832 if (rec != null) { 2833 mService.cancelIntentSenderLocked(rec, false); 2834 } 2835 } 2836 r.pendingResults = null; 2837 } 2838 2839 if (cleanServices) { 2840 cleanUpActivityServicesLocked(r); 2841 } 2842 2843 // Get rid of any pending idle timeouts. 2844 removeTimeoutsForActivityLocked(r); 2845 } 2846 2847 private void removeTimeoutsForActivityLocked(ActivityRecord r) { 2848 mStackSupervisor.removeTimeoutsForActivityLocked(r); 2849 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 2850 mHandler.removeMessages(STOP_TIMEOUT_MSG, r); 2851 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r); 2852 r.finishLaunchTickingLocked(); 2853 } 2854 2855 private void removeActivityFromHistoryLocked(ActivityRecord r) { 2856 mStackSupervisor.removeChildActivityContainers(r); 2857 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null); 2858 r.makeFinishing(); 2859 if (DEBUG_ADD_REMOVE) { 2860 RuntimeException here = new RuntimeException("here"); 2861 here.fillInStackTrace(); 2862 Slog.i(TAG, "Removing activity " + r + " from stack"); 2863 } 2864 r.takeFromHistory(); 2865 removeTimeoutsForActivityLocked(r); 2866 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)"); 2867 r.state = ActivityState.DESTROYED; 2868 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r); 2869 r.app = null; 2870 mWindowManager.removeAppToken(r.appToken); 2871 if (VALIDATE_TOKENS) { 2872 validateAppTokensLocked(); 2873 } 2874 final TaskRecord task = r.task; 2875 if (task != null && task.removeActivity(r)) { 2876 if (DEBUG_STACK) Slog.i(TAG, 2877 "removeActivityFromHistoryLocked: last activity removed from " + this); 2878 if (mStackSupervisor.isFrontStack(this) && task == topTask() && task.mOnTopOfHome) { 2879 mStackSupervisor.moveHomeToTop(); 2880 } 2881 removeTask(task); 2882 } 2883 cleanUpActivityServicesLocked(r); 2884 r.removeUriPermissionsLocked(); 2885 } 2886 2887 /** 2888 * Perform clean-up of service connections in an activity record. 2889 */ 2890 final void cleanUpActivityServicesLocked(ActivityRecord r) { 2891 // Throw away any services that have been bound by this activity. 2892 if (r.connections != null) { 2893 Iterator<ConnectionRecord> it = r.connections.iterator(); 2894 while (it.hasNext()) { 2895 ConnectionRecord c = it.next(); 2896 mService.mServices.removeConnectionLocked(c, null, r); 2897 } 2898 r.connections = null; 2899 } 2900 } 2901 2902 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) { 2903 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG); 2904 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason); 2905 mHandler.sendMessage(msg); 2906 } 2907 2908 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) { 2909 boolean lastIsOpaque = false; 2910 boolean activityRemoved = false; 2911 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 2912 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 2913 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 2914 final ActivityRecord r = activities.get(activityNdx); 2915 if (r.finishing) { 2916 continue; 2917 } 2918 if (r.fullscreen) { 2919 lastIsOpaque = true; 2920 } 2921 if (owner != null && r.app != owner) { 2922 continue; 2923 } 2924 if (!lastIsOpaque) { 2925 continue; 2926 } 2927 // We can destroy this one if we have its icicle saved and 2928 // it is not in the process of pausing/stopping/finishing. 2929 if (r.app != null && r != mResumedActivity && r != mPausingActivity 2930 && r.haveState && !r.visible && r.stopped 2931 && r.state != ActivityState.DESTROYING 2932 && r.state != ActivityState.DESTROYED) { 2933 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state 2934 + " resumed=" + mResumedActivity 2935 + " pausing=" + mPausingActivity); 2936 if (destroyActivityLocked(r, true, oomAdj, reason)) { 2937 activityRemoved = true; 2938 } 2939 } 2940 } 2941 } 2942 if (activityRemoved) { 2943 mStackSupervisor.resumeTopActivitiesLocked(); 2944 } 2945 } 2946 2947 /** 2948 * Destroy the current CLIENT SIDE instance of an activity. This may be 2949 * called both when actually finishing an activity, or when performing 2950 * a configuration switch where we destroy the current client-side object 2951 * but then create a new client-side object for this same HistoryRecord. 2952 */ 2953 final boolean destroyActivityLocked(ActivityRecord r, 2954 boolean removeFromApp, boolean oomAdj, String reason) { 2955 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v( 2956 TAG, "Removing activity from " + reason + ": token=" + r 2957 + ", app=" + (r.app != null ? r.app.processName : "(null)")); 2958 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY, 2959 r.userId, System.identityHashCode(r), 2960 r.task.taskId, r.shortComponentName, reason); 2961 2962 boolean removedFromHistory = false; 2963 2964 cleanUpActivityLocked(r, false, false); 2965 2966 final boolean hadApp = r.app != null; 2967 2968 if (hadApp) { 2969 if (removeFromApp) { 2970 r.app.activities.remove(r); 2971 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) { 2972 mService.mHeavyWeightProcess = null; 2973 mService.mHandler.sendEmptyMessage( 2974 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG); 2975 } 2976 if (r.app.activities.isEmpty()) { 2977 // No longer have activities, so update LRU list and oom adj. 2978 mService.updateLruProcessLocked(r.app, false, null); 2979 mService.updateOomAdjLocked(); 2980 } 2981 } 2982 2983 boolean skipDestroy = false; 2984 2985 try { 2986 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r); 2987 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing, 2988 r.configChangeFlags); 2989 } catch (Exception e) { 2990 // We can just ignore exceptions here... if the process 2991 // has crashed, our death notification will clean things 2992 // up. 2993 //Slog.w(TAG, "Exception thrown during finish", e); 2994 if (r.finishing) { 2995 removeActivityFromHistoryLocked(r); 2996 removedFromHistory = true; 2997 skipDestroy = true; 2998 } 2999 } 3000 3001 r.nowVisible = false; 3002 3003 // If the activity is finishing, we need to wait on removing it 3004 // from the list to give it a chance to do its cleanup. During 3005 // that time it may make calls back with its token so we need to 3006 // be able to find it on the list and so we don't want to remove 3007 // it from the list yet. Otherwise, we can just immediately put 3008 // it in the destroyed state since we are not removing it from the 3009 // list. 3010 if (r.finishing && !skipDestroy) { 3011 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r 3012 + " (destroy requested)"); 3013 r.state = ActivityState.DESTROYING; 3014 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r); 3015 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT); 3016 } else { 3017 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (destroy skipped)"); 3018 r.state = ActivityState.DESTROYED; 3019 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r); 3020 r.app = null; 3021 } 3022 } else { 3023 // remove this record from the history. 3024 if (r.finishing) { 3025 removeActivityFromHistoryLocked(r); 3026 removedFromHistory = true; 3027 } else { 3028 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (no app)"); 3029 r.state = ActivityState.DESTROYED; 3030 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r); 3031 r.app = null; 3032 } 3033 } 3034 3035 r.configChangeFlags = 0; 3036 3037 if (!mLRUActivities.remove(r) && hadApp) { 3038 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list"); 3039 } 3040 3041 return removedFromHistory; 3042 } 3043 3044 final void activityDestroyedLocked(IBinder token) { 3045 final long origId = Binder.clearCallingIdentity(); 3046 try { 3047 ActivityRecord r = ActivityRecord.forToken(token); 3048 if (r != null) { 3049 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r); 3050 } 3051 if (DEBUG_CONTAINERS) Slog.d(TAG, "activityDestroyedLocked: r=" + r); 3052 3053 if (isInStackLocked(token) != null) { 3054 if (r.state == ActivityState.DESTROYING) { 3055 cleanUpActivityLocked(r, true, false); 3056 removeActivityFromHistoryLocked(r); 3057 } 3058 } 3059 mStackSupervisor.resumeTopActivitiesLocked(); 3060 } finally { 3061 Binder.restoreCallingIdentity(origId); 3062 } 3063 } 3064 3065 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list, 3066 ProcessRecord app, String listName) { 3067 int i = list.size(); 3068 if (DEBUG_CLEANUP) Slog.v( 3069 TAG, "Removing app " + app + " from list " + listName 3070 + " with " + i + " entries"); 3071 while (i > 0) { 3072 i--; 3073 ActivityRecord r = list.get(i); 3074 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r); 3075 if (r.app == app) { 3076 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!"); 3077 list.remove(i); 3078 removeTimeoutsForActivityLocked(r); 3079 } 3080 } 3081 } 3082 3083 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) { 3084 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities"); 3085 removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app, 3086 "mStoppingActivities"); 3087 removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app, 3088 "mGoingToSleepActivities"); 3089 removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app, 3090 "mWaitingVisibleActivities"); 3091 removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app, 3092 "mFinishingActivities"); 3093 3094 boolean hasVisibleActivities = false; 3095 3096 // Clean out the history list. 3097 int i = numActivities(); 3098 if (DEBUG_CLEANUP) Slog.v( 3099 TAG, "Removing app " + app + " from history with " + i + " entries"); 3100 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3101 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3102 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3103 final ActivityRecord r = activities.get(activityNdx); 3104 --i; 3105 if (DEBUG_CLEANUP) Slog.v( 3106 TAG, "Record #" + i + " " + r + ": app=" + r.app); 3107 if (r.app == app) { 3108 boolean remove; 3109 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) { 3110 // Don't currently have state for the activity, or 3111 // it is finishing -- always remove it. 3112 remove = true; 3113 } else if (r.launchCount > 2 && 3114 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) { 3115 // We have launched this activity too many times since it was 3116 // able to run, so give up and remove it. 3117 remove = true; 3118 } else { 3119 // The process may be gone, but the activity lives on! 3120 remove = false; 3121 } 3122 if (remove) { 3123 if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) { 3124 RuntimeException here = new RuntimeException("here"); 3125 here.fillInStackTrace(); 3126 Slog.i(TAG, "Removing activity " + r + " from stack at " + i 3127 + ": haveState=" + r.haveState 3128 + " stateNotNeeded=" + r.stateNotNeeded 3129 + " finishing=" + r.finishing 3130 + " state=" + r.state, here); 3131 } 3132 if (!r.finishing) { 3133 Slog.w(TAG, "Force removing " + r + ": app died, no saved state"); 3134 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, 3135 r.userId, System.identityHashCode(r), 3136 r.task.taskId, r.shortComponentName, 3137 "proc died without state saved"); 3138 if (r.state == ActivityState.RESUMED) { 3139 mService.updateUsageStats(r, false); 3140 } 3141 } 3142 removeActivityFromHistoryLocked(r); 3143 3144 } else { 3145 // We have the current state for this activity, so 3146 // it can be restarted later when needed. 3147 if (localLOGV) Slog.v( 3148 TAG, "Keeping entry, setting app to null"); 3149 if (r.visible) { 3150 hasVisibleActivities = true; 3151 } 3152 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity " 3153 + r); 3154 r.app = null; 3155 r.nowVisible = false; 3156 if (!r.haveState) { 3157 if (DEBUG_SAVED_STATE) Slog.i(TAG, 3158 "App died, clearing saved state of " + r); 3159 r.icicle = null; 3160 } 3161 } 3162 3163 cleanUpActivityLocked(r, true, true); 3164 } 3165 } 3166 } 3167 3168 return hasVisibleActivities; 3169 } 3170 3171 final void updateTransitLocked(int transit, Bundle options) { 3172 if (options != null) { 3173 ActivityRecord r = topRunningActivityLocked(null); 3174 if (r != null && r.state != ActivityState.RESUMED) { 3175 r.updateOptionsLocked(options); 3176 } else { 3177 ActivityOptions.abort(options); 3178 } 3179 } 3180 mWindowManager.prepareAppTransition(transit, false); 3181 } 3182 3183 void updateTaskMovement(TaskRecord task, boolean toFront) { 3184 if (task.isPersistable) { 3185 task.mLastTimeMoved = System.currentTimeMillis(); 3186 // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most 3187 // recently will be most negative, tasks sent to the bottom before that will be less 3188 // negative. Similarly for recent tasks moved to the top which will be most positive. 3189 if (!toFront) { 3190 task.mLastTimeMoved *= -1; 3191 } 3192 } 3193 } 3194 3195 void moveHomeTaskToTop() { 3196 final int top = mTaskHistory.size() - 1; 3197 for (int taskNdx = top; taskNdx >= 0; --taskNdx) { 3198 final TaskRecord task = mTaskHistory.get(taskNdx); 3199 if (task.isHomeTask()) { 3200 if (DEBUG_TASKS || DEBUG_STACK) Slog.d(TAG, "moveHomeTaskToTop: moving " + task); 3201 mTaskHistory.remove(taskNdx); 3202 mTaskHistory.add(top, task); 3203 updateTaskMovement(task, true); 3204 mWindowManager.moveTaskToTop(task.taskId); 3205 return; 3206 } 3207 } 3208 } 3209 3210 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) { 3211 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr); 3212 3213 final int numTasks = mTaskHistory.size(); 3214 final int index = mTaskHistory.indexOf(tr); 3215 if (numTasks == 0 || index < 0) { 3216 // nothing to do! 3217 if (reason != null && 3218 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 3219 ActivityOptions.abort(options); 3220 } else { 3221 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options); 3222 } 3223 return; 3224 } 3225 3226 moveToFront(); 3227 3228 // Shift all activities with this task up to the top 3229 // of the stack, keeping them in the same internal order. 3230 insertTaskAtTop(tr); 3231 3232 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr); 3233 if (reason != null && 3234 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 3235 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 3236 ActivityRecord r = topRunningActivityLocked(null); 3237 if (r != null) { 3238 mNoAnimActivities.add(r); 3239 } 3240 ActivityOptions.abort(options); 3241 } else { 3242 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options); 3243 } 3244 3245 mWindowManager.moveTaskToTop(tr.taskId); 3246 3247 mStackSupervisor.resumeTopActivitiesLocked(); 3248 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId); 3249 3250 if (VALIDATE_TOKENS) { 3251 validateAppTokensLocked(); 3252 } 3253 } 3254 3255 /** 3256 * Worker method for rearranging history stack. Implements the function of moving all 3257 * activities for a specific task (gathering them if disjoint) into a single group at the 3258 * bottom of the stack. 3259 * 3260 * If a watcher is installed, the action is preflighted and the watcher has an opportunity 3261 * to premeptively cancel the move. 3262 * 3263 * @param taskId The taskId to collect and move to the bottom. 3264 * @return Returns true if the move completed, false if not. 3265 */ 3266 final boolean moveTaskToBackLocked(int taskId, ActivityRecord reason) { 3267 final TaskRecord tr = taskForIdLocked(taskId); 3268 if (tr == null) { 3269 Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId); 3270 return false; 3271 } 3272 3273 Slog.i(TAG, "moveTaskToBack: " + tr); 3274 3275 mStackSupervisor.endLockTaskModeIfTaskEnding(tr); 3276 3277 // If we have a watcher, preflight the move before committing to it. First check 3278 // for *other* available tasks, but if none are available, then try again allowing the 3279 // current task to be selected. 3280 if (mStackSupervisor.isFrontStack(this) && mService.mController != null) { 3281 ActivityRecord next = topRunningActivityLocked(null, taskId); 3282 if (next == null) { 3283 next = topRunningActivityLocked(null, 0); 3284 } 3285 if (next != null) { 3286 // ask watcher if this is allowed 3287 boolean moveOK = true; 3288 try { 3289 moveOK = mService.mController.activityResuming(next.packageName); 3290 } catch (RemoteException e) { 3291 mService.mController = null; 3292 Watchdog.getInstance().setActivityController(null); 3293 } 3294 if (!moveOK) { 3295 return false; 3296 } 3297 } 3298 } 3299 3300 if (DEBUG_TRANSITION) Slog.v(TAG, 3301 "Prepare to back transition: task=" + taskId); 3302 3303 mTaskHistory.remove(tr); 3304 mTaskHistory.add(0, tr); 3305 updateTaskMovement(tr, false); 3306 3307 // There is an assumption that moving a task to the back moves it behind the home activity. 3308 // We make sure here that some activity in the stack will launch home. 3309 int numTasks = mTaskHistory.size(); 3310 for (int taskNdx = numTasks - 1; taskNdx >= 1; --taskNdx) { 3311 final TaskRecord task = mTaskHistory.get(taskNdx); 3312 if (task.mOnTopOfHome) { 3313 break; 3314 } 3315 if (taskNdx == 1) { 3316 // Set the last task before tr to go to home. 3317 task.mOnTopOfHome = true; 3318 } 3319 } 3320 3321 if (reason != null && 3322 (reason.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { 3323 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); 3324 ActivityRecord r = topRunningActivityLocked(null); 3325 if (r != null) { 3326 mNoAnimActivities.add(r); 3327 } 3328 } else { 3329 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_TASK_TO_BACK, false); 3330 } 3331 mWindowManager.moveTaskToBottom(taskId); 3332 3333 if (VALIDATE_TOKENS) { 3334 validateAppTokensLocked(); 3335 } 3336 3337 final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null; 3338 if (task == tr && tr.mOnTopOfHome || numTasks <= 1 && isOnHomeDisplay()) { 3339 tr.mOnTopOfHome = false; 3340 return mStackSupervisor.resumeHomeActivity(null); 3341 } 3342 3343 mStackSupervisor.resumeTopActivitiesLocked(); 3344 return true; 3345 } 3346 3347 static final void logStartActivity(int tag, ActivityRecord r, 3348 TaskRecord task) { 3349 final Uri data = r.intent.getData(); 3350 final String strData = data != null ? data.toSafeString() : null; 3351 3352 EventLog.writeEvent(tag, 3353 r.userId, System.identityHashCode(r), task.taskId, 3354 r.shortComponentName, r.intent.getAction(), 3355 r.intent.getType(), strData, r.intent.getFlags()); 3356 } 3357 3358 /** 3359 * Make sure the given activity matches the current configuration. Returns 3360 * false if the activity had to be destroyed. Returns true if the 3361 * configuration is the same, or the activity will remain running as-is 3362 * for whatever reason. Ensures the HistoryRecord is updated with the 3363 * correct configuration and all other bookkeeping is handled. 3364 */ 3365 final boolean ensureActivityConfigurationLocked(ActivityRecord r, 3366 int globalChanges) { 3367 if (mConfigWillChange) { 3368 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3369 "Skipping config check (will change): " + r); 3370 return true; 3371 } 3372 3373 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3374 "Ensuring correct configuration: " + r); 3375 3376 // Short circuit: if the two configurations are the exact same 3377 // object (the common case), then there is nothing to do. 3378 Configuration newConfig = mService.mConfiguration; 3379 if (r.configuration == newConfig && !r.forceNewConfig) { 3380 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3381 "Configuration unchanged in " + r); 3382 return true; 3383 } 3384 3385 // We don't worry about activities that are finishing. 3386 if (r.finishing) { 3387 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3388 "Configuration doesn't matter in finishing " + r); 3389 r.stopFreezingScreenLocked(false); 3390 return true; 3391 } 3392 3393 // Okay we now are going to make this activity have the new config. 3394 // But then we need to figure out how it needs to deal with that. 3395 Configuration oldConfig = r.configuration; 3396 r.configuration = newConfig; 3397 3398 // Determine what has changed. May be nothing, if this is a config 3399 // that has come back from the app after going idle. In that case 3400 // we just want to leave the official config object now in the 3401 // activity and do nothing else. 3402 final int changes = oldConfig.diff(newConfig); 3403 if (changes == 0 && !r.forceNewConfig) { 3404 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3405 "Configuration no differences in " + r); 3406 return true; 3407 } 3408 3409 // If the activity isn't currently running, just leave the new 3410 // configuration and it will pick that up next time it starts. 3411 if (r.app == null || r.app.thread == null) { 3412 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3413 "Configuration doesn't matter not running " + r); 3414 r.stopFreezingScreenLocked(false); 3415 r.forceNewConfig = false; 3416 return true; 3417 } 3418 3419 // Figure out how to handle the changes between the configurations. 3420 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) { 3421 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x" 3422 + Integer.toHexString(changes) + ", handles=0x" 3423 + Integer.toHexString(r.info.getRealConfigChanged()) 3424 + ", newConfig=" + newConfig); 3425 } 3426 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) { 3427 // Aha, the activity isn't handling the change, so DIE DIE DIE. 3428 r.configChangeFlags |= changes; 3429 r.startFreezingScreenLocked(r.app, globalChanges); 3430 r.forceNewConfig = false; 3431 if (r.app == null || r.app.thread == null) { 3432 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3433 "Config is destroying non-running " + r); 3434 destroyActivityLocked(r, true, false, "config"); 3435 } else if (r.state == ActivityState.PAUSING) { 3436 // A little annoying: we are waiting for this activity to 3437 // finish pausing. Let's not do anything now, but just 3438 // flag that it needs to be restarted when done pausing. 3439 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3440 "Config is skipping already pausing " + r); 3441 r.configDestroy = true; 3442 return true; 3443 } else if (r.state == ActivityState.RESUMED) { 3444 // Try to optimize this case: the configuration is changing 3445 // and we need to restart the top, resumed activity. 3446 // Instead of doing the normal handshaking, just say 3447 // "restart!". 3448 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3449 "Config is relaunching resumed " + r); 3450 relaunchActivityLocked(r, r.configChangeFlags, true); 3451 r.configChangeFlags = 0; 3452 } else { 3453 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG, 3454 "Config is relaunching non-resumed " + r); 3455 relaunchActivityLocked(r, r.configChangeFlags, false); 3456 r.configChangeFlags = 0; 3457 } 3458 3459 // All done... tell the caller we weren't able to keep this 3460 // activity around. 3461 return false; 3462 } 3463 3464 // Default case: the activity can handle this new configuration, so 3465 // hand it over. Note that we don't need to give it the new 3466 // configuration, since we always send configuration changes to all 3467 // process when they happen so it can just use whatever configuration 3468 // it last got. 3469 if (r.app != null && r.app.thread != null) { 3470 try { 3471 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r); 3472 r.app.thread.scheduleActivityConfigurationChanged(r.appToken); 3473 } catch (RemoteException e) { 3474 // If process died, whatever. 3475 } 3476 } 3477 r.stopFreezingScreenLocked(false); 3478 3479 return true; 3480 } 3481 3482 private boolean relaunchActivityLocked(ActivityRecord r, 3483 int changes, boolean andResume) { 3484 List<ResultInfo> results = null; 3485 List<Intent> newIntents = null; 3486 if (andResume) { 3487 results = r.results; 3488 newIntents = r.newIntents; 3489 } 3490 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r 3491 + " with results=" + results + " newIntents=" + newIntents 3492 + " andResume=" + andResume); 3493 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY 3494 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r), 3495 r.task.taskId, r.shortComponentName); 3496 3497 r.startFreezingScreenLocked(r.app, 0); 3498 3499 mStackSupervisor.removeChildActivityContainers(r); 3500 3501 try { 3502 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, 3503 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ") 3504 + r); 3505 r.forceNewConfig = false; 3506 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents, 3507 changes, !andResume, new Configuration(mService.mConfiguration)); 3508 // Note: don't need to call pauseIfSleepingLocked() here, because 3509 // the caller will only pass in 'andResume' if this activity is 3510 // currently resumed, which implies we aren't sleeping. 3511 } catch (RemoteException e) { 3512 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e); 3513 } 3514 3515 if (andResume) { 3516 r.results = null; 3517 r.newIntents = null; 3518 r.state = ActivityState.RESUMED; 3519 } else { 3520 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); 3521 r.state = ActivityState.PAUSED; 3522 } 3523 3524 return true; 3525 } 3526 3527 boolean willActivityBeVisibleLocked(IBinder token) { 3528 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3529 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3530 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3531 final ActivityRecord r = activities.get(activityNdx); 3532 if (r.appToken == token) { 3533 return true; 3534 } 3535 if (r.fullscreen && !r.finishing) { 3536 return false; 3537 } 3538 } 3539 } 3540 final ActivityRecord r = ActivityRecord.forToken(token); 3541 if (r == null) { 3542 return false; 3543 } 3544 if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false," 3545 + " would have returned true for r=" + r); 3546 return !r.finishing; 3547 } 3548 3549 void closeSystemDialogsLocked() { 3550 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3551 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3552 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3553 final ActivityRecord r = activities.get(activityNdx); 3554 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) { 3555 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true); 3556 } 3557 } 3558 } 3559 } 3560 3561 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) { 3562 boolean didSomething = false; 3563 TaskRecord lastTask = null; 3564 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3565 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3566 int numActivities = activities.size(); 3567 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) { 3568 ActivityRecord r = activities.get(activityNdx); 3569 final boolean samePackage = r.packageName.equals(name) 3570 || (name == null && r.userId == userId); 3571 if ((userId == UserHandle.USER_ALL || r.userId == userId) 3572 && (samePackage || r.task == lastTask) 3573 && (r.app == null || evenPersistent || !r.app.persistent)) { 3574 if (!doit) { 3575 if (r.finishing) { 3576 // If this activity is just finishing, then it is not 3577 // interesting as far as something to stop. 3578 continue; 3579 } 3580 return true; 3581 } 3582 didSomething = true; 3583 Slog.i(TAG, " Force finishing activity " + r); 3584 if (samePackage) { 3585 if (r.app != null) { 3586 r.app.removed = true; 3587 } 3588 r.app = null; 3589 } 3590 lastTask = r.task; 3591 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop", 3592 true)) { 3593 // r has been deleted from mActivities, accommodate. 3594 --numActivities; 3595 --activityNdx; 3596 } 3597 } 3598 } 3599 } 3600 return didSomething; 3601 } 3602 3603 void getTasksLocked(List<RunningTaskInfo> list, int callingUid, boolean allowed) { 3604 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3605 final TaskRecord task = mTaskHistory.get(taskNdx); 3606 ActivityRecord r = null; 3607 ActivityRecord top = null; 3608 int numActivities = 0; 3609 int numRunning = 0; 3610 final ArrayList<ActivityRecord> activities = task.mActivities; 3611 if (activities.isEmpty()) { 3612 continue; 3613 } 3614 if (!allowed && !task.isHomeTask() && task.creatorUid != callingUid) { 3615 continue; 3616 } 3617 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3618 r = activities.get(activityNdx); 3619 3620 // Initialize state for next task if needed. 3621 if (top == null || (top.state == ActivityState.INITIALIZING)) { 3622 top = r; 3623 numActivities = numRunning = 0; 3624 } 3625 3626 // Add 'r' into the current task. 3627 numActivities++; 3628 if (r.app != null && r.app.thread != null) { 3629 numRunning++; 3630 } 3631 3632 if (localLOGV) Slog.v( 3633 TAG, r.intent.getComponent().flattenToShortString() 3634 + ": task=" + r.task); 3635 } 3636 3637 RunningTaskInfo ci = new RunningTaskInfo(); 3638 ci.id = task.taskId; 3639 ci.baseActivity = r.intent.getComponent(); 3640 ci.topActivity = top.intent.getComponent(); 3641 ci.lastActiveTime = task.lastActiveTime; 3642 3643 if (top.thumbHolder != null) { 3644 ci.description = top.thumbHolder.lastDescription; 3645 } 3646 ci.numActivities = numActivities; 3647 ci.numRunning = numRunning; 3648 //System.out.println( 3649 // "#" + maxNum + ": " + " descr=" + ci.description); 3650 list.add(ci); 3651 } 3652 } 3653 3654 public void unhandledBackLocked() { 3655 final int top = mTaskHistory.size() - 1; 3656 if (DEBUG_SWITCH) Slog.d( 3657 TAG, "Performing unhandledBack(): top activity at " + top); 3658 if (top >= 0) { 3659 final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities; 3660 int activityTop = activities.size() - 1; 3661 if (activityTop > 0) { 3662 finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null, 3663 "unhandled-back", true); 3664 } 3665 } 3666 } 3667 3668 /** 3669 * Reset local parameters because an app's activity died. 3670 * @param app The app of the activity that died. 3671 * @return result from removeHistoryRecordsForAppLocked. 3672 */ 3673 boolean handleAppDiedLocked(ProcessRecord app) { 3674 if (mPausingActivity != null && mPausingActivity.app == app) { 3675 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG, 3676 "App died while pausing: " + mPausingActivity); 3677 mPausingActivity = null; 3678 } 3679 if (mLastPausedActivity != null && mLastPausedActivity.app == app) { 3680 mLastPausedActivity = null; 3681 mLastNoHistoryActivity = null; 3682 } 3683 3684 return removeHistoryRecordsForAppLocked(app); 3685 } 3686 3687 void handleAppCrashLocked(ProcessRecord app) { 3688 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3689 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3690 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3691 final ActivityRecord r = activities.get(activityNdx); 3692 if (r.app == app) { 3693 Slog.w(TAG, " Force finishing activity " 3694 + r.intent.getComponent().flattenToShortString()); 3695 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false); 3696 } 3697 } 3698 } 3699 } 3700 3701 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll, 3702 boolean dumpClient, String dumpPackage, boolean needSep, String header) { 3703 boolean printed = false; 3704 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3705 final TaskRecord task = mTaskHistory.get(taskNdx); 3706 printed |= ActivityStackSupervisor.dumpHistoryList(fd, pw, 3707 mTaskHistory.get(taskNdx).mActivities, " ", "Hist", true, !dumpAll, 3708 dumpClient, dumpPackage, needSep, header, 3709 " Task id #" + task.taskId); 3710 if (printed) { 3711 header = null; 3712 } 3713 } 3714 return printed; 3715 } 3716 3717 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) { 3718 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(); 3719 3720 if ("all".equals(name)) { 3721 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3722 activities.addAll(mTaskHistory.get(taskNdx).mActivities); 3723 } 3724 } else if ("top".equals(name)) { 3725 final int top = mTaskHistory.size() - 1; 3726 if (top >= 0) { 3727 final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities; 3728 int listTop = list.size() - 1; 3729 if (listTop >= 0) { 3730 activities.add(list.get(listTop)); 3731 } 3732 } 3733 } else { 3734 ItemMatcher matcher = new ItemMatcher(); 3735 matcher.build(name); 3736 3737 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3738 for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) { 3739 if (matcher.match(r1, r1.intent.getComponent())) { 3740 activities.add(r1); 3741 } 3742 } 3743 } 3744 } 3745 3746 return activities; 3747 } 3748 3749 ActivityRecord restartPackage(String packageName) { 3750 ActivityRecord starting = topRunningActivityLocked(null); 3751 3752 // All activities that came from the package must be 3753 // restarted as if there was a config change. 3754 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { 3755 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; 3756 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 3757 final ActivityRecord a = activities.get(activityNdx); 3758 if (a.info.packageName.equals(packageName)) { 3759 a.forceNewConfig = true; 3760 if (starting != null && a == starting && a.visible) { 3761 a.startFreezingScreenLocked(starting.app, 3762 ActivityInfo.CONFIG_SCREEN_LAYOUT); 3763 } 3764 } 3765 } 3766 } 3767 3768 return starting; 3769 } 3770 3771 void removeTask(TaskRecord task) { 3772 mStackSupervisor.endLockTaskModeIfTaskEnding(task); 3773 mWindowManager.removeTask(task.taskId); 3774 final ActivityRecord r = mResumedActivity; 3775 if (r != null && r.task == task) { 3776 mResumedActivity = null; 3777 } 3778 3779 final int taskNdx = mTaskHistory.indexOf(task); 3780 final int topTaskNdx = mTaskHistory.size() - 1; 3781 if (task.mOnTopOfHome && taskNdx < topTaskNdx) { 3782 mTaskHistory.get(taskNdx + 1).mOnTopOfHome = true; 3783 } 3784 mTaskHistory.remove(task); 3785 updateTaskMovement(task, true); 3786 3787 if (task.mActivities.isEmpty()) { 3788 final boolean isVoiceSession = task.voiceSession != null; 3789 if (isVoiceSession) { 3790 try { 3791 task.voiceSession.taskFinished(task.intent, task.taskId); 3792 } catch (RemoteException e) { 3793 } 3794 } 3795 if (task.autoRemoveFromRecents() || isVoiceSession) { 3796 // Task creator asked to remove this when done, or this task was a voice 3797 // interaction, so it should not remain on the recent tasks list. 3798 mService.mRecentTasks.remove(task); 3799 } 3800 } 3801 3802 if (mTaskHistory.isEmpty()) { 3803 if (DEBUG_STACK) Slog.i(TAG, "removeTask: moving to back stack=" + this); 3804 if (isOnHomeDisplay()) { 3805 mStackSupervisor.moveHomeStack(!isHomeStack()); 3806 } 3807 if (mStacks != null) { 3808 mStacks.remove(this); 3809 mStacks.add(0, this); 3810 } 3811 mActivityContainer.onTaskListEmptyLocked(); 3812 } 3813 } 3814 3815 TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent, 3816 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, 3817 boolean toTop) { 3818 TaskRecord task = new TaskRecord(mService, taskId, info, intent, voiceSession, 3819 voiceInteractor); 3820 addTask(task, toTop, false); 3821 return task; 3822 } 3823 3824 ArrayList<TaskRecord> getAllTasks() { 3825 return new ArrayList<TaskRecord>(mTaskHistory); 3826 } 3827 3828 void addTask(final TaskRecord task, final boolean toTop, boolean moving) { 3829 task.stack = this; 3830 if (toTop) { 3831 insertTaskAtTop(task); 3832 } else { 3833 mTaskHistory.add(0, task); 3834 updateTaskMovement(task, false); 3835 } 3836 if (!moving && task.voiceSession != null) { 3837 try { 3838 task.voiceSession.taskStarted(task.intent, task.taskId); 3839 } catch (RemoteException e) { 3840 } 3841 } 3842 } 3843 3844 public int getStackId() { 3845 return mStackId; 3846 } 3847 3848 @Override 3849 public String toString() { 3850 return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this)) 3851 + " stackId=" + mStackId + ", " + mTaskHistory.size() + " tasks}"; 3852 } 3853} 3854