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