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