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