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