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