ActivityStack.java revision 4c499be0edc24eb2e2b9705dba52a2059823e4aa
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
1496            // Make sure to notify Keyguard as well if it is waiting for an activity to be drawn.
1497            mStackSupervisor.notifyActivityDrawnForKeyguard();
1498            return false;
1499        }
1500
1501        final TaskRecord nextTask = next.task;
1502        if (prevTask != null && prevTask.stack == this &&
1503                prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
1504            if (DEBUG_STACK)  mStackSupervisor.validateTopActivitiesLocked();
1505            if (prevTask == nextTask) {
1506                prevTask.setFrontOfTask();
1507            } else if (prevTask != topTask()) {
1508                // This task is going away but it was supposed to return to the home stack.
1509                // Now the task above it has to return to the home task instead.
1510                final int taskNdx = mTaskHistory.indexOf(prevTask) + 1;
1511                mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE);
1512            } else {
1513                if (DEBUG_STATES && isOnHomeDisplay()) Slog.d(TAG,
1514                        "resumeTopActivityLocked: Launching home next");
1515                // Only resume home if on home display
1516                final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
1517                        HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
1518                return isOnHomeDisplay() &&
1519                        mStackSupervisor.resumeHomeStackTask(returnTaskType, prev);
1520            }
1521        }
1522
1523        // If we are sleeping, and there is no resumed activity, and the top
1524        // activity is paused, well that is the state we want.
1525        if (mService.isSleepingOrShuttingDown()
1526                && mLastPausedActivity == next
1527                && mStackSupervisor.allPausedActivitiesComplete()) {
1528            // Make sure we have executed any pending transitions, since there
1529            // should be nothing left to do at this point.
1530            mWindowManager.executeAppTransition();
1531            mNoAnimActivities.clear();
1532            ActivityOptions.abort(options);
1533            if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Going to sleep and all paused");
1534            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1535            return false;
1536        }
1537
1538        // Make sure that the user who owns this activity is started.  If not,
1539        // we will just leave it as is because someone should be bringing
1540        // another user's activities to the top of the stack.
1541        if (mService.mStartedUsers.get(next.userId) == null) {
1542            Slog.w(TAG, "Skipping resume of top activity " + next
1543                    + ": user " + next.userId + " is stopped");
1544            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1545            return false;
1546        }
1547
1548        // The activity may be waiting for stop, but that is no longer
1549        // appropriate for it.
1550        mStackSupervisor.mStoppingActivities.remove(next);
1551        mStackSupervisor.mGoingToSleepActivities.remove(next);
1552        next.sleeping = false;
1553        mStackSupervisor.mWaitingVisibleActivities.remove(next);
1554
1555        if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1556
1557        // If we are currently pausing an activity, then don't do anything
1558        // until that is done.
1559        if (!mStackSupervisor.allPausedActivitiesComplete()) {
1560            if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG,
1561                    "resumeTopActivityLocked: Skip resume: some activity pausing.");
1562            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1563            return false;
1564        }
1565
1566        // Okay we are now going to start a switch, to 'next'.  We may first
1567        // have to pause the current activity, but this is an important point
1568        // where we have decided to go to 'next' so keep track of that.
1569        // XXX "App Redirected" dialog is getting too many false positives
1570        // at this point, so turn off for now.
1571        if (false) {
1572            if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1573                long now = SystemClock.uptimeMillis();
1574                final boolean inTime = mLastStartedActivity.startTime != 0
1575                        && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1576                final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1577                final int nextUid = next.info.applicationInfo.uid;
1578                if (inTime && lastUid != nextUid
1579                        && lastUid != next.launchedFromUid
1580                        && mService.checkPermission(
1581                                android.Manifest.permission.STOP_APP_SWITCHES,
1582                                -1, next.launchedFromUid)
1583                        != PackageManager.PERMISSION_GRANTED) {
1584                    mService.showLaunchWarningLocked(mLastStartedActivity, next);
1585                } else {
1586                    next.startTime = now;
1587                    mLastStartedActivity = next;
1588                }
1589            } else {
1590                next.startTime = SystemClock.uptimeMillis();
1591                mLastStartedActivity = next;
1592            }
1593        }
1594
1595        // We need to start pausing the current activity so the top one
1596        // can be resumed...
1597        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving);
1598        if (mResumedActivity != null) {
1599            pausing = true;
1600            startPausingLocked(userLeaving, false);
1601            if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Pausing " + mResumedActivity);
1602        }
1603        if (pausing) {
1604            if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG,
1605                    "resumeTopActivityLocked: Skip resume: need to start pausing");
1606            // At this point we want to put the upcoming activity's process
1607            // at the top of the LRU list, since we know we will be needing it
1608            // very soon and it would be a waste to let it get killed if it
1609            // happens to be sitting towards the end.
1610            if (next.app != null && next.app.thread != null) {
1611                mService.updateLruProcessLocked(next.app, true, null);
1612            }
1613            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1614            return true;
1615        }
1616
1617        // If the most recent activity was noHistory but was only stopped rather
1618        // than stopped+finished because the device went to sleep, we need to make
1619        // sure to finish it as we're making a new activity topmost.
1620        if (mService.isSleeping() && mLastNoHistoryActivity != null &&
1621                !mLastNoHistoryActivity.finishing) {
1622            if (DEBUG_STATES) Slog.d(TAG, "no-history finish of " + mLastNoHistoryActivity +
1623                    " on new resume");
1624            requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
1625                    null, "no-history", false);
1626            mLastNoHistoryActivity = null;
1627        }
1628
1629        if (prev != null && prev != next) {
1630            if (!prev.waitingVisible && next != null && !next.nowVisible) {
1631                prev.waitingVisible = true;
1632                mStackSupervisor.mWaitingVisibleActivities.add(prev);
1633                if (DEBUG_SWITCH) Slog.v(
1634                        TAG, "Resuming top, waiting visible to hide: " + prev);
1635            } else {
1636                // The next activity is already visible, so hide the previous
1637                // activity's windows right now so we can show the new one ASAP.
1638                // We only do this if the previous is finishing, which should mean
1639                // it is on top of the one being resumed so hiding it quickly
1640                // is good.  Otherwise, we want to do the normal route of allowing
1641                // the resumed activity to be shown so we can decide if the
1642                // previous should actually be hidden depending on whether the
1643                // new one is found to be full-screen or not.
1644                if (prev.finishing) {
1645                    mWindowManager.setAppVisibility(prev.appToken, false);
1646                    if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1647                            + prev + ", waitingVisible="
1648                            + (prev != null ? prev.waitingVisible : null)
1649                            + ", nowVisible=" + next.nowVisible);
1650                } else {
1651                    if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1652                        + prev + ", waitingVisible="
1653                        + (prev != null ? prev.waitingVisible : null)
1654                        + ", nowVisible=" + next.nowVisible);
1655                }
1656            }
1657        }
1658
1659        // Launching this app's activity, make sure the app is no longer
1660        // considered stopped.
1661        try {
1662            AppGlobals.getPackageManager().setPackageStoppedState(
1663                    next.packageName, false, next.userId); /* TODO: Verify if correct userid */
1664        } catch (RemoteException e1) {
1665        } catch (IllegalArgumentException e) {
1666            Slog.w(TAG, "Failed trying to unstop package "
1667                    + next.packageName + ": " + e);
1668        }
1669
1670        // We are starting up the next activity, so tell the window manager
1671        // that the previous one will be hidden soon.  This way it can know
1672        // to ignore it when computing the desired screen orientation.
1673        boolean anim = true;
1674        if (prev != null) {
1675            if (prev.finishing) {
1676                if (DEBUG_TRANSITION) Slog.v(TAG,
1677                        "Prepare close transition: prev=" + prev);
1678                if (mNoAnimActivities.contains(prev)) {
1679                    anim = false;
1680                    mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
1681                } else {
1682                    mWindowManager.prepareAppTransition(prev.task == next.task
1683                            ? AppTransition.TRANSIT_ACTIVITY_CLOSE
1684                            : AppTransition.TRANSIT_TASK_CLOSE, false);
1685                }
1686                mWindowManager.setAppWillBeHidden(prev.appToken);
1687                mWindowManager.setAppVisibility(prev.appToken, false);
1688            } else {
1689                if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: prev=" + prev);
1690                if (mNoAnimActivities.contains(next)) {
1691                    anim = false;
1692                    mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
1693                } else {
1694                    mWindowManager.prepareAppTransition(prev.task == next.task
1695                            ? AppTransition.TRANSIT_ACTIVITY_OPEN
1696                            : next.mLaunchTaskBehind
1697                                    ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
1698                                    : AppTransition.TRANSIT_TASK_OPEN, false);
1699                }
1700            }
1701            if (false) {
1702                mWindowManager.setAppWillBeHidden(prev.appToken);
1703                mWindowManager.setAppVisibility(prev.appToken, false);
1704            }
1705        } else {
1706            if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare open transition: no previous");
1707            if (mNoAnimActivities.contains(next)) {
1708                anim = false;
1709                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
1710            } else {
1711                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_ACTIVITY_OPEN, false);
1712            }
1713        }
1714
1715        Bundle resumeAnimOptions = null;
1716        if (anim) {
1717            ActivityOptions opts = next.getOptionsForTargetActivityLocked();
1718            if (opts != null) {
1719                resumeAnimOptions = opts.toBundle();
1720            }
1721            next.applyOptionsLocked();
1722        } else {
1723            next.clearOptionsLocked();
1724        }
1725
1726        ActivityStack lastStack = mStackSupervisor.getLastStack();
1727        if (next.app != null && next.app.thread != null) {
1728            if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1729
1730            // This activity is now becoming visible.
1731            mWindowManager.setAppVisibility(next.appToken, true);
1732
1733            // schedule launch ticks to collect information about slow apps.
1734            next.startLaunchTickingLocked();
1735
1736            ActivityRecord lastResumedActivity =
1737                    lastStack == null ? null :lastStack.mResumedActivity;
1738            ActivityState lastState = next.state;
1739
1740            mService.updateCpuStats();
1741
1742            if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
1743            next.state = ActivityState.RESUMED;
1744            mResumedActivity = next;
1745            next.task.touchActiveTime();
1746            mService.addRecentTaskLocked(next.task);
1747            mService.updateLruProcessLocked(next.app, true, null);
1748            updateLRUListLocked(next);
1749            mService.updateOomAdjLocked();
1750
1751            // Have the window manager re-evaluate the orientation of
1752            // the screen based on the new activity order.
1753            boolean notUpdated = true;
1754            if (mStackSupervisor.isFrontStack(this)) {
1755                Configuration config = mWindowManager.updateOrientationFromAppTokens(
1756                        mService.mConfiguration,
1757                        next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
1758                if (config != null) {
1759                    next.frozenBeforeDestroy = true;
1760                }
1761                notUpdated = !mService.updateConfigurationLocked(config, next, false, false);
1762            }
1763
1764            if (notUpdated) {
1765                // The configuration update wasn't able to keep the existing
1766                // instance of the activity, and instead started a new one.
1767                // We should be all done, but let's just make sure our activity
1768                // is still at the top and schedule another run if something
1769                // weird happened.
1770                ActivityRecord nextNext = topRunningActivityLocked(null);
1771                if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
1772                        "Activity config changed during resume: " + next
1773                        + ", new next: " + nextNext);
1774                if (nextNext != next) {
1775                    // Do over!
1776                    mStackSupervisor.scheduleResumeTopActivities();
1777                }
1778                if (mStackSupervisor.reportResumedActivityLocked(next)) {
1779                    mNoAnimActivities.clear();
1780                    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1781                    return true;
1782                }
1783                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1784                return false;
1785            }
1786
1787            try {
1788                // Deliver all pending results.
1789                ArrayList<ResultInfo> a = next.results;
1790                if (a != null) {
1791                    final int N = a.size();
1792                    if (!next.finishing && N > 0) {
1793                        if (DEBUG_RESULTS) Slog.v(
1794                                TAG, "Delivering results to " + next
1795                                + ": " + a);
1796                        next.app.thread.scheduleSendResult(next.appToken, a);
1797                    }
1798                }
1799
1800                if (next.newIntents != null) {
1801                    next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
1802                }
1803
1804                EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1805                        next.userId, System.identityHashCode(next),
1806                        next.task.taskId, next.shortComponentName);
1807
1808                next.sleeping = false;
1809                mService.showAskCompatModeDialogLocked(next);
1810                next.app.pendingUiClean = true;
1811                next.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_TOP);
1812                next.clearOptionsLocked();
1813                next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
1814                        mService.isNextTransitionForward(), resumeAnimOptions);
1815
1816                mStackSupervisor.checkReadyForSleepLocked();
1817
1818                if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Resumed " + next);
1819            } catch (Exception e) {
1820                // Whoops, need to restart this activity!
1821                if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1822                        + lastState + ": " + next);
1823                next.state = lastState;
1824                if (lastStack != null) {
1825                    lastStack.mResumedActivity = lastResumedActivity;
1826                }
1827                Slog.i(TAG, "Restarting because process died: " + next);
1828                if (!next.hasBeenLaunched) {
1829                    next.hasBeenLaunched = true;
1830                } else  if (SHOW_APP_STARTING_PREVIEW && lastStack != null &&
1831                        mStackSupervisor.isFrontStack(lastStack)) {
1832                    mWindowManager.setAppStartingWindow(
1833                            next.appToken, next.packageName, next.theme,
1834                            mService.compatibilityInfoForPackageLocked(next.info.applicationInfo),
1835                            next.nonLocalizedLabel, next.labelRes, next.icon, next.logo,
1836                            next.windowFlags, null, true);
1837                }
1838                mStackSupervisor.startSpecificActivityLocked(next, true, false);
1839                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1840                return true;
1841            }
1842
1843            // From this point on, if something goes wrong there is no way
1844            // to recover the activity.
1845            try {
1846                next.visible = true;
1847                completeResumeLocked(next);
1848            } catch (Exception e) {
1849                // If any exception gets thrown, toss away this
1850                // activity and try the next one.
1851                Slog.w(TAG, "Exception thrown during resume of " + next, e);
1852                requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
1853                        "resume-exception", true);
1854                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1855                return true;
1856            }
1857            next.stopped = false;
1858
1859        } else {
1860            // Whoops, need to restart this activity!
1861            if (!next.hasBeenLaunched) {
1862                next.hasBeenLaunched = true;
1863            } else {
1864                if (SHOW_APP_STARTING_PREVIEW) {
1865                    mWindowManager.setAppStartingWindow(
1866                            next.appToken, next.packageName, next.theme,
1867                            mService.compatibilityInfoForPackageLocked(
1868                                    next.info.applicationInfo),
1869                            next.nonLocalizedLabel,
1870                            next.labelRes, next.icon, next.logo, next.windowFlags,
1871                            null, true);
1872                }
1873                if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1874            }
1875            if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Restarting " + next);
1876            mStackSupervisor.startSpecificActivityLocked(next, true, true);
1877        }
1878
1879        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1880        return true;
1881    }
1882
1883    private void insertTaskAtTop(TaskRecord task) {
1884        // If this is being moved to the top by another activity or being launched from the home
1885        // activity, set mOnTopOfHome accordingly.
1886        if (isOnHomeDisplay()) {
1887            ActivityStack lastStack = mStackSupervisor.getLastStack();
1888            final boolean fromHome = lastStack.isHomeStack();
1889            if (!isHomeStack() && (fromHome || topTask() != task)) {
1890                task.setTaskToReturnTo(fromHome
1891                        ? lastStack.topTask() == null
1892                                ? HOME_ACTIVITY_TYPE
1893                                : lastStack.topTask().taskType
1894                        : APPLICATION_ACTIVITY_TYPE);
1895            }
1896        } else {
1897            task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
1898        }
1899
1900        mTaskHistory.remove(task);
1901        // Now put task at top.
1902        int taskNdx = mTaskHistory.size();
1903        if (!isCurrentProfileLocked(task.userId)) {
1904            // Put non-current user tasks below current user tasks.
1905            while (--taskNdx >= 0) {
1906                if (!isCurrentProfileLocked(mTaskHistory.get(taskNdx).userId)) {
1907                    break;
1908                }
1909            }
1910            ++taskNdx;
1911        }
1912        mTaskHistory.add(taskNdx, task);
1913        updateTaskMovement(task, true);
1914    }
1915
1916    final void startActivityLocked(ActivityRecord r, boolean newTask,
1917            boolean doResume, boolean keepCurTransition, Bundle options) {
1918        TaskRecord rTask = r.task;
1919        final int taskId = rTask.taskId;
1920        // mLaunchTaskBehind tasks get placed at the back of the task stack.
1921        if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
1922            // Last activity in task had been removed or ActivityManagerService is reusing task.
1923            // Insert or replace.
1924            // Might not even be in.
1925            insertTaskAtTop(rTask);
1926            mWindowManager.moveTaskToTop(taskId);
1927        }
1928        TaskRecord task = null;
1929        if (!newTask) {
1930            // If starting in an existing task, find where that is...
1931            boolean startIt = true;
1932            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1933                task = mTaskHistory.get(taskNdx);
1934                if (task.getTopActivity() == null) {
1935                    // All activities in task are finishing.
1936                    continue;
1937                }
1938                if (task == r.task) {
1939                    // Here it is!  Now, if this is not yet visible to the
1940                    // user, then just add it without starting; it will
1941                    // get started when the user navigates back to it.
1942                    if (!startIt) {
1943                        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
1944                                + task, new RuntimeException("here").fillInStackTrace());
1945                        task.addActivityToTop(r);
1946                        r.putInHistory();
1947                        mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
1948                                r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
1949                                (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0,
1950                                r.userId, r.info.configChanges, task.voiceSession != null,
1951                                r.mLaunchTaskBehind);
1952                        if (VALIDATE_TOKENS) {
1953                            validateAppTokensLocked();
1954                        }
1955                        ActivityOptions.abort(options);
1956                        return;
1957                    }
1958                    break;
1959                } else if (task.numFullscreen > 0) {
1960                    startIt = false;
1961                }
1962            }
1963        }
1964
1965        // Place a new activity at top of stack, so it is next to interact
1966        // with the user.
1967
1968        // If we are not placing the new activity frontmost, we do not want
1969        // to deliver the onUserLeaving callback to the actual frontmost
1970        // activity
1971        if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
1972            mStackSupervisor.mUserLeaving = false;
1973            if (DEBUG_USER_LEAVING) Slog.v(TAG,
1974                    "startActivity() behind front, mUserLeaving=false");
1975        }
1976
1977        task = r.task;
1978
1979        // Slot the activity into the history stack and proceed
1980        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
1981                new RuntimeException("here").fillInStackTrace());
1982        task.addActivityToTop(r);
1983        task.setFrontOfTask();
1984
1985        r.putInHistory();
1986        if (!isHomeStack() || numActivities() > 0) {
1987            // We want to show the starting preview window if we are
1988            // switching to a new task, or the next activity's process is
1989            // not currently running.
1990            boolean showStartingIcon = newTask;
1991            ProcessRecord proc = r.app;
1992            if (proc == null) {
1993                proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1994            }
1995            if (proc == null || proc.thread == null) {
1996                showStartingIcon = true;
1997            }
1998            if (DEBUG_TRANSITION) Slog.v(TAG,
1999                    "Prepare open transition: starting " + r);
2000            if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
2001                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition);
2002                mNoAnimActivities.add(r);
2003            } else {
2004                mWindowManager.prepareAppTransition(newTask
2005                        ? r.mLaunchTaskBehind
2006                                ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
2007                                : AppTransition.TRANSIT_TASK_OPEN
2008                        : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
2009                mNoAnimActivities.remove(r);
2010            }
2011            mWindowManager.addAppToken(task.mActivities.indexOf(r),
2012                    r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
2013                    (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId,
2014                    r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
2015            boolean doShow = true;
2016            if (newTask) {
2017                // Even though this activity is starting fresh, we still need
2018                // to reset it to make sure we apply affinities to move any
2019                // existing activities from other tasks in to it.
2020                // If the caller has requested that the target task be
2021                // reset, then do so.
2022                if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2023                    resetTaskIfNeededLocked(r, r);
2024                    doShow = topRunningNonDelayedActivityLocked(null) == r;
2025                }
2026            } else if (options != null && new ActivityOptions(options).getAnimationType()
2027                    == ActivityOptions.ANIM_SCENE_TRANSITION) {
2028                doShow = false;
2029            }
2030            if (r.mLaunchTaskBehind) {
2031                // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we
2032                // tell WindowManager that r is visible even though it is at the back of the stack.
2033                mWindowManager.setAppVisibility(r.appToken, true);
2034                ensureActivitiesVisibleLocked(null, 0);
2035            } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
2036                // Figure out if we are transitioning from another activity that is
2037                // "has the same starting icon" as the next one.  This allows the
2038                // window manager to keep the previous window it had previously
2039                // created, if it still had one.
2040                ActivityRecord prev = mResumedActivity;
2041                if (prev != null) {
2042                    // We don't want to reuse the previous starting preview if:
2043                    // (1) The current activity is in a different task.
2044                    if (prev.task != r.task) {
2045                        prev = null;
2046                    }
2047                    // (2) The current activity is already displayed.
2048                    else if (prev.nowVisible) {
2049                        prev = null;
2050                    }
2051                }
2052                mWindowManager.setAppStartingWindow(
2053                        r.appToken, r.packageName, r.theme,
2054                        mService.compatibilityInfoForPackageLocked(
2055                                r.info.applicationInfo), r.nonLocalizedLabel,
2056                        r.labelRes, r.icon, r.logo, r.windowFlags,
2057                        prev != null ? prev.appToken : null, showStartingIcon);
2058                r.mStartingWindowShown = true;
2059            }
2060        } else {
2061            // If this is the first activity, don't do any fancy animations,
2062            // because there is nothing for it to animate on top of.
2063            mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
2064                    r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
2065                    (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId,
2066                    r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
2067            ActivityOptions.abort(options);
2068            options = null;
2069        }
2070        if (VALIDATE_TOKENS) {
2071            validateAppTokensLocked();
2072        }
2073
2074        if (doResume) {
2075            mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
2076        }
2077    }
2078
2079    final void validateAppTokensLocked() {
2080        mValidateAppTokens.clear();
2081        mValidateAppTokens.ensureCapacity(numActivities());
2082        final int numTasks = mTaskHistory.size();
2083        for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) {
2084            TaskRecord task = mTaskHistory.get(taskNdx);
2085            final ArrayList<ActivityRecord> activities = task.mActivities;
2086            if (activities.isEmpty()) {
2087                continue;
2088            }
2089            TaskGroup group = new TaskGroup();
2090            group.taskId = task.taskId;
2091            mValidateAppTokens.add(group);
2092            final int numActivities = activities.size();
2093            for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
2094                final ActivityRecord r = activities.get(activityNdx);
2095                group.tokens.add(r.appToken);
2096            }
2097        }
2098        mWindowManager.validateAppTokens(mStackId, mValidateAppTokens);
2099    }
2100
2101    /**
2102     * Perform a reset of the given task, if needed as part of launching it.
2103     * Returns the new HistoryRecord at the top of the task.
2104     */
2105    /**
2106     * Helper method for #resetTaskIfNeededLocked.
2107     * We are inside of the task being reset...  we'll either finish this activity, push it out
2108     * for another task, or leave it as-is.
2109     * @param task The task containing the Activity (taskTop) that might be reset.
2110     * @param forceReset
2111     * @return An ActivityOptions that needs to be processed.
2112     */
2113    final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task, boolean forceReset) {
2114        ActivityOptions topOptions = null;
2115
2116        int replyChainEnd = -1;
2117        boolean canMoveOptions = true;
2118
2119        // We only do this for activities that are not the root of the task (since if we finish
2120        // the root, we may no longer have the task!).
2121        final ArrayList<ActivityRecord> activities = task.mActivities;
2122        final int numActivities = activities.size();
2123        final int rootActivityNdx = task.findEffectiveRootIndex();
2124        for (int i = numActivities - 1; i > rootActivityNdx; --i ) {
2125            ActivityRecord target = activities.get(i);
2126            if (target.frontOfTask)
2127                break;
2128
2129            final int flags = target.info.flags;
2130            final boolean finishOnTaskLaunch =
2131                    (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2132            final boolean allowTaskReparenting =
2133                    (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2134            final boolean clearWhenTaskReset =
2135                    (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2136
2137            if (!finishOnTaskLaunch
2138                    && !clearWhenTaskReset
2139                    && target.resultTo != null) {
2140                // If this activity is sending a reply to a previous
2141                // activity, we can't do anything with it now until
2142                // we reach the start of the reply chain.
2143                // XXX note that we are assuming the result is always
2144                // to the previous activity, which is almost always
2145                // the case but we really shouldn't count on.
2146                if (replyChainEnd < 0) {
2147                    replyChainEnd = i;
2148                }
2149            } else if (!finishOnTaskLaunch
2150                    && !clearWhenTaskReset
2151                    && allowTaskReparenting
2152                    && target.taskAffinity != null
2153                    && !target.taskAffinity.equals(task.affinity)) {
2154                // If this activity has an affinity for another
2155                // task, then we need to move it out of here.  We will
2156                // move it as far out of the way as possible, to the
2157                // bottom of the activity stack.  This also keeps it
2158                // correctly ordered with any activities we previously
2159                // moved.
2160                final TaskRecord targetTask;
2161                final ActivityRecord bottom =
2162                        !mTaskHistory.isEmpty() && !mTaskHistory.get(0).mActivities.isEmpty() ?
2163                                mTaskHistory.get(0).mActivities.get(0) : null;
2164                if (bottom != null && target.taskAffinity != null
2165                        && target.taskAffinity.equals(bottom.task.affinity)) {
2166                    // If the activity currently at the bottom has the
2167                    // same task affinity as the one we are moving,
2168                    // then merge it into the same task.
2169                    targetTask = bottom.task;
2170                    if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2171                            + " out to bottom task " + bottom.task);
2172                } else {
2173                    targetTask = createTaskRecord(mStackSupervisor.getNextTaskId(), target.info,
2174                            null, null, null, false);
2175                    targetTask.affinityIntent = target.intent;
2176                    if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2177                            + " out to new task " + target.task);
2178                }
2179
2180                final int targetTaskId = targetTask.taskId;
2181                mWindowManager.setAppGroupId(target.appToken, targetTaskId);
2182
2183                boolean noOptions = canMoveOptions;
2184                final int start = replyChainEnd < 0 ? i : replyChainEnd;
2185                for (int srcPos = start; srcPos >= i; --srcPos) {
2186                    final ActivityRecord p = activities.get(srcPos);
2187                    if (p.finishing) {
2188                        continue;
2189                    }
2190
2191                    canMoveOptions = false;
2192                    if (noOptions && topOptions == null) {
2193                        topOptions = p.takeOptionsLocked();
2194                        if (topOptions != null) {
2195                            noOptions = false;
2196                        }
2197                    }
2198                    if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task="
2199                            + task + " adding to task=" + targetTask
2200                            + " Callers=" + Debug.getCallers(4));
2201                    if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2202                            + " out to target's task " + target.task);
2203                    p.setTask(targetTask, null);
2204                    targetTask.addActivityAtBottom(p);
2205
2206                    mWindowManager.setAppGroupId(p.appToken, targetTaskId);
2207                }
2208
2209                mWindowManager.moveTaskToBottom(targetTaskId);
2210                if (VALIDATE_TOKENS) {
2211                    validateAppTokensLocked();
2212                }
2213
2214                replyChainEnd = -1;
2215            } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) {
2216                // If the activity should just be removed -- either
2217                // because it asks for it, or the task should be
2218                // cleared -- then finish it and anything that is
2219                // part of its reply chain.
2220                int end;
2221                if (clearWhenTaskReset) {
2222                    // In this case, we want to finish this activity
2223                    // and everything above it, so be sneaky and pretend
2224                    // like these are all in the reply chain.
2225                    end = numActivities - 1;
2226                } else if (replyChainEnd < 0) {
2227                    end = i;
2228                } else {
2229                    end = replyChainEnd;
2230                }
2231                boolean noOptions = canMoveOptions;
2232                for (int srcPos = i; srcPos <= end; srcPos++) {
2233                    ActivityRecord p = activities.get(srcPos);
2234                    if (p.finishing) {
2235                        continue;
2236                    }
2237                    canMoveOptions = false;
2238                    if (noOptions && topOptions == null) {
2239                        topOptions = p.takeOptionsLocked();
2240                        if (topOptions != null) {
2241                            noOptions = false;
2242                        }
2243                    }
2244                    if (DEBUG_TASKS) Slog.w(TAG,
2245                            "resetTaskIntendedTask: calling finishActivity on " + p);
2246                    if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) {
2247                        end--;
2248                        srcPos--;
2249                    }
2250                }
2251                replyChainEnd = -1;
2252            } else {
2253                // If we were in the middle of a chain, well the
2254                // activity that started it all doesn't want anything
2255                // special, so leave it all as-is.
2256                replyChainEnd = -1;
2257            }
2258        }
2259
2260        return topOptions;
2261    }
2262
2263    /**
2264     * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given
2265     * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop.
2266     * @param affinityTask The task we are looking for an affinity to.
2267     * @param task Task that resetTaskIfNeededLocked.taskTop belongs to.
2268     * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked.
2269     * @param forceReset Flag passed in to resetTaskIfNeededLocked.
2270     */
2271    private int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task,
2272            boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) {
2273        int replyChainEnd = -1;
2274        final int taskId = task.taskId;
2275        final String taskAffinity = task.affinity;
2276
2277        final ArrayList<ActivityRecord> activities = affinityTask.mActivities;
2278        final int numActivities = activities.size();
2279        final int rootActivityNdx = affinityTask.findEffectiveRootIndex();
2280
2281        // Do not operate on or below the effective root Activity.
2282        for (int i = numActivities - 1; i > rootActivityNdx; --i) {
2283            ActivityRecord target = activities.get(i);
2284            if (target.frontOfTask)
2285                break;
2286
2287            final int flags = target.info.flags;
2288            boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2289            boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2290
2291            if (target.resultTo != null) {
2292                // If this activity is sending a reply to a previous
2293                // activity, we can't do anything with it now until
2294                // we reach the start of the reply chain.
2295                // XXX note that we are assuming the result is always
2296                // to the previous activity, which is almost always
2297                // the case but we really shouldn't count on.
2298                if (replyChainEnd < 0) {
2299                    replyChainEnd = i;
2300                }
2301            } else if (topTaskIsHigher
2302                    && allowTaskReparenting
2303                    && taskAffinity != null
2304                    && taskAffinity.equals(target.taskAffinity)) {
2305                // This activity has an affinity for our task. Either remove it if we are
2306                // clearing or move it over to our task.  Note that
2307                // we currently punt on the case where we are resetting a
2308                // task that is not at the top but who has activities above
2309                // with an affinity to it...  this is really not a normal
2310                // case, and we will need to later pull that task to the front
2311                // and usually at that point we will do the reset and pick
2312                // up those remaining activities.  (This only happens if
2313                // someone starts an activity in a new task from an activity
2314                // in a task that is not currently on top.)
2315                if (forceReset || finishOnTaskLaunch) {
2316                    final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2317                    if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i);
2318                    for (int srcPos = start; srcPos >= i; --srcPos) {
2319                        final ActivityRecord p = activities.get(srcPos);
2320                        if (p.finishing) {
2321                            continue;
2322                        }
2323                        finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false);
2324                    }
2325                } else {
2326                    if (taskInsertionPoint < 0) {
2327                        taskInsertionPoint = task.mActivities.size();
2328
2329                    }
2330
2331                    final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2332                    if (DEBUG_TASKS) Slog.v(TAG, "Reparenting from task=" + affinityTask + ":"
2333                            + start + "-" + i + " to task=" + task + ":" + taskInsertionPoint);
2334                    for (int srcPos = start; srcPos >= i; --srcPos) {
2335                        final ActivityRecord p = activities.get(srcPos);
2336                        p.setTask(task, null);
2337                        task.addActivityAtIndex(taskInsertionPoint, p);
2338
2339                        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p
2340                                + " to stack at " + task,
2341                                new RuntimeException("here").fillInStackTrace());
2342                        if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos
2343                                + " in to resetting task " + task);
2344                        mWindowManager.setAppGroupId(p.appToken, taskId);
2345                    }
2346                    mWindowManager.moveTaskToTop(taskId);
2347                    if (VALIDATE_TOKENS) {
2348                        validateAppTokensLocked();
2349                    }
2350
2351                    // Now we've moved it in to place...  but what if this is
2352                    // a singleTop activity and we have put it on top of another
2353                    // instance of the same activity?  Then we drop the instance
2354                    // below so it remains singleTop.
2355                    if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2356                        ArrayList<ActivityRecord> taskActivities = task.mActivities;
2357                        int targetNdx = taskActivities.indexOf(target);
2358                        if (targetNdx > 0) {
2359                            ActivityRecord p = taskActivities.get(targetNdx - 1);
2360                            if (p.intent.getComponent().equals(target.intent.getComponent())) {
2361                                finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace",
2362                                        false);
2363                            }
2364                        }
2365                    }
2366                }
2367
2368                replyChainEnd = -1;
2369            }
2370        }
2371        return taskInsertionPoint;
2372    }
2373
2374    final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
2375            ActivityRecord newActivity) {
2376        boolean forceReset =
2377                (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
2378        if (ACTIVITY_INACTIVE_RESET_TIME > 0
2379                && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
2380            if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
2381                forceReset = true;
2382            }
2383        }
2384
2385        final TaskRecord task = taskTop.task;
2386
2387        /** False until we evaluate the TaskRecord associated with taskTop. Switches to true
2388         * for remaining tasks. Used for later tasks to reparent to task. */
2389        boolean taskFound = false;
2390
2391        /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */
2392        ActivityOptions topOptions = null;
2393
2394        // Preserve the location for reparenting in the new task.
2395        int reparentInsertionPoint = -1;
2396
2397        for (int i = mTaskHistory.size() - 1; i >= 0; --i) {
2398            final TaskRecord targetTask = mTaskHistory.get(i);
2399
2400            if (targetTask == task) {
2401                topOptions = resetTargetTaskIfNeededLocked(task, forceReset);
2402                taskFound = true;
2403            } else {
2404                reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task,
2405                        taskFound, forceReset, reparentInsertionPoint);
2406            }
2407        }
2408
2409        int taskNdx = mTaskHistory.indexOf(task);
2410        do {
2411            taskTop = mTaskHistory.get(taskNdx--).getTopActivity();
2412        } while (taskTop == null && taskNdx >= 0);
2413
2414        if (topOptions != null) {
2415            // If we got some ActivityOptions from an activity on top that
2416            // was removed from the task, propagate them to the new real top.
2417            if (taskTop != null) {
2418                taskTop.updateOptionsLocked(topOptions);
2419            } else {
2420                topOptions.abort();
2421            }
2422        }
2423
2424        return taskTop;
2425    }
2426
2427    void sendActivityResultLocked(int callingUid, ActivityRecord r,
2428            String resultWho, int requestCode, int resultCode, Intent data) {
2429
2430        if (callingUid > 0) {
2431            mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
2432                    data, r.getUriPermissionsLocked(), r.userId);
2433        }
2434
2435        if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2436                + " : who=" + resultWho + " req=" + requestCode
2437                + " res=" + resultCode + " data=" + data);
2438        if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2439            try {
2440                ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2441                list.add(new ResultInfo(resultWho, requestCode,
2442                        resultCode, data));
2443                r.app.thread.scheduleSendResult(r.appToken, list);
2444                return;
2445            } catch (Exception e) {
2446                Slog.w(TAG, "Exception thrown sending result to " + r, e);
2447            }
2448        }
2449
2450        r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2451    }
2452
2453    private void adjustFocusedActivityLocked(ActivityRecord r) {
2454        if (mStackSupervisor.isFrontStack(this) && mService.mFocusedActivity == r) {
2455            ActivityRecord next = topRunningActivityLocked(null);
2456            if (next != r) {
2457                final TaskRecord task = r.task;
2458                if (r.frontOfTask && task == topTask() && task.isOverHomeStack()) {
2459                    mStackSupervisor.moveHomeStackTaskToTop(task.getTaskToReturnTo());
2460                }
2461            }
2462            ActivityRecord top = mStackSupervisor.topRunningActivityLocked();
2463            if (top != null) {
2464                mService.setFocusedActivityLocked(top);
2465            }
2466        }
2467    }
2468
2469    final void stopActivityLocked(ActivityRecord r) {
2470        if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2471        if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2472                || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2473            if (!r.finishing) {
2474                if (!mService.isSleeping()) {
2475                    if (DEBUG_STATES) {
2476                        Slog.d(TAG, "no-history finish of " + r);
2477                    }
2478                    requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
2479                            "no-history", false);
2480                } else {
2481                    if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
2482                            + " on stop because we're just sleeping");
2483                }
2484            }
2485        }
2486
2487        if (r.app != null && r.app.thread != null) {
2488            adjustFocusedActivityLocked(r);
2489            r.resumeKeyDispatchingLocked();
2490            try {
2491                r.stopped = false;
2492                if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
2493                        + " (stop requested)");
2494                r.state = ActivityState.STOPPING;
2495                if (DEBUG_VISBILITY) Slog.v(
2496                        TAG, "Stopping visible=" + r.visible + " for " + r);
2497                if (!r.visible) {
2498                    mWindowManager.setAppVisibility(r.appToken, false);
2499                }
2500                r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
2501                if (mService.isSleepingOrShuttingDown()) {
2502                    r.setSleeping(true);
2503                }
2504                Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
2505                mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
2506            } catch (Exception e) {
2507                // Maybe just ignore exceptions here...  if the process
2508                // has crashed, our death notification will clean things
2509                // up.
2510                Slog.w(TAG, "Exception thrown during pause", e);
2511                // Just in case, assume it to be stopped.
2512                r.stopped = true;
2513                if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
2514                r.state = ActivityState.STOPPED;
2515                if (r.configDestroy) {
2516                    destroyActivityLocked(r, true, "stop-except");
2517                }
2518            }
2519        }
2520    }
2521
2522    /**
2523     * @return Returns true if the activity is being finished, false if for
2524     * some reason it is being left as-is.
2525     */
2526    final boolean requestFinishActivityLocked(IBinder token, int resultCode,
2527            Intent resultData, String reason, boolean oomAdj) {
2528        ActivityRecord r = isInStackLocked(token);
2529        if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
2530                TAG, "Finishing activity token=" + token + " r="
2531                + ", result=" + resultCode + ", data=" + resultData
2532                + ", reason=" + reason);
2533        if (r == null) {
2534            return false;
2535        }
2536
2537        finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
2538        return true;
2539    }
2540
2541    final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) {
2542        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2543            ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2544            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2545                ActivityRecord r = activities.get(activityNdx);
2546                if (r.resultTo == self && r.requestCode == requestCode) {
2547                    if ((r.resultWho == null && resultWho == null) ||
2548                        (r.resultWho != null && r.resultWho.equals(resultWho))) {
2549                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
2550                                false);
2551                    }
2552                }
2553            }
2554        }
2555        mService.updateOomAdjLocked();
2556    }
2557
2558    final void finishTopRunningActivityLocked(ProcessRecord app) {
2559        ActivityRecord r = topRunningActivityLocked(null);
2560        if (r != null && r.app == app) {
2561            // If the top running activity is from this crashing
2562            // process, then terminate it to avoid getting in a loop.
2563            Slog.w(TAG, "  Force finishing activity "
2564                    + r.intent.getComponent().flattenToShortString());
2565            int taskNdx = mTaskHistory.indexOf(r.task);
2566            int activityNdx = r.task.mActivities.indexOf(r);
2567            finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
2568            // Also terminate any activities below it that aren't yet
2569            // stopped, to avoid a situation where one will get
2570            // re-start our crashing activity once it gets resumed again.
2571            --activityNdx;
2572            if (activityNdx < 0) {
2573                do {
2574                    --taskNdx;
2575                    if (taskNdx < 0) {
2576                        break;
2577                    }
2578                    activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1;
2579                } while (activityNdx < 0);
2580            }
2581            if (activityNdx >= 0) {
2582                r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx);
2583                if (r.state == ActivityState.RESUMED
2584                        || r.state == ActivityState.PAUSING
2585                        || r.state == ActivityState.PAUSED) {
2586                    if (!r.isHomeActivity() || mService.mHomeProcess != r.app) {
2587                        Slog.w(TAG, "  Force finishing activity "
2588                                + r.intent.getComponent().flattenToShortString());
2589                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
2590                    }
2591                }
2592            }
2593        }
2594    }
2595
2596    final void finishVoiceTask(IVoiceInteractionSession session) {
2597        IBinder sessionBinder = session.asBinder();
2598        boolean didOne = false;
2599        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2600            TaskRecord tr = mTaskHistory.get(taskNdx);
2601            if (tr.voiceSession != null && tr.voiceSession.asBinder() == sessionBinder) {
2602                for (int activityNdx = tr.mActivities.size() - 1; activityNdx >= 0; --activityNdx) {
2603                    ActivityRecord r = tr.mActivities.get(activityNdx);
2604                    if (!r.finishing) {
2605                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "finish-voice",
2606                                false);
2607                        didOne = true;
2608                    }
2609                }
2610            }
2611        }
2612        if (didOne) {
2613            mService.updateOomAdjLocked();
2614        }
2615    }
2616
2617    final boolean finishActivityAffinityLocked(ActivityRecord r) {
2618        ArrayList<ActivityRecord> activities = r.task.mActivities;
2619        for (int index = activities.indexOf(r); index >= 0; --index) {
2620            ActivityRecord cur = activities.get(index);
2621            if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) {
2622                break;
2623            }
2624            finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true);
2625        }
2626        return true;
2627    }
2628
2629    final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
2630        // send the result
2631        ActivityRecord resultTo = r.resultTo;
2632        if (resultTo != null) {
2633            if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
2634                    + " who=" + r.resultWho + " req=" + r.requestCode
2635                    + " res=" + resultCode + " data=" + resultData);
2636            if (resultTo.userId != r.userId) {
2637                if (resultData != null) {
2638                    resultData.setContentUserHint(r.userId);
2639                }
2640            }
2641            if (r.info.applicationInfo.uid > 0) {
2642                mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
2643                        resultTo.packageName, resultData,
2644                        resultTo.getUriPermissionsLocked(), resultTo.userId);
2645            }
2646            resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
2647                                     resultData);
2648            r.resultTo = null;
2649        }
2650        else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
2651
2652        // Make sure this HistoryRecord is not holding on to other resources,
2653        // because clients have remote IPC references to this object so we
2654        // can't assume that will go away and want to avoid circular IPC refs.
2655        r.results = null;
2656        r.pendingResults = null;
2657        r.newIntents = null;
2658        r.icicle = null;
2659    }
2660
2661    /**
2662     * @return Returns true if this activity has been removed from the history
2663     * list, or false if it is still in the list and will be removed later.
2664     */
2665    final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
2666            String reason, boolean oomAdj) {
2667        if (r.finishing) {
2668            Slog.w(TAG, "Duplicate finish request for " + r);
2669            return false;
2670        }
2671
2672        r.makeFinishing();
2673        final TaskRecord task = r.task;
2674        EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2675                r.userId, System.identityHashCode(r),
2676                task.taskId, r.shortComponentName, reason);
2677        final ArrayList<ActivityRecord> activities = task.mActivities;
2678        final int index = activities.indexOf(r);
2679        if (index < (activities.size() - 1)) {
2680            task.setFrontOfTask();
2681            if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
2682                // If the caller asked that this activity (and all above it)
2683                // be cleared when the task is reset, don't lose that information,
2684                // but propagate it up to the next activity.
2685                ActivityRecord next = activities.get(index+1);
2686                next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
2687            }
2688        }
2689
2690        r.pauseKeyDispatchingLocked();
2691
2692        adjustFocusedActivityLocked(r);
2693
2694        finishActivityResultsLocked(r, resultCode, resultData);
2695
2696        if (mResumedActivity == r) {
2697            boolean endTask = index <= 0;
2698            if (DEBUG_VISBILITY || DEBUG_TRANSITION) Slog.v(TAG,
2699                    "Prepare close transition: finishing " + r);
2700            mWindowManager.prepareAppTransition(endTask
2701                    ? AppTransition.TRANSIT_TASK_CLOSE
2702                    : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
2703
2704            // Tell window manager to prepare for this one to be removed.
2705            mWindowManager.setAppVisibility(r.appToken, false);
2706
2707            if (mPausingActivity == null) {
2708                if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
2709                if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
2710                startPausingLocked(false, false);
2711            }
2712
2713            if (endTask) {
2714                mStackSupervisor.endLockTaskModeIfTaskEnding(task);
2715            }
2716        } else if (r.state != ActivityState.PAUSING) {
2717            // If the activity is PAUSING, we will complete the finish once
2718            // it is done pausing; else we can just directly finish it here.
2719            if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
2720            return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null;
2721        } else {
2722            if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
2723        }
2724
2725        return false;
2726    }
2727
2728    static final int FINISH_IMMEDIATELY = 0;
2729    static final int FINISH_AFTER_PAUSE = 1;
2730    static final int FINISH_AFTER_VISIBLE = 2;
2731
2732    final ActivityRecord finishCurrentActivityLocked(ActivityRecord r, int mode, boolean oomAdj) {
2733        // First things first: if this activity is currently visible,
2734        // and the resumed activity is not yet visible, then hold off on
2735        // finishing until the resumed one becomes visible.
2736        if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
2737            if (!mStackSupervisor.mStoppingActivities.contains(r)) {
2738                mStackSupervisor.mStoppingActivities.add(r);
2739                if (mStackSupervisor.mStoppingActivities.size() > 3
2740                        || r.frontOfTask && mTaskHistory.size() <= 1) {
2741                    // If we already have a few activities waiting to stop,
2742                    // then give up on things going idle and start clearing
2743                    // them out. Or if r is the last of activity of the last task the stack
2744                    // will be empty and must be cleared immediately.
2745                    mStackSupervisor.scheduleIdleLocked();
2746                } else {
2747                    mStackSupervisor.checkReadyForSleepLocked();
2748                }
2749            }
2750            if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
2751                    + " (finish requested)");
2752            r.state = ActivityState.STOPPING;
2753            if (oomAdj) {
2754                mService.updateOomAdjLocked();
2755            }
2756            return r;
2757        }
2758
2759        // make sure the record is cleaned out of other places.
2760        mStackSupervisor.mStoppingActivities.remove(r);
2761        mStackSupervisor.mGoingToSleepActivities.remove(r);
2762        mStackSupervisor.mWaitingVisibleActivities.remove(r);
2763        if (mResumedActivity == r) {
2764            mResumedActivity = null;
2765        }
2766        final ActivityState prevState = r.state;
2767        if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
2768        r.state = ActivityState.FINISHING;
2769
2770        if (mode == FINISH_IMMEDIATELY
2771                || prevState == ActivityState.STOPPED
2772                || prevState == ActivityState.INITIALIZING) {
2773            // If this activity is already stopped, we can just finish
2774            // it right now.
2775            r.makeFinishing();
2776            boolean activityRemoved = destroyActivityLocked(r, true, "finish-imm");
2777            if (activityRemoved) {
2778                mStackSupervisor.resumeTopActivitiesLocked();
2779            }
2780            if (DEBUG_CONTAINERS) Slog.d(TAG,
2781                    "destroyActivityLocked: finishCurrentActivityLocked r=" + r +
2782                    " destroy returned removed=" + activityRemoved);
2783            return activityRemoved ? null : r;
2784        }
2785
2786        // Need to go through the full pause cycle to get this
2787        // activity into the stopped state and then finish it.
2788        if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
2789        mStackSupervisor.mFinishingActivities.add(r);
2790        r.resumeKeyDispatchingLocked();
2791        mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null);
2792        return r;
2793    }
2794
2795    void finishAllActivitiesLocked(boolean immediately) {
2796        boolean noActivitiesInStack = true;
2797        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2798            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2799            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2800                final ActivityRecord r = activities.get(activityNdx);
2801                noActivitiesInStack = false;
2802                if (r.finishing && !immediately) {
2803                    continue;
2804                }
2805                Slog.d(TAG, "finishAllActivitiesLocked: finishing " + r + " immediately");
2806                finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
2807            }
2808        }
2809        if (noActivitiesInStack) {
2810            mActivityContainer.onTaskListEmptyLocked();
2811        }
2812    }
2813
2814    final boolean shouldUpRecreateTaskLocked(ActivityRecord srec, String destAffinity) {
2815        // Basic case: for simple app-centric recents, we need to recreate
2816        // the task if the affinity has changed.
2817        if (srec == null || srec.task.affinity == null ||
2818                !srec.task.affinity.equals(destAffinity)) {
2819            return true;
2820        }
2821        // Document-centric case: an app may be split in to multiple documents;
2822        // they need to re-create their task if this current activity is the root
2823        // of a document, unless simply finishing it will return them to the the
2824        // correct app behind.
2825        if (srec.frontOfTask && srec.task != null) {
2826            // Okay, this activity is at the root of its task.  What to do, what to do...
2827            if (srec.task.getTaskToReturnTo() != ActivityRecord.APPLICATION_ACTIVITY_TYPE) {
2828                // Finishing won't return to an application, so we need to recreate.
2829                return true;
2830            }
2831            // We now need to get the task below it to determine what to do.
2832            int taskIdx = mTaskHistory.indexOf(srec.task);
2833            if (taskIdx <= 0) {
2834                Slog.w(TAG, "shouldUpRecreateTask: task not in history for " + srec);
2835                return false;
2836            }
2837            if (taskIdx == 0) {
2838                // At the bottom of the stack, nothing to go back to.
2839                return true;
2840            }
2841            TaskRecord prevTask = mTaskHistory.get(taskIdx);
2842            if (!srec.task.affinity.equals(prevTask.affinity)) {
2843                // These are different apps, so need to recreate.
2844                return true;
2845            }
2846        }
2847        return false;
2848    }
2849
2850    final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode,
2851            Intent resultData) {
2852        final ActivityRecord srec = ActivityRecord.forToken(token);
2853        final TaskRecord task = srec.task;
2854        final ArrayList<ActivityRecord> activities = task.mActivities;
2855        final int start = activities.indexOf(srec);
2856        if (!mTaskHistory.contains(task) || (start < 0)) {
2857            return false;
2858        }
2859        int finishTo = start - 1;
2860        ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo);
2861        boolean foundParentInTask = false;
2862        final ComponentName dest = destIntent.getComponent();
2863        if (start > 0 && dest != null) {
2864            for (int i = finishTo; i >= 0; i--) {
2865                ActivityRecord r = activities.get(i);
2866                if (r.info.packageName.equals(dest.getPackageName()) &&
2867                        r.info.name.equals(dest.getClassName())) {
2868                    finishTo = i;
2869                    parent = r;
2870                    foundParentInTask = true;
2871                    break;
2872                }
2873            }
2874        }
2875
2876        IActivityController controller = mService.mController;
2877        if (controller != null) {
2878            ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
2879            if (next != null) {
2880                // ask watcher if this is allowed
2881                boolean resumeOK = true;
2882                try {
2883                    resumeOK = controller.activityResuming(next.packageName);
2884                } catch (RemoteException e) {
2885                    mService.mController = null;
2886                    Watchdog.getInstance().setActivityController(null);
2887                }
2888
2889                if (!resumeOK) {
2890                    return false;
2891                }
2892            }
2893        }
2894        final long origId = Binder.clearCallingIdentity();
2895        for (int i = start; i > finishTo; i--) {
2896            ActivityRecord r = activities.get(i);
2897            requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
2898            // Only return the supplied result for the first activity finished
2899            resultCode = Activity.RESULT_CANCELED;
2900            resultData = null;
2901        }
2902
2903        if (parent != null && foundParentInTask) {
2904            final int parentLaunchMode = parent.info.launchMode;
2905            final int destIntentFlags = destIntent.getFlags();
2906            if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
2907                    parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
2908                    parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
2909                    (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2910                parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
2911            } else {
2912                try {
2913                    ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
2914                            destIntent.getComponent(), 0, srec.userId);
2915                    int res = mStackSupervisor.startActivityLocked(srec.app.thread, destIntent,
2916                            null, aInfo, null, null, parent.appToken, null,
2917                            0, -1, parent.launchedFromUid, parent.launchedFromPackage,
2918                            0, null, true, null, null, null);
2919                    foundParentInTask = res == ActivityManager.START_SUCCESS;
2920                } catch (RemoteException e) {
2921                    foundParentInTask = false;
2922                }
2923                requestFinishActivityLocked(parent.appToken, resultCode,
2924                        resultData, "navigate-up", true);
2925            }
2926        }
2927        Binder.restoreCallingIdentity(origId);
2928        return foundParentInTask;
2929    }
2930    /**
2931     * Perform the common clean-up of an activity record.  This is called both
2932     * as part of destroyActivityLocked() (when destroying the client-side
2933     * representation) and cleaning things up as a result of its hosting
2934     * processing going away, in which case there is no remaining client-side
2935     * state to destroy so only the cleanup here is needed.
2936     */
2937    final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
2938            boolean setState) {
2939        if (mResumedActivity == r) {
2940            mResumedActivity = null;
2941        }
2942        if (mPausingActivity == r) {
2943            mPausingActivity = null;
2944        }
2945        mService.clearFocusedActivity(r);
2946
2947        r.configDestroy = false;
2948        r.frozenBeforeDestroy = false;
2949
2950        if (setState) {
2951            if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
2952            r.state = ActivityState.DESTROYED;
2953            if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
2954            r.app = null;
2955        }
2956
2957        // Make sure this record is no longer in the pending finishes list.
2958        // This could happen, for example, if we are trimming activities
2959        // down to the max limit while they are still waiting to finish.
2960        mStackSupervisor.mFinishingActivities.remove(r);
2961        mStackSupervisor.mWaitingVisibleActivities.remove(r);
2962
2963        // Remove any pending results.
2964        if (r.finishing && r.pendingResults != null) {
2965            for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
2966                PendingIntentRecord rec = apr.get();
2967                if (rec != null) {
2968                    mService.cancelIntentSenderLocked(rec, false);
2969                }
2970            }
2971            r.pendingResults = null;
2972        }
2973
2974        if (cleanServices) {
2975            cleanUpActivityServicesLocked(r);
2976        }
2977
2978        // Get rid of any pending idle timeouts.
2979        removeTimeoutsForActivityLocked(r);
2980        if (getVisibleBehindActivity() == r) {
2981            mStackSupervisor.requestVisibleBehindLocked(r, false);
2982        }
2983    }
2984
2985    private void removeTimeoutsForActivityLocked(ActivityRecord r) {
2986        mStackSupervisor.removeTimeoutsForActivityLocked(r);
2987        mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
2988        mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
2989        mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
2990        r.finishLaunchTickingLocked();
2991    }
2992
2993    private void removeActivityFromHistoryLocked(ActivityRecord r) {
2994        mStackSupervisor.removeChildActivityContainers(r);
2995        finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
2996        r.makeFinishing();
2997        if (DEBUG_ADD_REMOVE) {
2998            RuntimeException here = new RuntimeException("here");
2999            here.fillInStackTrace();
3000            Slog.i(TAG, "Removing activity " + r + " from stack");
3001        }
3002        r.takeFromHistory();
3003        removeTimeoutsForActivityLocked(r);
3004        if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)");
3005        r.state = ActivityState.DESTROYED;
3006        if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
3007        r.app = null;
3008        mWindowManager.removeAppToken(r.appToken);
3009        if (VALIDATE_TOKENS) {
3010            validateAppTokensLocked();
3011        }
3012        final TaskRecord task = r.task;
3013        if (task != null && task.removeActivity(r)) {
3014            if (DEBUG_STACK) Slog.i(TAG,
3015                    "removeActivityFromHistoryLocked: last activity removed from " + this);
3016            if (mStackSupervisor.isFrontStack(this) && task == topTask() &&
3017                    task.isOverHomeStack()) {
3018                mStackSupervisor.moveHomeStackTaskToTop(task.getTaskToReturnTo());
3019            }
3020            removeTask(task);
3021        }
3022        cleanUpActivityServicesLocked(r);
3023        r.removeUriPermissionsLocked();
3024    }
3025
3026    /**
3027     * Perform clean-up of service connections in an activity record.
3028     */
3029    final void cleanUpActivityServicesLocked(ActivityRecord r) {
3030        // Throw away any services that have been bound by this activity.
3031        if (r.connections != null) {
3032            Iterator<ConnectionRecord> it = r.connections.iterator();
3033            while (it.hasNext()) {
3034                ConnectionRecord c = it.next();
3035                mService.mServices.removeConnectionLocked(c, null, r);
3036            }
3037            r.connections = null;
3038        }
3039    }
3040
3041    final void scheduleDestroyActivities(ProcessRecord owner, String reason) {
3042        Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
3043        msg.obj = new ScheduleDestroyArgs(owner, reason);
3044        mHandler.sendMessage(msg);
3045    }
3046
3047    final void destroyActivitiesLocked(ProcessRecord owner, String reason) {
3048        boolean lastIsOpaque = false;
3049        boolean activityRemoved = false;
3050        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3051            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3052            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3053                final ActivityRecord r = activities.get(activityNdx);
3054                if (r.finishing) {
3055                    continue;
3056                }
3057                if (r.fullscreen) {
3058                    lastIsOpaque = true;
3059                }
3060                if (owner != null && r.app != owner) {
3061                    continue;
3062                }
3063                if (!lastIsOpaque) {
3064                    continue;
3065                }
3066                if (r.isDestroyable()) {
3067                    if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3068                            + " resumed=" + mResumedActivity
3069                            + " pausing=" + mPausingActivity + " for reason " + reason);
3070                    if (destroyActivityLocked(r, true, reason)) {
3071                        activityRemoved = true;
3072                    }
3073                }
3074            }
3075        }
3076        if (activityRemoved) {
3077            mStackSupervisor.resumeTopActivitiesLocked();
3078        }
3079    }
3080
3081    final boolean safelyDestroyActivityLocked(ActivityRecord r, String reason) {
3082        if (r.isDestroyable()) {
3083            if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3084                    + " resumed=" + mResumedActivity
3085                    + " pausing=" + mPausingActivity + " for reason " + reason);
3086            return destroyActivityLocked(r, true, reason);
3087        }
3088        return false;
3089    }
3090
3091    final int releaseSomeActivitiesLocked(ProcessRecord app, ArraySet<TaskRecord> tasks,
3092            String reason) {
3093        // Iterate over tasks starting at the back (oldest) first.
3094        if (DEBUG_RELEASE) Slog.d(TAG, "Trying to release some activities in " + app);
3095        int maxTasks = tasks.size() / 4;
3096        if (maxTasks < 1) {
3097            maxTasks = 1;
3098        }
3099        int numReleased = 0;
3100        for (int taskNdx = 0; taskNdx < mTaskHistory.size() && maxTasks > 0; taskNdx++) {
3101            final TaskRecord task = mTaskHistory.get(taskNdx);
3102            if (!tasks.contains(task)) {
3103                continue;
3104            }
3105            if (DEBUG_RELEASE) Slog.d(TAG, "Looking for activities to release in " + task);
3106            int curNum = 0;
3107            final ArrayList<ActivityRecord> activities = task.mActivities;
3108            for (int actNdx = 0; actNdx < activities.size(); actNdx++) {
3109                final ActivityRecord activity = activities.get(actNdx);
3110                if (activity.app == app && activity.isDestroyable()) {
3111                    if (DEBUG_RELEASE) Slog.v(TAG, "Destroying " + activity
3112                            + " in state " + activity.state + " resumed=" + mResumedActivity
3113                            + " pausing=" + mPausingActivity + " for reason " + reason);
3114                    destroyActivityLocked(activity, true, reason);
3115                    if (activities.get(actNdx) != activity) {
3116                        // Was removed from list, back up so we don't miss the next one.
3117                        actNdx--;
3118                    }
3119                    curNum++;
3120                }
3121            }
3122            if (curNum > 0) {
3123                numReleased += curNum;
3124                maxTasks--;
3125                if (mTaskHistory.get(taskNdx) != task) {
3126                    // The entire task got removed, back up so we don't miss the next one.
3127                    taskNdx--;
3128                }
3129            }
3130        }
3131        if (DEBUG_RELEASE) Slog.d(TAG, "Done releasing: did " + numReleased + " activities");
3132        return numReleased;
3133    }
3134
3135    /**
3136     * Destroy the current CLIENT SIDE instance of an activity.  This may be
3137     * called both when actually finishing an activity, or when performing
3138     * a configuration switch where we destroy the current client-side object
3139     * but then create a new client-side object for this same HistoryRecord.
3140     */
3141    final boolean destroyActivityLocked(ActivityRecord r, boolean removeFromApp, String reason) {
3142        if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
3143            TAG, "Removing activity from " + reason + ": token=" + r
3144              + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3145        EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3146                r.userId, System.identityHashCode(r),
3147                r.task.taskId, r.shortComponentName, reason);
3148
3149        boolean removedFromHistory = false;
3150
3151        cleanUpActivityLocked(r, false, false);
3152
3153        final boolean hadApp = r.app != null;
3154
3155        if (hadApp) {
3156            if (removeFromApp) {
3157                r.app.activities.remove(r);
3158                if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3159                    mService.mHeavyWeightProcess = null;
3160                    mService.mHandler.sendEmptyMessage(
3161                            ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3162                }
3163                if (r.app.activities.isEmpty()) {
3164                    // No longer have activities, so update LRU list and oom adj.
3165                    mService.updateLruProcessLocked(r.app, false, null);
3166                    mService.updateOomAdjLocked();
3167                }
3168            }
3169
3170            boolean skipDestroy = false;
3171
3172            try {
3173                if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3174                r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
3175                        r.configChangeFlags);
3176            } catch (Exception e) {
3177                // We can just ignore exceptions here...  if the process
3178                // has crashed, our death notification will clean things
3179                // up.
3180                //Slog.w(TAG, "Exception thrown during finish", e);
3181                if (r.finishing) {
3182                    removeActivityFromHistoryLocked(r);
3183                    removedFromHistory = true;
3184                    skipDestroy = true;
3185                }
3186            }
3187
3188            r.nowVisible = false;
3189
3190            // If the activity is finishing, we need to wait on removing it
3191            // from the list to give it a chance to do its cleanup.  During
3192            // that time it may make calls back with its token so we need to
3193            // be able to find it on the list and so we don't want to remove
3194            // it from the list yet.  Otherwise, we can just immediately put
3195            // it in the destroyed state since we are not removing it from the
3196            // list.
3197            if (r.finishing && !skipDestroy) {
3198                if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3199                        + " (destroy requested)");
3200                r.state = ActivityState.DESTROYING;
3201                Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r);
3202                mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3203            } else {
3204                if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (destroy skipped)");
3205                r.state = ActivityState.DESTROYED;
3206                if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
3207                r.app = null;
3208            }
3209        } else {
3210            // remove this record from the history.
3211            if (r.finishing) {
3212                removeActivityFromHistoryLocked(r);
3213                removedFromHistory = true;
3214            } else {
3215                if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (no app)");
3216                r.state = ActivityState.DESTROYED;
3217                if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
3218                r.app = null;
3219            }
3220        }
3221
3222        r.configChangeFlags = 0;
3223
3224        if (!mLRUActivities.remove(r) && hadApp) {
3225            Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3226        }
3227
3228        return removedFromHistory;
3229    }
3230
3231    final void activityDestroyedLocked(IBinder token) {
3232        final long origId = Binder.clearCallingIdentity();
3233        try {
3234            ActivityRecord r = ActivityRecord.forToken(token);
3235            if (r != null) {
3236                mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3237            }
3238            if (DEBUG_CONTAINERS) Slog.d(TAG, "activityDestroyedLocked: r=" + r);
3239
3240            if (isInStackLocked(token) != null) {
3241                if (r.state == ActivityState.DESTROYING) {
3242                    cleanUpActivityLocked(r, true, false);
3243                    removeActivityFromHistoryLocked(r);
3244                }
3245            }
3246            mStackSupervisor.resumeTopActivitiesLocked();
3247        } finally {
3248            Binder.restoreCallingIdentity(origId);
3249        }
3250    }
3251
3252    void releaseBackgroundResources() {
3253        if (hasVisibleBehindActivity() &&
3254                !mHandler.hasMessages(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG)) {
3255            final ActivityRecord r = getVisibleBehindActivity();
3256            if (DEBUG_STATES) Slog.d(TAG, "releaseBackgroundResources activtyDisplay=" +
3257                    mActivityContainer.mActivityDisplay + " visibleBehind=" + r + " app=" + r.app +
3258                    " thread=" + r.app.thread);
3259            if (r != null && r.app != null && r.app.thread != null) {
3260                try {
3261                    r.app.thread.scheduleCancelVisibleBehind(r.appToken);
3262                } catch (RemoteException e) {
3263                }
3264                mHandler.sendEmptyMessageDelayed(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG, 500);
3265            } else {
3266                Slog.e(TAG, "releaseBackgroundResources: activity " + r + " no longer running");
3267                backgroundResourcesReleased(r.appToken);
3268            }
3269        }
3270    }
3271
3272    final void backgroundResourcesReleased(IBinder token) {
3273        mHandler.removeMessages(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG);
3274        final ActivityRecord r = getVisibleBehindActivity();
3275        if (r != null) {
3276            mStackSupervisor.mStoppingActivities.add(r);
3277            setVisibleBehindActivity(null);
3278        }
3279        mStackSupervisor.resumeTopActivitiesLocked();
3280    }
3281
3282    boolean hasVisibleBehindActivity() {
3283        return isAttached() && mActivityContainer.mActivityDisplay.hasVisibleBehindActivity();
3284    }
3285
3286    void setVisibleBehindActivity(ActivityRecord r) {
3287        if (isAttached()) {
3288            mActivityContainer.mActivityDisplay.setVisibleBehindActivity(r);
3289        }
3290    }
3291
3292    ActivityRecord getVisibleBehindActivity() {
3293        return isAttached() ? mActivityContainer.mActivityDisplay.mVisibleBehindActivity : null;
3294    }
3295
3296    private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
3297            ProcessRecord app, String listName) {
3298        int i = list.size();
3299        if (DEBUG_CLEANUP) Slog.v(
3300            TAG, "Removing app " + app + " from list " + listName
3301            + " with " + i + " entries");
3302        while (i > 0) {
3303            i--;
3304            ActivityRecord r = list.get(i);
3305            if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
3306            if (r.app == app) {
3307                if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
3308                list.remove(i);
3309                removeTimeoutsForActivityLocked(r);
3310            }
3311        }
3312    }
3313
3314    boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
3315        removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
3316        removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app,
3317                "mStoppingActivities");
3318        removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app,
3319                "mGoingToSleepActivities");
3320        removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app,
3321                "mWaitingVisibleActivities");
3322        removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app,
3323                "mFinishingActivities");
3324
3325        boolean hasVisibleActivities = false;
3326
3327        // Clean out the history list.
3328        int i = numActivities();
3329        if (DEBUG_CLEANUP) Slog.v(
3330            TAG, "Removing app " + app + " from history with " + i + " entries");
3331        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3332            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3333            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3334                final ActivityRecord r = activities.get(activityNdx);
3335                --i;
3336                if (DEBUG_CLEANUP) Slog.v(
3337                    TAG, "Record #" + i + " " + r + ": app=" + r.app);
3338                if (r.app == app) {
3339                    boolean remove;
3340                    if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
3341                        // Don't currently have state for the activity, or
3342                        // it is finishing -- always remove it.
3343                        remove = true;
3344                    } else if (r.launchCount > 2 &&
3345                            r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
3346                        // We have launched this activity too many times since it was
3347                        // able to run, so give up and remove it.
3348                        remove = true;
3349                    } else {
3350                        // The process may be gone, but the activity lives on!
3351                        remove = false;
3352                    }
3353                    if (remove) {
3354                        if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
3355                            RuntimeException here = new RuntimeException("here");
3356                            here.fillInStackTrace();
3357                            Slog.i(TAG, "Removing activity " + r + " from stack at " + i
3358                                    + ": haveState=" + r.haveState
3359                                    + " stateNotNeeded=" + r.stateNotNeeded
3360                                    + " finishing=" + r.finishing
3361                                    + " state=" + r.state, here);
3362                        }
3363                        if (!r.finishing) {
3364                            Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
3365                            EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3366                                    r.userId, System.identityHashCode(r),
3367                                    r.task.taskId, r.shortComponentName,
3368                                    "proc died without state saved");
3369                            if (r.state == ActivityState.RESUMED) {
3370                                mService.updateUsageStats(r, false);
3371                            }
3372                        }
3373                        removeActivityFromHistoryLocked(r);
3374
3375                    } else {
3376                        // We have the current state for this activity, so
3377                        // it can be restarted later when needed.
3378                        if (localLOGV) Slog.v(
3379                            TAG, "Keeping entry, setting app to null");
3380                        if (r.visible) {
3381                            hasVisibleActivities = true;
3382                        }
3383                        if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
3384                                + r);
3385                        r.app = null;
3386                        r.nowVisible = false;
3387                        if (!r.haveState) {
3388                            if (DEBUG_SAVED_STATE) Slog.i(TAG,
3389                                    "App died, clearing saved state of " + r);
3390                            r.icicle = null;
3391                        }
3392                    }
3393
3394                    cleanUpActivityLocked(r, true, true);
3395                }
3396            }
3397        }
3398
3399        return hasVisibleActivities;
3400    }
3401
3402    final void updateTransitLocked(int transit, Bundle options) {
3403        if (options != null) {
3404            ActivityRecord r = topRunningActivityLocked(null);
3405            if (r != null && r.state != ActivityState.RESUMED) {
3406                r.updateOptionsLocked(options);
3407            } else {
3408                ActivityOptions.abort(options);
3409            }
3410        }
3411        mWindowManager.prepareAppTransition(transit, false);
3412    }
3413
3414    void updateTaskMovement(TaskRecord task, boolean toFront) {
3415        if (task.isPersistable) {
3416            task.mLastTimeMoved = System.currentTimeMillis();
3417            // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most
3418            // recently will be most negative, tasks sent to the bottom before that will be less
3419            // negative. Similarly for recent tasks moved to the top which will be most positive.
3420            if (!toFront) {
3421                task.mLastTimeMoved *= -1;
3422            }
3423        }
3424    }
3425
3426    void moveHomeStackTaskToTop(int homeStackTaskType) {
3427        final int top = mTaskHistory.size() - 1;
3428        for (int taskNdx = top; taskNdx >= 0; --taskNdx) {
3429            final TaskRecord task = mTaskHistory.get(taskNdx);
3430            if (task.taskType == homeStackTaskType) {
3431                if (DEBUG_TASKS || DEBUG_STACK)
3432                    Slog.d(TAG, "moveHomeStackTaskToTop: moving " + task);
3433                mTaskHistory.remove(taskNdx);
3434                mTaskHistory.add(top, task);
3435                updateTaskMovement(task, true);
3436                mWindowManager.moveTaskToTop(task.taskId);
3437                return;
3438            }
3439        }
3440    }
3441
3442    final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
3443        if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3444
3445        final int numTasks = mTaskHistory.size();
3446        final int index = mTaskHistory.indexOf(tr);
3447        if (numTasks == 0 || index < 0)  {
3448            // nothing to do!
3449            if (reason != null &&
3450                    (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3451                ActivityOptions.abort(options);
3452            } else {
3453                updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
3454            }
3455            return;
3456        }
3457
3458        moveToFront();
3459
3460        // Shift all activities with this task up to the top
3461        // of the stack, keeping them in the same internal order.
3462        insertTaskAtTop(tr);
3463
3464        if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr);
3465        if (reason != null &&
3466                (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3467            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
3468            ActivityRecord r = topRunningActivityLocked(null);
3469            if (r != null) {
3470                mNoAnimActivities.add(r);
3471            }
3472            ActivityOptions.abort(options);
3473        } else {
3474            updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
3475        }
3476
3477        mWindowManager.moveTaskToTop(tr.taskId);
3478
3479        mStackSupervisor.resumeTopActivitiesLocked();
3480        EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId);
3481
3482        if (VALIDATE_TOKENS) {
3483            validateAppTokensLocked();
3484        }
3485    }
3486
3487    /**
3488     * Worker method for rearranging history stack. Implements the function of moving all
3489     * activities for a specific task (gathering them if disjoint) into a single group at the
3490     * bottom of the stack.
3491     *
3492     * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3493     * to premeptively cancel the move.
3494     *
3495     * @param taskId The taskId to collect and move to the bottom.
3496     * @return Returns true if the move completed, false if not.
3497     */
3498    final boolean moveTaskToBackLocked(int taskId, ActivityRecord reason) {
3499        final TaskRecord tr = taskForIdLocked(taskId);
3500        if (tr == null) {
3501            Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId);
3502            return false;
3503        }
3504
3505        Slog.i(TAG, "moveTaskToBack: " + tr);
3506
3507        mStackSupervisor.endLockTaskModeIfTaskEnding(tr);
3508
3509        // If we have a watcher, preflight the move before committing to it.  First check
3510        // for *other* available tasks, but if none are available, then try again allowing the
3511        // current task to be selected.
3512        if (mStackSupervisor.isFrontStack(this) && mService.mController != null) {
3513            ActivityRecord next = topRunningActivityLocked(null, taskId);
3514            if (next == null) {
3515                next = topRunningActivityLocked(null, 0);
3516            }
3517            if (next != null) {
3518                // ask watcher if this is allowed
3519                boolean moveOK = true;
3520                try {
3521                    moveOK = mService.mController.activityResuming(next.packageName);
3522                } catch (RemoteException e) {
3523                    mService.mController = null;
3524                    Watchdog.getInstance().setActivityController(null);
3525                }
3526                if (!moveOK) {
3527                    return false;
3528                }
3529            }
3530        }
3531
3532        if (DEBUG_TRANSITION) Slog.v(TAG,
3533                "Prepare to back transition: task=" + taskId);
3534
3535        mTaskHistory.remove(tr);
3536        mTaskHistory.add(0, tr);
3537        updateTaskMovement(tr, false);
3538
3539        // There is an assumption that moving a task to the back moves it behind the home activity.
3540        // We make sure here that some activity in the stack will launch home.
3541        int numTasks = mTaskHistory.size();
3542        for (int taskNdx = numTasks - 1; taskNdx >= 1; --taskNdx) {
3543            final TaskRecord task = mTaskHistory.get(taskNdx);
3544            if (task.isOverHomeStack()) {
3545                break;
3546            }
3547            if (taskNdx == 1) {
3548                // Set the last task before tr to go to home.
3549                task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
3550            }
3551        }
3552
3553        if (reason != null &&
3554                (reason.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3555            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
3556            ActivityRecord r = topRunningActivityLocked(null);
3557            if (r != null) {
3558                mNoAnimActivities.add(r);
3559            }
3560        } else {
3561            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_TASK_TO_BACK, false);
3562        }
3563        mWindowManager.moveTaskToBottom(taskId);
3564
3565        if (VALIDATE_TOKENS) {
3566            validateAppTokensLocked();
3567        }
3568
3569        final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null;
3570        if (task == tr && tr.isOverHomeStack() || numTasks <= 1 && isOnHomeDisplay()) {
3571            final int taskToReturnTo = tr.getTaskToReturnTo();
3572            tr.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
3573            return mStackSupervisor.resumeHomeStackTask(taskToReturnTo, null);
3574        }
3575
3576        mStackSupervisor.resumeTopActivitiesLocked();
3577        return true;
3578    }
3579
3580    static final void logStartActivity(int tag, ActivityRecord r,
3581            TaskRecord task) {
3582        final Uri data = r.intent.getData();
3583        final String strData = data != null ? data.toSafeString() : null;
3584
3585        EventLog.writeEvent(tag,
3586                r.userId, System.identityHashCode(r), task.taskId,
3587                r.shortComponentName, r.intent.getAction(),
3588                r.intent.getType(), strData, r.intent.getFlags());
3589    }
3590
3591    /**
3592     * Make sure the given activity matches the current configuration.  Returns
3593     * false if the activity had to be destroyed.  Returns true if the
3594     * configuration is the same, or the activity will remain running as-is
3595     * for whatever reason.  Ensures the HistoryRecord is updated with the
3596     * correct configuration and all other bookkeeping is handled.
3597     */
3598    final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3599            int globalChanges) {
3600        if (mConfigWillChange) {
3601            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3602                    "Skipping config check (will change): " + r);
3603            return true;
3604        }
3605
3606        if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3607                "Ensuring correct configuration: " + r);
3608
3609        // Short circuit: if the two configurations are the exact same
3610        // object (the common case), then there is nothing to do.
3611        Configuration newConfig = mService.mConfiguration;
3612        if (r.configuration == newConfig && !r.forceNewConfig) {
3613            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3614                    "Configuration unchanged in " + r);
3615            return true;
3616        }
3617
3618        // We don't worry about activities that are finishing.
3619        if (r.finishing) {
3620            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3621                    "Configuration doesn't matter in finishing " + r);
3622            r.stopFreezingScreenLocked(false);
3623            return true;
3624        }
3625
3626        // Okay we now are going to make this activity have the new config.
3627        // But then we need to figure out how it needs to deal with that.
3628        Configuration oldConfig = r.configuration;
3629        r.configuration = newConfig;
3630
3631        // Determine what has changed.  May be nothing, if this is a config
3632        // that has come back from the app after going idle.  In that case
3633        // we just want to leave the official config object now in the
3634        // activity and do nothing else.
3635        final int changes = oldConfig.diff(newConfig);
3636        if (changes == 0 && !r.forceNewConfig) {
3637            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3638                    "Configuration no differences in " + r);
3639            return true;
3640        }
3641
3642        // If the activity isn't currently running, just leave the new
3643        // configuration and it will pick that up next time it starts.
3644        if (r.app == null || r.app.thread == null) {
3645            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3646                    "Configuration doesn't matter not running " + r);
3647            r.stopFreezingScreenLocked(false);
3648            r.forceNewConfig = false;
3649            return true;
3650        }
3651
3652        // Figure out how to handle the changes between the configurations.
3653        if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3654            Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3655                    + Integer.toHexString(changes) + ", handles=0x"
3656                    + Integer.toHexString(r.info.getRealConfigChanged())
3657                    + ", newConfig=" + newConfig);
3658        }
3659        if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
3660            // Aha, the activity isn't handling the change, so DIE DIE DIE.
3661            r.configChangeFlags |= changes;
3662            r.startFreezingScreenLocked(r.app, globalChanges);
3663            r.forceNewConfig = false;
3664            if (r.app == null || r.app.thread == null) {
3665                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3666                        "Config is destroying non-running " + r);
3667                destroyActivityLocked(r, true, "config");
3668            } else if (r.state == ActivityState.PAUSING) {
3669                // A little annoying: we are waiting for this activity to
3670                // finish pausing.  Let's not do anything now, but just
3671                // flag that it needs to be restarted when done pausing.
3672                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3673                        "Config is skipping already pausing " + r);
3674                r.configDestroy = true;
3675                return true;
3676            } else if (r.state == ActivityState.RESUMED) {
3677                // Try to optimize this case: the configuration is changing
3678                // and we need to restart the top, resumed activity.
3679                // Instead of doing the normal handshaking, just say
3680                // "restart!".
3681                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3682                        "Config is relaunching resumed " + r);
3683                relaunchActivityLocked(r, r.configChangeFlags, true);
3684                r.configChangeFlags = 0;
3685            } else {
3686                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3687                        "Config is relaunching non-resumed " + r);
3688                relaunchActivityLocked(r, r.configChangeFlags, false);
3689                r.configChangeFlags = 0;
3690            }
3691
3692            // All done...  tell the caller we weren't able to keep this
3693            // activity around.
3694            return false;
3695        }
3696
3697        // Default case: the activity can handle this new configuration, so
3698        // hand it over.  Note that we don't need to give it the new
3699        // configuration, since we always send configuration changes to all
3700        // process when they happen so it can just use whatever configuration
3701        // it last got.
3702        if (r.app != null && r.app.thread != null) {
3703            try {
3704                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
3705                r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
3706            } catch (RemoteException e) {
3707                // If process died, whatever.
3708            }
3709        }
3710        r.stopFreezingScreenLocked(false);
3711
3712        return true;
3713    }
3714
3715    private boolean relaunchActivityLocked(ActivityRecord r,
3716            int changes, boolean andResume) {
3717        List<ResultInfo> results = null;
3718        List<Intent> newIntents = null;
3719        if (andResume) {
3720            results = r.results;
3721            newIntents = r.newIntents;
3722        }
3723        if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
3724                + " with results=" + results + " newIntents=" + newIntents
3725                + " andResume=" + andResume);
3726        EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
3727                : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
3728                r.task.taskId, r.shortComponentName);
3729
3730        r.startFreezingScreenLocked(r.app, 0);
3731
3732        mStackSupervisor.removeChildActivityContainers(r);
3733
3734        try {
3735            if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
3736                    (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
3737                    + r);
3738            r.forceNewConfig = false;
3739            r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
3740                    changes, !andResume, new Configuration(mService.mConfiguration));
3741            // Note: don't need to call pauseIfSleepingLocked() here, because
3742            // the caller will only pass in 'andResume' if this activity is
3743            // currently resumed, which implies we aren't sleeping.
3744        } catch (RemoteException e) {
3745            if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
3746        }
3747
3748        if (andResume) {
3749            r.results = null;
3750            r.newIntents = null;
3751            r.state = ActivityState.RESUMED;
3752        } else {
3753            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3754            r.state = ActivityState.PAUSED;
3755        }
3756
3757        return true;
3758    }
3759
3760    boolean willActivityBeVisibleLocked(IBinder token) {
3761        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3762            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3763            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3764                final ActivityRecord r = activities.get(activityNdx);
3765                if (r.appToken == token) {
3766                    return true;
3767                }
3768                if (r.fullscreen && !r.finishing) {
3769                    return false;
3770                }
3771            }
3772        }
3773        final ActivityRecord r = ActivityRecord.forToken(token);
3774        if (r == null) {
3775            return false;
3776        }
3777        if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false,"
3778                + " would have returned true for r=" + r);
3779        return !r.finishing;
3780    }
3781
3782    void closeSystemDialogsLocked() {
3783        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3784            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3785            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3786                final ActivityRecord r = activities.get(activityNdx);
3787                if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
3788                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true);
3789                }
3790            }
3791        }
3792    }
3793
3794    boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
3795        boolean didSomething = false;
3796        TaskRecord lastTask = null;
3797        ComponentName homeActivity = null;
3798        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3799            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3800            int numActivities = activities.size();
3801            for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
3802                ActivityRecord r = activities.get(activityNdx);
3803                final boolean samePackage = r.packageName.equals(name)
3804                        || (name == null && r.userId == userId);
3805                if ((userId == UserHandle.USER_ALL || r.userId == userId)
3806                        && (samePackage || r.task == lastTask)
3807                        && (r.app == null || evenPersistent || !r.app.persistent)) {
3808                    if (!doit) {
3809                        if (r.finishing) {
3810                            // If this activity is just finishing, then it is not
3811                            // interesting as far as something to stop.
3812                            continue;
3813                        }
3814                        return true;
3815                    }
3816                    if (r.isHomeActivity()) {
3817                        if (homeActivity != null && homeActivity.equals(r.realActivity)) {
3818                            Slog.i(TAG, "Skip force-stop again " + r);
3819                            continue;
3820                        } else {
3821                            homeActivity = r.realActivity;
3822                        }
3823                    }
3824                    didSomething = true;
3825                    Slog.i(TAG, "  Force finishing activity " + r);
3826                    if (samePackage) {
3827                        if (r.app != null) {
3828                            r.app.removed = true;
3829                        }
3830                        r.app = null;
3831                    }
3832                    lastTask = r.task;
3833                    if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop",
3834                            true)) {
3835                        // r has been deleted from mActivities, accommodate.
3836                        --numActivities;
3837                        --activityNdx;
3838                    }
3839                }
3840            }
3841        }
3842        return didSomething;
3843    }
3844
3845    void getTasksLocked(List<RunningTaskInfo> list, int callingUid, boolean allowed) {
3846        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3847            final TaskRecord task = mTaskHistory.get(taskNdx);
3848            ActivityRecord r = null;
3849            ActivityRecord top = null;
3850            int numActivities = 0;
3851            int numRunning = 0;
3852            final ArrayList<ActivityRecord> activities = task.mActivities;
3853            if (activities.isEmpty()) {
3854                continue;
3855            }
3856            if (!allowed && !task.isHomeTask() && task.effectiveUid != callingUid) {
3857                continue;
3858            }
3859            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3860                r = activities.get(activityNdx);
3861
3862                // Initialize state for next task if needed.
3863                if (top == null || (top.state == ActivityState.INITIALIZING)) {
3864                    top = r;
3865                    numActivities = numRunning = 0;
3866                }
3867
3868                // Add 'r' into the current task.
3869                numActivities++;
3870                if (r.app != null && r.app.thread != null) {
3871                    numRunning++;
3872                }
3873
3874                if (localLOGV) Slog.v(
3875                    TAG, r.intent.getComponent().flattenToShortString()
3876                    + ": task=" + r.task);
3877            }
3878
3879            RunningTaskInfo ci = new RunningTaskInfo();
3880            ci.id = task.taskId;
3881            ci.baseActivity = r.intent.getComponent();
3882            ci.topActivity = top.intent.getComponent();
3883            ci.lastActiveTime = task.lastActiveTime;
3884
3885            if (top.task != null) {
3886                ci.description = top.task.lastDescription;
3887            }
3888            ci.numActivities = numActivities;
3889            ci.numRunning = numRunning;
3890            //System.out.println(
3891            //    "#" + maxNum + ": " + " descr=" + ci.description);
3892            list.add(ci);
3893        }
3894    }
3895
3896    public void unhandledBackLocked() {
3897        final int top = mTaskHistory.size() - 1;
3898        if (DEBUG_SWITCH) Slog.d(
3899            TAG, "Performing unhandledBack(): top activity at " + top);
3900        if (top >= 0) {
3901            final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
3902            int activityTop = activities.size() - 1;
3903            if (activityTop > 0) {
3904                finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
3905                        "unhandled-back", true);
3906            }
3907        }
3908    }
3909
3910    /**
3911     * Reset local parameters because an app's activity died.
3912     * @param app The app of the activity that died.
3913     * @return result from removeHistoryRecordsForAppLocked.
3914     */
3915    boolean handleAppDiedLocked(ProcessRecord app) {
3916        if (mPausingActivity != null && mPausingActivity.app == app) {
3917            if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
3918                    "App died while pausing: " + mPausingActivity);
3919            mPausingActivity = null;
3920        }
3921        if (mLastPausedActivity != null && mLastPausedActivity.app == app) {
3922            mLastPausedActivity = null;
3923            mLastNoHistoryActivity = null;
3924        }
3925
3926        return removeHistoryRecordsForAppLocked(app);
3927    }
3928
3929    void handleAppCrashLocked(ProcessRecord app) {
3930        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3931            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3932            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3933                final ActivityRecord r = activities.get(activityNdx);
3934                if (r.app == app) {
3935                    Slog.w(TAG, "  Force finishing activity "
3936                            + r.intent.getComponent().flattenToShortString());
3937                    // Force the destroy to skip right to removal.
3938                    r.app = null;
3939                    finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
3940                }
3941            }
3942        }
3943    }
3944
3945    boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3946            boolean dumpClient, String dumpPackage, boolean needSep, String header) {
3947        boolean printed = false;
3948        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3949            final TaskRecord task = mTaskHistory.get(taskNdx);
3950            printed |= ActivityStackSupervisor.dumpHistoryList(fd, pw,
3951                    mTaskHistory.get(taskNdx).mActivities, "    ", "Hist", true, !dumpAll,
3952                    dumpClient, dumpPackage, needSep, header,
3953                    "    Task id #" + task.taskId);
3954            if (printed) {
3955                header = null;
3956            }
3957        }
3958        return printed;
3959    }
3960
3961    ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
3962        ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
3963
3964        if ("all".equals(name)) {
3965            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3966                activities.addAll(mTaskHistory.get(taskNdx).mActivities);
3967            }
3968        } else if ("top".equals(name)) {
3969            final int top = mTaskHistory.size() - 1;
3970            if (top >= 0) {
3971                final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities;
3972                int listTop = list.size() - 1;
3973                if (listTop >= 0) {
3974                    activities.add(list.get(listTop));
3975                }
3976            }
3977        } else {
3978            ItemMatcher matcher = new ItemMatcher();
3979            matcher.build(name);
3980
3981            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3982                for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) {
3983                    if (matcher.match(r1, r1.intent.getComponent())) {
3984                        activities.add(r1);
3985                    }
3986                }
3987            }
3988        }
3989
3990        return activities;
3991    }
3992
3993    ActivityRecord restartPackage(String packageName) {
3994        ActivityRecord starting = topRunningActivityLocked(null);
3995
3996        // All activities that came from the package must be
3997        // restarted as if there was a config change.
3998        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3999            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4000            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4001                final ActivityRecord a = activities.get(activityNdx);
4002                if (a.info.packageName.equals(packageName)) {
4003                    a.forceNewConfig = true;
4004                    if (starting != null && a == starting && a.visible) {
4005                        a.startFreezingScreenLocked(starting.app,
4006                                ActivityInfo.CONFIG_SCREEN_LAYOUT);
4007                    }
4008                }
4009            }
4010        }
4011
4012        return starting;
4013    }
4014
4015    void removeTask(TaskRecord task) {
4016        mStackSupervisor.endLockTaskModeIfTaskEnding(task);
4017        mWindowManager.removeTask(task.taskId);
4018        final ActivityRecord r = mResumedActivity;
4019        if (r != null && r.task == task) {
4020            mResumedActivity = null;
4021        }
4022
4023        final int taskNdx = mTaskHistory.indexOf(task);
4024        final int topTaskNdx = mTaskHistory.size() - 1;
4025        if (task.isOverHomeStack() && taskNdx < topTaskNdx) {
4026            final TaskRecord nextTask = mTaskHistory.get(taskNdx + 1);
4027            if (!nextTask.isOverHomeStack()) {
4028                nextTask.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
4029            }
4030        }
4031        mTaskHistory.remove(task);
4032        updateTaskMovement(task, true);
4033
4034        if (task.mActivities.isEmpty()) {
4035            final boolean isVoiceSession = task.voiceSession != null;
4036            if (isVoiceSession) {
4037                try {
4038                    task.voiceSession.taskFinished(task.intent, task.taskId);
4039                } catch (RemoteException e) {
4040                }
4041            }
4042            if (task.autoRemoveFromRecents() || isVoiceSession) {
4043                // Task creator asked to remove this when done, or this task was a voice
4044                // interaction, so it should not remain on the recent tasks list.
4045                mService.mRecentTasks.remove(task);
4046                task.removedFromRecents(mService.mTaskPersister);
4047            }
4048        }
4049
4050        if (mTaskHistory.isEmpty()) {
4051            if (DEBUG_STACK) Slog.i(TAG, "removeTask: moving to back stack=" + this);
4052            if (isOnHomeDisplay()) {
4053                mStackSupervisor.moveHomeStack(!isHomeStack());
4054            }
4055            if (mStacks != null) {
4056                mStacks.remove(this);
4057                mStacks.add(0, this);
4058            }
4059            mActivityContainer.onTaskListEmptyLocked();
4060        }
4061    }
4062
4063    TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
4064            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
4065            boolean toTop) {
4066        TaskRecord task = new TaskRecord(mService, taskId, info, intent, voiceSession,
4067                voiceInteractor);
4068        addTask(task, toTop, false);
4069        return task;
4070    }
4071
4072    ArrayList<TaskRecord> getAllTasks() {
4073        return new ArrayList<TaskRecord>(mTaskHistory);
4074    }
4075
4076    void addTask(final TaskRecord task, final boolean toTop, boolean moving) {
4077        task.stack = this;
4078        if (toTop) {
4079            insertTaskAtTop(task);
4080        } else {
4081            mTaskHistory.add(0, task);
4082            updateTaskMovement(task, false);
4083        }
4084        if (!moving && task.voiceSession != null) {
4085            try {
4086                task.voiceSession.taskStarted(task.intent, task.taskId);
4087            } catch (RemoteException e) {
4088            }
4089        }
4090    }
4091
4092    public int getStackId() {
4093        return mStackId;
4094    }
4095
4096    @Override
4097    public String toString() {
4098        return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this))
4099                + " stackId=" + mStackId + ", " + mTaskHistory.size() + " tasks}";
4100    }
4101}
4102