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