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