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