2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.am;
19 import static com.android.server.am.ActivityManagerService.TAG;
20 import static com.android.server.am.ActivityManagerService.localLOGV;
21 import static com.android.server.am.ActivityManagerService.DEBUG_CLEANUP;
22 import static com.android.server.am.ActivityManagerService.DEBUG_CONFIGURATION;
23 import static com.android.server.am.ActivityManagerService.DEBUG_PAUSE;
24 import static com.android.server.am.ActivityManagerService.DEBUG_RESULTS;
25 import static com.android.server.am.ActivityManagerService.DEBUG_STACK;
26 import static com.android.server.am.ActivityManagerService.DEBUG_SWITCH;
27 import static com.android.server.am.ActivityManagerService.DEBUG_TASKS;
28 import static com.android.server.am.ActivityManagerService.DEBUG_TRANSITION;
29 import static com.android.server.am.ActivityManagerService.DEBUG_USER_LEAVING;
30 import static com.android.server.am.ActivityManagerService.DEBUG_VISBILITY;
31 import static com.android.server.am.ActivityManagerService.VALIDATE_TOKENS;
33 import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
34 import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
36 import static com.android.server.am.ActivityStackSupervisor.DEBUG_ADD_REMOVE;
37 import static com.android.server.am.ActivityStackSupervisor.DEBUG_APP;
38 import static com.android.server.am.ActivityStackSupervisor.DEBUG_CONTAINERS;
39 import static com.android.server.am.ActivityStackSupervisor.DEBUG_RELEASE;
40 import static com.android.server.am.ActivityStackSupervisor.DEBUG_SAVED_STATE;
41 import static com.android.server.am.ActivityStackSupervisor.DEBUG_SCREENSHOTS;
42 import static com.android.server.am.ActivityStackSupervisor.DEBUG_STATES;
43 import static com.android.server.am.ActivityStackSupervisor.HOME_STACK_ID;
45 import android.util.ArraySet;
46 import com.android.internal.app.IVoiceInteractor;
47 import com.android.internal.content.ReferrerIntent;
48 import com.android.internal.os.BatteryStatsImpl;
49 import com.android.server.Watchdog;
50 import com.android.server.am.ActivityManagerService.ItemMatcher;
51 import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
52 import com.android.server.wm.AppTransition;
53 import com.android.server.wm.TaskGroup;
54 import com.android.server.wm.WindowManagerService;
56 import android.app.Activity;
57 import android.app.ActivityManager;
58 import android.app.ActivityOptions;
59 import android.app.AppGlobals;
60 import android.app.IActivityController;
61 import android.app.ResultInfo;
62 import android.app.ActivityManager.RunningTaskInfo;
63 import android.content.ComponentName;
64 import android.content.Intent;
65 import android.content.pm.ActivityInfo;
66 import android.content.pm.PackageManager;
67 import android.content.res.Configuration;
68 import android.graphics.Bitmap;
69 import android.net.Uri;
70 import android.os.Binder;
71 import android.os.Bundle;
72 import android.os.Debug;
73 import android.os.Handler;
74 import android.os.IBinder;
75 import android.os.Looper;
76 import android.os.Message;
77 import android.os.PersistableBundle;
78 import android.os.RemoteException;
79 import android.os.SystemClock;
80 import android.os.Trace;
81 import android.os.UserHandle;
82 import android.service.voice.IVoiceInteractionSession;
83 import android.util.EventLog;
84 import android.util.Slog;
85 import android.view.Display;
87 import java.io.FileDescriptor;
88 import java.io.PrintWriter;
89 import java.lang.ref.WeakReference;
90 import java.util.ArrayList;
91 import java.util.Iterator;
92 import java.util.List;
93 import java.util.Objects;
96 * State and management of a single stack of activities.
98 final class ActivityStack {
100 // Ticks during which we check progress while waiting for an app to launch.
101 static final int LAUNCH_TICK = 500;
103 // How long we wait until giving up on the last activity to pause. This
104 // is short because it directly impacts the responsiveness of starting the
106 static final int PAUSE_TIMEOUT = 500;
108 // How long we wait for the activity to tell us it has stopped before
109 // giving up. This is a good amount of time because we really need this
110 // from the application in order to get its saved state.
111 static final int STOP_TIMEOUT = 10*1000;
113 // How long we wait until giving up on an activity telling us it has
114 // finished destroying itself.
115 static final int DESTROY_TIMEOUT = 10*1000;
117 // How long until we reset a task when the user returns to it. Currently
119 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
121 // How long between activity launches that we consider safe to not warn
122 // the user about an unexpected activity being launched on top.
123 static final long START_WARN_TIME = 5*1000;
125 // Set to false to disable the preview that is shown while a new activity
127 static final boolean SHOW_APP_STARTING_PREVIEW = true;
129 // How long to wait for all background Activities to redraw following a call to
130 // convertToTranslucent().
131 static final long TRANSLUCENT_CONVERSION_TIMEOUT = 2000;
133 static final boolean SCREENSHOT_FORCE_565 = ActivityManager.isLowRamDeviceStatic();
147 final ActivityManagerService mService;
148 final WindowManagerService mWindowManager;
151 * The back history of all previous (and possibly still
152 * running) activities. It contains #TaskRecord objects.
154 private ArrayList<TaskRecord> mTaskHistory = new ArrayList<TaskRecord>();
157 * Used for validating app tokens with window manager.
159 final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>();
162 * List of running activities, sorted by recent usage.
163 * The first entry in the list is the least recently used.
164 * It contains HistoryRecord objects.
166 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
169 * Animations that for the current transition have requested not to
170 * be considered for the transition animation.
172 final ArrayList<ActivityRecord> mNoAnimActivities = new ArrayList<ActivityRecord>();
175 * When we are in the process of pausing an activity, before starting the
176 * next one, this variable holds the activity that is currently being paused.
178 ActivityRecord mPausingActivity = null;
181 * This is the last activity that we put into the paused state. This is
182 * used to determine if we need to do an activity transition while sleeping,
183 * when we normally hold the top activity paused.
185 ActivityRecord mLastPausedActivity = null;
188 * Activities that specify No History must be removed once the user navigates away from them.
189 * If the device goes to sleep with such an activity in the paused state then we save it here
190 * and finish it later if another activity replaces it on wakeup.
192 ActivityRecord mLastNoHistoryActivity = null;
195 * Current activity that is resumed, or null if there is none.
197 ActivityRecord mResumedActivity = null;
200 * This is the last activity that has been started. It is only used to
201 * identify when multiple activities are started at once so that the user
202 * can be warned they may not be in the activity they think they are.
204 ActivityRecord mLastStartedActivity = null;
206 // The topmost Activity passed to convertToTranslucent(). When non-null it means we are
207 // waiting for all Activities in mUndrawnActivitiesBelowTopTranslucent to be removed as they
208 // are drawn. When the last member of mUndrawnActivitiesBelowTopTranslucent is removed the
209 // Activity in mTranslucentActivityWaiting is notified via
210 // Activity.onTranslucentConversionComplete(false). If a timeout occurs prior to the last
211 // background activity being drawn then the same call will be made with a true value.
212 ActivityRecord mTranslucentActivityWaiting = null;
213 private ArrayList<ActivityRecord> mUndrawnActivitiesBelowTopTranslucent =
214 new ArrayList<ActivityRecord>();
217 * Set when we know we are going to be calling updateConfiguration()
218 * soon, so want to skip intermediate config checks.
220 boolean mConfigWillChange;
222 long mLaunchStartTime = 0;
223 long mFullyDrawnStartTime = 0;
228 final ActivityContainer mActivityContainer;
229 /** The other stacks, in order, on the attached display. Updated at attach/detach time. */
230 ArrayList<ActivityStack> mStacks;
231 /** The attached Display's unique identifier, or -1 if detached */
234 /** Run all ActivityStacks through this */
235 final ActivityStackSupervisor mStackSupervisor;
237 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
238 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
239 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
240 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
241 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
242 static final int TRANSLUCENT_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
243 static final int RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG =
244 ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
246 static class ScheduleDestroyArgs {
247 final ProcessRecord mOwner;
248 final String mReason;
249 ScheduleDestroyArgs(ProcessRecord owner, String reason) {
255 final Handler mHandler;
257 final class ActivityStackHandler extends Handler {
259 // if (localLOGV) Slog.v(TAG, "Handler started!");
261 ActivityStackHandler(Looper looper) {
266 public void handleMessage(Message msg) {
268 case PAUSE_TIMEOUT_MSG: {
269 ActivityRecord r = (ActivityRecord)msg.obj;
270 // We don't at this point know if the activity is fullscreen,
271 // so we need to be conservative and assume it isn't.
272 Slog.w(TAG, "Activity pause timeout for " + r);
273 synchronized (mService) {
275 mService.logAppTooSlow(r.app, r.pauseTime, "pausing " + r);
277 activityPausedLocked(r.appToken, true);
280 case LAUNCH_TICK_MSG: {
281 ActivityRecord r = (ActivityRecord)msg.obj;
282 synchronized (mService) {
283 if (r.continueLaunchTickingLocked()) {
284 mService.logAppTooSlow(r.app, r.launchTickTime, "launching " + r);
288 case DESTROY_TIMEOUT_MSG: {
289 ActivityRecord r = (ActivityRecord)msg.obj;
290 // We don't at this point know if the activity is fullscreen,
291 // so we need to be conservative and assume it isn't.
292 Slog.w(TAG, "Activity destroy timeout for " + r);
293 synchronized (mService) {
294 activityDestroyedLocked(r != null ? r.appToken : null, "destroyTimeout");
297 case STOP_TIMEOUT_MSG: {
298 ActivityRecord r = (ActivityRecord)msg.obj;
299 // We don't at this point know if the activity is fullscreen,
300 // so we need to be conservative and assume it isn't.
301 Slog.w(TAG, "Activity stop timeout for " + r);
302 synchronized (mService) {
303 if (r.isInHistory()) {
304 activityStoppedLocked(r, null, null, null);
308 case DESTROY_ACTIVITIES_MSG: {
309 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
310 synchronized (mService) {
311 destroyActivitiesLocked(args.mOwner, args.mReason);
314 case TRANSLUCENT_TIMEOUT_MSG: {
315 synchronized (mService) {
316 notifyActivityDrawnLocked(null);
319 case RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG: {
320 synchronized (mService) {
321 final ActivityRecord r = getVisibleBehindActivity();
322 Slog.e(TAG, "Timeout waiting for cancelVisibleBehind player=" + r);
324 mService.killAppAtUsersRequest(r.app, null);
332 int numActivities() {
334 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
335 count += mTaskHistory.get(taskNdx).mActivities.size();
340 ActivityStack(ActivityStackSupervisor.ActivityContainer activityContainer) {
341 mActivityContainer = activityContainer;
342 mStackSupervisor = activityContainer.getOuter();
343 mService = mStackSupervisor.mService;
344 mHandler = new ActivityStackHandler(mService.mHandler.getLooper());
345 mWindowManager = mService.mWindowManager;
346 mStackId = activityContainer.mStackId;
347 mCurrentUser = mService.mCurrentUserId;
351 * Checks whether the userid is a profile of the current user.
353 private boolean isCurrentProfileLocked(int userId) {
354 if (userId == mCurrentUser) return true;
355 for (int i = 0; i < mService.mCurrentProfileIds.length; i++) {
356 if (mService.mCurrentProfileIds[i] == userId) return true;
361 boolean okToShowLocked(ActivityRecord r) {
362 return isCurrentProfileLocked(r.userId)
363 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0;
366 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
367 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
368 ActivityRecord r = mTaskHistory.get(taskNdx).topRunningActivityLocked(notTop);
376 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
377 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
378 final TaskRecord task = mTaskHistory.get(taskNdx);
379 final ArrayList<ActivityRecord> activities = task.mActivities;
380 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
381 ActivityRecord r = activities.get(activityNdx);
382 if (!r.finishing && !r.delayedResume && r != notTop && okToShowLocked(r)) {
391 * This is a simplified version of topRunningActivityLocked that provides a number of
392 * optional skip-over modes. It is intended for use with the ActivityController hook only.
394 * @param token If non-null, any history records matching this token will be skipped.
395 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
397 * @return Returns the HistoryRecord of the next activity on the stack.
399 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
400 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
401 TaskRecord task = mTaskHistory.get(taskNdx);
402 if (task.taskId == taskId) {
405 ArrayList<ActivityRecord> activities = task.mActivities;
406 for (int i = activities.size() - 1; i >= 0; --i) {
407 final ActivityRecord r = activities.get(i);
408 // Note: the taskId check depends on real taskId fields being non-zero
409 if (!r.finishing && (token != r.appToken) && okToShowLocked(r)) {
417 final ActivityRecord topActivity() {
418 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
419 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
420 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
421 final ActivityRecord r = activities.get(activityNdx);
430 final TaskRecord topTask() {
431 final int size = mTaskHistory.size();
433 return mTaskHistory.get(size - 1);
438 TaskRecord taskForIdLocked(int id) {
439 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
440 final TaskRecord task = mTaskHistory.get(taskNdx);
441 if (task.taskId == id) {
448 ActivityRecord isInStackLocked(IBinder token) {
449 final ActivityRecord r = ActivityRecord.forToken(token);
451 final TaskRecord task = r.task;
452 if (task != null && task.mActivities.contains(r) && mTaskHistory.contains(task)) {
453 if (task.stack != this) Slog.w(TAG,
454 "Illegal state! task does not point to stack it is in.");
461 final boolean updateLRUListLocked(ActivityRecord r) {
462 final boolean hadit = mLRUActivities.remove(r);
463 mLRUActivities.add(r);
467 final boolean isHomeStack() {
468 return mStackId == HOME_STACK_ID;
471 final boolean isOnHomeDisplay() {
472 return isAttached() &&
473 mActivityContainer.mActivityDisplay.mDisplayId == Display.DEFAULT_DISPLAY;
476 final void moveToFront(String reason) {
478 if (isOnHomeDisplay()) {
479 mStackSupervisor.moveHomeStack(isHomeStack(), reason);
481 mStacks.remove(this);
483 final TaskRecord task = topTask();
485 mWindowManager.moveTaskToTop(task.taskId);
490 final boolean isAttached() {
491 return mStacks != null;
495 * Returns the top activity in any existing task matching the given
496 * Intent. Returns null if no such task is found.
498 ActivityRecord findTaskLocked(ActivityRecord target) {
499 Intent intent = target.intent;
500 ActivityInfo info = target.info;
501 ComponentName cls = intent.getComponent();
502 if (info.targetActivity != null) {
503 cls = new ComponentName(info.packageName, info.targetActivity);
505 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
506 boolean isDocument = intent != null & intent.isDocument();
507 // If documentData is non-null then it must match the existing task data.
508 Uri documentData = isDocument ? intent.getData() : null;
510 if (DEBUG_TASKS) Slog.d(TAG, "Looking for task of " + target + " in " + this);
511 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
512 final TaskRecord task = mTaskHistory.get(taskNdx);
513 if (task.voiceSession != null) {
514 // We never match voice sessions; those always run independently.
515 if (DEBUG_TASKS) Slog.d(TAG, "Skipping " + task + ": voice session");
518 if (task.userId != userId) {
519 // Looking for a different task.
520 if (DEBUG_TASKS) Slog.d(TAG, "Skipping " + task + ": different user");
523 final ActivityRecord r = task.getTopActivity();
524 if (r == null || r.finishing || r.userId != userId ||
525 r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
526 if (DEBUG_TASKS) Slog.d(TAG, "Skipping " + task + ": mismatch root " + r);
530 final Intent taskIntent = task.intent;
531 final Intent affinityIntent = task.affinityIntent;
532 final boolean taskIsDocument;
533 final Uri taskDocumentData;
534 if (taskIntent != null && taskIntent.isDocument()) {
535 taskIsDocument = true;
536 taskDocumentData = taskIntent.getData();
537 } else if (affinityIntent != null && affinityIntent.isDocument()) {
538 taskIsDocument = true;
539 taskDocumentData = affinityIntent.getData();
541 taskIsDocument = false;
542 taskDocumentData = null;
545 if (DEBUG_TASKS) Slog.d(TAG, "Comparing existing cls="
546 + taskIntent.getComponent().flattenToShortString()
547 + "/aff=" + r.task.rootAffinity + " to new cls="
548 + intent.getComponent().flattenToShortString() + "/aff=" + info.taskAffinity);
549 if (!isDocument && !taskIsDocument && task.rootAffinity != null) {
550 if (task.rootAffinity.equals(target.taskAffinity)) {
551 if (DEBUG_TASKS) Slog.d(TAG, "Found matching affinity!");
554 } else if (taskIntent != null && taskIntent.getComponent() != null &&
555 taskIntent.getComponent().compareTo(cls) == 0 &&
556 Objects.equals(documentData, taskDocumentData)) {
557 if (DEBUG_TASKS) Slog.d(TAG, "Found matching class!");
559 if (DEBUG_TASKS) Slog.d(TAG, "For Intent " + intent + " bringing to top: "
562 } else if (affinityIntent != null && affinityIntent.getComponent() != null &&
563 affinityIntent.getComponent().compareTo(cls) == 0 &&
564 Objects.equals(documentData, taskDocumentData)) {
565 if (DEBUG_TASKS) Slog.d(TAG, "Found matching class!");
567 if (DEBUG_TASKS) Slog.d(TAG, "For Intent " + intent + " bringing to top: "
570 } else if (DEBUG_TASKS) {
571 Slog.d(TAG, "Not a match: " + task);
579 * Returns the first activity (starting from the top of the stack) that
580 * is the same as the given activity. Returns null if no such activity
583 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
584 ComponentName cls = intent.getComponent();
585 if (info.targetActivity != null) {
586 cls = new ComponentName(info.packageName, info.targetActivity);
588 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
590 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
591 TaskRecord task = mTaskHistory.get(taskNdx);
592 if (!isCurrentProfileLocked(task.userId)) {
595 final ArrayList<ActivityRecord> activities = task.mActivities;
596 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
597 ActivityRecord r = activities.get(activityNdx);
598 if (!r.finishing && r.intent.getComponent().equals(cls) && r.userId == userId) {
599 //Slog.i(TAG, "Found matching class!");
601 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
611 * Move the activities around in the stack to bring a user to the foreground.
613 final void switchUserLocked(int userId) {
614 if (mCurrentUser == userId) {
617 mCurrentUser = userId;
619 // Move userId's tasks to the top.
620 int index = mTaskHistory.size();
621 for (int i = 0; i < index; ) {
622 TaskRecord task = mTaskHistory.get(i);
623 if (isCurrentProfileLocked(task.userId)) {
624 if (DEBUG_TASKS) Slog.d(TAG, "switchUserLocked: stack=" + getStackId() +
625 " moving " + task + " to top");
626 mTaskHistory.remove(i);
627 mTaskHistory.add(task);
629 // Use same value for i.
634 if (VALIDATE_TOKENS) {
635 validateAppTokensLocked();
639 void minimalResumeActivityLocked(ActivityRecord r) {
640 r.state = ActivityState.RESUMED;
641 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
642 + " (starting new instance)");
644 mResumedActivity = r;
645 r.task.touchActiveTime();
646 mService.addRecentTaskLocked(r.task);
647 completeResumeLocked(r);
648 mStackSupervisor.checkReadyForSleepLocked();
650 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
653 private void startLaunchTraces() {
654 if (mFullyDrawnStartTime != 0) {
655 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
657 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching", 0);
658 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
661 private void stopFullyDrawnTraceIfNeeded() {
662 if (mFullyDrawnStartTime != 0 && mLaunchStartTime == 0) {
663 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
664 mFullyDrawnStartTime = 0;
668 void setLaunchTime(ActivityRecord r) {
669 if (r.displayStartTime == 0) {
670 r.fullyDrawnStartTime = r.displayStartTime = SystemClock.uptimeMillis();
671 if (mLaunchStartTime == 0) {
673 mLaunchStartTime = mFullyDrawnStartTime = r.displayStartTime;
675 } else if (mLaunchStartTime == 0) {
677 mLaunchStartTime = mFullyDrawnStartTime = SystemClock.uptimeMillis();
681 void clearLaunchTime(ActivityRecord r) {
682 // Make sure that there is no activity waiting for this to launch.
683 if (mStackSupervisor.mWaitingActivityLaunched.isEmpty()) {
684 r.displayStartTime = r.fullyDrawnStartTime = 0;
686 mStackSupervisor.removeTimeoutsForActivityLocked(r);
687 mStackSupervisor.scheduleIdleTimeoutLocked(r);
691 void awakeFromSleepingLocked() {
692 // Ensure activities are no longer sleeping.
693 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
694 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
695 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
696 activities.get(activityNdx).setSleeping(false);
699 if (mPausingActivity != null) {
700 Slog.d(TAG, "awakeFromSleepingLocked: previously pausing activity didn't pause");
701 activityPausedLocked(mPausingActivity.appToken, true);
706 * @return true if something must be done before going to sleep.
708 boolean checkReadyForSleepLocked() {
709 if (mResumedActivity != null) {
710 // Still have something resumed; can't sleep until it is paused.
711 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
712 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
713 startPausingLocked(false, true, false, false);
716 if (mPausingActivity != null) {
717 // Still waiting for something to pause; can't sleep yet.
718 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
726 ensureActivitiesVisibleLocked(null, 0);
728 // Make sure any stopped but visible activities are now sleeping.
729 // This ensures that the activity's onStop() is called.
730 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
731 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
732 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
733 final ActivityRecord r = activities.get(activityNdx);
734 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
741 public final Bitmap screenshotActivities(ActivityRecord who) {
742 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "screenshotActivities: " + who);
744 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tNo display");
749 // This is an optimization -- since we never show Home or Recents within Recents itself,
750 // we can just go ahead and skip taking the screenshot if this is the home stack.
751 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tHome stack");
755 int w = mService.mThumbnailWidth;
756 int h = mService.mThumbnailHeight;
758 if (DEBUG_SCREENSHOTS) Slog.d(TAG, "\tTaking screenshot");
759 return mWindowManager.screenshotApplications(who.appToken, Display.DEFAULT_DISPLAY,
760 w, h, SCREENSHOT_FORCE_565);
762 Slog.e(TAG, "Invalid thumbnail dimensions: " + w + "x" + h);
767 * Start pausing the currently resumed activity. It is an error to call this if there
768 * is already an activity being paused or there is no resumed activity.
770 * @param userLeaving True if this should result in an onUserLeaving to the current activity.
771 * @param uiSleeping True if this is happening with the user interface going to sleep (the
772 * screen turning off).
773 * @param resuming True if this is being called as part of resuming the top activity, so
774 * we shouldn't try to instigate a resume here.
775 * @param dontWait True if the caller does not want to wait for the pause to complete. If
776 * set to true, we will immediately complete the pause here before returning.
777 * @return Returns true if an activity now is in the PAUSING state, and we are waiting for
778 * it to tell us when it is done.
780 final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,
782 if (mPausingActivity != null) {
783 Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity
784 + " state=" + mPausingActivity.state);
785 if (!mService.isSleeping()) {
786 // Avoid recursion among check for sleep and complete pause during sleeping.
787 // Because activity will be paused immediately after resume, just let pause
788 // be completed by the order of activity paused from clients.
789 completePauseLocked(false);
792 ActivityRecord prev = mResumedActivity;
795 Slog.wtf(TAG, "Trying to pause when nothing is resumed");
796 mStackSupervisor.resumeTopActivitiesLocked();
801 if (mActivityContainer.mParentActivity == null) {
802 // Top level stack, not a child. Look for child stacks.
803 mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait);
806 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
807 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
808 mResumedActivity = null;
809 mPausingActivity = prev;
810 mLastPausedActivity = prev;
811 mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
812 || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
813 prev.state = ActivityState.PAUSING;
814 prev.task.touchActiveTime();
815 clearLaunchTime(prev);
816 final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();
817 if (mService.mHasRecents && (next == null || next.noDisplay || next.task != prev.task || uiSleeping)) {
818 prev.updateThumbnailLocked(screenshotActivities(prev), null);
820 stopFullyDrawnTraceIfNeeded();
822 mService.updateCpuStats();
824 if (prev.app != null && prev.app.thread != null) {
825 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
827 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
828 prev.userId, System.identityHashCode(prev),
829 prev.shortComponentName);
830 mService.updateUsageStats(prev, false);
831 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
832 userLeaving, prev.configChangeFlags, dontWait);
833 } catch (Exception e) {
834 // Ignore exception, if process died other code will cleanup.
835 Slog.w(TAG, "Exception thrown during pause", e);
836 mPausingActivity = null;
837 mLastPausedActivity = null;
838 mLastNoHistoryActivity = null;
841 mPausingActivity = null;
842 mLastPausedActivity = null;
843 mLastNoHistoryActivity = null;
846 // If we are not going to sleep, we want to ensure the device is
847 // awake until the next activity is started.
848 if (!mService.isSleepingOrShuttingDown()) {
849 mStackSupervisor.acquireLaunchWakelock();
852 if (mPausingActivity != null) {
853 // Have the window manager pause its key dispatching until the new
854 // activity has started. If we're pausing the activity just because
855 // the screen is being turned off and the UI is sleeping, don't interrupt
856 // key dispatch; the same activity will pick it up again on wakeup.
858 prev.pauseKeyDispatchingLocked();
860 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
864 // If the caller said they don't want to wait for the pause, then complete
866 completePauseLocked(false);
870 // Schedule a pause timeout in case the app doesn't respond.
871 // We don't give it much time because this directly impacts the
872 // responsiveness seen by the user.
873 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
875 prev.pauseTime = SystemClock.uptimeMillis();
876 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
877 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
882 // This activity failed to schedule the
883 // pause, so just treat it as being paused now.
884 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
886 mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null);
892 final void activityPausedLocked(IBinder token, boolean timeout) {
893 if (DEBUG_PAUSE) Slog.v(
894 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
896 final ActivityRecord r = isInStackLocked(token);
898 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
899 if (mPausingActivity == r) {
900 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
901 + (timeout ? " (due to timeout)" : " (pause complete)"));
902 completePauseLocked(true);
904 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
905 r.userId, System.identityHashCode(r), r.shortComponentName,
906 mPausingActivity != null
907 ? mPausingActivity.shortComponentName : "(none)");
908 if (r.finishing && r.state == ActivityState.PAUSING) {
909 if (DEBUG_PAUSE) Slog.v(TAG,
910 "Executing finish of failed to pause activity: " + r);
911 finishCurrentActivityLocked(r, FINISH_AFTER_VISIBLE, false);
917 final void activityStoppedLocked(ActivityRecord r, Bundle icicle,
918 PersistableBundle persistentState, CharSequence description) {
919 if (r.state != ActivityState.STOPPING) {
920 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
921 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
924 if (persistentState != null) {
925 r.persistentState = persistentState;
926 mService.notifyTaskPersisterLocked(r.task, false);
928 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
929 if (icicle != null) {
930 // If icicle is null, this is happening due to a timeout, so we
931 // haven't really saved the state.
935 r.updateThumbnailLocked(null, description);
938 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
939 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
941 r.state = ActivityState.STOPPED;
942 if (mActivityContainer.mActivityDisplay.mVisibleBehindActivity == r) {
943 mStackSupervisor.requestVisibleBehindLocked(r, false);
946 r.clearOptionsLocked();
948 if (r.configDestroy) {
949 destroyActivityLocked(r, true, "stop-config");
950 mStackSupervisor.resumeTopActivitiesLocked();
952 mStackSupervisor.updatePreviousProcessLocked(r);
958 private void completePauseLocked(boolean resumeNext) {
959 ActivityRecord prev = mPausingActivity;
960 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
963 prev.state = ActivityState.PAUSED;
964 if (prev.finishing) {
965 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
966 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
967 } else if (prev.app != null) {
968 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
969 if (prev.waitingVisible) {
970 prev.waitingVisible = false;
971 mStackSupervisor.mWaitingVisibleActivities.remove(prev);
972 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
973 TAG, "Complete pause, no longer waiting: " + prev);
975 if (prev.configDestroy) {
976 // The previous is being paused because the configuration
977 // is changing, which means it is actually stopping...
978 // To juggle the fact that we are also starting a new
979 // instance right now, we need to first completely stop
980 // the current instance before starting the new one.
981 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
982 destroyActivityLocked(prev, true, "pause-config");
983 } else if (!hasVisibleBehindActivity()) {
984 // If we were visible then resumeTopActivities will release resources before
986 mStackSupervisor.mStoppingActivities.add(prev);
987 if (mStackSupervisor.mStoppingActivities.size() > 3 ||
988 prev.frontOfTask && mTaskHistory.size() <= 1) {
989 // If we already have a few activities waiting to stop,
990 // then give up on things going idle and start clearing
991 // them out. Or if r is the last of activity of the last task the stack
992 // will be empty and must be cleared immediately.
993 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
994 mStackSupervisor.scheduleIdleLocked();
996 mStackSupervisor.checkReadyForSleepLocked();
1000 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1003 mPausingActivity = null;
1007 final ActivityStack topStack = mStackSupervisor.getFocusedStack();
1008 if (!mService.isSleepingOrShuttingDown()) {
1009 mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null);
1011 mStackSupervisor.checkReadyForSleepLocked();
1012 ActivityRecord top = topStack.topRunningActivityLocked(null);
1013 if (top == null || (prev != null && top != prev)) {
1014 // If there are no more activities available to run,
1015 // do resume anyway to start something. Also if the top
1016 // activity on the stack is not the just paused activity,
1017 // we need to go ahead and resume it to ensure we complete
1018 // an in-flight app switch.
1019 mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null);
1025 prev.resumeKeyDispatchingLocked();
1027 if (prev.app != null && prev.cpuTimeAtResume > 0
1028 && mService.mBatteryStatsService.isOnBattery()) {
1029 long diff = mService.mProcessCpuTracker.getCpuTimeForPid(prev.app.pid)
1030 - prev.cpuTimeAtResume;
1032 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1033 synchronized (bsi) {
1034 BatteryStatsImpl.Uid.Proc ps =
1035 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1036 prev.info.packageName);
1038 ps.addForegroundTimeLocked(diff);
1043 prev.cpuTimeAtResume = 0; // reset it
1046 // Notfiy when the task stack has changed
1047 mService.notifyTaskStackChangedLocked();
1051 * Once we know that we have asked an application to put an activity in
1052 * the resumed state (either by launching it or explicitly telling it),
1053 * this function updates the rest of our state to match that fact.
1055 private void completeResumeLocked(ActivityRecord next) {
1057 next.results = null;
1058 next.newIntents = null;
1060 if (next.isHomeActivity() && next.isNotResolverActivity()) {
1061 ProcessRecord app = next.task.mActivities.get(0).app;
1062 if (app != null && app != mService.mHomeProcess) {
1063 mService.mHomeProcess = app;
1067 if (next.nowVisible) {
1068 // We won't get a call to reportActivityVisibleLocked() so dismiss lockscreen now.
1069 mStackSupervisor.notifyActivityDrawnForKeyguard();
1072 // schedule an idle timeout in case the app doesn't do it for us.
1073 mStackSupervisor.scheduleIdleTimeoutLocked(next);
1075 mStackSupervisor.reportResumedActivityLocked(next);
1077 next.resumeKeyDispatchingLocked();
1078 mNoAnimActivities.clear();
1080 // Mark the point when the activity is resuming
1081 // TODO: To be more accurate, the mark should be before the onCreate,
1082 // not after the onResume. But for subsequent starts, onResume is fine.
1083 if (next.app != null) {
1084 next.cpuTimeAtResume = mService.mProcessCpuTracker.getCpuTimeForPid(next.app.pid);
1086 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1089 next.returningOptions = null;
1091 if (mActivityContainer.mActivityDisplay.mVisibleBehindActivity == next) {
1092 // When resuming an activity, require it to call requestVisibleBehind() again.
1093 mActivityContainer.mActivityDisplay.setVisibleBehindActivity(null);
1097 private void setVisibile(ActivityRecord r, boolean visible) {
1098 r.visible = visible;
1099 mWindowManager.setAppVisibility(r.appToken, visible);
1100 final ArrayList<ActivityContainer> containers = r.mChildContainers;
1101 for (int containerNdx = containers.size() - 1; containerNdx >= 0; --containerNdx) {
1102 ActivityContainer container = containers.get(containerNdx);
1103 container.setVisible(visible);
1107 // Find the first visible activity above the passed activity and if it is translucent return it
1108 // otherwise return null;
1109 ActivityRecord findNextTranslucentActivity(ActivityRecord r) {
1110 TaskRecord task = r.task;
1115 ActivityStack stack = task.stack;
1116 if (stack == null) {
1120 int stackNdx = mStacks.indexOf(stack);
1122 ArrayList<TaskRecord> tasks = stack.mTaskHistory;
1123 int taskNdx = tasks.indexOf(task);
1125 ArrayList<ActivityRecord> activities = task.mActivities;
1126 int activityNdx = activities.indexOf(r) + 1;
1128 final int numStacks = mStacks.size();
1129 while (stackNdx < numStacks) {
1130 tasks = mStacks.get(stackNdx).mTaskHistory;
1131 final int numTasks = tasks.size();
1132 while (taskNdx < numTasks) {
1133 activities = tasks.get(taskNdx).mActivities;
1134 final int numActivities = activities.size();
1135 while (activityNdx < numActivities) {
1136 final ActivityRecord activity = activities.get(activityNdx);
1137 if (!activity.finishing) {
1138 return activity.fullscreen ? null : activity;
1152 // Checks if any of the stacks above this one has a fullscreen activity behind it.
1153 // If so, this stack is hidden, otherwise it is visible.
1154 private boolean isStackVisible() {
1155 if (!isAttached()) {
1159 if (mStackSupervisor.isFrontStack(this)) {
1164 * Start at the task above this one and go up, looking for a visible
1165 * fullscreen activity, or a translucent activity that requested the
1166 * wallpaper to be shown behind it.
1168 for (int i = mStacks.indexOf(this) + 1; i < mStacks.size(); i++) {
1169 final ArrayList<TaskRecord> tasks = mStacks.get(i).getAllTasks();
1170 for (int taskNdx = 0; taskNdx < tasks.size(); taskNdx++) {
1171 final TaskRecord task = tasks.get(taskNdx);
1172 final ArrayList<ActivityRecord> activities = task.mActivities;
1173 for (int activityNdx = 0; activityNdx < activities.size(); activityNdx++) {
1174 final ActivityRecord r = activities.get(activityNdx);
1176 // Conditions for an activity to obscure the stack we're
1178 // 1. Not Finishing AND Visible AND:
1180 // - Full Screen Activity OR
1181 // - On top of Home and our stack is NOT home
1182 if (!r.finishing && r.visible && (r.fullscreen ||
1183 (!isHomeStack() && r.frontOfTask && task.isOverHomeStack()))) {
1194 * Make sure that all activities that need to be visible (that is, they
1195 * currently can be seen by the user) actually are.
1197 final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges) {
1198 ActivityRecord top = topRunningActivityLocked(null);
1202 if (DEBUG_VISBILITY) Slog.v(
1203 TAG, "ensureActivitiesVisible behind " + top
1204 + " configChanges=0x" + Integer.toHexString(configChanges));
1206 if (mTranslucentActivityWaiting != top) {
1207 mUndrawnActivitiesBelowTopTranslucent.clear();
1208 if (mTranslucentActivityWaiting != null) {
1209 // Call the callback with a timeout indication.
1210 notifyActivityDrawnLocked(null);
1211 mTranslucentActivityWaiting = null;
1213 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG);
1216 // If the top activity is not fullscreen, then we need to
1217 // make sure any activities under it are now visible.
1218 boolean aboveTop = true;
1219 boolean behindFullscreen = !isStackVisible();
1221 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1222 final TaskRecord task = mTaskHistory.get(taskNdx);
1223 final ArrayList<ActivityRecord> activities = task.mActivities;
1224 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1225 final ActivityRecord r = activities.get(activityNdx);
1229 if (aboveTop && r != top) {
1233 // mLaunchingBehind: Activities launching behind are at the back of the task stack
1234 // but must be drawn initially for the animation as though they were visible.
1235 if (!behindFullscreen || r.mLaunchTaskBehind) {
1236 if (DEBUG_VISBILITY) Slog.v(
1237 TAG, "Make visible? " + r + " finishing=" + r.finishing
1238 + " state=" + r.state);
1240 // First: if this is not the current activity being started, make
1241 // sure it matches the current configuration.
1242 if (r != starting) {
1243 ensureActivityConfigurationLocked(r, 0);
1246 if (r.app == null || r.app.thread == null) {
1247 // This activity needs to be visible, but isn't even
1248 // running... get it started, but don't resume it
1250 if (DEBUG_VISBILITY) Slog.v(TAG, "Start and freeze screen for " + r);
1251 if (r != starting) {
1252 r.startFreezingScreenLocked(r.app, configChanges);
1254 if (!r.visible || r.mLaunchTaskBehind) {
1255 if (DEBUG_VISBILITY) Slog.v(
1256 TAG, "Starting and making visible: " + r);
1257 setVisibile(r, true);
1259 if (r != starting) {
1260 mStackSupervisor.startSpecificActivityLocked(r, false, false);
1263 } else if (r.visible) {
1264 // If this activity is already visible, then there is nothing
1266 if (DEBUG_VISBILITY) Slog.v(TAG, "Skipping: already visible at " + r);
1267 r.stopFreezingScreenLocked(false);
1269 if (r.returningOptions != null) {
1270 r.app.thread.scheduleOnNewActivityOptions(r.appToken,
1271 r.returningOptions);
1273 } catch(RemoteException e) {
1276 // This activity is not currently visible, but is running.
1277 // Tell it to become visible.
1279 if (r.state != ActivityState.RESUMED && r != starting) {
1280 // If this activity is paused, tell it
1281 // to now show its window.
1282 if (DEBUG_VISBILITY) Slog.v(
1283 TAG, "Making visible and scheduling visibility: " + r);
1285 if (mTranslucentActivityWaiting != null) {
1286 r.updateOptionsLocked(r.returningOptions);
1287 mUndrawnActivitiesBelowTopTranslucent.add(r);
1289 setVisibile(r, true);
1291 r.app.pendingUiClean = true;
1292 r.app.thread.scheduleWindowVisibility(r.appToken, true);
1293 r.stopFreezingScreenLocked(false);
1294 } catch (Exception e) {
1295 // Just skip on any failure; we'll make it
1296 // visible when it next restarts.
1297 Slog.w(TAG, "Exception thrown making visibile: "
1298 + r.intent.getComponent(), e);
1303 // Aggregate current change flags.
1304 configChanges |= r.configChangeFlags;
1307 // At this point, nothing else needs to be shown
1308 if (DEBUG_VISBILITY) Slog.v(TAG, "Fullscreen: at " + r);
1309 behindFullscreen = true;
1310 } else if (!isHomeStack() && r.frontOfTask && task.isOverHomeStack()) {
1311 if (DEBUG_VISBILITY) Slog.v(TAG, "Showing home: at " + r);
1312 behindFullscreen = true;
1315 if (DEBUG_VISBILITY) Slog.v(
1316 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1317 + " state=" + r.state
1318 + " behindFullscreen=" + behindFullscreen);
1319 // Now for any activities that aren't visible to the user, make
1320 // sure they no longer are keeping the screen frozen.
1322 if (DEBUG_VISBILITY) Slog.v(TAG, "Making invisible: " + r);
1324 setVisibile(r, false);
1328 if (r.app != null && r.app.thread != null) {
1329 if (DEBUG_VISBILITY) Slog.v(
1330 TAG, "Scheduling invisibility: " + r);
1331 r.app.thread.scheduleWindowVisibility(r.appToken, false);
1339 // This case created for transitioning activities from
1340 // translucent to opaque {@link Activity#convertToOpaque}.
1341 if (getVisibleBehindActivity() == r) {
1342 releaseBackgroundResources();
1344 if (!mStackSupervisor.mStoppingActivities.contains(r)) {
1345 mStackSupervisor.mStoppingActivities.add(r);
1347 mStackSupervisor.scheduleIdleLocked();
1354 } catch (Exception e) {
1355 // Just skip on any failure; we'll make it
1356 // visible when it next restarts.
1357 Slog.w(TAG, "Exception thrown making hidden: "
1358 + r.intent.getComponent(), e);
1361 if (DEBUG_VISBILITY) Slog.v(TAG, "Already invisible: " + r);
1367 if (mTranslucentActivityWaiting != null &&
1368 mUndrawnActivitiesBelowTopTranslucent.isEmpty()) {
1369 // Nothing is getting drawn or everything was already visible, don't wait for timeout.
1370 notifyActivityDrawnLocked(null);
1374 void convertToTranslucent(ActivityRecord r) {
1375 mTranslucentActivityWaiting = r;
1376 mUndrawnActivitiesBelowTopTranslucent.clear();
1377 mHandler.sendEmptyMessageDelayed(TRANSLUCENT_TIMEOUT_MSG, TRANSLUCENT_CONVERSION_TIMEOUT);
1381 * Called as activities below the top translucent activity are redrawn. When the last one is
1382 * redrawn notify the top activity by calling
1383 * {@link Activity#onTranslucentConversionComplete}.
1385 * @param r The most recent background activity to be drawn. Or, if r is null then a timeout
1386 * occurred and the activity will be notified immediately.
1388 void notifyActivityDrawnLocked(ActivityRecord r) {
1389 mActivityContainer.setDrawn();
1391 || (mUndrawnActivitiesBelowTopTranslucent.remove(r) &&
1392 mUndrawnActivitiesBelowTopTranslucent.isEmpty())) {
1393 // The last undrawn activity below the top has just been drawn. If there is an
1394 // opaque activity at the top, notify it that it can become translucent safely now.
1395 final ActivityRecord waitingActivity = mTranslucentActivityWaiting;
1396 mTranslucentActivityWaiting = null;
1397 mUndrawnActivitiesBelowTopTranslucent.clear();
1398 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG);
1400 if (waitingActivity != null) {
1401 mWindowManager.setWindowOpaque(waitingActivity.appToken, false);
1402 if (waitingActivity.app != null && waitingActivity.app.thread != null) {
1404 waitingActivity.app.thread.scheduleTranslucentConversionComplete(
1405 waitingActivity.appToken, r != null);
1406 } catch (RemoteException e) {
1413 /** If any activities below the top running one are in the INITIALIZING state and they have a
1414 * starting window displayed then remove that starting window. It is possible that the activity
1415 * in this state will never resumed in which case that starting window will be orphaned. */
1416 void cancelInitializingActivities() {
1417 final ActivityRecord topActivity = topRunningActivityLocked(null);
1418 boolean aboveTop = true;
1419 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1420 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
1421 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1422 final ActivityRecord r = activities.get(activityNdx);
1424 if (r == topActivity) {
1430 if (r.state == ActivityState.INITIALIZING && r.mStartingWindowShown) {
1431 if (DEBUG_VISBILITY) Slog.w(TAG, "Found orphaned starting window " + r);
1432 r.mStartingWindowShown = false;
1433 mWindowManager.removeAppStartingWindow(r.appToken);
1440 * Ensure that the top activity in the stack is resumed.
1442 * @param prev The previously resumed activity, for when in the process
1443 * of pausing; can be null to call from elsewhere.
1445 * @return Returns true if something is being resumed, or false if
1448 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1449 return resumeTopActivityLocked(prev, null);
1452 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
1453 if (mStackSupervisor.inResumeTopActivity) {
1454 // Don't even start recursing.
1458 boolean result = false;
1460 // Protect against recursion.
1461 mStackSupervisor.inResumeTopActivity = true;
1462 if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
1463 mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
1464 mService.updateSleepIfNeededLocked();
1466 result = resumeTopActivityInnerLocked(prev, options);
1468 mStackSupervisor.inResumeTopActivity = false;
1473 final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
1474 if (ActivityManagerService.DEBUG_LOCKSCREEN) mService.logLockScreen("");
1476 if (!mService.mBooting && !mService.mBooted) {
1481 ActivityRecord parent = mActivityContainer.mParentActivity;
1482 if ((parent != null && parent.state != ActivityState.RESUMED) ||
1483 !mActivityContainer.isAttachedLocked()) {
1484 // Do not resume this stack if its parent is not resumed.
1485 // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st.
1489 cancelInitializingActivities();
1491 // Find the first activity that is not finishing.
1492 final ActivityRecord next = topRunningActivityLocked(null);
1494 // Remember how we'll process this pause/resume situation, and ensure
1495 // that the state is reset however we wind up proceeding.
1496 final boolean userLeaving = mStackSupervisor.mUserLeaving;
1497 mStackSupervisor.mUserLeaving = false;
1499 final TaskRecord prevTask = prev != null ? prev.task : null;
1501 // There are no more activities! Let's just start up the
1503 ActivityOptions.abort(options);
1504 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: No more activities go home");
1505 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1506 // Only resume home if on home display
1507 final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
1508 HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
1509 return isOnHomeDisplay() &&
1510 mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "noMoreActivities");
1513 next.delayedResume = false;
1515 // If the top activity is the resumed one, nothing to do.
1516 if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
1517 mStackSupervisor.allResumedActivitiesComplete()) {
1518 // Make sure we have executed any pending transitions, since there
1519 // should be nothing left to do at this point.
1520 mWindowManager.executeAppTransition();
1521 mNoAnimActivities.clear();
1522 ActivityOptions.abort(options);
1523 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Top activity resumed " + next);
1524 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1528 final TaskRecord nextTask = next.task;
1529 if (prevTask != null && prevTask.stack == this &&
1530 prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
1531 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1532 if (prevTask == nextTask) {
1533 prevTask.setFrontOfTask();
1534 } else if (prevTask != topTask()) {
1535 // This task is going away but it was supposed to return to the home stack.
1536 // Now the task above it has to return to the home task instead.
1537 final int taskNdx = mTaskHistory.indexOf(prevTask) + 1;
1538 mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE);
1539 } else if (!isOnHomeDisplay()) {
1541 } else if (!isHomeStack()){
1542 if (DEBUG_STATES) Slog.d(TAG,
1543 "resumeTopActivityLocked: Launching home next");
1544 final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
1545 HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
1546 return mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "prevFinished");
1550 // If we are sleeping, and there is no resumed activity, and the top
1551 // activity is paused, well that is the state we want.
1552 if (mService.isSleepingOrShuttingDown()
1553 && mLastPausedActivity == next
1554 && mStackSupervisor.allPausedActivitiesComplete()) {
1555 // Make sure we have executed any pending transitions, since there
1556 // should be nothing left to do at this point.
1557 mWindowManager.executeAppTransition();
1558 mNoAnimActivities.clear();
1559 ActivityOptions.abort(options);
1560 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Going to sleep and all paused");
1561 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1565 // Make sure that the user who owns this activity is started. If not,
1566 // we will just leave it as is because someone should be bringing
1567 // another user's activities to the top of the stack.
1568 if (mService.mStartedUsers.get(next.userId) == null) {
1569 Slog.w(TAG, "Skipping resume of top activity " + next
1570 + ": user " + next.userId + " is stopped");
1571 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1575 // The activity may be waiting for stop, but that is no longer
1576 // appropriate for it.
1577 mStackSupervisor.mStoppingActivities.remove(next);
1578 mStackSupervisor.mGoingToSleepActivities.remove(next);
1579 next.sleeping = false;
1580 mStackSupervisor.mWaitingVisibleActivities.remove(next);
1581 next.waitingVisible = false;
1583 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1585 // If we are currently pausing an activity, then don't do anything
1586 // until that is done.
1587 if (!mStackSupervisor.allPausedActivitiesComplete()) {
1588 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG,
1589 "resumeTopActivityLocked: Skip resume: some activity pausing.");
1590 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1594 // Okay we are now going to start a switch, to 'next'. We may first
1595 // have to pause the current activity, but this is an important point
1596 // where we have decided to go to 'next' so keep track of that.
1597 // XXX "App Redirected" dialog is getting too many false positives
1598 // at this point, so turn off for now.
1600 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1601 long now = SystemClock.uptimeMillis();
1602 final boolean inTime = mLastStartedActivity.startTime != 0
1603 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1604 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1605 final int nextUid = next.info.applicationInfo.uid;
1606 if (inTime && lastUid != nextUid
1607 && lastUid != next.launchedFromUid
1608 && mService.checkPermission(
1609 android.Manifest.permission.STOP_APP_SWITCHES,
1610 -1, next.launchedFromUid)
1611 != PackageManager.PERMISSION_GRANTED) {
1612 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1614 next.startTime = now;
1615 mLastStartedActivity = next;
1618 next.startTime = SystemClock.uptimeMillis();
1619 mLastStartedActivity = next;
1623 // We need to start pausing the current activity so the top one
1624 // can be resumed...
1625 boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
1626 boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
1627 if (mResumedActivity != null) {
1628 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Pausing " + mResumedActivity);
1629 pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
1632 if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG,
1633 "resumeTopActivityLocked: Skip resume: need to start pausing");
1634 // At this point we want to put the upcoming activity's process
1635 // at the top of the LRU list, since we know we will be needing it
1636 // very soon and it would be a waste to let it get killed if it
1637 // happens to be sitting towards the end.
1638 if (next.app != null && next.app.thread != null) {
1639 mService.updateLruProcessLocked(next.app, true, null);
1641 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1645 // If the most recent activity was noHistory but was only stopped rather
1646 // than stopped+finished because the device went to sleep, we need to make
1647 // sure to finish it as we're making a new activity topmost.
1648 if (mService.isSleeping() && mLastNoHistoryActivity != null &&
1649 !mLastNoHistoryActivity.finishing) {
1650 if (DEBUG_STATES) Slog.d(TAG, "no-history finish of " + mLastNoHistoryActivity +
1652 requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
1653 null, "no-history", false);
1654 mLastNoHistoryActivity = null;
1657 if (prev != null && prev != next) {
1658 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1659 prev.waitingVisible = true;
1660 mStackSupervisor.mWaitingVisibleActivities.add(prev);
1661 if (DEBUG_SWITCH) Slog.v(
1662 TAG, "Resuming top, waiting visible to hide: " + prev);
1664 // The next activity is already visible, so hide the previous
1665 // activity's windows right now so we can show the new one ASAP.
1666 // We only do this if the previous is finishing, which should mean
1667 // it is on top of the one being resumed so hiding it quickly
1668 // is good. Otherwise, we want to do the normal route of allowing
1669 // the resumed activity to be shown so we can decide if the
1670 // previous should actually be hidden depending on whether the
1671 // new one is found to be full-screen or not.
1672 if (prev.finishing) {
1673 mWindowManager.setAppVisibility(prev.appToken, false);
1674 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1675 + prev + ", waitingVisible="
1676 + (prev != null ? prev.waitingVisible : null)
1677 + ", nowVisible=" + next.nowVisible);
1679 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1680 + prev + ", waitingVisible="
1681 + (prev != null ? prev.waitingVisible : null)
1682 + ", nowVisible=" + next.nowVisible);
1687 // Launching this app's activity, make sure the app is no longer
1688 // considered stopped.
1690 AppGlobals.getPackageManager().setPackageStoppedState(
1691 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
1692 } catch (RemoteException e1) {
1693 } catch (IllegalArgumentException e) {
1694 Slog.w(TAG, "Failed trying to unstop package "
1695 + next.packageName + ": " + e);
1698 // We are starting up the next activity, so tell the window manager
1699 // that the previous one will be hidden soon. This way it can know
1700 // to ignore it when computing the desired screen orientation.
1701 boolean anim = true;
1703 if (prev.finishing) {
1704 if (DEBUG_TRANSITION) Slog.v(TAG,
1705 "Prepare close transition: prev=" + prev);
1706 if (mNoAnimActivities.contains(prev)) {
1708 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
1710 mWindowManager.prepareAppTransition(prev.task == next.task
1711 ? AppTransition.TRANSIT_ACTIVITY_CLOSE
1712 : AppTransition.TRANSIT_TASK_CLOSE, false);
1714 mWindowManager.setAppWillBeHidden(prev.appToken);
1715 mWindowManager.setAppVisibility(prev.appToken, false);
1717 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: prev=" + prev);
1718 if (mNoAnimActivities.contains(next)) {
1720 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
1722 mWindowManager.prepareAppTransition(prev.task == next.task
1723 ? AppTransition.TRANSIT_ACTIVITY_OPEN
1724 : next.mLaunchTaskBehind
1725 ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
1726 : AppTransition.TRANSIT_TASK_OPEN, false);
1730 mWindowManager.setAppWillBeHidden(prev.appToken);
1731 mWindowManager.setAppVisibility(prev.appToken, false);
1734 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: no previous");
1735 if (mNoAnimActivities.contains(next)) {
1737 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
1739 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_ACTIVITY_OPEN, false);
1743 Bundle resumeAnimOptions = null;
1745 ActivityOptions opts = next.getOptionsForTargetActivityLocked();
1747 resumeAnimOptions = opts.toBundle();
1749 next.applyOptionsLocked();
1751 next.clearOptionsLocked();
1754 ActivityStack lastStack = mStackSupervisor.getLastStack();
1755 if (next.app != null && next.app.thread != null) {
1756 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1758 // This activity is now becoming visible.
1759 mWindowManager.setAppVisibility(next.appToken, true);
1761 // schedule launch ticks to collect information about slow apps.
1762 next.startLaunchTickingLocked();
1764 ActivityRecord lastResumedActivity =
1765 lastStack == null ? null :lastStack.mResumedActivity;
1766 ActivityState lastState = next.state;
1768 mService.updateCpuStats();
1770 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
1771 next.state = ActivityState.RESUMED;
1772 mResumedActivity = next;
1773 next.task.touchActiveTime();
1774 mService.addRecentTaskLocked(next.task);
1775 mService.updateLruProcessLocked(next.app, true, null);
1776 updateLRUListLocked(next);
1777 mService.updateOomAdjLocked();
1779 // Have the window manager re-evaluate the orientation of
1780 // the screen based on the new activity order.
1781 boolean notUpdated = true;
1782 if (mStackSupervisor.isFrontStack(this)) {
1783 Configuration config = mWindowManager.updateOrientationFromAppTokens(
1784 mService.mConfiguration,
1785 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
1786 if (config != null) {
1787 next.frozenBeforeDestroy = true;
1789 notUpdated = !mService.updateConfigurationLocked(config, next, false, false);
1793 // The configuration update wasn't able to keep the existing
1794 // instance of the activity, and instead started a new one.
1795 // We should be all done, but let's just make sure our activity
1796 // is still at the top and schedule another run if something
1798 ActivityRecord nextNext = topRunningActivityLocked(null);
1799 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
1800 "Activity config changed during resume: " + next
1801 + ", new next: " + nextNext);
1802 if (nextNext != next) {
1804 mStackSupervisor.scheduleResumeTopActivities();
1806 if (mStackSupervisor.reportResumedActivityLocked(next)) {
1807 mNoAnimActivities.clear();
1808 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1811 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1816 // Deliver all pending results.
1817 ArrayList<ResultInfo> a = next.results;
1819 final int N = a.size();
1820 if (!next.finishing && N > 0) {
1821 if (DEBUG_RESULTS) Slog.v(
1822 TAG, "Delivering results to " + next
1824 next.app.thread.scheduleSendResult(next.appToken, a);
1828 if (next.newIntents != null) {
1829 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
1832 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, next.userId,
1833 System.identityHashCode(next), next.task.taskId, next.shortComponentName);
1835 next.sleeping = false;
1836 mService.showAskCompatModeDialogLocked(next);
1837 next.app.pendingUiClean = true;
1838 next.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_TOP);
1839 next.clearOptionsLocked();
1840 next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
1841 mService.isNextTransitionForward(), resumeAnimOptions);
1843 mStackSupervisor.checkReadyForSleepLocked();
1845 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Resumed " + next);
1846 } catch (Exception e) {
1847 // Whoops, need to restart this activity!
1848 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1849 + lastState + ": " + next);
1850 next.state = lastState;
1851 if (lastStack != null) {
1852 lastStack.mResumedActivity = lastResumedActivity;
1854 Slog.i(TAG, "Restarting because process died: " + next);
1855 if (!next.hasBeenLaunched) {
1856 next.hasBeenLaunched = true;
1857 } else if (SHOW_APP_STARTING_PREVIEW && lastStack != null &&
1858 mStackSupervisor.isFrontStack(lastStack)) {
1859 mWindowManager.setAppStartingWindow(
1860 next.appToken, next.packageName, next.theme,
1861 mService.compatibilityInfoForPackageLocked(next.info.applicationInfo),
1862 next.nonLocalizedLabel, next.labelRes, next.icon, next.logo,
1863 next.windowFlags, null, true);
1865 mStackSupervisor.startSpecificActivityLocked(next, true, false);
1866 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1870 // From this point on, if something goes wrong there is no way
1871 // to recover the activity.
1873 next.visible = true;
1874 completeResumeLocked(next);
1875 } catch (Exception e) {
1876 // If any exception gets thrown, toss away this
1877 // activity and try the next one.
1878 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1879 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
1880 "resume-exception", true);
1881 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1884 next.stopped = false;
1887 // Whoops, need to restart this activity!
1888 if (!next.hasBeenLaunched) {
1889 next.hasBeenLaunched = true;
1891 if (SHOW_APP_STARTING_PREVIEW) {
1892 mWindowManager.setAppStartingWindow(
1893 next.appToken, next.packageName, next.theme,
1894 mService.compatibilityInfoForPackageLocked(
1895 next.info.applicationInfo),
1896 next.nonLocalizedLabel,
1897 next.labelRes, next.icon, next.logo, next.windowFlags,
1900 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1902 if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Restarting " + next);
1903 mStackSupervisor.startSpecificActivityLocked(next, true, true);
1906 if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1910 private TaskRecord getNextTask(TaskRecord targetTask) {
1911 final int index = mTaskHistory.indexOf(targetTask);
1913 final int numTasks = mTaskHistory.size();
1914 for (int i = index + 1; i < numTasks; ++i) {
1915 TaskRecord task = mTaskHistory.get(i);
1916 if (task.userId == targetTask.userId) {
1924 private void insertTaskAtTop(TaskRecord task) {
1925 // If the moving task is over home stack, transfer its return type to next task
1926 if (task.isOverHomeStack()) {
1927 final TaskRecord nextTask = getNextTask(task);
1928 if (nextTask != null) {
1929 nextTask.setTaskToReturnTo(task.getTaskToReturnTo());
1933 // If this is being moved to the top by another activity or being launched from the home
1934 // activity, set mTaskToReturnTo accordingly.
1935 if (isOnHomeDisplay()) {
1936 ActivityStack lastStack = mStackSupervisor.getLastStack();
1937 final boolean fromHome = lastStack.isHomeStack();
1938 if (!isHomeStack() && (fromHome || topTask() != task)) {
1939 task.setTaskToReturnTo(fromHome
1940 ? lastStack.topTask() == null
1941 ? HOME_ACTIVITY_TYPE
1942 : lastStack.topTask().taskType
1943 : APPLICATION_ACTIVITY_TYPE);
1946 task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
1949 mTaskHistory.remove(task);
1950 // Now put task at top.
1951 int taskNdx = mTaskHistory.size();
1952 if (!isCurrentProfileLocked(task.userId)) {
1953 // Put non-current user tasks below current user tasks.
1954 while (--taskNdx >= 0) {
1955 if (!isCurrentProfileLocked(mTaskHistory.get(taskNdx).userId)) {
1961 mTaskHistory.add(taskNdx, task);
1962 updateTaskMovement(task, true);
1965 final void startActivityLocked(ActivityRecord r, boolean newTask,
1966 boolean doResume, boolean keepCurTransition, Bundle options) {
1967 TaskRecord rTask = r.task;
1968 final int taskId = rTask.taskId;
1969 // mLaunchTaskBehind tasks get placed at the back of the task stack.
1970 if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
1971 // Last activity in task had been removed or ActivityManagerService is reusing task.
1972 // Insert or replace.
1973 // Might not even be in.
1974 insertTaskAtTop(rTask);
1975 mWindowManager.moveTaskToTop(taskId);
1977 TaskRecord task = null;
1979 // If starting in an existing task, find where that is...
1980 boolean startIt = true;
1981 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1982 task = mTaskHistory.get(taskNdx);
1983 if (task.getTopActivity() == null) {
1984 // All activities in task are finishing.
1987 if (task == r.task) {
1988 // Here it is! Now, if this is not yet visible to the
1989 // user, then just add it without starting; it will
1990 // get started when the user navigates back to it.
1992 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
1993 + task, new RuntimeException("here").fillInStackTrace());
1994 task.addActivityToTop(r);
1996 mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
1997 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
1998 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0,
1999 r.userId, r.info.configChanges, task.voiceSession != null,
2000 r.mLaunchTaskBehind);
2001 if (VALIDATE_TOKENS) {
2002 validateAppTokensLocked();
2004 ActivityOptions.abort(options);
2008 } else if (task.numFullscreen > 0) {
2014 // Place a new activity at top of stack, so it is next to interact
2017 // If we are not placing the new activity frontmost, we do not want
2018 // to deliver the onUserLeaving callback to the actual frontmost
2020 if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
2021 mStackSupervisor.mUserLeaving = false;
2022 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2023 "startActivity() behind front, mUserLeaving=false");
2028 // Slot the activity into the history stack and proceed
2029 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
2030 new RuntimeException("here").fillInStackTrace());
2031 task.addActivityToTop(r);
2032 task.setFrontOfTask();
2035 if (!isHomeStack() || numActivities() > 0) {
2036 // We want to show the starting preview window if we are
2037 // switching to a new task, or the next activity's process is
2038 // not currently running.
2039 boolean showStartingIcon = newTask;
2040 ProcessRecord proc = r.app;
2042 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
2044 if (proc == null || proc.thread == null) {
2045 showStartingIcon = true;
2047 if (DEBUG_TRANSITION) Slog.v(TAG,
2048 "Prepare open transition: starting " + r);
2049 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
2050 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition);
2051 mNoAnimActivities.add(r);
2053 mWindowManager.prepareAppTransition(newTask
2054 ? r.mLaunchTaskBehind
2055 ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
2056 : AppTransition.TRANSIT_TASK_OPEN
2057 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
2058 mNoAnimActivities.remove(r);
2060 mWindowManager.addAppToken(task.mActivities.indexOf(r),
2061 r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
2062 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId,
2063 r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
2064 boolean doShow = true;
2066 // Even though this activity is starting fresh, we still need
2067 // to reset it to make sure we apply affinities to move any
2068 // existing activities from other tasks in to it.
2069 // If the caller has requested that the target task be
2070 // reset, then do so.
2071 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2072 resetTaskIfNeededLocked(r, r);
2073 doShow = topRunningNonDelayedActivityLocked(null) == r;
2075 } else if (options != null && new ActivityOptions(options).getAnimationType()
2076 == ActivityOptions.ANIM_SCENE_TRANSITION) {
2079 if (r.mLaunchTaskBehind) {
2080 // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we
2081 // tell WindowManager that r is visible even though it is at the back of the stack.
2082 mWindowManager.setAppVisibility(r.appToken, true);
2083 ensureActivitiesVisibleLocked(null, 0);
2084 } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
2085 // Figure out if we are transitioning from another activity that is
2086 // "has the same starting icon" as the next one. This allows the
2087 // window manager to keep the previous window it had previously
2088 // created, if it still had one.
2089 ActivityRecord prev = mResumedActivity;
2091 // We don't want to reuse the previous starting preview if:
2092 // (1) The current activity is in a different task.
2093 if (prev.task != r.task) {
2096 // (2) The current activity is already displayed.
2097 else if (prev.nowVisible) {
2101 mWindowManager.setAppStartingWindow(
2102 r.appToken, r.packageName, r.theme,
2103 mService.compatibilityInfoForPackageLocked(
2104 r.info.applicationInfo), r.nonLocalizedLabel,
2105 r.labelRes, r.icon, r.logo, r.windowFlags,
2106 prev != null ? prev.appToken : null, showStartingIcon);
2107 r.mStartingWindowShown = true;
2110 // If this is the first activity, don't do any fancy animations,
2111 // because there is nothing for it to animate on top of.
2112 mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
2113 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
2114 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId,
2115 r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
2116 ActivityOptions.abort(options);
2119 if (VALIDATE_TOKENS) {
2120 validateAppTokensLocked();
2124 mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
2128 final void validateAppTokensLocked() {
2129 mValidateAppTokens.clear();
2130 mValidateAppTokens.ensureCapacity(numActivities());
2131 final int numTasks = mTaskHistory.size();
2132 for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) {
2133 TaskRecord task = mTaskHistory.get(taskNdx);
2134 final ArrayList<ActivityRecord> activities = task.mActivities;
2135 if (activities.isEmpty()) {
2138 TaskGroup group = new TaskGroup();
2139 group.taskId = task.taskId;
2140 mValidateAppTokens.add(group);
2141 final int numActivities = activities.size();
2142 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
2143 final ActivityRecord r = activities.get(activityNdx);
2144 group.tokens.add(r.appToken);
2147 mWindowManager.validateAppTokens(mStackId, mValidateAppTokens);
2151 * Perform a reset of the given task, if needed as part of launching it.
2152 * Returns the new HistoryRecord at the top of the task.
2155 * Helper method for #resetTaskIfNeededLocked.
2156 * We are inside of the task being reset... we'll either finish this activity, push it out
2157 * for another task, or leave it as-is.
2158 * @param task The task containing the Activity (taskTop) that might be reset.
2160 * @return An ActivityOptions that needs to be processed.
2162 final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task, boolean forceReset) {
2163 ActivityOptions topOptions = null;
2165 int replyChainEnd = -1;
2166 boolean canMoveOptions = true;
2168 // We only do this for activities that are not the root of the task (since if we finish
2169 // the root, we may no longer have the task!).
2170 final ArrayList<ActivityRecord> activities = task.mActivities;
2171 final int numActivities = activities.size();
2172 final int rootActivityNdx = task.findEffectiveRootIndex();
2173 for (int i = numActivities - 1; i > rootActivityNdx; --i ) {
2174 ActivityRecord target = activities.get(i);
2175 if (target.frontOfTask)
2178 final int flags = target.info.flags;
2179 final boolean finishOnTaskLaunch =
2180 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2181 final boolean allowTaskReparenting =
2182 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2183 final boolean clearWhenTaskReset =
2184 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2186 if (!finishOnTaskLaunch
2187 && !clearWhenTaskReset
2188 && target.resultTo != null) {
2189 // If this activity is sending a reply to a previous
2190 // activity, we can't do anything with it now until
2191 // we reach the start of the reply chain.
2192 // XXX note that we are assuming the result is always
2193 // to the previous activity, which is almost always
2194 // the case but we really shouldn't count on.
2195 if (replyChainEnd < 0) {
2198 } else if (!finishOnTaskLaunch
2199 && !clearWhenTaskReset
2200 && allowTaskReparenting
2201 && target.taskAffinity != null
2202 && !target.taskAffinity.equals(task.affinity)) {
2203 // If this activity has an affinity for another
2204 // task, then we need to move it out of here. We will
2205 // move it as far out of the way as possible, to the
2206 // bottom of the activity stack. This also keeps it
2207 // correctly ordered with any activities we previously
2209 final TaskRecord targetTask;
2210 final ActivityRecord bottom =
2211 !mTaskHistory.isEmpty() && !mTaskHistory.get(0).mActivities.isEmpty() ?
2212 mTaskHistory.get(0).mActivities.get(0) : null;
2213 if (bottom != null && target.taskAffinity != null
2214 && target.taskAffinity.equals(bottom.task.affinity)) {
2215 // If the activity currently at the bottom has the
2216 // same task affinity as the one we are moving,
2217 // then merge it into the same task.
2218 targetTask = bottom.task;
2219 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2220 + " out to bottom task " + bottom.task);
2222 targetTask = createTaskRecord(mStackSupervisor.getNextTaskId(), target.info,
2223 null, null, null, false);
2224 targetTask.affinityIntent = target.intent;
2225 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2226 + " out to new task " + target.task);
2229 final int targetTaskId = targetTask.taskId;
2230 mWindowManager.setAppGroupId(target.appToken, targetTaskId);
2232 boolean noOptions = canMoveOptions;
2233 final int start = replyChainEnd < 0 ? i : replyChainEnd;
2234 for (int srcPos = start; srcPos >= i; --srcPos) {
2235 final ActivityRecord p = activities.get(srcPos);
2240 canMoveOptions = false;
2241 if (noOptions && topOptions == null) {
2242 topOptions = p.takeOptionsLocked();
2243 if (topOptions != null) {
2247 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task="
2248 + task + " adding to task=" + targetTask
2249 + " Callers=" + Debug.getCallers(4));
2250 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2251 + " out to target's task " + target.task);
2252 p.setTask(targetTask, null);
2253 targetTask.addActivityAtBottom(p);
2255 mWindowManager.setAppGroupId(p.appToken, targetTaskId);
2258 mWindowManager.moveTaskToBottom(targetTaskId);
2259 if (VALIDATE_TOKENS) {
2260 validateAppTokensLocked();
2264 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) {
2265 // If the activity should just be removed -- either
2266 // because it asks for it, or the task should be
2267 // cleared -- then finish it and anything that is
2268 // part of its reply chain.
2270 if (clearWhenTaskReset) {
2271 // In this case, we want to finish this activity
2272 // and everything above it, so be sneaky and pretend
2273 // like these are all in the reply chain.
2274 end = activities.size() - 1;
2275 } else if (replyChainEnd < 0) {
2278 end = replyChainEnd;
2280 boolean noOptions = canMoveOptions;
2281 for (int srcPos = i; srcPos <= end; srcPos++) {
2282 ActivityRecord p = activities.get(srcPos);
2286 canMoveOptions = false;
2287 if (noOptions && topOptions == null) {
2288 topOptions = p.takeOptionsLocked();
2289 if (topOptions != null) {
2293 if (DEBUG_TASKS) Slog.w(TAG,
2294 "resetTaskIntendedTask: calling finishActivity on " + p);
2295 if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) {
2302 // If we were in the middle of a chain, well the
2303 // activity that started it all doesn't want anything
2304 // special, so leave it all as-is.
2313 * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given
2314 * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop.
2315 * @param affinityTask The task we are looking for an affinity to.
2316 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to.
2317 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked.
2318 * @param forceReset Flag passed in to resetTaskIfNeededLocked.
2320 private int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task,
2321 boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) {
2322 int replyChainEnd = -1;
2323 final int taskId = task.taskId;
2324 final String taskAffinity = task.affinity;
2326 final ArrayList<ActivityRecord> activities = affinityTask.mActivities;
2327 final int numActivities = activities.size();
2328 final int rootActivityNdx = affinityTask.findEffectiveRootIndex();
2330 // Do not operate on or below the effective root Activity.
2331 for (int i = numActivities - 1; i > rootActivityNdx; --i) {
2332 ActivityRecord target = activities.get(i);
2333 if (target.frontOfTask)
2336 final int flags = target.info.flags;
2337 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2338 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2340 if (target.resultTo != null) {
2341 // If this activity is sending a reply to a previous
2342 // activity, we can't do anything with it now until
2343 // we reach the start of the reply chain.
2344 // XXX note that we are assuming the result is always
2345 // to the previous activity, which is almost always
2346 // the case but we really shouldn't count on.
2347 if (replyChainEnd < 0) {
2350 } else if (topTaskIsHigher
2351 && allowTaskReparenting
2352 && taskAffinity != null
2353 && taskAffinity.equals(target.taskAffinity)) {
2354 // This activity has an affinity for our task. Either remove it if we are
2355 // clearing or move it over to our task. Note that
2356 // we currently punt on the case where we are resetting a
2357 // task that is not at the top but who has activities above
2358 // with an affinity to it... this is really not a normal
2359 // case, and we will need to later pull that task to the front
2360 // and usually at that point we will do the reset and pick
2361 // up those remaining activities. (This only happens if
2362 // someone starts an activity in a new task from an activity
2363 // in a task that is not currently on top.)
2364 if (forceReset || finishOnTaskLaunch) {
2365 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2366 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i);
2367 for (int srcPos = start; srcPos >= i; --srcPos) {
2368 final ActivityRecord p = activities.get(srcPos);
2372 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false);
2375 if (taskInsertionPoint < 0) {
2376 taskInsertionPoint = task.mActivities.size();
2380 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2381 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting from task=" + affinityTask + ":"
2382 + start + "-" + i + " to task=" + task + ":" + taskInsertionPoint);
2383 for (int srcPos = start; srcPos >= i; --srcPos) {
2384 final ActivityRecord p = activities.get(srcPos);
2385 p.setTask(task, null);
2386 task.addActivityAtIndex(taskInsertionPoint, p);
2388 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p
2389 + " to stack at " + task,
2390 new RuntimeException("here").fillInStackTrace());
2391 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos
2392 + " in to resetting task " + task);
2393 mWindowManager.setAppGroupId(p.appToken, taskId);
2395 mWindowManager.moveTaskToTop(taskId);
2396 if (VALIDATE_TOKENS) {
2397 validateAppTokensLocked();
2400 // Now we've moved it in to place... but what if this is
2401 // a singleTop activity and we have put it on top of another
2402 // instance of the same activity? Then we drop the instance
2403 // below so it remains singleTop.
2404 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2405 ArrayList<ActivityRecord> taskActivities = task.mActivities;
2406 int targetNdx = taskActivities.indexOf(target);
2407 if (targetNdx > 0) {
2408 ActivityRecord p = taskActivities.get(targetNdx - 1);
2409 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2410 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace",
2420 return taskInsertionPoint;
2423 final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
2424 ActivityRecord newActivity) {
2425 boolean forceReset =
2426 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
2427 if (ACTIVITY_INACTIVE_RESET_TIME > 0
2428 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
2429 if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
2434 final TaskRecord task = taskTop.task;
2436 /** False until we evaluate the TaskRecord associated with taskTop. Switches to true
2437 * for remaining tasks. Used for later tasks to reparent to task. */
2438 boolean taskFound = false;
2440 /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */
2441 ActivityOptions topOptions = null;
2443 // Preserve the location for reparenting in the new task.
2444 int reparentInsertionPoint = -1;
2446 for (int i = mTaskHistory.size() - 1; i >= 0; --i) {
2447 final TaskRecord targetTask = mTaskHistory.get(i);
2449 if (targetTask == task) {
2450 topOptions = resetTargetTaskIfNeededLocked(task, forceReset);
2453 reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task,
2454 taskFound, forceReset, reparentInsertionPoint);
2458 int taskNdx = mTaskHistory.indexOf(task);
2461 taskTop = mTaskHistory.get(taskNdx--).getTopActivity();
2462 } while (taskTop == null && taskNdx >= 0);
2465 if (topOptions != null) {
2466 // If we got some ActivityOptions from an activity on top that
2467 // was removed from the task, propagate them to the new real top.
2468 if (taskTop != null) {
2469 taskTop.updateOptionsLocked(topOptions);
2478 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2479 String resultWho, int requestCode, int resultCode, Intent data) {
2481 if (callingUid > 0) {
2482 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
2483 data, r.getUriPermissionsLocked(), r.userId);
2486 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2487 + " : who=" + resultWho + " req=" + requestCode
2488 + " res=" + resultCode + " data=" + data);
2489 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2491 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2492 list.add(new ResultInfo(resultWho, requestCode,
2494 r.app.thread.scheduleSendResult(r.appToken, list);
2496 } catch (Exception e) {
2497 Slog.w(TAG, "Exception thrown sending result to " + r, e);
2501 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2504 private void adjustFocusedActivityLocked(ActivityRecord r, String reason) {
2505 if (mStackSupervisor.isFrontStack(this) && mService.mFocusedActivity == r) {
2506 ActivityRecord next = topRunningActivityLocked(null);
2508 final TaskRecord task = r.task;
2509 if (r.frontOfTask && task == topTask() && task.isOverHomeStack()) {
2510 mStackSupervisor.moveHomeStackTaskToTop(task.getTaskToReturnTo(),
2511 reason + " adjustFocus");
2514 ActivityRecord top = mStackSupervisor.topRunningActivityLocked();
2516 mService.setFocusedActivityLocked(top, reason + " adjustTopFocus");
2521 final void stopActivityLocked(ActivityRecord r) {
2522 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2523 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2524 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2526 if (!mService.isSleeping()) {
2528 Slog.d(TAG, "no-history finish of " + r);
2530 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
2531 "no-history", false);
2533 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
2534 + " on stop because we're just sleeping");
2539 if (r.app != null && r.app.thread != null) {
2540 adjustFocusedActivityLocked(r, "stopActivity");
2541 r.resumeKeyDispatchingLocked();
2544 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
2545 + " (stop requested)");
2546 r.state = ActivityState.STOPPING;
2547 if (DEBUG_VISBILITY) Slog.v(
2548 TAG, "Stopping visible=" + r.visible + " for " + r);
2550 mWindowManager.setAppVisibility(r.appToken, false);
2552 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
2553 if (mService.isSleepingOrShuttingDown()) {
2554 r.setSleeping(true);
2556 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
2557 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
2558 } catch (Exception e) {
2559 // Maybe just ignore exceptions here... if the process
2560 // has crashed, our death notification will clean things
2562 Slog.w(TAG, "Exception thrown during pause", e);
2563 // Just in case, assume it to be stopped.
2565 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
2566 r.state = ActivityState.STOPPED;
2567 if (r.configDestroy) {
2568 destroyActivityLocked(r, true, "stop-except");
2575 * @return Returns true if the activity is being finished, false if for
2576 * some reason it is being left as-is.
2578 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
2579 Intent resultData, String reason, boolean oomAdj) {
2580 ActivityRecord r = isInStackLocked(token);
2581 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
2582 TAG, "Finishing activity token=" + token + " r="
2583 + ", result=" + resultCode + ", data=" + resultData
2584 + ", reason=" + reason);
2589 finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
2593 final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) {
2594 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2595 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2596 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2597 ActivityRecord r = activities.get(activityNdx);
2598 if (r.resultTo == self && r.requestCode == requestCode) {
2599 if ((r.resultWho == null && resultWho == null) ||
2600 (r.resultWho != null && r.resultWho.equals(resultWho))) {
2601 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
2607 mService.updateOomAdjLocked();
2610 final void finishTopRunningActivityLocked(ProcessRecord app) {
2611 ActivityRecord r = topRunningActivityLocked(null);
2612 if (r != null && r.app == app) {
2613 // If the top running activity is from this crashing
2614 // process, then terminate it to avoid getting in a loop.
2615 Slog.w(TAG, " Force finishing activity 1 "
2616 + r.intent.getComponent().flattenToShortString());
2617 int taskNdx = mTaskHistory.indexOf(r.task);
2618 int activityNdx = r.task.mActivities.indexOf(r);
2619 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
2620 // Also terminate any activities below it that aren't yet
2621 // stopped, to avoid a situation where one will get
2622 // re-start our crashing activity once it gets resumed again.
2624 if (activityNdx < 0) {
2630 activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1;
2631 } while (activityNdx < 0);
2633 if (activityNdx >= 0) {
2634 r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx);
2635 if (r.state == ActivityState.RESUMED
2636 || r.state == ActivityState.PAUSING
2637 || r.state == ActivityState.PAUSED) {
2638 if (!r.isHomeActivity() || mService.mHomeProcess != r.app) {
2639 Slog.w(TAG, " Force finishing activity 2 "
2640 + r.intent.getComponent().flattenToShortString());
2641 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
2648 final void finishVoiceTask(IVoiceInteractionSession session) {
2649 IBinder sessionBinder = session.asBinder();
2650 boolean didOne = false;
2651 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2652 TaskRecord tr = mTaskHistory.get(taskNdx);
2653 if (tr.voiceSession != null && tr.voiceSession.asBinder() == sessionBinder) {
2654 for (int activityNdx = tr.mActivities.size() - 1; activityNdx >= 0; --activityNdx) {
2655 ActivityRecord r = tr.mActivities.get(activityNdx);
2657 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "finish-voice",
2665 mService.updateOomAdjLocked();
2669 final boolean finishActivityAffinityLocked(ActivityRecord r) {
2670 ArrayList<ActivityRecord> activities = r.task.mActivities;
2671 for (int index = activities.indexOf(r); index >= 0; --index) {
2672 ActivityRecord cur = activities.get(index);
2673 if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) {
2676 finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true);
2681 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
2683 ActivityRecord resultTo = r.resultTo;
2684 if (resultTo != null) {
2685 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
2686 + " who=" + r.resultWho + " req=" + r.requestCode
2687 + " res=" + resultCode + " data=" + resultData);
2688 if (resultTo.userId != r.userId) {
2689 if (resultData != null) {
2690 resultData.setContentUserHint(r.userId);
2693 if (r.info.applicationInfo.uid > 0) {
2694 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
2695 resultTo.packageName, resultData,
2696 resultTo.getUriPermissionsLocked(), resultTo.userId);
2698 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
2702 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
2704 // Make sure this HistoryRecord is not holding on to other resources,
2705 // because clients have remote IPC references to this object so we
2706 // can't assume that will go away and want to avoid circular IPC refs.
2708 r.pendingResults = null;
2709 r.newIntents = null;
2714 * @return Returns true if this activity has been removed from the history
2715 * list, or false if it is still in the list and will be removed later.
2717 final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
2718 String reason, boolean oomAdj) {
2720 Slog.w(TAG, "Duplicate finish request for " + r);
2725 final TaskRecord task = r.task;
2726 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2727 r.userId, System.identityHashCode(r),
2728 task.taskId, r.shortComponentName, reason);
2729 final ArrayList<ActivityRecord> activities = task.mActivities;
2730 final int index = activities.indexOf(r);
2731 if (index < (activities.size() - 1)) {
2732 task.setFrontOfTask();
2733 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
2734 // If the caller asked that this activity (and all above it)
2735 // be cleared when the task is reset, don't lose that information,
2736 // but propagate it up to the next activity.
2737 ActivityRecord next = activities.get(index+1);
2738 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
2742 r.pauseKeyDispatchingLocked();
2744 adjustFocusedActivityLocked(r, "finishActivity");
2746 finishActivityResultsLocked(r, resultCode, resultData);
2748 if (mResumedActivity == r) {
2749 boolean endTask = index <= 0;
2750 if (DEBUG_VISBILITY || DEBUG_TRANSITION) Slog.v(TAG,
2751 "Prepare close transition: finishing " + r);
2752 mWindowManager.prepareAppTransition(endTask
2753 ? AppTransition.TRANSIT_TASK_CLOSE
2754 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
2756 // Tell window manager to prepare for this one to be removed.
2757 mWindowManager.setAppVisibility(r.appToken, false);
2759 if (mPausingActivity == null) {
2760 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
2761 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
2762 startPausingLocked(false, false, false, false);
2766 mStackSupervisor.endLockTaskModeIfTaskEnding(task);
2768 } else if (r.state != ActivityState.PAUSING) {
2769 // If the activity is PAUSING, we will complete the finish once
2770 // it is done pausing; else we can just directly finish it here.
2771 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
2772 return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null;
2774 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
2780 static final int FINISH_IMMEDIATELY = 0;
2781 static final int FINISH_AFTER_PAUSE = 1;
2782 static final int FINISH_AFTER_VISIBLE = 2;
2784 final ActivityRecord finishCurrentActivityLocked(ActivityRecord r, int mode, boolean oomAdj) {
2785 // First things first: if this activity is currently visible,
2786 // and the resumed activity is not yet visible, then hold off on
2787 // finishing until the resumed one becomes visible.
2788 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
2789 if (!mStackSupervisor.mStoppingActivities.contains(r)) {
2790 mStackSupervisor.mStoppingActivities.add(r);
2791 if (mStackSupervisor.mStoppingActivities.size() > 3
2792 || r.frontOfTask && mTaskHistory.size() <= 1) {
2793 // If we already have a few activities waiting to stop,
2794 // then give up on things going idle and start clearing
2795 // them out. Or if r is the last of activity of the last task the stack
2796 // will be empty and must be cleared immediately.
2797 mStackSupervisor.scheduleIdleLocked();
2799 mStackSupervisor.checkReadyForSleepLocked();
2802 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
2803 + " (finish requested)");
2804 r.state = ActivityState.STOPPING;
2806 mService.updateOomAdjLocked();
2811 // make sure the record is cleaned out of other places.
2812 mStackSupervisor.mStoppingActivities.remove(r);
2813 mStackSupervisor.mGoingToSleepActivities.remove(r);
2814 mStackSupervisor.mWaitingVisibleActivities.remove(r);
2815 r.waitingVisible = false;
2816 if (mResumedActivity == r) {
2817 mResumedActivity = null;
2819 final ActivityState prevState = r.state;
2820 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
2821 r.state = ActivityState.FINISHING;
2823 if (mode == FINISH_IMMEDIATELY
2824 || prevState == ActivityState.STOPPED
2825 || prevState == ActivityState.INITIALIZING) {
2826 // If this activity is already stopped, we can just finish
2829 boolean activityRemoved = destroyActivityLocked(r, true, "finish-imm");
2830 if (activityRemoved) {
2831 mStackSupervisor.resumeTopActivitiesLocked();
2833 if (DEBUG_CONTAINERS) Slog.d(TAG,
2834 "destroyActivityLocked: finishCurrentActivityLocked r=" + r +
2835 " destroy returned removed=" + activityRemoved);
2836 return activityRemoved ? null : r;
2839 // Need to go through the full pause cycle to get this
2840 // activity into the stopped state and then finish it.
2841 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
2842 mStackSupervisor.mFinishingActivities.add(r);
2843 r.resumeKeyDispatchingLocked();
2844 mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null);
2848 void finishAllActivitiesLocked(boolean immediately) {
2849 boolean noActivitiesInStack = true;
2850 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2851 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2852 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2853 final ActivityRecord r = activities.get(activityNdx);
2854 noActivitiesInStack = false;
2855 if (r.finishing && !immediately) {
2858 Slog.d(TAG, "finishAllActivitiesLocked: finishing " + r + " immediately");
2859 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
2862 if (noActivitiesInStack) {
2863 mActivityContainer.onTaskListEmptyLocked();
2867 final boolean shouldUpRecreateTaskLocked(ActivityRecord srec, String destAffinity) {
2868 // Basic case: for simple app-centric recents, we need to recreate
2869 // the task if the affinity has changed.
2870 if (srec == null || srec.task.affinity == null ||
2871 !srec.task.affinity.equals(destAffinity)) {
2874 // Document-centric case: an app may be split in to multiple documents;
2875 // they need to re-create their task if this current activity is the root
2876 // of a document, unless simply finishing it will return them to the the
2877 // correct app behind.
2878 if (srec.frontOfTask && srec.task != null && srec.task.getBaseIntent() != null
2879 && srec.task.getBaseIntent().isDocument()) {
2880 // Okay, this activity is at the root of its task. What to do, what to do...
2881 if (srec.task.getTaskToReturnTo() != ActivityRecord.APPLICATION_ACTIVITY_TYPE) {
2882 // Finishing won't return to an application, so we need to recreate.
2885 // We now need to get the task below it to determine what to do.
2886 int taskIdx = mTaskHistory.indexOf(srec.task);
2888 Slog.w(TAG, "shouldUpRecreateTask: task not in history for " + srec);
2892 // At the bottom of the stack, nothing to go back to.
2895 TaskRecord prevTask = mTaskHistory.get(taskIdx);
2896 if (!srec.task.affinity.equals(prevTask.affinity)) {
2897 // These are different apps, so need to recreate.
2904 final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode,
2905 Intent resultData) {
2906 final ActivityRecord srec = ActivityRecord.forToken(token);
2907 final TaskRecord task = srec.task;
2908 final ArrayList<ActivityRecord> activities = task.mActivities;
2909 final int start = activities.indexOf(srec);
2910 if (!mTaskHistory.contains(task) || (start < 0)) {
2913 int finishTo = start - 1;
2914 ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo);
2915 boolean foundParentInTask = false;
2916 final ComponentName dest = destIntent.getComponent();
2917 if (start > 0 && dest != null) {
2918 for (int i = finishTo; i >= 0; i--) {
2919 ActivityRecord r = activities.get(i);
2920 if (r.info.packageName.equals(dest.getPackageName()) &&
2921 r.info.name.equals(dest.getClassName())) {
2924 foundParentInTask = true;
2930 IActivityController controller = mService.mController;
2931 if (controller != null) {
2932 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
2934 // ask watcher if this is allowed
2935 boolean resumeOK = true;
2937 resumeOK = controller.activityResuming(next.packageName);
2938 } catch (RemoteException e) {
2939 mService.mController = null;
2940 Watchdog.getInstance().setActivityController(null);
2948 final long origId = Binder.clearCallingIdentity();
2949 for (int i = start; i > finishTo; i--) {
2950 ActivityRecord r = activities.get(i);
2951 requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
2952 // Only return the supplied result for the first activity finished
2953 resultCode = Activity.RESULT_CANCELED;
2957 if (parent != null && foundParentInTask) {
2958 final int parentLaunchMode = parent.info.launchMode;
2959 final int destIntentFlags = destIntent.getFlags();
2960 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
2961 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
2962 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
2963 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2964 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent,
2968 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
2969 destIntent.getComponent(), 0, srec.userId);
2970 int res = mStackSupervisor.startActivityLocked(srec.app.thread, destIntent,
2971 null, aInfo, null, null, parent.appToken, null,
2972 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
2973 -1, parent.launchedFromUid, 0, null, true, null, null, null);
2974 foundParentInTask = res == ActivityManager.START_SUCCESS;
2975 } catch (RemoteException e) {
2976 foundParentInTask = false;
2978 requestFinishActivityLocked(parent.appToken, resultCode,
2979 resultData, "navigate-up", true);
2982 Binder.restoreCallingIdentity(origId);
2983 return foundParentInTask;
2986 * Perform the common clean-up of an activity record. This is called both
2987 * as part of destroyActivityLocked() (when destroying the client-side
2988 * representation) and cleaning things up as a result of its hosting
2989 * processing going away, in which case there is no remaining client-side
2990 * state to destroy so only the cleanup here is needed.
2992 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
2994 if (mResumedActivity == r) {
2995 mResumedActivity = null;
2997 if (mPausingActivity == r) {
2998 mPausingActivity = null;
3000 mService.clearFocusedActivity(r);
3002 r.configDestroy = false;
3003 r.frozenBeforeDestroy = false;
3006 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3007 r.state = ActivityState.DESTROYED;
3008 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
3012 // Make sure this record is no longer in the pending finishes list.
3013 // This could happen, for example, if we are trimming activities
3014 // down to the max limit while they are still waiting to finish.
3015 mStackSupervisor.mFinishingActivities.remove(r);
3016 mStackSupervisor.mWaitingVisibleActivities.remove(r);
3017 r.waitingVisible = false;
3019 // Remove any pending results.
3020 if (r.finishing && r.pendingResults != null) {
3021 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3022 PendingIntentRecord rec = apr.get();
3024 mService.cancelIntentSenderLocked(rec, false);
3027 r.pendingResults = null;
3030 if (cleanServices) {
3031 cleanUpActivityServicesLocked(r);
3034 // Get rid of any pending idle timeouts.
3035 removeTimeoutsForActivityLocked(r);
3036 if (getVisibleBehindActivity() == r) {
3037 mStackSupervisor.requestVisibleBehindLocked(r, false);
3041 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
3042 mStackSupervisor.removeTimeoutsForActivityLocked(r);
3043 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3044 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
3045 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3046 r.finishLaunchTickingLocked();
3049 private void removeActivityFromHistoryLocked(ActivityRecord r, String reason) {
3050 mStackSupervisor.removeChildActivityContainers(r);
3051 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
3053 if (DEBUG_ADD_REMOVE) {
3054 RuntimeException here = new RuntimeException("here");
3055 here.fillInStackTrace();
3056 Slog.i(TAG, "Removing activity " + r + " from stack");
3058 r.takeFromHistory();
3059 removeTimeoutsForActivityLocked(r);
3060 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)");
3061 r.state = ActivityState.DESTROYED;
3062 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
3064 mWindowManager.removeAppToken(r.appToken);
3065 if (VALIDATE_TOKENS) {
3066 validateAppTokensLocked();
3068 final TaskRecord task = r.task;
3069 if (task != null && task.removeActivity(r)) {
3070 if (DEBUG_STACK) Slog.i(TAG,
3071 "removeActivityFromHistoryLocked: last activity removed from " + this);
3072 if (mStackSupervisor.isFrontStack(this) && task == topTask() &&
3073 task.isOverHomeStack()) {
3074 mStackSupervisor.moveHomeStackTaskToTop(task.getTaskToReturnTo(), reason);
3076 removeTask(task, reason);
3078 cleanUpActivityServicesLocked(r);
3079 r.removeUriPermissionsLocked();
3083 * Perform clean-up of service connections in an activity record.
3085 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3086 // Throw away any services that have been bound by this activity.
3087 if (r.connections != null) {
3088 Iterator<ConnectionRecord> it = r.connections.iterator();
3089 while (it.hasNext()) {
3090 ConnectionRecord c = it.next();
3091 mService.mServices.removeConnectionLocked(c, null, r);
3093 r.connections = null;
3097 final void scheduleDestroyActivities(ProcessRecord owner, String reason) {
3098 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
3099 msg.obj = new ScheduleDestroyArgs(owner, reason);
3100 mHandler.sendMessage(msg);
3103 final void destroyActivitiesLocked(ProcessRecord owner, String reason) {
3104 boolean lastIsOpaque = false;
3105 boolean activityRemoved = false;
3106 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3107 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3108 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3109 final ActivityRecord r = activities.get(activityNdx);
3114 lastIsOpaque = true;
3116 if (owner != null && r.app != owner) {
3119 if (!lastIsOpaque) {
3122 if (r.isDestroyable()) {
3123 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3124 + " resumed=" + mResumedActivity
3125 + " pausing=" + mPausingActivity + " for reason " + reason);
3126 if (destroyActivityLocked(r, true, reason)) {
3127 activityRemoved = true;
3132 if (activityRemoved) {
3133 mStackSupervisor.resumeTopActivitiesLocked();
3137 final boolean safelyDestroyActivityLocked(ActivityRecord r, String reason) {
3138 if (r.isDestroyable()) {
3139 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3140 + " resumed=" + mResumedActivity
3141 + " pausing=" + mPausingActivity + " for reason " + reason);
3142 return destroyActivityLocked(r, true, reason);
3147 final int releaseSomeActivitiesLocked(ProcessRecord app, ArraySet<TaskRecord> tasks,
3149 // Iterate over tasks starting at the back (oldest) first.
3150 if (DEBUG_RELEASE) Slog.d(TAG, "Trying to release some activities in " + app);
3151 int maxTasks = tasks.size() / 4;
3155 int numReleased = 0;
3156 for (int taskNdx = 0; taskNdx < mTaskHistory.size() && maxTasks > 0; taskNdx++) {
3157 final TaskRecord task = mTaskHistory.get(taskNdx);
3158 if (!tasks.contains(task)) {
3161 if (DEBUG_RELEASE) Slog.d(TAG, "Looking for activities to release in " + task);
3163 final ArrayList<ActivityRecord> activities = task.mActivities;
3164 for (int actNdx = 0; actNdx < activities.size(); actNdx++) {
3165 final ActivityRecord activity = activities.get(actNdx);
3166 if (activity.app == app && activity.isDestroyable()) {
3167 if (DEBUG_RELEASE) Slog.v(TAG, "Destroying " + activity
3168 + " in state " + activity.state + " resumed=" + mResumedActivity
3169 + " pausing=" + mPausingActivity + " for reason " + reason);
3170 destroyActivityLocked(activity, true, reason);
3171 if (activities.get(actNdx) != activity) {
3172 // Was removed from list, back up so we don't miss the next one.
3179 numReleased += curNum;
3181 if (mTaskHistory.get(taskNdx) != task) {
3182 // The entire task got removed, back up so we don't miss the next one.
3187 if (DEBUG_RELEASE) Slog.d(TAG, "Done releasing: did " + numReleased + " activities");
3192 * Destroy the current CLIENT SIDE instance of an activity. This may be
3193 * called both when actually finishing an activity, or when performing
3194 * a configuration switch where we destroy the current client-side object
3195 * but then create a new client-side object for this same HistoryRecord.
3197 final boolean destroyActivityLocked(ActivityRecord r, boolean removeFromApp, String reason) {
3198 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
3199 TAG, "Removing activity from " + reason + ": token=" + r
3200 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3201 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3202 r.userId, System.identityHashCode(r),
3203 r.task.taskId, r.shortComponentName, reason);
3205 boolean removedFromHistory = false;
3207 cleanUpActivityLocked(r, false, false);
3209 final boolean hadApp = r.app != null;
3212 if (removeFromApp) {
3213 r.app.activities.remove(r);
3214 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3215 mService.mHeavyWeightProcess = null;
3216 mService.mHandler.sendEmptyMessage(
3217 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3219 if (r.app.activities.isEmpty()) {
3220 // Update any services we are bound to that might care about whether
3221 // their client may have activities.
3222 mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
3223 // No longer have activities, so update LRU list and oom adj.
3224 mService.updateLruProcessLocked(r.app, false, null);
3225 mService.updateOomAdjLocked();
3229 boolean skipDestroy = false;
3232 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3233 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
3234 r.configChangeFlags);
3235 } catch (Exception e) {
3236 // We can just ignore exceptions here... if the process
3237 // has crashed, our death notification will clean things
3239 //Slog.w(TAG, "Exception thrown during finish", e);
3241 removeActivityFromHistoryLocked(r, reason + " exceptionInScheduleDestroy");
3242 removedFromHistory = true;
3247 r.nowVisible = false;
3249 // If the activity is finishing, we need to wait on removing it
3250 // from the list to give it a chance to do its cleanup. During
3251 // that time it may make calls back with its token so we need to
3252 // be able to find it on the list and so we don't want to remove
3253 // it from the list yet. Otherwise, we can just immediately put
3254 // it in the destroyed state since we are not removing it from the
3256 if (r.finishing && !skipDestroy) {
3257 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3258 + " (destroy requested)");
3259 r.state = ActivityState.DESTROYING;
3260 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r);
3261 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3263 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (destroy skipped)");
3264 r.state = ActivityState.DESTROYED;
3265 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
3269 // remove this record from the history.
3271 removeActivityFromHistoryLocked(r, reason + " hadNoApp");
3272 removedFromHistory = true;
3274 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (no app)");
3275 r.state = ActivityState.DESTROYED;
3276 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
3281 r.configChangeFlags = 0;
3283 if (!mLRUActivities.remove(r) && hadApp) {
3284 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3287 return removedFromHistory;
3290 final void activityDestroyedLocked(IBinder token, String reason) {
3291 final long origId = Binder.clearCallingIdentity();
3293 ActivityRecord r = ActivityRecord.forToken(token);
3295 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3297 if (DEBUG_CONTAINERS) Slog.d(TAG, "activityDestroyedLocked: r=" + r);
3299 if (isInStackLocked(token) != null) {
3300 if (r.state == ActivityState.DESTROYING) {
3301 cleanUpActivityLocked(r, true, false);
3302 removeActivityFromHistoryLocked(r, reason);
3305 mStackSupervisor.resumeTopActivitiesLocked();
3307 Binder.restoreCallingIdentity(origId);
3311 void releaseBackgroundResources() {
3312 if (hasVisibleBehindActivity() &&
3313 !mHandler.hasMessages(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG)) {
3314 final ActivityRecord r = getVisibleBehindActivity();
3315 if (r == topRunningActivityLocked(null)) {
3316 // Don't release the top activity if it has requested to run behind the next
3320 if (DEBUG_STATES) Slog.d(TAG, "releaseBackgroundResources activtyDisplay=" +
3321 mActivityContainer.mActivityDisplay + " visibleBehind=" + r + " app=" + r.app +
3322 " thread=" + r.app.thread);
3323 if (r != null && r.app != null && r.app.thread != null) {
3325 r.app.thread.scheduleCancelVisibleBehind(r.appToken);
3326 } catch (RemoteException e) {
3328 mHandler.sendEmptyMessageDelayed(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG, 500);
3330 Slog.e(TAG, "releaseBackgroundResources: activity " + r + " no longer running");
3331 backgroundResourcesReleased();
3336 final void backgroundResourcesReleased() {
3337 mHandler.removeMessages(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG);
3338 final ActivityRecord r = getVisibleBehindActivity();
3340 mStackSupervisor.mStoppingActivities.add(r);
3341 setVisibleBehindActivity(null);
3342 mStackSupervisor.scheduleIdleTimeoutLocked(null);
3344 mStackSupervisor.resumeTopActivitiesLocked();
3347 boolean hasVisibleBehindActivity() {
3348 return isAttached() && mActivityContainer.mActivityDisplay.hasVisibleBehindActivity();
3351 void setVisibleBehindActivity(ActivityRecord r) {
3353 mActivityContainer.mActivityDisplay.setVisibleBehindActivity(r);
3357 ActivityRecord getVisibleBehindActivity() {
3358 return isAttached() ? mActivityContainer.mActivityDisplay.mVisibleBehindActivity : null;
3361 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
3362 ProcessRecord app, String listName) {
3363 int i = list.size();
3364 if (DEBUG_CLEANUP) Slog.v(
3365 TAG, "Removing app " + app + " from list " + listName
3366 + " with " + i + " entries");
3369 ActivityRecord r = list.get(i);
3370 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
3372 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
3374 removeTimeoutsForActivityLocked(r);
3379 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
3380 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
3381 removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app,
3382 "mStoppingActivities");
3383 removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app,
3384 "mGoingToSleepActivities");
3385 removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app,
3386 "mWaitingVisibleActivities");
3387 removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app,
3388 "mFinishingActivities");
3390 boolean hasVisibleActivities = false;
3392 // Clean out the history list.
3393 int i = numActivities();
3394 if (DEBUG_CLEANUP) Slog.v(
3395 TAG, "Removing app " + app + " from history with " + i + " entries");
3396 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3397 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3398 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3399 final ActivityRecord r = activities.get(activityNdx);
3401 if (DEBUG_CLEANUP) Slog.v(
3402 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3405 hasVisibleActivities = true;
3408 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
3409 // Don't currently have state for the activity, or
3410 // it is finishing -- always remove it.
3412 } else if (r.launchCount > 2 &&
3413 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
3414 // We have launched this activity too many times since it was
3415 // able to run, so give up and remove it.
3418 // The process may be gone, but the activity lives on!
3422 if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
3423 RuntimeException here = new RuntimeException("here");
3424 here.fillInStackTrace();
3425 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
3426 + ": haveState=" + r.haveState
3427 + " stateNotNeeded=" + r.stateNotNeeded
3428 + " finishing=" + r.finishing
3429 + " state=" + r.state, here);
3432 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
3433 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3434 r.userId, System.identityHashCode(r),
3435 r.task.taskId, r.shortComponentName,
3436 "proc died without state saved");
3437 if (r.state == ActivityState.RESUMED) {
3438 mService.updateUsageStats(r, false);
3441 removeActivityFromHistoryLocked(r, "appDied");
3444 // We have the current state for this activity, so
3445 // it can be restarted later when needed.
3446 if (localLOGV) Slog.v(
3447 TAG, "Keeping entry, setting app to null");
3448 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
3451 r.nowVisible = false;
3453 if (DEBUG_SAVED_STATE) Slog.i(TAG,
3454 "App died, clearing saved state of " + r);
3459 cleanUpActivityLocked(r, true, true);
3464 return hasVisibleActivities;
3467 final void updateTransitLocked(int transit, Bundle options) {
3468 if (options != null) {
3469 ActivityRecord r = topRunningActivityLocked(null);
3470 if (r != null && r.state != ActivityState.RESUMED) {
3471 r.updateOptionsLocked(options);
3473 ActivityOptions.abort(options);
3476 mWindowManager.prepareAppTransition(transit, false);
3479 void updateTaskMovement(TaskRecord task, boolean toFront) {
3480 if (task.isPersistable) {
3481 task.mLastTimeMoved = System.currentTimeMillis();
3482 // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most
3483 // recently will be most negative, tasks sent to the bottom before that will be less
3484 // negative. Similarly for recent tasks moved to the top which will be most positive.
3486 task.mLastTimeMoved *= -1;
3491 void moveHomeStackTaskToTop(int homeStackTaskType) {
3492 final int top = mTaskHistory.size() - 1;
3493 for (int taskNdx = top; taskNdx >= 0; --taskNdx) {
3494 final TaskRecord task = mTaskHistory.get(taskNdx);
3495 if (task.taskType == homeStackTaskType) {
3496 if (DEBUG_TASKS || DEBUG_STACK)
3497 Slog.d(TAG, "moveHomeStackTaskToTop: moving " + task);
3498 mTaskHistory.remove(taskNdx);
3499 mTaskHistory.add(top, task);
3500 updateTaskMovement(task, true);
3501 mWindowManager.moveTaskToTop(task.taskId);
3507 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord source, Bundle options,
3509 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3511 final int numTasks = mTaskHistory.size();
3512 final int index = mTaskHistory.indexOf(tr);
3513 if (numTasks == 0 || index < 0) {
3515 if (source != null &&
3516 (source.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3517 ActivityOptions.abort(options);
3519 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
3524 // Shift all activities with this task up to the top
3525 // of the stack, keeping them in the same internal order.
3526 insertTaskAtTop(tr);
3527 moveToFront(reason);
3529 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr);
3530 if (source != null &&
3531 (source.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3532 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
3533 ActivityRecord r = topRunningActivityLocked(null);
3535 mNoAnimActivities.add(r);
3537 ActivityOptions.abort(options);
3539 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
3542 mStackSupervisor.resumeTopActivitiesLocked();
3543 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId);
3545 if (VALIDATE_TOKENS) {
3546 validateAppTokensLocked();
3551 * Worker method for rearranging history stack. Implements the function of moving all
3552 * activities for a specific task (gathering them if disjoint) into a single group at the
3553 * bottom of the stack.
3555 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3556 * to premeptively cancel the move.
3558 * @param taskId The taskId to collect and move to the bottom.
3559 * @return Returns true if the move completed, false if not.
3561 final boolean moveTaskToBackLocked(int taskId) {
3562 final TaskRecord tr = taskForIdLocked(taskId);
3564 Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId);
3568 Slog.i(TAG, "moveTaskToBack: " + tr);
3570 mStackSupervisor.endLockTaskModeIfTaskEnding(tr);
3572 // If we have a watcher, preflight the move before committing to it. First check
3573 // for *other* available tasks, but if none are available, then try again allowing the
3574 // current task to be selected.
3575 if (mStackSupervisor.isFrontStack(this) && mService.mController != null) {
3576 ActivityRecord next = topRunningActivityLocked(null, taskId);
3578 next = topRunningActivityLocked(null, 0);
3581 // ask watcher if this is allowed
3582 boolean moveOK = true;
3584 moveOK = mService.mController.activityResuming(next.packageName);
3585 } catch (RemoteException e) {
3586 mService.mController = null;
3587 Watchdog.getInstance().setActivityController(null);
3595 if (DEBUG_TRANSITION) Slog.v(TAG,
3596 "Prepare to back transition: task=" + taskId);
3598 boolean prevIsHome = false;
3599 if (tr.isOverHomeStack()) {
3600 final TaskRecord nextTask = getNextTask(tr);
3601 if (nextTask != null) {
3602 nextTask.setTaskToReturnTo(tr.getTaskToReturnTo());
3607 mTaskHistory.remove(tr);
3608 mTaskHistory.add(0, tr);
3609 updateTaskMovement(tr, false);
3611 // There is an assumption that moving a task to the back moves it behind the home activity.
3612 // We make sure here that some activity in the stack will launch home.
3613 int numTasks = mTaskHistory.size();
3614 for (int taskNdx = numTasks - 1; taskNdx >= 1; --taskNdx) {
3615 final TaskRecord task = mTaskHistory.get(taskNdx);
3616 if (task.isOverHomeStack()) {
3620 // Set the last task before tr to go to home.
3621 task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
3625 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_TASK_TO_BACK, false);
3626 mWindowManager.moveTaskToBottom(taskId);
3628 if (VALIDATE_TOKENS) {
3629 validateAppTokensLocked();
3632 final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null;
3633 if (prevIsHome || task == tr && tr.isOverHomeStack()
3634 || numTasks <= 1 && isOnHomeDisplay()) {
3635 if (!mService.mBooting && !mService.mBooted) {
3639 final int taskToReturnTo = tr.getTaskToReturnTo();
3640 tr.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
3641 return mStackSupervisor.resumeHomeStackTask(taskToReturnTo, null, "moveTaskToBack");
3644 mStackSupervisor.resumeTopActivitiesLocked();
3648 static final void logStartActivity(int tag, ActivityRecord r,
3650 final Uri data = r.intent.getData();
3651 final String strData = data != null ? data.toSafeString() : null;
3653 EventLog.writeEvent(tag,
3654 r.userId, System.identityHashCode(r), task.taskId,
3655 r.shortComponentName, r.intent.getAction(),
3656 r.intent.getType(), strData, r.intent.getFlags());
3660 * Make sure the given activity matches the current configuration. Returns
3661 * false if the activity had to be destroyed. Returns true if the
3662 * configuration is the same, or the activity will remain running as-is
3663 * for whatever reason. Ensures the HistoryRecord is updated with the
3664 * correct configuration and all other bookkeeping is handled.
3666 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3667 int globalChanges) {
3668 if (mConfigWillChange) {
3669 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3670 "Skipping config check (will change): " + r);
3674 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3675 "Ensuring correct configuration: " + r);
3677 // Short circuit: if the two configurations are the exact same
3678 // object (the common case), then there is nothing to do.
3679 Configuration newConfig = mService.mConfiguration;
3680 if (r.configuration == newConfig && !r.forceNewConfig) {
3681 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3682 "Configuration unchanged in " + r);
3686 // We don't worry about activities that are finishing.
3688 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3689 "Configuration doesn't matter in finishing " + r);
3690 r.stopFreezingScreenLocked(false);
3694 // Okay we now are going to make this activity have the new config.
3695 // But then we need to figure out how it needs to deal with that.
3696 Configuration oldConfig = r.configuration;
3697 r.configuration = newConfig;
3699 // Determine what has changed. May be nothing, if this is a config
3700 // that has come back from the app after going idle. In that case
3701 // we just want to leave the official config object now in the
3702 // activity and do nothing else.
3703 final int changes = oldConfig.diff(newConfig);
3704 if (changes == 0 && !r.forceNewConfig) {
3705 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3706 "Configuration no differences in " + r);
3710 // If the activity isn't currently running, just leave the new
3711 // configuration and it will pick that up next time it starts.
3712 if (r.app == null || r.app.thread == null) {
3713 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3714 "Configuration doesn't matter not running " + r);
3715 r.stopFreezingScreenLocked(false);
3716 r.forceNewConfig = false;
3720 // Figure out how to handle the changes between the configurations.
3721 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3722 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3723 + Integer.toHexString(changes) + ", handles=0x"
3724 + Integer.toHexString(r.info.getRealConfigChanged())
3725 + ", newConfig=" + newConfig);
3727 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
3728 // Aha, the activity isn't handling the change, so DIE DIE DIE.
3729 r.configChangeFlags |= changes;
3730 r.startFreezingScreenLocked(r.app, globalChanges);
3731 r.forceNewConfig = false;
3732 if (r.app == null || r.app.thread == null) {
3733 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3734 "Config is destroying non-running " + r);
3735 destroyActivityLocked(r, true, "config");
3736 } else if (r.state == ActivityState.PAUSING) {
3737 // A little annoying: we are waiting for this activity to
3738 // finish pausing. Let's not do anything now, but just
3739 // flag that it needs to be restarted when done pausing.
3740 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3741 "Config is skipping already pausing " + r);
3742 r.configDestroy = true;
3744 } else if (r.state == ActivityState.RESUMED) {
3745 // Try to optimize this case: the configuration is changing
3746 // and we need to restart the top, resumed activity.
3747 // Instead of doing the normal handshaking, just say
3749 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3750 "Config is relaunching resumed " + r);
3751 relaunchActivityLocked(r, r.configChangeFlags, true);
3752 r.configChangeFlags = 0;
3754 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3755 "Config is relaunching non-resumed " + r);
3756 relaunchActivityLocked(r, r.configChangeFlags, false);
3757 r.configChangeFlags = 0;
3760 // All done... tell the caller we weren't able to keep this
3765 // Default case: the activity can handle this new configuration, so
3766 // hand it over. Note that we don't need to give it the new
3767 // configuration, since we always send configuration changes to all
3768 // process when they happen so it can just use whatever configuration
3770 if (r.app != null && r.app.thread != null) {
3772 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
3773 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
3774 } catch (RemoteException e) {
3775 // If process died, whatever.
3778 r.stopFreezingScreenLocked(false);
3783 private boolean relaunchActivityLocked(ActivityRecord r,
3784 int changes, boolean andResume) {
3785 List<ResultInfo> results = null;
3786 List<ReferrerIntent> newIntents = null;
3788 results = r.results;
3789 newIntents = r.newIntents;
3791 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
3792 + " with results=" + results + " newIntents=" + newIntents
3793 + " andResume=" + andResume);
3794 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
3795 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
3796 r.task.taskId, r.shortComponentName);
3798 r.startFreezingScreenLocked(r.app, 0);
3800 mStackSupervisor.removeChildActivityContainers(r);
3803 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
3804 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
3806 r.forceNewConfig = false;
3807 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
3808 changes, !andResume, new Configuration(mService.mConfiguration));
3809 // Note: don't need to call pauseIfSleepingLocked() here, because
3810 // the caller will only pass in 'andResume' if this activity is
3811 // currently resumed, which implies we aren't sleeping.
3812 } catch (RemoteException e) {
3813 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
3818 r.newIntents = null;
3819 r.state = ActivityState.RESUMED;
3821 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3822 r.state = ActivityState.PAUSED;
3828 boolean willActivityBeVisibleLocked(IBinder token) {
3829 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3830 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3831 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3832 final ActivityRecord r = activities.get(activityNdx);
3833 if (r.appToken == token) {
3836 if (r.fullscreen && !r.finishing) {
3841 final ActivityRecord r = ActivityRecord.forToken(token);
3845 if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false,"
3846 + " would have returned true for r=" + r);
3847 return !r.finishing;
3850 void closeSystemDialogsLocked() {
3851 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3852 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3853 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3854 final ActivityRecord r = activities.get(activityNdx);
3855 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
3856 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true);
3862 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
3863 boolean didSomething = false;
3864 TaskRecord lastTask = null;
3865 ComponentName homeActivity = null;
3866 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3867 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3868 int numActivities = activities.size();
3869 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
3870 ActivityRecord r = activities.get(activityNdx);
3871 final boolean samePackage = r.packageName.equals(name)
3872 || (name == null && r.userId == userId);
3873 if ((userId == UserHandle.USER_ALL || r.userId == userId)
3874 && (samePackage || r.task == lastTask)
3875 && (r.app == null || evenPersistent || !r.app.persistent)) {
3878 // If this activity is just finishing, then it is not
3879 // interesting as far as something to stop.
3884 if (r.isHomeActivity()) {
3885 if (homeActivity != null && homeActivity.equals(r.realActivity)) {
3886 Slog.i(TAG, "Skip force-stop again " + r);
3889 homeActivity = r.realActivity;
3892 didSomething = true;
3893 Slog.i(TAG, " Force finishing activity 3 " + r);
3895 if (r.app != null) {
3896 r.app.removed = true;
3901 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop",
3903 // r has been deleted from mActivities, accommodate.
3910 return didSomething;
3913 void getTasksLocked(List<RunningTaskInfo> list, int callingUid, boolean allowed) {
3914 boolean focusedStack = mStackSupervisor.getFocusedStack() == this;
3915 boolean topTask = true;
3916 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3917 final TaskRecord task = mTaskHistory.get(taskNdx);
3918 if (task.getTopActivity() == null) {
3921 ActivityRecord r = null;
3922 ActivityRecord top = null;
3923 int numActivities = 0;
3925 final ArrayList<ActivityRecord> activities = task.mActivities;
3926 if (!allowed && !task.isHomeTask() && task.effectiveUid != callingUid) {
3929 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3930 r = activities.get(activityNdx);
3932 // Initialize state for next task if needed.
3933 if (top == null || (top.state == ActivityState.INITIALIZING)) {
3935 numActivities = numRunning = 0;
3938 // Add 'r' into the current task.
3940 if (r.app != null && r.app.thread != null) {
3944 if (localLOGV) Slog.v(
3945 TAG, r.intent.getComponent().flattenToShortString()
3946 + ": task=" + r.task);
3949 RunningTaskInfo ci = new RunningTaskInfo();
3950 ci.id = task.taskId;
3951 ci.baseActivity = r.intent.getComponent();
3952 ci.topActivity = top.intent.getComponent();
3953 ci.lastActiveTime = task.lastActiveTime;
3954 if (focusedStack && topTask) {
3955 // Give the latest time to ensure foreground task can be sorted
3956 // at the first, because lastActiveTime of creating task is 0.
3957 ci.lastActiveTime = System.currentTimeMillis();
3961 if (top.task != null) {
3962 ci.description = top.task.lastDescription;
3964 ci.numActivities = numActivities;
3965 ci.numRunning = numRunning;
3970 public void unhandledBackLocked() {
3971 final int top = mTaskHistory.size() - 1;
3972 if (DEBUG_SWITCH) Slog.d(
3973 TAG, "Performing unhandledBack(): top activity at " + top);
3975 final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
3976 int activityTop = activities.size() - 1;
3977 if (activityTop > 0) {
3978 finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
3979 "unhandled-back", true);
3985 * Reset local parameters because an app's activity died.
3986 * @param app The app of the activity that died.
3987 * @return result from removeHistoryRecordsForAppLocked.
3989 boolean handleAppDiedLocked(ProcessRecord app) {
3990 if (mPausingActivity != null && mPausingActivity.app == app) {
3991 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
3992 "App died while pausing: " + mPausingActivity);
3993 mPausingActivity = null;
3995 if (mLastPausedActivity != null && mLastPausedActivity.app == app) {
3996 mLastPausedActivity = null;
3997 mLastNoHistoryActivity = null;
4000 return removeHistoryRecordsForAppLocked(app);
4003 void handleAppCrashLocked(ProcessRecord app) {
4004 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4005 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4006 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4007 final ActivityRecord r = activities.get(activityNdx);
4009 Slog.w(TAG, " Force finishing activity 4 "
4010 + r.intent.getComponent().flattenToShortString());
4011 // Force the destroy to skip right to removal.
4013 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
4019 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
4020 boolean dumpClient, String dumpPackage, boolean needSep, String header) {
4021 boolean printed = false;
4022 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4023 final TaskRecord task = mTaskHistory.get(taskNdx);
4024 printed |= ActivityStackSupervisor.dumpHistoryList(fd, pw,
4025 mTaskHistory.get(taskNdx).mActivities, " ", "Hist", true, !dumpAll,
4026 dumpClient, dumpPackage, needSep, header,
4027 " Task id #" + task.taskId);
4035 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
4036 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
4038 if ("all".equals(name)) {
4039 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4040 activities.addAll(mTaskHistory.get(taskNdx).mActivities);
4042 } else if ("top".equals(name)) {
4043 final int top = mTaskHistory.size() - 1;
4045 final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities;
4046 int listTop = list.size() - 1;
4048 activities.add(list.get(listTop));
4052 ItemMatcher matcher = new ItemMatcher();
4053 matcher.build(name);
4055 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4056 for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) {
4057 if (matcher.match(r1, r1.intent.getComponent())) {
4067 ActivityRecord restartPackage(String packageName) {
4068 ActivityRecord starting = topRunningActivityLocked(null);
4070 // All activities that came from the package must be
4071 // restarted as if there was a config change.
4072 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4073 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4074 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4075 final ActivityRecord a = activities.get(activityNdx);
4076 if (a.info.packageName.equals(packageName)) {
4077 a.forceNewConfig = true;
4078 if (starting != null && a == starting && a.visible) {
4079 a.startFreezingScreenLocked(starting.app,
4080 ActivityInfo.CONFIG_SCREEN_LAYOUT);
4089 void removeTask(TaskRecord task, String reason) {
4090 mStackSupervisor.endLockTaskModeIfTaskEnding(task);
4091 mWindowManager.removeTask(task.taskId);
4092 final ActivityRecord r = mResumedActivity;
4093 if (r != null && r.task == task) {
4094 mResumedActivity = null;
4097 final int taskNdx = mTaskHistory.indexOf(task);
4098 final int topTaskNdx = mTaskHistory.size() - 1;
4099 if (task.isOverHomeStack() && taskNdx < topTaskNdx) {
4100 final TaskRecord nextTask = mTaskHistory.get(taskNdx + 1);
4101 if (!nextTask.isOverHomeStack()) {
4102 nextTask.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
4105 mTaskHistory.remove(task);
4106 updateTaskMovement(task, true);
4108 if (task.mActivities.isEmpty()) {
4109 final boolean isVoiceSession = task.voiceSession != null;
4110 if (isVoiceSession) {
4112 task.voiceSession.taskFinished(task.intent, task.taskId);
4113 } catch (RemoteException e) {
4116 if (task.autoRemoveFromRecents() || isVoiceSession) {
4117 // Task creator asked to remove this when done, or this task was a voice
4118 // interaction, so it should not remain on the recent tasks list.
4119 mService.mRecentTasks.remove(task);
4120 task.removedFromRecents();
4124 if (mTaskHistory.isEmpty()) {
4125 if (DEBUG_STACK) Slog.i(TAG, "removeTask: moving to back stack=" + this);
4126 if (isOnHomeDisplay()) {
4127 mStackSupervisor.moveHomeStack(!isHomeStack(), reason + " leftTaskHistoryEmpty");
4129 if (mStacks != null) {
4130 mStacks.remove(this);
4131 mStacks.add(0, this);
4133 mActivityContainer.onTaskListEmptyLocked();
4137 TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
4138 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
4140 TaskRecord task = new TaskRecord(mService, taskId, info, intent, voiceSession,
4142 addTask(task, toTop, false);
4146 ArrayList<TaskRecord> getAllTasks() {
4147 return new ArrayList<TaskRecord>(mTaskHistory);
4150 void addTask(final TaskRecord task, final boolean toTop, boolean moving) {
4153 insertTaskAtTop(task);
4155 mTaskHistory.add(0, task);
4156 updateTaskMovement(task, false);
4158 if (!moving && task.voiceSession != null) {
4160 task.voiceSession.taskStarted(task.intent, task.taskId);
4161 } catch (RemoteException e) {
4166 public int getStackId() {
4171 public String toString() {
4172 return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this))
4173 + " stackId=" + mStackId + ", " + mTaskHistory.size() + " tasks}";