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