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