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