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