ActivityStack.java revision 91097de49b0f683b00e26a75dbc0ac6082344137
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            mService.setFocusedActivityLocked(mStackSupervisor.topRunningActivityLocked());
2333        }
2334    }
2335
2336    final void stopActivityLocked(ActivityRecord r) {
2337        if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2338        if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2339                || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2340            if (!r.finishing) {
2341                if (!mService.isSleeping()) {
2342                    if (DEBUG_STATES) {
2343                        Slog.d(TAG, "no-history finish of " + r);
2344                    }
2345                    requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
2346                            "no-history", false);
2347                } else {
2348                    if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
2349                            + " on stop because we're just sleeping");
2350                }
2351            }
2352        }
2353
2354        if (r.app != null && r.app.thread != null) {
2355            adjustFocusedActivityLocked(r);
2356            r.resumeKeyDispatchingLocked();
2357            try {
2358                r.stopped = false;
2359                if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
2360                        + " (stop requested)");
2361                r.state = ActivityState.STOPPING;
2362                if (DEBUG_VISBILITY) Slog.v(
2363                        TAG, "Stopping visible=" + r.visible + " for " + r);
2364                if (!r.visible) {
2365                    mWindowManager.setAppVisibility(r.appToken, false);
2366                }
2367                r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
2368                if (mService.isSleepingOrShuttingDown()) {
2369                    r.setSleeping(true);
2370                }
2371                Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
2372                mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
2373            } catch (Exception e) {
2374                // Maybe just ignore exceptions here...  if the process
2375                // has crashed, our death notification will clean things
2376                // up.
2377                Slog.w(TAG, "Exception thrown during pause", e);
2378                // Just in case, assume it to be stopped.
2379                r.stopped = true;
2380                if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
2381                r.state = ActivityState.STOPPED;
2382                if (r.configDestroy) {
2383                    destroyActivityLocked(r, true, false, "stop-except");
2384                }
2385            }
2386        }
2387    }
2388
2389    /**
2390     * @return Returns true if the activity is being finished, false if for
2391     * some reason it is being left as-is.
2392     */
2393    final boolean requestFinishActivityLocked(IBinder token, int resultCode,
2394            Intent resultData, String reason, boolean oomAdj) {
2395        ActivityRecord r = isInStackLocked(token);
2396        if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
2397                TAG, "Finishing activity token=" + token + " r="
2398                + ", result=" + resultCode + ", data=" + resultData
2399                + ", reason=" + reason);
2400        if (r == null) {
2401            return false;
2402        }
2403
2404        finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
2405        return true;
2406    }
2407
2408    final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) {
2409        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2410            ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2411            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2412                ActivityRecord r = activities.get(activityNdx);
2413                if (r.resultTo == self && r.requestCode == requestCode) {
2414                    if ((r.resultWho == null && resultWho == null) ||
2415                        (r.resultWho != null && r.resultWho.equals(resultWho))) {
2416                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
2417                                false);
2418                    }
2419                }
2420            }
2421        }
2422        mService.updateOomAdjLocked();
2423    }
2424
2425    final void finishTopRunningActivityLocked(ProcessRecord app) {
2426        ActivityRecord r = topRunningActivityLocked(null);
2427        if (r != null && r.app == app) {
2428            // If the top running activity is from this crashing
2429            // process, then terminate it to avoid getting in a loop.
2430            Slog.w(TAG, "  Force finishing activity "
2431                    + r.intent.getComponent().flattenToShortString());
2432            int taskNdx = mTaskHistory.indexOf(r.task);
2433            int activityNdx = r.task.mActivities.indexOf(r);
2434            finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
2435            // Also terminate any activities below it that aren't yet
2436            // stopped, to avoid a situation where one will get
2437            // re-start our crashing activity once it gets resumed again.
2438            --activityNdx;
2439            if (activityNdx < 0) {
2440                do {
2441                    --taskNdx;
2442                    if (taskNdx < 0) {
2443                        break;
2444                    }
2445                    activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1;
2446                } while (activityNdx < 0);
2447            }
2448            if (activityNdx >= 0) {
2449                r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx);
2450                if (r.state == ActivityState.RESUMED
2451                        || r.state == ActivityState.PAUSING
2452                        || r.state == ActivityState.PAUSED) {
2453                    if (!r.isHomeActivity() || mService.mHomeProcess != r.app) {
2454                        Slog.w(TAG, "  Force finishing activity "
2455                                + r.intent.getComponent().flattenToShortString());
2456                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
2457                    }
2458                }
2459            }
2460        }
2461    }
2462
2463    final boolean finishActivityAffinityLocked(ActivityRecord r) {
2464        ArrayList<ActivityRecord> activities = r.task.mActivities;
2465        for (int index = activities.indexOf(r); index >= 0; --index) {
2466            ActivityRecord cur = activities.get(index);
2467            if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) {
2468                break;
2469            }
2470            finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true);
2471        }
2472        return true;
2473    }
2474
2475    final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
2476        // send the result
2477        ActivityRecord resultTo = r.resultTo;
2478        if (resultTo != null) {
2479            if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
2480                    + " who=" + r.resultWho + " req=" + r.requestCode
2481                    + " res=" + resultCode + " data=" + resultData);
2482            if (r.info.applicationInfo.uid > 0) {
2483                mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
2484                        resultTo.packageName, resultData,
2485                        resultTo.getUriPermissionsLocked());
2486            }
2487            resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
2488                                     resultData);
2489            r.resultTo = null;
2490        }
2491        else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
2492
2493        // Make sure this HistoryRecord is not holding on to other resources,
2494        // because clients have remote IPC references to this object so we
2495        // can't assume that will go away and want to avoid circular IPC refs.
2496        r.results = null;
2497        r.pendingResults = null;
2498        r.newIntents = null;
2499        r.icicle = null;
2500    }
2501
2502    /**
2503     * @return Returns true if this activity has been removed from the history
2504     * list, or false if it is still in the list and will be removed later.
2505     */
2506    final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
2507            String reason, boolean oomAdj) {
2508        if (r.finishing) {
2509            Slog.w(TAG, "Duplicate finish request for " + r);
2510            return false;
2511        }
2512
2513        r.makeFinishing();
2514        final TaskRecord task = r.task;
2515        EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2516                r.userId, System.identityHashCode(r),
2517                task.taskId, r.shortComponentName, reason);
2518        final ArrayList<ActivityRecord> activities = task.mActivities;
2519        final int index = activities.indexOf(r);
2520        if (index < (activities.size() - 1)) {
2521            task.setFrontOfTask();
2522            if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
2523                // If the caller asked that this activity (and all above it)
2524                // be cleared when the task is reset, don't lose that information,
2525                // but propagate it up to the next activity.
2526                ActivityRecord next = activities.get(index+1);
2527                next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
2528            }
2529        }
2530
2531        r.pauseKeyDispatchingLocked();
2532
2533        adjustFocusedActivityLocked(r);
2534
2535        finishActivityResultsLocked(r, resultCode, resultData);
2536
2537        if (!mService.mPendingThumbnails.isEmpty()) {
2538            // There are clients waiting to receive thumbnails so, in case
2539            // this is an activity that someone is waiting for, add it
2540            // to the pending list so we can correctly update the clients.
2541            mStackSupervisor.mCancelledThumbnails.add(r);
2542        }
2543
2544        if (mResumedActivity == r) {
2545            boolean endTask = index <= 0;
2546            if (DEBUG_VISBILITY || DEBUG_TRANSITION) Slog.v(TAG,
2547                    "Prepare close transition: finishing " + r);
2548            mWindowManager.prepareAppTransition(endTask
2549                    ? AppTransition.TRANSIT_TASK_CLOSE
2550                    : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
2551
2552            // Tell window manager to prepare for this one to be removed.
2553            mWindowManager.setAppVisibility(r.appToken, false);
2554
2555            if (mPausingActivity == null) {
2556                if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
2557                if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
2558                startPausingLocked(false, false);
2559            }
2560
2561            if (endTask) {
2562                mStackSupervisor.endLockTaskModeIfTaskEnding(task);
2563            }
2564        } else if (r.state != ActivityState.PAUSING) {
2565            // If the activity is PAUSING, we will complete the finish once
2566            // it is done pausing; else we can just directly finish it here.
2567            if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
2568            return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null;
2569        } else {
2570            if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
2571        }
2572
2573        return false;
2574    }
2575
2576    static final int FINISH_IMMEDIATELY = 0;
2577    static final int FINISH_AFTER_PAUSE = 1;
2578    static final int FINISH_AFTER_VISIBLE = 2;
2579
2580    final ActivityRecord finishCurrentActivityLocked(ActivityRecord r, int mode, boolean oomAdj) {
2581        // First things first: if this activity is currently visible,
2582        // and the resumed activity is not yet visible, then hold off on
2583        // finishing until the resumed one becomes visible.
2584        if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
2585            if (!mStackSupervisor.mStoppingActivities.contains(r)) {
2586                mStackSupervisor.mStoppingActivities.add(r);
2587                if (mStackSupervisor.mStoppingActivities.size() > 3
2588                        || r.frontOfTask && mTaskHistory.size() <= 1) {
2589                    // If we already have a few activities waiting to stop,
2590                    // then give up on things going idle and start clearing
2591                    // them out. Or if r is the last of activity of the last task the stack
2592                    // will be empty and must be cleared immediately.
2593                    mStackSupervisor.scheduleIdleLocked();
2594                } else {
2595                    mStackSupervisor.checkReadyForSleepLocked();
2596                }
2597            }
2598            if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
2599                    + " (finish requested)");
2600            r.state = ActivityState.STOPPING;
2601            if (oomAdj) {
2602                mService.updateOomAdjLocked();
2603            }
2604            return r;
2605        }
2606
2607        // make sure the record is cleaned out of other places.
2608        mStackSupervisor.mStoppingActivities.remove(r);
2609        mStackSupervisor.mGoingToSleepActivities.remove(r);
2610        mStackSupervisor.mWaitingVisibleActivities.remove(r);
2611        if (mResumedActivity == r) {
2612            mResumedActivity = null;
2613        }
2614        final ActivityState prevState = r.state;
2615        if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
2616        r.state = ActivityState.FINISHING;
2617
2618        if (mode == FINISH_IMMEDIATELY
2619                || prevState == ActivityState.STOPPED
2620                || prevState == ActivityState.INITIALIZING) {
2621            // If this activity is already stopped, we can just finish
2622            // it right now.
2623            boolean activityRemoved = destroyActivityLocked(r, true,
2624                    oomAdj, "finish-imm");
2625            if (activityRemoved) {
2626                mStackSupervisor.resumeTopActivitiesLocked();
2627            }
2628            return activityRemoved ? null : r;
2629        }
2630
2631        // Need to go through the full pause cycle to get this
2632        // activity into the stopped state and then finish it.
2633        if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
2634        mStackSupervisor.mFinishingActivities.add(r);
2635        r.resumeKeyDispatchingLocked();
2636        mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null);
2637        return r;
2638    }
2639
2640    void finishAllActivitiesLocked() {
2641        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2642            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2643            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2644                final ActivityRecord r = activities.get(activityNdx);
2645                if (r.finishing) {
2646                    continue;
2647                }
2648                Slog.d(TAG, "finishAllActivitiesLocked: finishing " + r);
2649                finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
2650            }
2651        }
2652    }
2653
2654    final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode,
2655            Intent resultData) {
2656        final ActivityRecord srec = ActivityRecord.forToken(token);
2657        final TaskRecord task = srec.task;
2658        final ArrayList<ActivityRecord> activities = task.mActivities;
2659        final int start = activities.indexOf(srec);
2660        if (!mTaskHistory.contains(task) || (start < 0)) {
2661            return false;
2662        }
2663        int finishTo = start - 1;
2664        ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo);
2665        boolean foundParentInTask = false;
2666        final ComponentName dest = destIntent.getComponent();
2667        if (start > 0 && dest != null) {
2668            for (int i = finishTo; i >= 0; i--) {
2669                ActivityRecord r = activities.get(i);
2670                if (r.info.packageName.equals(dest.getPackageName()) &&
2671                        r.info.name.equals(dest.getClassName())) {
2672                    finishTo = i;
2673                    parent = r;
2674                    foundParentInTask = true;
2675                    break;
2676                }
2677            }
2678        }
2679
2680        IActivityController controller = mService.mController;
2681        if (controller != null) {
2682            ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
2683            if (next != null) {
2684                // ask watcher if this is allowed
2685                boolean resumeOK = true;
2686                try {
2687                    resumeOK = controller.activityResuming(next.packageName);
2688                } catch (RemoteException e) {
2689                    mService.mController = null;
2690                    Watchdog.getInstance().setActivityController(null);
2691                }
2692
2693                if (!resumeOK) {
2694                    return false;
2695                }
2696            }
2697        }
2698        final long origId = Binder.clearCallingIdentity();
2699        for (int i = start; i > finishTo; i--) {
2700            ActivityRecord r = activities.get(i);
2701            requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
2702            // Only return the supplied result for the first activity finished
2703            resultCode = Activity.RESULT_CANCELED;
2704            resultData = null;
2705        }
2706
2707        if (parent != null && foundParentInTask) {
2708            final int parentLaunchMode = parent.info.launchMode;
2709            final int destIntentFlags = destIntent.getFlags();
2710            if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
2711                    parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
2712                    parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
2713                    (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2714                parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
2715            } else {
2716                try {
2717                    ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
2718                            destIntent.getComponent(), 0, srec.userId);
2719                    int res = mStackSupervisor.startActivityLocked(srec.app.thread, destIntent,
2720                            null, aInfo, null, null, parent.appToken, null,
2721                            0, -1, parent.launchedFromUid, parent.launchedFromPackage,
2722                            0, null, true, null, null);
2723                    foundParentInTask = res == ActivityManager.START_SUCCESS;
2724                } catch (RemoteException e) {
2725                    foundParentInTask = false;
2726                }
2727                requestFinishActivityLocked(parent.appToken, resultCode,
2728                        resultData, "navigate-up", true);
2729            }
2730        }
2731        Binder.restoreCallingIdentity(origId);
2732        return foundParentInTask;
2733    }
2734    /**
2735     * Perform the common clean-up of an activity record.  This is called both
2736     * as part of destroyActivityLocked() (when destroying the client-side
2737     * representation) and cleaning things up as a result of its hosting
2738     * processing going away, in which case there is no remaining client-side
2739     * state to destroy so only the cleanup here is needed.
2740     */
2741    final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
2742            boolean setState) {
2743        if (mResumedActivity == r) {
2744            mResumedActivity = null;
2745        }
2746        if (mPausingActivity == r) {
2747            mPausingActivity = null;
2748        }
2749        mService.clearFocusedActivity(r);
2750
2751        r.configDestroy = false;
2752        r.frozenBeforeDestroy = false;
2753
2754        if (setState) {
2755            if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
2756            r.state = ActivityState.DESTROYED;
2757            if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
2758            r.app = null;
2759        }
2760
2761        // Make sure this record is no longer in the pending finishes list.
2762        // This could happen, for example, if we are trimming activities
2763        // down to the max limit while they are still waiting to finish.
2764        mStackSupervisor.mFinishingActivities.remove(r);
2765        mStackSupervisor.mWaitingVisibleActivities.remove(r);
2766
2767        // Remove any pending results.
2768        if (r.finishing && r.pendingResults != null) {
2769            for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
2770                PendingIntentRecord rec = apr.get();
2771                if (rec != null) {
2772                    mService.cancelIntentSenderLocked(rec, false);
2773                }
2774            }
2775            r.pendingResults = null;
2776        }
2777
2778        if (cleanServices) {
2779            cleanUpActivityServicesLocked(r);
2780        }
2781
2782        if (!mService.mPendingThumbnails.isEmpty()) {
2783            // There are clients waiting to receive thumbnails so, in case
2784            // this is an activity that someone is waiting for, add it
2785            // to the pending list so we can correctly update the clients.
2786            mStackSupervisor.mCancelledThumbnails.add(r);
2787        }
2788
2789        // Get rid of any pending idle timeouts.
2790        removeTimeoutsForActivityLocked(r);
2791    }
2792
2793    private void removeTimeoutsForActivityLocked(ActivityRecord r) {
2794        mStackSupervisor.removeTimeoutsForActivityLocked(r);
2795        mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
2796        mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
2797        mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
2798        r.finishLaunchTickingLocked();
2799    }
2800
2801    private void removeActivityFromHistoryLocked(ActivityRecord r) {
2802        mStackSupervisor.removeChildActivityContainers(r);
2803        finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
2804        r.makeFinishing();
2805        if (DEBUG_ADD_REMOVE) {
2806            RuntimeException here = new RuntimeException("here");
2807            here.fillInStackTrace();
2808            Slog.i(TAG, "Removing activity " + r + " from stack");
2809        }
2810        r.takeFromHistory();
2811        removeTimeoutsForActivityLocked(r);
2812        if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)");
2813        r.state = ActivityState.DESTROYED;
2814        if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
2815        r.app = null;
2816        mWindowManager.removeAppToken(r.appToken);
2817        if (VALIDATE_TOKENS) {
2818            validateAppTokensLocked();
2819        }
2820        final TaskRecord task = r.task;
2821        if (task != null && task.removeActivity(r)) {
2822            if (DEBUG_STACK) Slog.i(TAG,
2823                    "removeActivityFromHistoryLocked: last activity removed from " + this);
2824            if (mStackSupervisor.isFrontStack(this) && task == topTask() && task.mOnTopOfHome) {
2825                mStackSupervisor.moveHomeToTop();
2826            }
2827            removeTask(task);
2828        }
2829        cleanUpActivityServicesLocked(r);
2830        r.removeUriPermissionsLocked();
2831    }
2832
2833    /**
2834     * Perform clean-up of service connections in an activity record.
2835     */
2836    final void cleanUpActivityServicesLocked(ActivityRecord r) {
2837        // Throw away any services that have been bound by this activity.
2838        if (r.connections != null) {
2839            Iterator<ConnectionRecord> it = r.connections.iterator();
2840            while (it.hasNext()) {
2841                ConnectionRecord c = it.next();
2842                mService.mServices.removeConnectionLocked(c, null, r);
2843            }
2844            r.connections = null;
2845        }
2846    }
2847
2848    final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
2849        Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
2850        msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
2851        mHandler.sendMessage(msg);
2852    }
2853
2854    final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
2855        boolean lastIsOpaque = false;
2856        boolean activityRemoved = false;
2857        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2858            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2859            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2860                final ActivityRecord r = activities.get(activityNdx);
2861                if (r.finishing) {
2862                    continue;
2863                }
2864                if (r.fullscreen) {
2865                    lastIsOpaque = true;
2866                }
2867                if (owner != null && r.app != owner) {
2868                    continue;
2869                }
2870                if (!lastIsOpaque) {
2871                    continue;
2872                }
2873                // We can destroy this one if we have its icicle saved and
2874                // it is not in the process of pausing/stopping/finishing.
2875                if (r.app != null && r != mResumedActivity && r != mPausingActivity
2876                        && r.haveState && !r.visible && r.stopped
2877                        && r.state != ActivityState.DESTROYING
2878                        && r.state != ActivityState.DESTROYED) {
2879                    if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
2880                            + " resumed=" + mResumedActivity
2881                            + " pausing=" + mPausingActivity);
2882                    if (destroyActivityLocked(r, true, oomAdj, reason)) {
2883                        activityRemoved = true;
2884                    }
2885                }
2886            }
2887        }
2888        if (activityRemoved) {
2889            mStackSupervisor.resumeTopActivitiesLocked();
2890        }
2891    }
2892
2893    /**
2894     * Destroy the current CLIENT SIDE instance of an activity.  This may be
2895     * called both when actually finishing an activity, or when performing
2896     * a configuration switch where we destroy the current client-side object
2897     * but then create a new client-side object for this same HistoryRecord.
2898     */
2899    final boolean destroyActivityLocked(ActivityRecord r,
2900            boolean removeFromApp, boolean oomAdj, String reason) {
2901        if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
2902            TAG, "Removing activity from " + reason + ": token=" + r
2903              + ", app=" + (r.app != null ? r.app.processName : "(null)"));
2904        EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
2905                r.userId, System.identityHashCode(r),
2906                r.task.taskId, r.shortComponentName, reason);
2907
2908        boolean removedFromHistory = false;
2909
2910        cleanUpActivityLocked(r, false, false);
2911
2912        final boolean hadApp = r.app != null;
2913
2914        if (hadApp) {
2915            if (removeFromApp) {
2916                r.app.activities.remove(r);
2917                if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
2918                    mService.mHeavyWeightProcess = null;
2919                    mService.mHandler.sendEmptyMessage(
2920                            ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
2921                }
2922                if (r.app.activities.isEmpty()) {
2923                    // No longer have activities, so update LRU list and oom adj.
2924                    mService.updateLruProcessLocked(r.app, false, null);
2925                    mService.updateOomAdjLocked();
2926                }
2927            }
2928
2929            boolean skipDestroy = false;
2930
2931            try {
2932                if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
2933                r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
2934                        r.configChangeFlags);
2935            } catch (Exception e) {
2936                // We can just ignore exceptions here...  if the process
2937                // has crashed, our death notification will clean things
2938                // up.
2939                //Slog.w(TAG, "Exception thrown during finish", e);
2940                if (r.finishing) {
2941                    removeActivityFromHistoryLocked(r);
2942                    removedFromHistory = true;
2943                    skipDestroy = true;
2944                }
2945            }
2946
2947            r.nowVisible = false;
2948
2949            // If the activity is finishing, we need to wait on removing it
2950            // from the list to give it a chance to do its cleanup.  During
2951            // that time it may make calls back with its token so we need to
2952            // be able to find it on the list and so we don't want to remove
2953            // it from the list yet.  Otherwise, we can just immediately put
2954            // it in the destroyed state since we are not removing it from the
2955            // list.
2956            if (r.finishing && !skipDestroy) {
2957                if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
2958                        + " (destroy requested)");
2959                r.state = ActivityState.DESTROYING;
2960                Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r);
2961                mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
2962            } else {
2963                if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (destroy skipped)");
2964                r.state = ActivityState.DESTROYED;
2965                if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
2966                r.app = null;
2967            }
2968        } else {
2969            // remove this record from the history.
2970            if (r.finishing) {
2971                removeActivityFromHistoryLocked(r);
2972                removedFromHistory = true;
2973            } else {
2974                if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (no app)");
2975                r.state = ActivityState.DESTROYED;
2976                if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
2977                r.app = null;
2978            }
2979        }
2980
2981        r.configChangeFlags = 0;
2982
2983        if (!mLRUActivities.remove(r) && hadApp) {
2984            Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
2985        }
2986
2987        return removedFromHistory;
2988    }
2989
2990    final void activityDestroyedLocked(IBinder token) {
2991        final long origId = Binder.clearCallingIdentity();
2992        try {
2993            ActivityRecord r = ActivityRecord.forToken(token);
2994            if (r != null) {
2995                mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
2996            }
2997
2998            if (isInStackLocked(token) != null) {
2999                if (r.state == ActivityState.DESTROYING) {
3000                    cleanUpActivityLocked(r, true, false);
3001                    removeActivityFromHistoryLocked(r);
3002                }
3003            }
3004            mStackSupervisor.resumeTopActivitiesLocked();
3005        } finally {
3006            Binder.restoreCallingIdentity(origId);
3007        }
3008    }
3009
3010    private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
3011            ProcessRecord app, String listName) {
3012        int i = list.size();
3013        if (DEBUG_CLEANUP) Slog.v(
3014            TAG, "Removing app " + app + " from list " + listName
3015            + " with " + i + " entries");
3016        while (i > 0) {
3017            i--;
3018            ActivityRecord r = list.get(i);
3019            if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
3020            if (r.app == app) {
3021                if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
3022                list.remove(i);
3023                removeTimeoutsForActivityLocked(r);
3024            }
3025        }
3026    }
3027
3028    boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
3029        removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
3030        removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app,
3031                "mStoppingActivities");
3032        removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app,
3033                "mGoingToSleepActivities");
3034        removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app,
3035                "mWaitingVisibleActivities");
3036        removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app,
3037                "mFinishingActivities");
3038
3039        boolean hasVisibleActivities = false;
3040
3041        // Clean out the history list.
3042        int i = numActivities();
3043        if (DEBUG_CLEANUP) Slog.v(
3044            TAG, "Removing app " + app + " from history with " + i + " entries");
3045        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3046            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3047            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3048                final ActivityRecord r = activities.get(activityNdx);
3049                --i;
3050                if (DEBUG_CLEANUP) Slog.v(
3051                    TAG, "Record #" + i + " " + r + ": app=" + r.app);
3052                if (r.app == app) {
3053                    boolean remove;
3054                    if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
3055                        // Don't currently have state for the activity, or
3056                        // it is finishing -- always remove it.
3057                        remove = true;
3058                    } else if (r.launchCount > 2 &&
3059                            r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
3060                        // We have launched this activity too many times since it was
3061                        // able to run, so give up and remove it.
3062                        remove = true;
3063                    } else {
3064                        // The process may be gone, but the activity lives on!
3065                        remove = false;
3066                    }
3067                    if (remove) {
3068                        if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
3069                            RuntimeException here = new RuntimeException("here");
3070                            here.fillInStackTrace();
3071                            Slog.i(TAG, "Removing activity " + r + " from stack at " + i
3072                                    + ": haveState=" + r.haveState
3073                                    + " stateNotNeeded=" + r.stateNotNeeded
3074                                    + " finishing=" + r.finishing
3075                                    + " state=" + r.state, here);
3076                        }
3077                        if (!r.finishing) {
3078                            Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
3079                            EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3080                                    r.userId, System.identityHashCode(r),
3081                                    r.task.taskId, r.shortComponentName,
3082                                    "proc died without state saved");
3083                            if (r.state == ActivityState.RESUMED) {
3084                                mService.updateUsageStats(r, false);
3085                            }
3086                        }
3087                        removeActivityFromHistoryLocked(r);
3088
3089                    } else {
3090                        // We have the current state for this activity, so
3091                        // it can be restarted later when needed.
3092                        if (localLOGV) Slog.v(
3093                            TAG, "Keeping entry, setting app to null");
3094                        if (r.visible) {
3095                            hasVisibleActivities = true;
3096                        }
3097                        if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
3098                                + r);
3099                        r.app = null;
3100                        r.nowVisible = false;
3101                        if (!r.haveState) {
3102                            if (DEBUG_SAVED_STATE) Slog.i(TAG,
3103                                    "App died, clearing saved state of " + r);
3104                            r.icicle = null;
3105                        }
3106                    }
3107
3108                    cleanUpActivityLocked(r, true, true);
3109                }
3110            }
3111        }
3112
3113        return hasVisibleActivities;
3114    }
3115
3116    final void updateTransitLocked(int transit, Bundle options) {
3117        if (options != null) {
3118            ActivityRecord r = topRunningActivityLocked(null);
3119            if (r != null && r.state != ActivityState.RESUMED) {
3120                r.updateOptionsLocked(options);
3121            } else {
3122                ActivityOptions.abort(options);
3123            }
3124        }
3125        mWindowManager.prepareAppTransition(transit, false);
3126    }
3127
3128    void moveHomeTaskToTop() {
3129        final int top = mTaskHistory.size() - 1;
3130        for (int taskNdx = top; taskNdx >= 0; --taskNdx) {
3131            final TaskRecord task = mTaskHistory.get(taskNdx);
3132            if (task.isHomeTask()) {
3133                if (DEBUG_TASKS || DEBUG_STACK) Slog.d(TAG, "moveHomeTaskToTop: moving " + task);
3134                mTaskHistory.remove(taskNdx);
3135                mTaskHistory.add(top, task);
3136                mWindowManager.moveTaskToTop(task.taskId);
3137                return;
3138            }
3139        }
3140    }
3141
3142    final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
3143        if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3144
3145        final int numTasks = mTaskHistory.size();
3146        final int index = mTaskHistory.indexOf(tr);
3147        if (numTasks == 0 || index < 0)  {
3148            // nothing to do!
3149            if (reason != null &&
3150                    (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3151                ActivityOptions.abort(options);
3152            } else {
3153                updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
3154            }
3155            return;
3156        }
3157
3158        moveToFront();
3159
3160        // Shift all activities with this task up to the top
3161        // of the stack, keeping them in the same internal order.
3162        insertTaskAtTop(tr);
3163
3164        if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr);
3165        if (reason != null &&
3166                (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3167            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
3168            ActivityRecord r = topRunningActivityLocked(null);
3169            if (r != null) {
3170                mNoAnimActivities.add(r);
3171            }
3172            ActivityOptions.abort(options);
3173        } else {
3174            updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
3175        }
3176
3177        mWindowManager.moveTaskToTop(tr.taskId);
3178
3179        mStackSupervisor.resumeTopActivitiesLocked();
3180        EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId);
3181
3182        if (VALIDATE_TOKENS) {
3183            validateAppTokensLocked();
3184        }
3185    }
3186
3187    /**
3188     * Worker method for rearranging history stack. Implements the function of moving all
3189     * activities for a specific task (gathering them if disjoint) into a single group at the
3190     * bottom of the stack.
3191     *
3192     * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3193     * to premeptively cancel the move.
3194     *
3195     * @param taskId The taskId to collect and move to the bottom.
3196     * @return Returns true if the move completed, false if not.
3197     */
3198    final boolean moveTaskToBackLocked(int taskId, ActivityRecord reason) {
3199        final TaskRecord tr = taskForIdLocked(taskId);
3200        if (tr == null) {
3201            Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId);
3202            return false;
3203        }
3204
3205        Slog.i(TAG, "moveTaskToBack: " + tr);
3206
3207        mStackSupervisor.endLockTaskModeIfTaskEnding(tr);
3208
3209        // If we have a watcher, preflight the move before committing to it.  First check
3210        // for *other* available tasks, but if none are available, then try again allowing the
3211        // current task to be selected.
3212        if (mStackSupervisor.isFrontStack(this) && mService.mController != null) {
3213            ActivityRecord next = topRunningActivityLocked(null, taskId);
3214            if (next == null) {
3215                next = topRunningActivityLocked(null, 0);
3216            }
3217            if (next != null) {
3218                // ask watcher if this is allowed
3219                boolean moveOK = true;
3220                try {
3221                    moveOK = mService.mController.activityResuming(next.packageName);
3222                } catch (RemoteException e) {
3223                    mService.mController = null;
3224                    Watchdog.getInstance().setActivityController(null);
3225                }
3226                if (!moveOK) {
3227                    return false;
3228                }
3229            }
3230        }
3231
3232        if (DEBUG_TRANSITION) Slog.v(TAG,
3233                "Prepare to back transition: task=" + taskId);
3234
3235        mTaskHistory.remove(tr);
3236        mTaskHistory.add(0, tr);
3237
3238        // There is an assumption that moving a task to the back moves it behind the home activity.
3239        // We make sure here that some activity in the stack will launch home.
3240        ActivityRecord lastActivity = null;
3241        int numTasks = mTaskHistory.size();
3242        for (int taskNdx = numTasks - 1; taskNdx >= 1; --taskNdx) {
3243            final TaskRecord task = mTaskHistory.get(taskNdx);
3244            if (task.mOnTopOfHome) {
3245                break;
3246            }
3247            if (taskNdx == 1) {
3248                // Set the last task before tr to go to home.
3249                task.mOnTopOfHome = true;
3250            }
3251        }
3252
3253        if (reason != null &&
3254                (reason.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3255            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
3256            ActivityRecord r = topRunningActivityLocked(null);
3257            if (r != null) {
3258                mNoAnimActivities.add(r);
3259            }
3260        } else {
3261            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_TASK_TO_BACK, false);
3262        }
3263        mWindowManager.moveTaskToBottom(taskId);
3264
3265        if (VALIDATE_TOKENS) {
3266            validateAppTokensLocked();
3267        }
3268
3269        final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null;
3270        if (task == tr && tr.mOnTopOfHome || numTasks <= 1 && isOnHomeDisplay()) {
3271            tr.mOnTopOfHome = false;
3272            return mStackSupervisor.resumeHomeActivity(null);
3273        }
3274
3275        mStackSupervisor.resumeTopActivitiesLocked();
3276        return true;
3277    }
3278
3279    static final void logStartActivity(int tag, ActivityRecord r,
3280            TaskRecord task) {
3281        final Uri data = r.intent.getData();
3282        final String strData = data != null ? data.toSafeString() : null;
3283
3284        EventLog.writeEvent(tag,
3285                r.userId, System.identityHashCode(r), task.taskId,
3286                r.shortComponentName, r.intent.getAction(),
3287                r.intent.getType(), strData, r.intent.getFlags());
3288    }
3289
3290    /**
3291     * Make sure the given activity matches the current configuration.  Returns
3292     * false if the activity had to be destroyed.  Returns true if the
3293     * configuration is the same, or the activity will remain running as-is
3294     * for whatever reason.  Ensures the HistoryRecord is updated with the
3295     * correct configuration and all other bookkeeping is handled.
3296     */
3297    final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3298            int globalChanges) {
3299        if (mConfigWillChange) {
3300            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3301                    "Skipping config check (will change): " + r);
3302            return true;
3303        }
3304
3305        if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3306                "Ensuring correct configuration: " + r);
3307
3308        // Short circuit: if the two configurations are the exact same
3309        // object (the common case), then there is nothing to do.
3310        Configuration newConfig = mService.mConfiguration;
3311        if (r.configuration == newConfig && !r.forceNewConfig) {
3312            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3313                    "Configuration unchanged in " + r);
3314            return true;
3315        }
3316
3317        // We don't worry about activities that are finishing.
3318        if (r.finishing) {
3319            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3320                    "Configuration doesn't matter in finishing " + r);
3321            r.stopFreezingScreenLocked(false);
3322            return true;
3323        }
3324
3325        // Okay we now are going to make this activity have the new config.
3326        // But then we need to figure out how it needs to deal with that.
3327        Configuration oldConfig = r.configuration;
3328        r.configuration = newConfig;
3329
3330        // Determine what has changed.  May be nothing, if this is a config
3331        // that has come back from the app after going idle.  In that case
3332        // we just want to leave the official config object now in the
3333        // activity and do nothing else.
3334        final int changes = oldConfig.diff(newConfig);
3335        if (changes == 0 && !r.forceNewConfig) {
3336            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3337                    "Configuration no differences in " + r);
3338            return true;
3339        }
3340
3341        // If the activity isn't currently running, just leave the new
3342        // configuration and it will pick that up next time it starts.
3343        if (r.app == null || r.app.thread == null) {
3344            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3345                    "Configuration doesn't matter not running " + r);
3346            r.stopFreezingScreenLocked(false);
3347            r.forceNewConfig = false;
3348            return true;
3349        }
3350
3351        // Figure out how to handle the changes between the configurations.
3352        if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3353            Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3354                    + Integer.toHexString(changes) + ", handles=0x"
3355                    + Integer.toHexString(r.info.getRealConfigChanged())
3356                    + ", newConfig=" + newConfig);
3357        }
3358        if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
3359            // Aha, the activity isn't handling the change, so DIE DIE DIE.
3360            r.configChangeFlags |= changes;
3361            r.startFreezingScreenLocked(r.app, globalChanges);
3362            r.forceNewConfig = false;
3363            if (r.app == null || r.app.thread == null) {
3364                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3365                        "Config is destroying non-running " + r);
3366                destroyActivityLocked(r, true, false, "config");
3367            } else if (r.state == ActivityState.PAUSING) {
3368                // A little annoying: we are waiting for this activity to
3369                // finish pausing.  Let's not do anything now, but just
3370                // flag that it needs to be restarted when done pausing.
3371                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3372                        "Config is skipping already pausing " + r);
3373                r.configDestroy = true;
3374                return true;
3375            } else if (r.state == ActivityState.RESUMED) {
3376                // Try to optimize this case: the configuration is changing
3377                // and we need to restart the top, resumed activity.
3378                // Instead of doing the normal handshaking, just say
3379                // "restart!".
3380                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3381                        "Config is relaunching resumed " + r);
3382                relaunchActivityLocked(r, r.configChangeFlags, true);
3383                r.configChangeFlags = 0;
3384            } else {
3385                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3386                        "Config is relaunching non-resumed " + r);
3387                relaunchActivityLocked(r, r.configChangeFlags, false);
3388                r.configChangeFlags = 0;
3389            }
3390
3391            // All done...  tell the caller we weren't able to keep this
3392            // activity around.
3393            return false;
3394        }
3395
3396        // Default case: the activity can handle this new configuration, so
3397        // hand it over.  Note that we don't need to give it the new
3398        // configuration, since we always send configuration changes to all
3399        // process when they happen so it can just use whatever configuration
3400        // it last got.
3401        if (r.app != null && r.app.thread != null) {
3402            try {
3403                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
3404                r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
3405            } catch (RemoteException e) {
3406                // If process died, whatever.
3407            }
3408        }
3409        r.stopFreezingScreenLocked(false);
3410
3411        return true;
3412    }
3413
3414    private boolean relaunchActivityLocked(ActivityRecord r,
3415            int changes, boolean andResume) {
3416        List<ResultInfo> results = null;
3417        List<Intent> newIntents = null;
3418        if (andResume) {
3419            results = r.results;
3420            newIntents = r.newIntents;
3421        }
3422        if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
3423                + " with results=" + results + " newIntents=" + newIntents
3424                + " andResume=" + andResume);
3425        EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
3426                : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
3427                r.task.taskId, r.shortComponentName);
3428
3429        r.startFreezingScreenLocked(r.app, 0);
3430
3431        mStackSupervisor.removeChildActivityContainers(r);
3432
3433        try {
3434            if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
3435                    (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
3436                    + r);
3437            r.forceNewConfig = false;
3438            r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
3439                    changes, !andResume, new Configuration(mService.mConfiguration));
3440            // Note: don't need to call pauseIfSleepingLocked() here, because
3441            // the caller will only pass in 'andResume' if this activity is
3442            // currently resumed, which implies we aren't sleeping.
3443        } catch (RemoteException e) {
3444            if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
3445        }
3446
3447        if (andResume) {
3448            r.results = null;
3449            r.newIntents = null;
3450            r.state = ActivityState.RESUMED;
3451        } else {
3452            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3453            r.state = ActivityState.PAUSED;
3454        }
3455
3456        return true;
3457    }
3458
3459    boolean willActivityBeVisibleLocked(IBinder token) {
3460        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3461            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3462            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3463                final ActivityRecord r = activities.get(activityNdx);
3464                if (r.appToken == token) {
3465                    return true;
3466                }
3467                if (r.fullscreen && !r.finishing) {
3468                    return false;
3469                }
3470            }
3471        }
3472        final ActivityRecord r = ActivityRecord.forToken(token);
3473        if (r == null) {
3474            return false;
3475        }
3476        if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false,"
3477                + " would have returned true for r=" + r);
3478        return !r.finishing;
3479    }
3480
3481    void closeSystemDialogsLocked() {
3482        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3483            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3484            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3485                final ActivityRecord r = activities.get(activityNdx);
3486                if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
3487                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true);
3488                }
3489            }
3490        }
3491    }
3492
3493    boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
3494        boolean didSomething = false;
3495        TaskRecord lastTask = null;
3496        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3497            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3498            int numActivities = activities.size();
3499            for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
3500                ActivityRecord r = activities.get(activityNdx);
3501                final boolean samePackage = r.packageName.equals(name)
3502                        || (name == null && r.userId == userId);
3503                if ((userId == UserHandle.USER_ALL || r.userId == userId)
3504                        && (samePackage || r.task == lastTask)
3505                        && (r.app == null || evenPersistent || !r.app.persistent)) {
3506                    if (!doit) {
3507                        if (r.finishing) {
3508                            // If this activity is just finishing, then it is not
3509                            // interesting as far as something to stop.
3510                            continue;
3511                        }
3512                        return true;
3513                    }
3514                    didSomething = true;
3515                    Slog.i(TAG, "  Force finishing activity " + r);
3516                    if (samePackage) {
3517                        if (r.app != null) {
3518                            r.app.removed = true;
3519                        }
3520                        r.app = null;
3521                    }
3522                    lastTask = r.task;
3523                    if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop",
3524                            true)) {
3525                        // r has been deleted from mActivities, accommodate.
3526                        --numActivities;
3527                        --activityNdx;
3528                    }
3529                }
3530            }
3531        }
3532        return didSomething;
3533    }
3534
3535    ActivityRecord getTasksLocked(IThumbnailReceiver receiver,
3536            PendingThumbnailsRecord pending, List<RunningTaskInfo> list) {
3537        ActivityRecord topRecord = null;
3538        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3539            final TaskRecord task = mTaskHistory.get(taskNdx);
3540            ActivityRecord r = null;
3541            ActivityRecord top = null;
3542            int numActivities = 0;
3543            int numRunning = 0;
3544            final ArrayList<ActivityRecord> activities = task.mActivities;
3545            if (activities.isEmpty()) {
3546                continue;
3547            }
3548            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3549                r = activities.get(activityNdx);
3550
3551                // Initialize state for next task if needed.
3552                if (top == null || (top.state == ActivityState.INITIALIZING)) {
3553                    top = r;
3554                    numActivities = numRunning = 0;
3555                }
3556
3557                // Add 'r' into the current task.
3558                numActivities++;
3559                if (r.app != null && r.app.thread != null) {
3560                    numRunning++;
3561                }
3562
3563                if (localLOGV) Slog.v(
3564                    TAG, r.intent.getComponent().flattenToShortString()
3565                    + ": task=" + r.task);
3566            }
3567
3568            RunningTaskInfo ci = new RunningTaskInfo();
3569            ci.id = task.taskId;
3570            ci.baseActivity = r.intent.getComponent();
3571            ci.topActivity = top.intent.getComponent();
3572            ci.lastActiveTime = task.lastActiveTime;
3573
3574            if (top.thumbHolder != null) {
3575                ci.description = top.thumbHolder.lastDescription;
3576            }
3577            ci.numActivities = numActivities;
3578            ci.numRunning = numRunning;
3579            //System.out.println(
3580            //    "#" + maxNum + ": " + " descr=" + ci.description);
3581            if (receiver != null) {
3582                if (localLOGV) Slog.v(
3583                    TAG, "State=" + top.state + "Idle=" + top.idle
3584                    + " app=" + top.app
3585                    + " thr=" + (top.app != null ? top.app.thread : null));
3586                if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
3587                    if (top.idle && top.app != null && top.app.thread != null) {
3588                        topRecord = top;
3589                    } else {
3590                        top.thumbnailNeeded = true;
3591                    }
3592                }
3593                pending.pendingRecords.add(top);
3594            }
3595            list.add(ci);
3596        }
3597        return topRecord;
3598    }
3599
3600    public void unhandledBackLocked() {
3601        final int top = mTaskHistory.size() - 1;
3602        if (DEBUG_SWITCH) Slog.d(
3603            TAG, "Performing unhandledBack(): top activity at " + top);
3604        if (top >= 0) {
3605            final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
3606            int activityTop = activities.size() - 1;
3607            if (activityTop > 0) {
3608                finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
3609                        "unhandled-back", true);
3610            }
3611        }
3612    }
3613
3614    /**
3615     * Reset local parameters because an app's activity died.
3616     * @param app The app of the activity that died.
3617     * @return result from removeHistoryRecordsForAppLocked.
3618     */
3619    boolean handleAppDiedLocked(ProcessRecord app) {
3620        if (mPausingActivity != null && mPausingActivity.app == app) {
3621            if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
3622                    "App died while pausing: " + mPausingActivity);
3623            mPausingActivity = null;
3624        }
3625        if (mLastPausedActivity != null && mLastPausedActivity.app == app) {
3626            mLastPausedActivity = null;
3627            mLastNoHistoryActivity = null;
3628        }
3629
3630        return removeHistoryRecordsForAppLocked(app);
3631    }
3632
3633    void handleAppCrashLocked(ProcessRecord app) {
3634        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3635            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3636            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3637                final ActivityRecord r = activities.get(activityNdx);
3638                if (r.app == app) {
3639                    Slog.w(TAG, "  Force finishing activity "
3640                            + r.intent.getComponent().flattenToShortString());
3641                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
3642                }
3643            }
3644        }
3645    }
3646
3647    boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3648            boolean dumpClient, String dumpPackage, boolean needSep, String header) {
3649        boolean printed = false;
3650        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3651            final TaskRecord task = mTaskHistory.get(taskNdx);
3652            printed |= ActivityStackSupervisor.dumpHistoryList(fd, pw,
3653                    mTaskHistory.get(taskNdx).mActivities, "    ", "Hist", true, !dumpAll,
3654                    dumpClient, dumpPackage, needSep, header,
3655                    "    Task id #" + task.taskId);
3656            if (printed) {
3657                header = null;
3658            }
3659        }
3660        return printed;
3661    }
3662
3663    ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
3664        ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
3665
3666        if ("all".equals(name)) {
3667            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3668                activities.addAll(mTaskHistory.get(taskNdx).mActivities);
3669            }
3670        } else if ("top".equals(name)) {
3671            final int top = mTaskHistory.size() - 1;
3672            if (top >= 0) {
3673                final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities;
3674                int listTop = list.size() - 1;
3675                if (listTop >= 0) {
3676                    activities.add(list.get(listTop));
3677                }
3678            }
3679        } else {
3680            ItemMatcher matcher = new ItemMatcher();
3681            matcher.build(name);
3682
3683            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3684                for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) {
3685                    if (matcher.match(r1, r1.intent.getComponent())) {
3686                        activities.add(r1);
3687                    }
3688                }
3689            }
3690        }
3691
3692        return activities;
3693    }
3694
3695    ActivityRecord restartPackage(String packageName) {
3696        ActivityRecord starting = topRunningActivityLocked(null);
3697
3698        // All activities that came from the package must be
3699        // restarted as if there was a config change.
3700        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3701            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3702            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3703                final ActivityRecord a = activities.get(activityNdx);
3704                if (a.info.packageName.equals(packageName)) {
3705                    a.forceNewConfig = true;
3706                    if (starting != null && a == starting && a.visible) {
3707                        a.startFreezingScreenLocked(starting.app,
3708                                ActivityInfo.CONFIG_SCREEN_LAYOUT);
3709                    }
3710                }
3711            }
3712        }
3713
3714        return starting;
3715    }
3716
3717    void removeTask(TaskRecord task) {
3718        mStackSupervisor.endLockTaskModeIfTaskEnding(task);
3719        mWindowManager.removeTask(task.taskId);
3720        final ActivityRecord r = mResumedActivity;
3721        if (r != null && r.task == task) {
3722            mResumedActivity = null;
3723        }
3724
3725        final int taskNdx = mTaskHistory.indexOf(task);
3726        final int topTaskNdx = mTaskHistory.size() - 1;
3727        if (task.mOnTopOfHome && taskNdx < topTaskNdx) {
3728            mTaskHistory.get(taskNdx + 1).mOnTopOfHome = true;
3729        }
3730        mTaskHistory.remove(task);
3731        if (task.voiceInteractor != null) {
3732            // This task was a voice interaction, so it should not remain on the
3733            // recent tasks list.
3734            mService.mRecentTasks.remove(task);
3735        }
3736
3737        if (mTaskHistory.isEmpty()) {
3738            if (DEBUG_STACK) Slog.i(TAG, "removeTask: moving to back stack=" + this);
3739            if (isOnHomeDisplay()) {
3740                mStackSupervisor.moveHomeStack(!isHomeStack());
3741            }
3742            if (mStacks != null) {
3743                mStacks.remove(this);
3744                mStacks.add(0, this);
3745            }
3746        }
3747    }
3748
3749    TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
3750            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
3751            boolean toTop) {
3752        TaskRecord task = new TaskRecord(taskId, info, intent, voiceSession, voiceInteractor);
3753        addTask(task, toTop);
3754        return task;
3755    }
3756
3757    ArrayList<TaskRecord> getAllTasks() {
3758        return new ArrayList<TaskRecord>(mTaskHistory);
3759    }
3760
3761    void addTask(final TaskRecord task, final boolean toTop) {
3762        task.stack = this;
3763        if (toTop) {
3764            insertTaskAtTop(task);
3765        } else {
3766            mTaskHistory.add(0, task);
3767        }
3768    }
3769
3770    public int getStackId() {
3771        return mStackId;
3772    }
3773
3774    @Override
3775    public String toString() {
3776        return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this))
3777                + " stackId=" + mStackId + ", " + mTaskHistory.size() + " tasks}";
3778    }
3779}
3780