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