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