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