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