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