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