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