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