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