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