ActivityStack.java revision 9bcc6e83d98dc5608d15f38c12d397be650c637c
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.getTopActivity() == null) {
1886                    // All activities in task are finishing.
1887                    continue;
1888                }
1889                if (task == r.task) {
1890                    // Here it is!  Now, if this is not yet visible to the
1891                    // user, then just add it without starting; it will
1892                    // get started when the user navigates back to it.
1893                    if (!startIt) {
1894                        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
1895                                + task, new RuntimeException("here").fillInStackTrace());
1896                        task.addActivityToTop(r);
1897                        r.putInHistory();
1898                        mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
1899                                r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
1900                                (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0,
1901                                r.userId, r.info.configChanges, task.voiceSession != null,
1902                                r.mLaunchTaskBehind);
1903                        if (VALIDATE_TOKENS) {
1904                            validateAppTokensLocked();
1905                        }
1906                        ActivityOptions.abort(options);
1907                        return;
1908                    }
1909                    break;
1910                } else if (task.numFullscreen > 0) {
1911                    startIt = false;
1912                }
1913            }
1914        }
1915
1916        // Place a new activity at top of stack, so it is next to interact
1917        // with the user.
1918
1919        // If we are not placing the new activity frontmost, we do not want
1920        // to deliver the onUserLeaving callback to the actual frontmost
1921        // activity
1922        if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
1923            mStackSupervisor.mUserLeaving = false;
1924            if (DEBUG_USER_LEAVING) Slog.v(TAG,
1925                    "startActivity() behind front, mUserLeaving=false");
1926        }
1927
1928        task = r.task;
1929
1930        // Slot the activity into the history stack and proceed
1931        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
1932                new RuntimeException("here").fillInStackTrace());
1933        task.addActivityToTop(r);
1934        task.setFrontOfTask();
1935
1936        r.putInHistory();
1937        if (!isHomeStack() || numActivities() > 0) {
1938            // We want to show the starting preview window if we are
1939            // switching to a new task, or the next activity's process is
1940            // not currently running.
1941            boolean showStartingIcon = newTask;
1942            ProcessRecord proc = r.app;
1943            if (proc == null) {
1944                proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1945            }
1946            if (proc == null || proc.thread == null) {
1947                showStartingIcon = true;
1948            }
1949            if (DEBUG_TRANSITION) Slog.v(TAG,
1950                    "Prepare open transition: starting " + r);
1951            if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
1952                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition);
1953                mNoAnimActivities.add(r);
1954            } else {
1955                mWindowManager.prepareAppTransition(newTask
1956                        ? r.mLaunchTaskBehind
1957                                ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
1958                                : AppTransition.TRANSIT_TASK_OPEN
1959                        : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
1960                mNoAnimActivities.remove(r);
1961            }
1962            mWindowManager.addAppToken(task.mActivities.indexOf(r),
1963                    r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
1964                    (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId,
1965                    r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
1966            boolean doShow = true;
1967            if (newTask) {
1968                // Even though this activity is starting fresh, we still need
1969                // to reset it to make sure we apply affinities to move any
1970                // existing activities from other tasks in to it.
1971                // If the caller has requested that the target task be
1972                // reset, then do so.
1973                if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1974                    resetTaskIfNeededLocked(r, r);
1975                    doShow = topRunningNonDelayedActivityLocked(null) == r;
1976                }
1977            } else if (options != null && new ActivityOptions(options).getAnimationType()
1978                    == ActivityOptions.ANIM_SCENE_TRANSITION) {
1979                doShow = false;
1980            }
1981            if (r.mLaunchTaskBehind) {
1982                // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we
1983                // tell WindowManager that r is visible even though it is at the back of the stack.
1984                mWindowManager.setAppVisibility(r.appToken, true);
1985                ensureActivitiesVisibleLocked(null, 0);
1986            } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
1987                // Figure out if we are transitioning from another activity that is
1988                // "has the same starting icon" as the next one.  This allows the
1989                // window manager to keep the previous window it had previously
1990                // created, if it still had one.
1991                ActivityRecord prev = mResumedActivity;
1992                if (prev != null) {
1993                    // We don't want to reuse the previous starting preview if:
1994                    // (1) The current activity is in a different task.
1995                    if (prev.task != r.task) {
1996                        prev = null;
1997                    }
1998                    // (2) The current activity is already displayed.
1999                    else if (prev.nowVisible) {
2000                        prev = null;
2001                    }
2002                }
2003                mWindowManager.setAppStartingWindow(
2004                        r.appToken, r.packageName, r.theme,
2005                        mService.compatibilityInfoForPackageLocked(
2006                                r.info.applicationInfo), r.nonLocalizedLabel,
2007                        r.labelRes, r.icon, r.logo, r.windowFlags,
2008                        prev != null ? prev.appToken : null, showStartingIcon);
2009                r.mStartingWindowShown = true;
2010            }
2011        } else {
2012            // If this is the first activity, don't do any fancy animations,
2013            // because there is nothing for it to animate on top of.
2014            mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
2015                    r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
2016                    (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId,
2017                    r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
2018            ActivityOptions.abort(options);
2019            options = null;
2020        }
2021        if (VALIDATE_TOKENS) {
2022            validateAppTokensLocked();
2023        }
2024
2025        if (doResume) {
2026            mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
2027        }
2028    }
2029
2030    final void validateAppTokensLocked() {
2031        mValidateAppTokens.clear();
2032        mValidateAppTokens.ensureCapacity(numActivities());
2033        final int numTasks = mTaskHistory.size();
2034        for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) {
2035            TaskRecord task = mTaskHistory.get(taskNdx);
2036            final ArrayList<ActivityRecord> activities = task.mActivities;
2037            if (activities.isEmpty()) {
2038                continue;
2039            }
2040            TaskGroup group = new TaskGroup();
2041            group.taskId = task.taskId;
2042            mValidateAppTokens.add(group);
2043            final int numActivities = activities.size();
2044            for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
2045                final ActivityRecord r = activities.get(activityNdx);
2046                group.tokens.add(r.appToken);
2047            }
2048        }
2049        mWindowManager.validateAppTokens(mStackId, mValidateAppTokens);
2050    }
2051
2052    /**
2053     * Perform a reset of the given task, if needed as part of launching it.
2054     * Returns the new HistoryRecord at the top of the task.
2055     */
2056    /**
2057     * Helper method for #resetTaskIfNeededLocked.
2058     * We are inside of the task being reset...  we'll either finish this activity, push it out
2059     * for another task, or leave it as-is.
2060     * @param task The task containing the Activity (taskTop) that might be reset.
2061     * @param forceReset
2062     * @return An ActivityOptions that needs to be processed.
2063     */
2064    final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task, boolean forceReset) {
2065        ActivityOptions topOptions = null;
2066
2067        int replyChainEnd = -1;
2068        boolean canMoveOptions = true;
2069
2070        // We only do this for activities that are not the root of the task (since if we finish
2071        // the root, we may no longer have the task!).
2072        final ArrayList<ActivityRecord> activities = task.mActivities;
2073        final int numActivities = activities.size();
2074        final int rootActivityNdx = task.findEffectiveRootIndex();
2075        for (int i = numActivities - 1; i > rootActivityNdx; --i ) {
2076            ActivityRecord target = activities.get(i);
2077            if (target.frontOfTask)
2078                break;
2079
2080            final int flags = target.info.flags;
2081            final boolean finishOnTaskLaunch =
2082                    (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2083            final boolean allowTaskReparenting =
2084                    (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2085            final boolean clearWhenTaskReset =
2086                    (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2087
2088            if (!finishOnTaskLaunch
2089                    && !clearWhenTaskReset
2090                    && target.resultTo != null) {
2091                // If this activity is sending a reply to a previous
2092                // activity, we can't do anything with it now until
2093                // we reach the start of the reply chain.
2094                // XXX note that we are assuming the result is always
2095                // to the previous activity, which is almost always
2096                // the case but we really shouldn't count on.
2097                if (replyChainEnd < 0) {
2098                    replyChainEnd = i;
2099                }
2100            } else if (!finishOnTaskLaunch
2101                    && !clearWhenTaskReset
2102                    && allowTaskReparenting
2103                    && target.taskAffinity != null
2104                    && !target.taskAffinity.equals(task.affinity)) {
2105                // If this activity has an affinity for another
2106                // task, then we need to move it out of here.  We will
2107                // move it as far out of the way as possible, to the
2108                // bottom of the activity stack.  This also keeps it
2109                // correctly ordered with any activities we previously
2110                // moved.
2111                final TaskRecord targetTask;
2112                final ActivityRecord bottom =
2113                        !mTaskHistory.isEmpty() && !mTaskHistory.get(0).mActivities.isEmpty() ?
2114                                mTaskHistory.get(0).mActivities.get(0) : null;
2115                if (bottom != null && target.taskAffinity != null
2116                        && target.taskAffinity.equals(bottom.task.affinity)) {
2117                    // If the activity currently at the bottom has the
2118                    // same task affinity as the one we are moving,
2119                    // then merge it into the same task.
2120                    targetTask = bottom.task;
2121                    if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2122                            + " out to bottom task " + bottom.task);
2123                } else {
2124                    targetTask = createTaskRecord(mStackSupervisor.getNextTaskId(), target.info,
2125                            null, null, null, false);
2126                    targetTask.affinityIntent = target.intent;
2127                    if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2128                            + " out to new task " + target.task);
2129                }
2130
2131                final int targetTaskId = targetTask.taskId;
2132                mWindowManager.setAppGroupId(target.appToken, targetTaskId);
2133
2134                boolean noOptions = canMoveOptions;
2135                final int start = replyChainEnd < 0 ? i : replyChainEnd;
2136                for (int srcPos = start; srcPos >= i; --srcPos) {
2137                    final ActivityRecord p = activities.get(srcPos);
2138                    if (p.finishing) {
2139                        continue;
2140                    }
2141
2142                    canMoveOptions = false;
2143                    if (noOptions && topOptions == null) {
2144                        topOptions = p.takeOptionsLocked();
2145                        if (topOptions != null) {
2146                            noOptions = false;
2147                        }
2148                    }
2149                    if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task="
2150                            + task + " adding to task=" + targetTask
2151                            + " Callers=" + Debug.getCallers(4));
2152                    if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2153                            + " out to target's task " + target.task);
2154                    p.setTask(targetTask, null);
2155                    targetTask.addActivityAtBottom(p);
2156
2157                    mWindowManager.setAppGroupId(p.appToken, targetTaskId);
2158                }
2159
2160                mWindowManager.moveTaskToBottom(targetTaskId);
2161                if (VALIDATE_TOKENS) {
2162                    validateAppTokensLocked();
2163                }
2164
2165                replyChainEnd = -1;
2166            } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) {
2167                // If the activity should just be removed -- either
2168                // because it asks for it, or the task should be
2169                // cleared -- then finish it and anything that is
2170                // part of its reply chain.
2171                int end;
2172                if (clearWhenTaskReset) {
2173                    // In this case, we want to finish this activity
2174                    // and everything above it, so be sneaky and pretend
2175                    // like these are all in the reply chain.
2176                    end = numActivities - 1;
2177                } else if (replyChainEnd < 0) {
2178                    end = i;
2179                } else {
2180                    end = replyChainEnd;
2181                }
2182                boolean noOptions = canMoveOptions;
2183                for (int srcPos = i; srcPos <= end; srcPos++) {
2184                    ActivityRecord p = activities.get(srcPos);
2185                    if (p.finishing) {
2186                        continue;
2187                    }
2188                    canMoveOptions = false;
2189                    if (noOptions && topOptions == null) {
2190                        topOptions = p.takeOptionsLocked();
2191                        if (topOptions != null) {
2192                            noOptions = false;
2193                        }
2194                    }
2195                    if (DEBUG_TASKS) Slog.w(TAG,
2196                            "resetTaskIntendedTask: calling finishActivity on " + p);
2197                    if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) {
2198                        end--;
2199                        srcPos--;
2200                    }
2201                }
2202                replyChainEnd = -1;
2203            } else {
2204                // If we were in the middle of a chain, well the
2205                // activity that started it all doesn't want anything
2206                // special, so leave it all as-is.
2207                replyChainEnd = -1;
2208            }
2209        }
2210
2211        return topOptions;
2212    }
2213
2214    /**
2215     * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given
2216     * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop.
2217     * @param affinityTask The task we are looking for an affinity to.
2218     * @param task Task that resetTaskIfNeededLocked.taskTop belongs to.
2219     * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked.
2220     * @param forceReset Flag passed in to resetTaskIfNeededLocked.
2221     */
2222    private int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task,
2223            boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) {
2224        int replyChainEnd = -1;
2225        final int taskId = task.taskId;
2226        final String taskAffinity = task.affinity;
2227
2228        final ArrayList<ActivityRecord> activities = affinityTask.mActivities;
2229        final int numActivities = activities.size();
2230        final int rootActivityNdx = affinityTask.findEffectiveRootIndex();
2231
2232        // Do not operate on or below the effective root Activity.
2233        for (int i = numActivities - 1; i > rootActivityNdx; --i) {
2234            ActivityRecord target = activities.get(i);
2235            if (target.frontOfTask)
2236                break;
2237
2238            final int flags = target.info.flags;
2239            boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2240            boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2241
2242            if (target.resultTo != null) {
2243                // If this activity is sending a reply to a previous
2244                // activity, we can't do anything with it now until
2245                // we reach the start of the reply chain.
2246                // XXX note that we are assuming the result is always
2247                // to the previous activity, which is almost always
2248                // the case but we really shouldn't count on.
2249                if (replyChainEnd < 0) {
2250                    replyChainEnd = i;
2251                }
2252            } else if (topTaskIsHigher
2253                    && allowTaskReparenting
2254                    && taskAffinity != null
2255                    && taskAffinity.equals(target.taskAffinity)) {
2256                // This activity has an affinity for our task. Either remove it if we are
2257                // clearing or move it over to our task.  Note that
2258                // we currently punt on the case where we are resetting a
2259                // task that is not at the top but who has activities above
2260                // with an affinity to it...  this is really not a normal
2261                // case, and we will need to later pull that task to the front
2262                // and usually at that point we will do the reset and pick
2263                // up those remaining activities.  (This only happens if
2264                // someone starts an activity in a new task from an activity
2265                // in a task that is not currently on top.)
2266                if (forceReset || finishOnTaskLaunch) {
2267                    final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2268                    if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i);
2269                    for (int srcPos = start; srcPos >= i; --srcPos) {
2270                        final ActivityRecord p = activities.get(srcPos);
2271                        if (p.finishing) {
2272                            continue;
2273                        }
2274                        finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false);
2275                    }
2276                } else {
2277                    if (taskInsertionPoint < 0) {
2278                        taskInsertionPoint = task.mActivities.size();
2279
2280                    }
2281
2282                    final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2283                    if (DEBUG_TASKS) Slog.v(TAG, "Reparenting from task=" + affinityTask + ":"
2284                            + start + "-" + i + " to task=" + task + ":" + taskInsertionPoint);
2285                    for (int srcPos = start; srcPos >= i; --srcPos) {
2286                        final ActivityRecord p = activities.get(srcPos);
2287                        p.setTask(task, null);
2288                        task.addActivityAtIndex(taskInsertionPoint, p);
2289
2290                        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p
2291                                + " to stack at " + task,
2292                                new RuntimeException("here").fillInStackTrace());
2293                        if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos
2294                                + " in to resetting task " + task);
2295                        mWindowManager.setAppGroupId(p.appToken, taskId);
2296                    }
2297                    mWindowManager.moveTaskToTop(taskId);
2298                    if (VALIDATE_TOKENS) {
2299                        validateAppTokensLocked();
2300                    }
2301
2302                    // Now we've moved it in to place...  but what if this is
2303                    // a singleTop activity and we have put it on top of another
2304                    // instance of the same activity?  Then we drop the instance
2305                    // below so it remains singleTop.
2306                    if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2307                        ArrayList<ActivityRecord> taskActivities = task.mActivities;
2308                        int targetNdx = taskActivities.indexOf(target);
2309                        if (targetNdx > 0) {
2310                            ActivityRecord p = taskActivities.get(targetNdx - 1);
2311                            if (p.intent.getComponent().equals(target.intent.getComponent())) {
2312                                finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace",
2313                                        false);
2314                            }
2315                        }
2316                    }
2317                }
2318
2319                replyChainEnd = -1;
2320            }
2321        }
2322        return taskInsertionPoint;
2323    }
2324
2325    final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
2326            ActivityRecord newActivity) {
2327        boolean forceReset =
2328                (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
2329        if (ACTIVITY_INACTIVE_RESET_TIME > 0
2330                && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
2331            if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
2332                forceReset = true;
2333            }
2334        }
2335
2336        final TaskRecord task = taskTop.task;
2337
2338        /** False until we evaluate the TaskRecord associated with taskTop. Switches to true
2339         * for remaining tasks. Used for later tasks to reparent to task. */
2340        boolean taskFound = false;
2341
2342        /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */
2343        ActivityOptions topOptions = null;
2344
2345        // Preserve the location for reparenting in the new task.
2346        int reparentInsertionPoint = -1;
2347
2348        for (int i = mTaskHistory.size() - 1; i >= 0; --i) {
2349            final TaskRecord targetTask = mTaskHistory.get(i);
2350
2351            if (targetTask == task) {
2352                topOptions = resetTargetTaskIfNeededLocked(task, forceReset);
2353                taskFound = true;
2354            } else {
2355                reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task,
2356                        taskFound, forceReset, reparentInsertionPoint);
2357            }
2358        }
2359
2360        int taskNdx = mTaskHistory.indexOf(task);
2361        do {
2362            taskTop = mTaskHistory.get(taskNdx--).getTopActivity();
2363        } while (taskTop == null && taskNdx >= 0);
2364
2365        if (topOptions != null) {
2366            // If we got some ActivityOptions from an activity on top that
2367            // was removed from the task, propagate them to the new real top.
2368            if (taskTop != null) {
2369                taskTop.updateOptionsLocked(topOptions);
2370            } else {
2371                topOptions.abort();
2372            }
2373        }
2374
2375        return taskTop;
2376    }
2377
2378    void sendActivityResultLocked(int callingUid, ActivityRecord r,
2379            String resultWho, int requestCode, int resultCode, Intent data) {
2380
2381        if (callingUid > 0) {
2382            mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
2383                    data, r.getUriPermissionsLocked(), r.userId);
2384        }
2385
2386        if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2387                + " : who=" + resultWho + " req=" + requestCode
2388                + " res=" + resultCode + " data=" + data);
2389        if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2390            try {
2391                ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2392                list.add(new ResultInfo(resultWho, requestCode,
2393                        resultCode, data));
2394                r.app.thread.scheduleSendResult(r.appToken, list);
2395                return;
2396            } catch (Exception e) {
2397                Slog.w(TAG, "Exception thrown sending result to " + r, e);
2398            }
2399        }
2400
2401        r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2402    }
2403
2404    private void adjustFocusedActivityLocked(ActivityRecord r) {
2405        if (mStackSupervisor.isFrontStack(this) && mService.mFocusedActivity == r) {
2406            ActivityRecord next = topRunningActivityLocked(null);
2407            if (next != r) {
2408                final TaskRecord task = r.task;
2409                if (r.frontOfTask && task == topTask() && task.isOverHomeStack()) {
2410                    mStackSupervisor.moveHomeStackTaskToTop(task.getTaskToReturnTo());
2411                }
2412            }
2413            ActivityRecord top = mStackSupervisor.topRunningActivityLocked();
2414            if (top != null) {
2415                mService.setFocusedActivityLocked(top);
2416            }
2417        }
2418    }
2419
2420    final void stopActivityLocked(ActivityRecord r) {
2421        if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2422        if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2423                || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2424            if (!r.finishing) {
2425                if (!mService.isSleeping()) {
2426                    if (DEBUG_STATES) {
2427                        Slog.d(TAG, "no-history finish of " + r);
2428                    }
2429                    requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
2430                            "no-history", false);
2431                } else {
2432                    if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
2433                            + " on stop because we're just sleeping");
2434                }
2435            }
2436        }
2437
2438        if (r.app != null && r.app.thread != null) {
2439            adjustFocusedActivityLocked(r);
2440            r.resumeKeyDispatchingLocked();
2441            try {
2442                r.stopped = false;
2443                if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
2444                        + " (stop requested)");
2445                r.state = ActivityState.STOPPING;
2446                if (DEBUG_VISBILITY) Slog.v(
2447                        TAG, "Stopping visible=" + r.visible + " for " + r);
2448                if (!r.visible) {
2449                    mWindowManager.setAppVisibility(r.appToken, false);
2450                }
2451                r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
2452                if (mService.isSleepingOrShuttingDown()) {
2453                    r.setSleeping(true);
2454                }
2455                Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
2456                mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
2457            } catch (Exception e) {
2458                // Maybe just ignore exceptions here...  if the process
2459                // has crashed, our death notification will clean things
2460                // up.
2461                Slog.w(TAG, "Exception thrown during pause", e);
2462                // Just in case, assume it to be stopped.
2463                r.stopped = true;
2464                if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
2465                r.state = ActivityState.STOPPED;
2466                if (r.configDestroy) {
2467                    destroyActivityLocked(r, true, "stop-except");
2468                }
2469            }
2470        }
2471    }
2472
2473    /**
2474     * @return Returns true if the activity is being finished, false if for
2475     * some reason it is being left as-is.
2476     */
2477    final boolean requestFinishActivityLocked(IBinder token, int resultCode,
2478            Intent resultData, String reason, boolean oomAdj) {
2479        ActivityRecord r = isInStackLocked(token);
2480        if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
2481                TAG, "Finishing activity token=" + token + " r="
2482                + ", result=" + resultCode + ", data=" + resultData
2483                + ", reason=" + reason);
2484        if (r == null) {
2485            return false;
2486        }
2487
2488        finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
2489        return true;
2490    }
2491
2492    final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) {
2493        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2494            ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2495            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2496                ActivityRecord r = activities.get(activityNdx);
2497                if (r.resultTo == self && r.requestCode == requestCode) {
2498                    if ((r.resultWho == null && resultWho == null) ||
2499                        (r.resultWho != null && r.resultWho.equals(resultWho))) {
2500                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
2501                                false);
2502                    }
2503                }
2504            }
2505        }
2506        mService.updateOomAdjLocked();
2507    }
2508
2509    final void finishTopRunningActivityLocked(ProcessRecord app) {
2510        ActivityRecord r = topRunningActivityLocked(null);
2511        if (r != null && r.app == app) {
2512            // If the top running activity is from this crashing
2513            // process, then terminate it to avoid getting in a loop.
2514            Slog.w(TAG, "  Force finishing activity "
2515                    + r.intent.getComponent().flattenToShortString());
2516            int taskNdx = mTaskHistory.indexOf(r.task);
2517            int activityNdx = r.task.mActivities.indexOf(r);
2518            finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
2519            // Also terminate any activities below it that aren't yet
2520            // stopped, to avoid a situation where one will get
2521            // re-start our crashing activity once it gets resumed again.
2522            --activityNdx;
2523            if (activityNdx < 0) {
2524                do {
2525                    --taskNdx;
2526                    if (taskNdx < 0) {
2527                        break;
2528                    }
2529                    activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1;
2530                } while (activityNdx < 0);
2531            }
2532            if (activityNdx >= 0) {
2533                r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx);
2534                if (r.state == ActivityState.RESUMED
2535                        || r.state == ActivityState.PAUSING
2536                        || r.state == ActivityState.PAUSED) {
2537                    if (!r.isHomeActivity() || mService.mHomeProcess != r.app) {
2538                        Slog.w(TAG, "  Force finishing activity "
2539                                + r.intent.getComponent().flattenToShortString());
2540                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
2541                    }
2542                }
2543            }
2544        }
2545    }
2546
2547    final void finishVoiceTask(IVoiceInteractionSession session) {
2548        IBinder sessionBinder = session.asBinder();
2549        boolean didOne = false;
2550        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2551            TaskRecord tr = mTaskHistory.get(taskNdx);
2552            if (tr.voiceSession != null && tr.voiceSession.asBinder() == sessionBinder) {
2553                for (int activityNdx = tr.mActivities.size() - 1; activityNdx >= 0; --activityNdx) {
2554                    ActivityRecord r = tr.mActivities.get(activityNdx);
2555                    if (!r.finishing) {
2556                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "finish-voice",
2557                                false);
2558                        didOne = true;
2559                    }
2560                }
2561            }
2562        }
2563        if (didOne) {
2564            mService.updateOomAdjLocked();
2565        }
2566    }
2567
2568    final boolean finishActivityAffinityLocked(ActivityRecord r) {
2569        ArrayList<ActivityRecord> activities = r.task.mActivities;
2570        for (int index = activities.indexOf(r); index >= 0; --index) {
2571            ActivityRecord cur = activities.get(index);
2572            if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) {
2573                break;
2574            }
2575            finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true);
2576        }
2577        return true;
2578    }
2579
2580    final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
2581        // send the result
2582        ActivityRecord resultTo = r.resultTo;
2583        if (resultTo != null) {
2584            if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
2585                    + " who=" + r.resultWho + " req=" + r.requestCode
2586                    + " res=" + resultCode + " data=" + resultData);
2587            if (resultTo.userId != r.userId) {
2588                if (resultData != null) {
2589                    resultData.setContentUserHint(r.userId);
2590                }
2591            }
2592            if (r.info.applicationInfo.uid > 0) {
2593                mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
2594                        resultTo.packageName, resultData,
2595                        resultTo.getUriPermissionsLocked(), resultTo.userId);
2596            }
2597            resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
2598                                     resultData);
2599            r.resultTo = null;
2600        }
2601        else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
2602
2603        // Make sure this HistoryRecord is not holding on to other resources,
2604        // because clients have remote IPC references to this object so we
2605        // can't assume that will go away and want to avoid circular IPC refs.
2606        r.results = null;
2607        r.pendingResults = null;
2608        r.newIntents = null;
2609        r.icicle = null;
2610    }
2611
2612    /**
2613     * @return Returns true if this activity has been removed from the history
2614     * list, or false if it is still in the list and will be removed later.
2615     */
2616    final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
2617            String reason, boolean oomAdj) {
2618        if (r.finishing) {
2619            Slog.w(TAG, "Duplicate finish request for " + r);
2620            return false;
2621        }
2622
2623        r.makeFinishing();
2624        final TaskRecord task = r.task;
2625        EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2626                r.userId, System.identityHashCode(r),
2627                task.taskId, r.shortComponentName, reason);
2628        final ArrayList<ActivityRecord> activities = task.mActivities;
2629        final int index = activities.indexOf(r);
2630        if (index < (activities.size() - 1)) {
2631            task.setFrontOfTask();
2632            if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
2633                // If the caller asked that this activity (and all above it)
2634                // be cleared when the task is reset, don't lose that information,
2635                // but propagate it up to the next activity.
2636                ActivityRecord next = activities.get(index+1);
2637                next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
2638            }
2639        }
2640
2641        r.pauseKeyDispatchingLocked();
2642
2643        adjustFocusedActivityLocked(r);
2644
2645        finishActivityResultsLocked(r, resultCode, resultData);
2646
2647        if (mResumedActivity == r) {
2648            boolean endTask = index <= 0;
2649            if (DEBUG_VISBILITY || DEBUG_TRANSITION) Slog.v(TAG,
2650                    "Prepare close transition: finishing " + r);
2651            mWindowManager.prepareAppTransition(endTask
2652                    ? AppTransition.TRANSIT_TASK_CLOSE
2653                    : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
2654
2655            // Tell window manager to prepare for this one to be removed.
2656            mWindowManager.setAppVisibility(r.appToken, false);
2657
2658            if (mPausingActivity == null) {
2659                if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
2660                if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
2661                startPausingLocked(false, false);
2662            }
2663
2664            if (endTask) {
2665                mStackSupervisor.endLockTaskModeIfTaskEnding(task);
2666            }
2667        } else if (r.state != ActivityState.PAUSING) {
2668            // If the activity is PAUSING, we will complete the finish once
2669            // it is done pausing; else we can just directly finish it here.
2670            if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
2671            return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null;
2672        } else {
2673            if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
2674        }
2675
2676        return false;
2677    }
2678
2679    static final int FINISH_IMMEDIATELY = 0;
2680    static final int FINISH_AFTER_PAUSE = 1;
2681    static final int FINISH_AFTER_VISIBLE = 2;
2682
2683    final ActivityRecord finishCurrentActivityLocked(ActivityRecord r, int mode, boolean oomAdj) {
2684        // First things first: if this activity is currently visible,
2685        // and the resumed activity is not yet visible, then hold off on
2686        // finishing until the resumed one becomes visible.
2687        if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
2688            if (!mStackSupervisor.mStoppingActivities.contains(r)) {
2689                mStackSupervisor.mStoppingActivities.add(r);
2690                if (mStackSupervisor.mStoppingActivities.size() > 3
2691                        || r.frontOfTask && mTaskHistory.size() <= 1) {
2692                    // If we already have a few activities waiting to stop,
2693                    // then give up on things going idle and start clearing
2694                    // them out. Or if r is the last of activity of the last task the stack
2695                    // will be empty and must be cleared immediately.
2696                    mStackSupervisor.scheduleIdleLocked();
2697                } else {
2698                    mStackSupervisor.checkReadyForSleepLocked();
2699                }
2700            }
2701            if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
2702                    + " (finish requested)");
2703            r.state = ActivityState.STOPPING;
2704            if (oomAdj) {
2705                mService.updateOomAdjLocked();
2706            }
2707            return r;
2708        }
2709
2710        // make sure the record is cleaned out of other places.
2711        mStackSupervisor.mStoppingActivities.remove(r);
2712        mStackSupervisor.mGoingToSleepActivities.remove(r);
2713        mStackSupervisor.mWaitingVisibleActivities.remove(r);
2714        if (mResumedActivity == r) {
2715            mResumedActivity = null;
2716        }
2717        final ActivityState prevState = r.state;
2718        if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
2719        r.state = ActivityState.FINISHING;
2720
2721        if (mode == FINISH_IMMEDIATELY
2722                || prevState == ActivityState.STOPPED
2723                || prevState == ActivityState.INITIALIZING) {
2724            // If this activity is already stopped, we can just finish
2725            // it right now.
2726            r.makeFinishing();
2727            boolean activityRemoved = destroyActivityLocked(r, true, "finish-imm");
2728            if (activityRemoved) {
2729                mStackSupervisor.resumeTopActivitiesLocked();
2730            }
2731            if (DEBUG_CONTAINERS) Slog.d(TAG,
2732                    "destroyActivityLocked: finishCurrentActivityLocked r=" + r +
2733                    " destroy returned removed=" + activityRemoved);
2734            return activityRemoved ? null : r;
2735        }
2736
2737        // Need to go through the full pause cycle to get this
2738        // activity into the stopped state and then finish it.
2739        if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
2740        mStackSupervisor.mFinishingActivities.add(r);
2741        r.resumeKeyDispatchingLocked();
2742        mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null);
2743        return r;
2744    }
2745
2746    void finishAllActivitiesLocked(boolean immediately) {
2747        boolean noActivitiesInStack = true;
2748        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2749            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2750            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2751                final ActivityRecord r = activities.get(activityNdx);
2752                noActivitiesInStack = false;
2753                if (r.finishing && !immediately) {
2754                    continue;
2755                }
2756                Slog.d(TAG, "finishAllActivitiesLocked: finishing " + r + " immediately");
2757                finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
2758            }
2759        }
2760        if (noActivitiesInStack) {
2761            mActivityContainer.onTaskListEmptyLocked();
2762        }
2763    }
2764
2765    final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode,
2766            Intent resultData) {
2767        final ActivityRecord srec = ActivityRecord.forToken(token);
2768        final TaskRecord task = srec.task;
2769        final ArrayList<ActivityRecord> activities = task.mActivities;
2770        final int start = activities.indexOf(srec);
2771        if (!mTaskHistory.contains(task) || (start < 0)) {
2772            return false;
2773        }
2774        int finishTo = start - 1;
2775        ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo);
2776        boolean foundParentInTask = false;
2777        final ComponentName dest = destIntent.getComponent();
2778        if (start > 0 && dest != null) {
2779            for (int i = finishTo; i >= 0; i--) {
2780                ActivityRecord r = activities.get(i);
2781                if (r.info.packageName.equals(dest.getPackageName()) &&
2782                        r.info.name.equals(dest.getClassName())) {
2783                    finishTo = i;
2784                    parent = r;
2785                    foundParentInTask = true;
2786                    break;
2787                }
2788            }
2789        }
2790
2791        IActivityController controller = mService.mController;
2792        if (controller != null) {
2793            ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
2794            if (next != null) {
2795                // ask watcher if this is allowed
2796                boolean resumeOK = true;
2797                try {
2798                    resumeOK = controller.activityResuming(next.packageName);
2799                } catch (RemoteException e) {
2800                    mService.mController = null;
2801                    Watchdog.getInstance().setActivityController(null);
2802                }
2803
2804                if (!resumeOK) {
2805                    return false;
2806                }
2807            }
2808        }
2809        final long origId = Binder.clearCallingIdentity();
2810        for (int i = start; i > finishTo; i--) {
2811            ActivityRecord r = activities.get(i);
2812            requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
2813            // Only return the supplied result for the first activity finished
2814            resultCode = Activity.RESULT_CANCELED;
2815            resultData = null;
2816        }
2817
2818        if (parent != null && foundParentInTask) {
2819            final int parentLaunchMode = parent.info.launchMode;
2820            final int destIntentFlags = destIntent.getFlags();
2821            if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
2822                    parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
2823                    parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
2824                    (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2825                parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
2826            } else {
2827                try {
2828                    ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
2829                            destIntent.getComponent(), 0, srec.userId);
2830                    int res = mStackSupervisor.startActivityLocked(srec.app.thread, destIntent,
2831                            null, aInfo, null, null, parent.appToken, null,
2832                            0, -1, parent.launchedFromUid, parent.launchedFromPackage,
2833                            0, null, true, null, null);
2834                    foundParentInTask = res == ActivityManager.START_SUCCESS;
2835                } catch (RemoteException e) {
2836                    foundParentInTask = false;
2837                }
2838                requestFinishActivityLocked(parent.appToken, resultCode,
2839                        resultData, "navigate-up", true);
2840            }
2841        }
2842        Binder.restoreCallingIdentity(origId);
2843        return foundParentInTask;
2844    }
2845    /**
2846     * Perform the common clean-up of an activity record.  This is called both
2847     * as part of destroyActivityLocked() (when destroying the client-side
2848     * representation) and cleaning things up as a result of its hosting
2849     * processing going away, in which case there is no remaining client-side
2850     * state to destroy so only the cleanup here is needed.
2851     */
2852    final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
2853            boolean setState) {
2854        if (mResumedActivity == r) {
2855            mResumedActivity = null;
2856        }
2857        if (mPausingActivity == r) {
2858            mPausingActivity = null;
2859        }
2860        mService.clearFocusedActivity(r);
2861
2862        r.configDestroy = false;
2863        r.frozenBeforeDestroy = false;
2864
2865        if (setState) {
2866            if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
2867            r.state = ActivityState.DESTROYED;
2868            if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
2869            r.app = null;
2870        }
2871
2872        // Make sure this record is no longer in the pending finishes list.
2873        // This could happen, for example, if we are trimming activities
2874        // down to the max limit while they are still waiting to finish.
2875        mStackSupervisor.mFinishingActivities.remove(r);
2876        mStackSupervisor.mWaitingVisibleActivities.remove(r);
2877
2878        // Remove any pending results.
2879        if (r.finishing && r.pendingResults != null) {
2880            for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
2881                PendingIntentRecord rec = apr.get();
2882                if (rec != null) {
2883                    mService.cancelIntentSenderLocked(rec, false);
2884                }
2885            }
2886            r.pendingResults = null;
2887        }
2888
2889        if (cleanServices) {
2890            cleanUpActivityServicesLocked(r);
2891        }
2892
2893        // Get rid of any pending idle timeouts.
2894        removeTimeoutsForActivityLocked(r);
2895        if (getMediaPlayer() == r) {
2896            mStackSupervisor.setMediaPlayingLocked(r, false);
2897        }
2898    }
2899
2900    private void removeTimeoutsForActivityLocked(ActivityRecord r) {
2901        mStackSupervisor.removeTimeoutsForActivityLocked(r);
2902        mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
2903        mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
2904        mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
2905        r.finishLaunchTickingLocked();
2906    }
2907
2908    private void removeActivityFromHistoryLocked(ActivityRecord r) {
2909        mStackSupervisor.removeChildActivityContainers(r);
2910        finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
2911        r.makeFinishing();
2912        if (DEBUG_ADD_REMOVE) {
2913            RuntimeException here = new RuntimeException("here");
2914            here.fillInStackTrace();
2915            Slog.i(TAG, "Removing activity " + r + " from stack");
2916        }
2917        r.takeFromHistory();
2918        removeTimeoutsForActivityLocked(r);
2919        if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)");
2920        r.state = ActivityState.DESTROYED;
2921        if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
2922        r.app = null;
2923        mWindowManager.removeAppToken(r.appToken);
2924        if (VALIDATE_TOKENS) {
2925            validateAppTokensLocked();
2926        }
2927        final TaskRecord task = r.task;
2928        if (task != null && task.removeActivity(r)) {
2929            if (DEBUG_STACK) Slog.i(TAG,
2930                    "removeActivityFromHistoryLocked: last activity removed from " + this);
2931            if (mStackSupervisor.isFrontStack(this) && task == topTask() &&
2932                    task.isOverHomeStack()) {
2933                mStackSupervisor.moveHomeStackTaskToTop(task.getTaskToReturnTo());
2934            }
2935            removeTask(task);
2936        }
2937        cleanUpActivityServicesLocked(r);
2938        r.removeUriPermissionsLocked();
2939    }
2940
2941    /**
2942     * Perform clean-up of service connections in an activity record.
2943     */
2944    final void cleanUpActivityServicesLocked(ActivityRecord r) {
2945        // Throw away any services that have been bound by this activity.
2946        if (r.connections != null) {
2947            Iterator<ConnectionRecord> it = r.connections.iterator();
2948            while (it.hasNext()) {
2949                ConnectionRecord c = it.next();
2950                mService.mServices.removeConnectionLocked(c, null, r);
2951            }
2952            r.connections = null;
2953        }
2954    }
2955
2956    final void scheduleDestroyActivities(ProcessRecord owner, String reason) {
2957        Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
2958        msg.obj = new ScheduleDestroyArgs(owner, reason);
2959        mHandler.sendMessage(msg);
2960    }
2961
2962    final void destroyActivitiesLocked(ProcessRecord owner, String reason) {
2963        boolean lastIsOpaque = false;
2964        boolean activityRemoved = false;
2965        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2966            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2967            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2968                final ActivityRecord r = activities.get(activityNdx);
2969                if (r.finishing) {
2970                    continue;
2971                }
2972                if (r.fullscreen) {
2973                    lastIsOpaque = true;
2974                }
2975                if (owner != null && r.app != owner) {
2976                    continue;
2977                }
2978                if (!lastIsOpaque) {
2979                    continue;
2980                }
2981                // We can destroy this one if we have its icicle saved and
2982                // it is not in the process of pausing/stopping/finishing.
2983                if (r.app != null && r != mResumedActivity && r != mPausingActivity
2984                        && r.haveState && !r.visible && r.stopped
2985                        && r.state != ActivityState.DESTROYING
2986                        && r.state != ActivityState.DESTROYED) {
2987                    if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
2988                            + " resumed=" + mResumedActivity
2989                            + " pausing=" + mPausingActivity);
2990                    if (destroyActivityLocked(r, true, reason)) {
2991                        activityRemoved = true;
2992                    }
2993                }
2994            }
2995        }
2996        if (activityRemoved) {
2997            mStackSupervisor.resumeTopActivitiesLocked();
2998        }
2999    }
3000
3001    /**
3002     * Destroy the current CLIENT SIDE instance of an activity.  This may be
3003     * called both when actually finishing an activity, or when performing
3004     * a configuration switch where we destroy the current client-side object
3005     * but then create a new client-side object for this same HistoryRecord.
3006     */
3007    final boolean destroyActivityLocked(ActivityRecord r, boolean removeFromApp, String reason) {
3008        if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
3009            TAG, "Removing activity from " + reason + ": token=" + r
3010              + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3011        EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3012                r.userId, System.identityHashCode(r),
3013                r.task.taskId, r.shortComponentName, reason);
3014
3015        boolean removedFromHistory = false;
3016
3017        cleanUpActivityLocked(r, false, false);
3018
3019        final boolean hadApp = r.app != null;
3020
3021        if (hadApp) {
3022            if (removeFromApp) {
3023                r.app.activities.remove(r);
3024                if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3025                    mService.mHeavyWeightProcess = null;
3026                    mService.mHandler.sendEmptyMessage(
3027                            ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3028                }
3029                if (r.app.activities.isEmpty()) {
3030                    // No longer have activities, so update LRU list and oom adj.
3031                    mService.updateLruProcessLocked(r.app, false, null);
3032                    mService.updateOomAdjLocked();
3033                }
3034            }
3035
3036            boolean skipDestroy = false;
3037
3038            try {
3039                if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3040                r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
3041                        r.configChangeFlags);
3042            } catch (Exception e) {
3043                // We can just ignore exceptions here...  if the process
3044                // has crashed, our death notification will clean things
3045                // up.
3046                //Slog.w(TAG, "Exception thrown during finish", e);
3047                if (r.finishing) {
3048                    removeActivityFromHistoryLocked(r);
3049                    removedFromHistory = true;
3050                    skipDestroy = true;
3051                }
3052            }
3053
3054            r.nowVisible = false;
3055
3056            // If the activity is finishing, we need to wait on removing it
3057            // from the list to give it a chance to do its cleanup.  During
3058            // that time it may make calls back with its token so we need to
3059            // be able to find it on the list and so we don't want to remove
3060            // it from the list yet.  Otherwise, we can just immediately put
3061            // it in the destroyed state since we are not removing it from the
3062            // list.
3063            if (r.finishing && !skipDestroy) {
3064                if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3065                        + " (destroy requested)");
3066                r.state = ActivityState.DESTROYING;
3067                Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r);
3068                mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3069            } else {
3070                if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (destroy skipped)");
3071                r.state = ActivityState.DESTROYED;
3072                if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
3073                r.app = null;
3074            }
3075        } else {
3076            // remove this record from the history.
3077            if (r.finishing) {
3078                removeActivityFromHistoryLocked(r);
3079                removedFromHistory = true;
3080            } else {
3081                if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (no app)");
3082                r.state = ActivityState.DESTROYED;
3083                if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
3084                r.app = null;
3085            }
3086        }
3087
3088        r.configChangeFlags = 0;
3089
3090        if (!mLRUActivities.remove(r) && hadApp) {
3091            Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3092        }
3093
3094        return removedFromHistory;
3095    }
3096
3097    final void activityDestroyedLocked(IBinder token) {
3098        final long origId = Binder.clearCallingIdentity();
3099        try {
3100            ActivityRecord r = ActivityRecord.forToken(token);
3101            if (r != null) {
3102                mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3103            }
3104            if (DEBUG_CONTAINERS) Slog.d(TAG, "activityDestroyedLocked: r=" + r);
3105
3106            if (isInStackLocked(token) != null) {
3107                if (r.state == ActivityState.DESTROYING) {
3108                    cleanUpActivityLocked(r, true, false);
3109                    removeActivityFromHistoryLocked(r);
3110                }
3111            }
3112            mStackSupervisor.resumeTopActivitiesLocked();
3113        } finally {
3114            Binder.restoreCallingIdentity(origId);
3115        }
3116    }
3117
3118    void releaseMediaResources() {
3119        if (isMediaPlaying() && !mHandler.hasMessages(STOP_MEDIA_PLAYING_TIMEOUT_MSG)) {
3120            final ActivityRecord r = getMediaPlayer();
3121            if (DEBUG_STATES) Slog.d(TAG, "releaseMediaResources activtyDisplay=" +
3122                    mActivityContainer.mActivityDisplay + " mediaPlayer=" + r + " app=" + r.app +
3123                    " thread=" + r.app.thread);
3124            if (r != null && r.app != null && r.app.thread != null) {
3125                try {
3126                    r.app.thread.scheduleStopMediaPlaying(r.appToken);
3127                } catch (RemoteException e) {
3128                }
3129                mHandler.sendEmptyMessageDelayed(STOP_MEDIA_PLAYING_TIMEOUT_MSG, 500);
3130            } else {
3131                Slog.e(TAG, "releaseMediaResources: activity " + r + " no longer running");
3132                mediaResourcesReleased(r.appToken);
3133            }
3134        }
3135    }
3136
3137    final void mediaResourcesReleased(IBinder token) {
3138        mHandler.removeMessages(STOP_MEDIA_PLAYING_TIMEOUT_MSG);
3139        final ActivityRecord r = getMediaPlayer();
3140        if (r != null) {
3141            mStackSupervisor.mStoppingActivities.add(r);
3142            setMediaPlayer(null);
3143        }
3144        mStackSupervisor.resumeTopActivitiesLocked();
3145    }
3146
3147    boolean isMediaPlaying() {
3148        return isAttached() && mActivityContainer.mActivityDisplay.isMediaPlaying();
3149    }
3150
3151    void setMediaPlayer(ActivityRecord r) {
3152        if (isAttached()) {
3153            mActivityContainer.mActivityDisplay.setMediaPlaying(r);
3154        }
3155    }
3156
3157    ActivityRecord getMediaPlayer() {
3158        return isAttached() ? mActivityContainer.mActivityDisplay.mMediaPlayingActivity : null;
3159    }
3160
3161    private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
3162            ProcessRecord app, String listName) {
3163        int i = list.size();
3164        if (DEBUG_CLEANUP) Slog.v(
3165            TAG, "Removing app " + app + " from list " + listName
3166            + " with " + i + " entries");
3167        while (i > 0) {
3168            i--;
3169            ActivityRecord r = list.get(i);
3170            if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
3171            if (r.app == app) {
3172                if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
3173                list.remove(i);
3174                removeTimeoutsForActivityLocked(r);
3175            }
3176        }
3177    }
3178
3179    boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
3180        removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
3181        removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app,
3182                "mStoppingActivities");
3183        removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app,
3184                "mGoingToSleepActivities");
3185        removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app,
3186                "mWaitingVisibleActivities");
3187        removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app,
3188                "mFinishingActivities");
3189
3190        boolean hasVisibleActivities = false;
3191
3192        // Clean out the history list.
3193        int i = numActivities();
3194        if (DEBUG_CLEANUP) Slog.v(
3195            TAG, "Removing app " + app + " from history with " + i + " entries");
3196        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3197            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3198            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3199                final ActivityRecord r = activities.get(activityNdx);
3200                --i;
3201                if (DEBUG_CLEANUP) Slog.v(
3202                    TAG, "Record #" + i + " " + r + ": app=" + r.app);
3203                if (r.app == app) {
3204                    boolean remove;
3205                    if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
3206                        // Don't currently have state for the activity, or
3207                        // it is finishing -- always remove it.
3208                        remove = true;
3209                    } else if (r.launchCount > 2 &&
3210                            r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
3211                        // We have launched this activity too many times since it was
3212                        // able to run, so give up and remove it.
3213                        remove = true;
3214                    } else {
3215                        // The process may be gone, but the activity lives on!
3216                        remove = false;
3217                    }
3218                    if (remove) {
3219                        if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
3220                            RuntimeException here = new RuntimeException("here");
3221                            here.fillInStackTrace();
3222                            Slog.i(TAG, "Removing activity " + r + " from stack at " + i
3223                                    + ": haveState=" + r.haveState
3224                                    + " stateNotNeeded=" + r.stateNotNeeded
3225                                    + " finishing=" + r.finishing
3226                                    + " state=" + r.state, here);
3227                        }
3228                        if (!r.finishing) {
3229                            Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
3230                            EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3231                                    r.userId, System.identityHashCode(r),
3232                                    r.task.taskId, r.shortComponentName,
3233                                    "proc died without state saved");
3234                            if (r.state == ActivityState.RESUMED) {
3235                                mService.updateUsageStats(r, false);
3236                            }
3237                        }
3238                        removeActivityFromHistoryLocked(r);
3239
3240                    } else {
3241                        // We have the current state for this activity, so
3242                        // it can be restarted later when needed.
3243                        if (localLOGV) Slog.v(
3244                            TAG, "Keeping entry, setting app to null");
3245                        if (r.visible) {
3246                            hasVisibleActivities = true;
3247                        }
3248                        if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
3249                                + r);
3250                        r.app = null;
3251                        r.nowVisible = false;
3252                        if (!r.haveState) {
3253                            if (DEBUG_SAVED_STATE) Slog.i(TAG,
3254                                    "App died, clearing saved state of " + r);
3255                            r.icicle = null;
3256                        }
3257                    }
3258
3259                    cleanUpActivityLocked(r, true, true);
3260                }
3261            }
3262        }
3263
3264        return hasVisibleActivities;
3265    }
3266
3267    final void updateTransitLocked(int transit, Bundle options) {
3268        if (options != null) {
3269            ActivityRecord r = topRunningActivityLocked(null);
3270            if (r != null && r.state != ActivityState.RESUMED) {
3271                r.updateOptionsLocked(options);
3272            } else {
3273                ActivityOptions.abort(options);
3274            }
3275        }
3276        mWindowManager.prepareAppTransition(transit, false);
3277    }
3278
3279    void updateTaskMovement(TaskRecord task, boolean toFront) {
3280        if (task.isPersistable) {
3281            task.mLastTimeMoved = System.currentTimeMillis();
3282            // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most
3283            // recently will be most negative, tasks sent to the bottom before that will be less
3284            // negative. Similarly for recent tasks moved to the top which will be most positive.
3285            if (!toFront) {
3286                task.mLastTimeMoved *= -1;
3287            }
3288        }
3289    }
3290
3291    void moveHomeStackTaskToTop(int homeStackTaskType) {
3292        final int top = mTaskHistory.size() - 1;
3293        for (int taskNdx = top; taskNdx >= 0; --taskNdx) {
3294            final TaskRecord task = mTaskHistory.get(taskNdx);
3295            if (task.taskType == homeStackTaskType) {
3296                if (DEBUG_TASKS || DEBUG_STACK)
3297                    Slog.d(TAG, "moveHomeStackTaskToTop: moving " + task);
3298                mTaskHistory.remove(taskNdx);
3299                mTaskHistory.add(top, task);
3300                updateTaskMovement(task, true);
3301                mWindowManager.moveTaskToTop(task.taskId);
3302                return;
3303            }
3304        }
3305    }
3306
3307    final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
3308        if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3309
3310        final int numTasks = mTaskHistory.size();
3311        final int index = mTaskHistory.indexOf(tr);
3312        if (numTasks == 0 || index < 0)  {
3313            // nothing to do!
3314            if (reason != null &&
3315                    (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3316                ActivityOptions.abort(options);
3317            } else {
3318                updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
3319            }
3320            return;
3321        }
3322
3323        moveToFront();
3324
3325        // Shift all activities with this task up to the top
3326        // of the stack, keeping them in the same internal order.
3327        insertTaskAtTop(tr);
3328
3329        if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr);
3330        if (reason != null &&
3331                (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3332            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
3333            ActivityRecord r = topRunningActivityLocked(null);
3334            if (r != null) {
3335                mNoAnimActivities.add(r);
3336            }
3337            ActivityOptions.abort(options);
3338        } else {
3339            updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
3340        }
3341
3342        mWindowManager.moveTaskToTop(tr.taskId);
3343
3344        mStackSupervisor.resumeTopActivitiesLocked();
3345        EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId);
3346
3347        if (VALIDATE_TOKENS) {
3348            validateAppTokensLocked();
3349        }
3350    }
3351
3352    /**
3353     * Worker method for rearranging history stack. Implements the function of moving all
3354     * activities for a specific task (gathering them if disjoint) into a single group at the
3355     * bottom of the stack.
3356     *
3357     * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3358     * to premeptively cancel the move.
3359     *
3360     * @param taskId The taskId to collect and move to the bottom.
3361     * @return Returns true if the move completed, false if not.
3362     */
3363    final boolean moveTaskToBackLocked(int taskId, ActivityRecord reason) {
3364        final TaskRecord tr = taskForIdLocked(taskId);
3365        if (tr == null) {
3366            Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId);
3367            return false;
3368        }
3369
3370        Slog.i(TAG, "moveTaskToBack: " + tr);
3371
3372        mStackSupervisor.endLockTaskModeIfTaskEnding(tr);
3373
3374        // If we have a watcher, preflight the move before committing to it.  First check
3375        // for *other* available tasks, but if none are available, then try again allowing the
3376        // current task to be selected.
3377        if (mStackSupervisor.isFrontStack(this) && mService.mController != null) {
3378            ActivityRecord next = topRunningActivityLocked(null, taskId);
3379            if (next == null) {
3380                next = topRunningActivityLocked(null, 0);
3381            }
3382            if (next != null) {
3383                // ask watcher if this is allowed
3384                boolean moveOK = true;
3385                try {
3386                    moveOK = mService.mController.activityResuming(next.packageName);
3387                } catch (RemoteException e) {
3388                    mService.mController = null;
3389                    Watchdog.getInstance().setActivityController(null);
3390                }
3391                if (!moveOK) {
3392                    return false;
3393                }
3394            }
3395        }
3396
3397        if (DEBUG_TRANSITION) Slog.v(TAG,
3398                "Prepare to back transition: task=" + taskId);
3399
3400        mTaskHistory.remove(tr);
3401        mTaskHistory.add(0, tr);
3402        updateTaskMovement(tr, false);
3403
3404        // There is an assumption that moving a task to the back moves it behind the home activity.
3405        // We make sure here that some activity in the stack will launch home.
3406        int numTasks = mTaskHistory.size();
3407        for (int taskNdx = numTasks - 1; taskNdx >= 1; --taskNdx) {
3408            final TaskRecord task = mTaskHistory.get(taskNdx);
3409            if (task.isOverHomeStack()) {
3410                break;
3411            }
3412            if (taskNdx == 1) {
3413                // Set the last task before tr to go to home.
3414                task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
3415            }
3416        }
3417
3418        if (reason != null &&
3419                (reason.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3420            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
3421            ActivityRecord r = topRunningActivityLocked(null);
3422            if (r != null) {
3423                mNoAnimActivities.add(r);
3424            }
3425        } else {
3426            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_TASK_TO_BACK, false);
3427        }
3428        mWindowManager.moveTaskToBottom(taskId);
3429
3430        if (VALIDATE_TOKENS) {
3431            validateAppTokensLocked();
3432        }
3433
3434        final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null;
3435        if (task == tr && tr.isOverHomeStack() || numTasks <= 1 && isOnHomeDisplay()) {
3436            final int taskToReturnTo = tr.getTaskToReturnTo();
3437            tr.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
3438            return mStackSupervisor.resumeHomeStackTask(taskToReturnTo, null);
3439        }
3440
3441        mStackSupervisor.resumeTopActivitiesLocked();
3442        return true;
3443    }
3444
3445    static final void logStartActivity(int tag, ActivityRecord r,
3446            TaskRecord task) {
3447        final Uri data = r.intent.getData();
3448        final String strData = data != null ? data.toSafeString() : null;
3449
3450        EventLog.writeEvent(tag,
3451                r.userId, System.identityHashCode(r), task.taskId,
3452                r.shortComponentName, r.intent.getAction(),
3453                r.intent.getType(), strData, r.intent.getFlags());
3454    }
3455
3456    /**
3457     * Make sure the given activity matches the current configuration.  Returns
3458     * false if the activity had to be destroyed.  Returns true if the
3459     * configuration is the same, or the activity will remain running as-is
3460     * for whatever reason.  Ensures the HistoryRecord is updated with the
3461     * correct configuration and all other bookkeeping is handled.
3462     */
3463    final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3464            int globalChanges) {
3465        if (mConfigWillChange) {
3466            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3467                    "Skipping config check (will change): " + r);
3468            return true;
3469        }
3470
3471        if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3472                "Ensuring correct configuration: " + r);
3473
3474        // Short circuit: if the two configurations are the exact same
3475        // object (the common case), then there is nothing to do.
3476        Configuration newConfig = mService.mConfiguration;
3477        if (r.configuration == newConfig && !r.forceNewConfig) {
3478            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3479                    "Configuration unchanged in " + r);
3480            return true;
3481        }
3482
3483        // We don't worry about activities that are finishing.
3484        if (r.finishing) {
3485            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3486                    "Configuration doesn't matter in finishing " + r);
3487            r.stopFreezingScreenLocked(false);
3488            return true;
3489        }
3490
3491        // Okay we now are going to make this activity have the new config.
3492        // But then we need to figure out how it needs to deal with that.
3493        Configuration oldConfig = r.configuration;
3494        r.configuration = newConfig;
3495
3496        // Determine what has changed.  May be nothing, if this is a config
3497        // that has come back from the app after going idle.  In that case
3498        // we just want to leave the official config object now in the
3499        // activity and do nothing else.
3500        final int changes = oldConfig.diff(newConfig);
3501        if (changes == 0 && !r.forceNewConfig) {
3502            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3503                    "Configuration no differences in " + r);
3504            return true;
3505        }
3506
3507        // If the activity isn't currently running, just leave the new
3508        // configuration and it will pick that up next time it starts.
3509        if (r.app == null || r.app.thread == null) {
3510            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3511                    "Configuration doesn't matter not running " + r);
3512            r.stopFreezingScreenLocked(false);
3513            r.forceNewConfig = false;
3514            return true;
3515        }
3516
3517        // Figure out how to handle the changes between the configurations.
3518        if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3519            Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3520                    + Integer.toHexString(changes) + ", handles=0x"
3521                    + Integer.toHexString(r.info.getRealConfigChanged())
3522                    + ", newConfig=" + newConfig);
3523        }
3524        if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
3525            // Aha, the activity isn't handling the change, so DIE DIE DIE.
3526            r.configChangeFlags |= changes;
3527            r.startFreezingScreenLocked(r.app, globalChanges);
3528            r.forceNewConfig = false;
3529            if (r.app == null || r.app.thread == null) {
3530                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3531                        "Config is destroying non-running " + r);
3532                destroyActivityLocked(r, true, "config");
3533            } else if (r.state == ActivityState.PAUSING) {
3534                // A little annoying: we are waiting for this activity to
3535                // finish pausing.  Let's not do anything now, but just
3536                // flag that it needs to be restarted when done pausing.
3537                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3538                        "Config is skipping already pausing " + r);
3539                r.configDestroy = true;
3540                return true;
3541            } else if (r.state == ActivityState.RESUMED) {
3542                // Try to optimize this case: the configuration is changing
3543                // and we need to restart the top, resumed activity.
3544                // Instead of doing the normal handshaking, just say
3545                // "restart!".
3546                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3547                        "Config is relaunching resumed " + r);
3548                relaunchActivityLocked(r, r.configChangeFlags, true);
3549                r.configChangeFlags = 0;
3550            } else {
3551                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3552                        "Config is relaunching non-resumed " + r);
3553                relaunchActivityLocked(r, r.configChangeFlags, false);
3554                r.configChangeFlags = 0;
3555            }
3556
3557            // All done...  tell the caller we weren't able to keep this
3558            // activity around.
3559            return false;
3560        }
3561
3562        // Default case: the activity can handle this new configuration, so
3563        // hand it over.  Note that we don't need to give it the new
3564        // configuration, since we always send configuration changes to all
3565        // process when they happen so it can just use whatever configuration
3566        // it last got.
3567        if (r.app != null && r.app.thread != null) {
3568            try {
3569                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
3570                r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
3571            } catch (RemoteException e) {
3572                // If process died, whatever.
3573            }
3574        }
3575        r.stopFreezingScreenLocked(false);
3576
3577        return true;
3578    }
3579
3580    private boolean relaunchActivityLocked(ActivityRecord r,
3581            int changes, boolean andResume) {
3582        List<ResultInfo> results = null;
3583        List<Intent> newIntents = null;
3584        if (andResume) {
3585            results = r.results;
3586            newIntents = r.newIntents;
3587        }
3588        if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
3589                + " with results=" + results + " newIntents=" + newIntents
3590                + " andResume=" + andResume);
3591        EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
3592                : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
3593                r.task.taskId, r.shortComponentName);
3594
3595        r.startFreezingScreenLocked(r.app, 0);
3596
3597        mStackSupervisor.removeChildActivityContainers(r);
3598
3599        try {
3600            if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
3601                    (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
3602                    + r);
3603            r.forceNewConfig = false;
3604            r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
3605                    changes, !andResume, new Configuration(mService.mConfiguration));
3606            // Note: don't need to call pauseIfSleepingLocked() here, because
3607            // the caller will only pass in 'andResume' if this activity is
3608            // currently resumed, which implies we aren't sleeping.
3609        } catch (RemoteException e) {
3610            if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
3611        }
3612
3613        if (andResume) {
3614            r.results = null;
3615            r.newIntents = null;
3616            r.state = ActivityState.RESUMED;
3617        } else {
3618            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3619            r.state = ActivityState.PAUSED;
3620        }
3621
3622        return true;
3623    }
3624
3625    boolean willActivityBeVisibleLocked(IBinder token) {
3626        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3627            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3628            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3629                final ActivityRecord r = activities.get(activityNdx);
3630                if (r.appToken == token) {
3631                    return true;
3632                }
3633                if (r.fullscreen && !r.finishing) {
3634                    return false;
3635                }
3636            }
3637        }
3638        final ActivityRecord r = ActivityRecord.forToken(token);
3639        if (r == null) {
3640            return false;
3641        }
3642        if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false,"
3643                + " would have returned true for r=" + r);
3644        return !r.finishing;
3645    }
3646
3647    void closeSystemDialogsLocked() {
3648        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3649            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3650            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3651                final ActivityRecord r = activities.get(activityNdx);
3652                if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
3653                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true);
3654                }
3655            }
3656        }
3657    }
3658
3659    boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
3660        boolean didSomething = false;
3661        TaskRecord lastTask = null;
3662        ComponentName homeActivity = null;
3663        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3664            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3665            int numActivities = activities.size();
3666            for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
3667                ActivityRecord r = activities.get(activityNdx);
3668                final boolean samePackage = r.packageName.equals(name)
3669                        || (name == null && r.userId == userId);
3670                if ((userId == UserHandle.USER_ALL || r.userId == userId)
3671                        && (samePackage || r.task == lastTask)
3672                        && (r.app == null || evenPersistent || !r.app.persistent)) {
3673                    if (!doit) {
3674                        if (r.finishing) {
3675                            // If this activity is just finishing, then it is not
3676                            // interesting as far as something to stop.
3677                            continue;
3678                        }
3679                        return true;
3680                    }
3681                    if (r.isHomeActivity()) {
3682                        if (homeActivity != null && homeActivity.equals(r.realActivity)) {
3683                            Slog.i(TAG, "Skip force-stop again " + r);
3684                            continue;
3685                        } else {
3686                            homeActivity = r.realActivity;
3687                        }
3688                    }
3689                    didSomething = true;
3690                    Slog.i(TAG, "  Force finishing activity " + r);
3691                    if (samePackage) {
3692                        if (r.app != null) {
3693                            r.app.removed = true;
3694                        }
3695                        r.app = null;
3696                    }
3697                    lastTask = r.task;
3698                    if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop",
3699                            true)) {
3700                        // r has been deleted from mActivities, accommodate.
3701                        --numActivities;
3702                        --activityNdx;
3703                    }
3704                }
3705            }
3706        }
3707        return didSomething;
3708    }
3709
3710    void getTasksLocked(List<RunningTaskInfo> list, int callingUid, boolean allowed) {
3711        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3712            final TaskRecord task = mTaskHistory.get(taskNdx);
3713            ActivityRecord r = null;
3714            ActivityRecord top = null;
3715            int numActivities = 0;
3716            int numRunning = 0;
3717            final ArrayList<ActivityRecord> activities = task.mActivities;
3718            if (activities.isEmpty()) {
3719                continue;
3720            }
3721            if (!allowed && !task.isHomeTask() && task.creatorUid != callingUid) {
3722                continue;
3723            }
3724            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3725                r = activities.get(activityNdx);
3726
3727                // Initialize state for next task if needed.
3728                if (top == null || (top.state == ActivityState.INITIALIZING)) {
3729                    top = r;
3730                    numActivities = numRunning = 0;
3731                }
3732
3733                // Add 'r' into the current task.
3734                numActivities++;
3735                if (r.app != null && r.app.thread != null) {
3736                    numRunning++;
3737                }
3738
3739                if (localLOGV) Slog.v(
3740                    TAG, r.intent.getComponent().flattenToShortString()
3741                    + ": task=" + r.task);
3742            }
3743
3744            RunningTaskInfo ci = new RunningTaskInfo();
3745            ci.id = task.taskId;
3746            ci.baseActivity = r.intent.getComponent();
3747            ci.topActivity = top.intent.getComponent();
3748            ci.lastActiveTime = task.lastActiveTime;
3749
3750            if (top.task != null) {
3751                ci.description = top.task.lastDescription;
3752            }
3753            ci.numActivities = numActivities;
3754            ci.numRunning = numRunning;
3755            //System.out.println(
3756            //    "#" + maxNum + ": " + " descr=" + ci.description);
3757            list.add(ci);
3758        }
3759    }
3760
3761    public void unhandledBackLocked() {
3762        final int top = mTaskHistory.size() - 1;
3763        if (DEBUG_SWITCH) Slog.d(
3764            TAG, "Performing unhandledBack(): top activity at " + top);
3765        if (top >= 0) {
3766            final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
3767            int activityTop = activities.size() - 1;
3768            if (activityTop > 0) {
3769                finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
3770                        "unhandled-back", true);
3771            }
3772        }
3773    }
3774
3775    /**
3776     * Reset local parameters because an app's activity died.
3777     * @param app The app of the activity that died.
3778     * @return result from removeHistoryRecordsForAppLocked.
3779     */
3780    boolean handleAppDiedLocked(ProcessRecord app) {
3781        if (mPausingActivity != null && mPausingActivity.app == app) {
3782            if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
3783                    "App died while pausing: " + mPausingActivity);
3784            mPausingActivity = null;
3785        }
3786        if (mLastPausedActivity != null && mLastPausedActivity.app == app) {
3787            mLastPausedActivity = null;
3788            mLastNoHistoryActivity = null;
3789        }
3790
3791        return removeHistoryRecordsForAppLocked(app);
3792    }
3793
3794    void handleAppCrashLocked(ProcessRecord app) {
3795        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3796            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3797            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3798                final ActivityRecord r = activities.get(activityNdx);
3799                if (r.app == app) {
3800                    Slog.w(TAG, "  Force finishing activity "
3801                            + r.intent.getComponent().flattenToShortString());
3802                    // Force the destroy to skip right to removal.
3803                    r.app = null;
3804                    finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
3805                }
3806            }
3807        }
3808    }
3809
3810    boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
3811            boolean dumpClient, String dumpPackage, boolean needSep, String header) {
3812        boolean printed = false;
3813        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3814            final TaskRecord task = mTaskHistory.get(taskNdx);
3815            printed |= ActivityStackSupervisor.dumpHistoryList(fd, pw,
3816                    mTaskHistory.get(taskNdx).mActivities, "    ", "Hist", true, !dumpAll,
3817                    dumpClient, dumpPackage, needSep, header,
3818                    "    Task id #" + task.taskId);
3819            if (printed) {
3820                header = null;
3821            }
3822        }
3823        return printed;
3824    }
3825
3826    ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
3827        ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
3828
3829        if ("all".equals(name)) {
3830            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3831                activities.addAll(mTaskHistory.get(taskNdx).mActivities);
3832            }
3833        } else if ("top".equals(name)) {
3834            final int top = mTaskHistory.size() - 1;
3835            if (top >= 0) {
3836                final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities;
3837                int listTop = list.size() - 1;
3838                if (listTop >= 0) {
3839                    activities.add(list.get(listTop));
3840                }
3841            }
3842        } else {
3843            ItemMatcher matcher = new ItemMatcher();
3844            matcher.build(name);
3845
3846            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3847                for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) {
3848                    if (matcher.match(r1, r1.intent.getComponent())) {
3849                        activities.add(r1);
3850                    }
3851                }
3852            }
3853        }
3854
3855        return activities;
3856    }
3857
3858    ActivityRecord restartPackage(String packageName) {
3859        ActivityRecord starting = topRunningActivityLocked(null);
3860
3861        // All activities that came from the package must be
3862        // restarted as if there was a config change.
3863        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3864            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3865            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3866                final ActivityRecord a = activities.get(activityNdx);
3867                if (a.info.packageName.equals(packageName)) {
3868                    a.forceNewConfig = true;
3869                    if (starting != null && a == starting && a.visible) {
3870                        a.startFreezingScreenLocked(starting.app,
3871                                ActivityInfo.CONFIG_SCREEN_LAYOUT);
3872                    }
3873                }
3874            }
3875        }
3876
3877        return starting;
3878    }
3879
3880    void removeTask(TaskRecord task) {
3881        mStackSupervisor.endLockTaskModeIfTaskEnding(task);
3882        mWindowManager.removeTask(task.taskId);
3883        final ActivityRecord r = mResumedActivity;
3884        if (r != null && r.task == task) {
3885            mResumedActivity = null;
3886        }
3887
3888        final int taskNdx = mTaskHistory.indexOf(task);
3889        final int topTaskNdx = mTaskHistory.size() - 1;
3890        if (task.isOverHomeStack() && taskNdx < topTaskNdx) {
3891            final TaskRecord nextTask = mTaskHistory.get(taskNdx + 1);
3892            if (!nextTask.isOverHomeStack()) {
3893                nextTask.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
3894            }
3895        }
3896        mTaskHistory.remove(task);
3897        updateTaskMovement(task, true);
3898
3899        if (task.mActivities.isEmpty()) {
3900            final boolean isVoiceSession = task.voiceSession != null;
3901            if (isVoiceSession) {
3902                try {
3903                    task.voiceSession.taskFinished(task.intent, task.taskId);
3904                } catch (RemoteException e) {
3905                }
3906            }
3907            if (task.autoRemoveFromRecents() || isVoiceSession) {
3908                // Task creator asked to remove this when done, or this task was a voice
3909                // interaction, so it should not remain on the recent tasks list.
3910                mService.mRecentTasks.remove(task);
3911                task.closeRecentsChain();
3912            }
3913        }
3914
3915        if (mTaskHistory.isEmpty()) {
3916            if (DEBUG_STACK) Slog.i(TAG, "removeTask: moving to back stack=" + this);
3917            if (isOnHomeDisplay()) {
3918                mStackSupervisor.moveHomeStack(!isHomeStack());
3919            }
3920            if (mStacks != null) {
3921                mStacks.remove(this);
3922                mStacks.add(0, this);
3923            }
3924            mActivityContainer.onTaskListEmptyLocked();
3925        }
3926    }
3927
3928    TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
3929            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
3930            boolean toTop) {
3931        TaskRecord task = new TaskRecord(mService, taskId, info, intent, voiceSession,
3932                voiceInteractor);
3933        addTask(task, toTop, false);
3934        return task;
3935    }
3936
3937    ArrayList<TaskRecord> getAllTasks() {
3938        return new ArrayList<TaskRecord>(mTaskHistory);
3939    }
3940
3941    void addTask(final TaskRecord task, final boolean toTop, boolean moving) {
3942        task.stack = this;
3943        if (toTop) {
3944            insertTaskAtTop(task);
3945        } else {
3946            mTaskHistory.add(0, task);
3947            updateTaskMovement(task, false);
3948        }
3949        if (!moving && task.voiceSession != null) {
3950            try {
3951                task.voiceSession.taskStarted(task.intent, task.taskId);
3952            } catch (RemoteException e) {
3953            }
3954        }
3955    }
3956
3957    public int getStackId() {
3958        return mStackId;
3959    }
3960
3961    @Override
3962    public String toString() {
3963        return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this))
3964                + " stackId=" + mStackId + ", " + mTaskHistory.size() + " tasks}";
3965    }
3966}
3967