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