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