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