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