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