ActivityStack.java revision d3bbb13fe29e8b6c931497daeb124669e050b419
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 android.app.ActivityManager.StackId.DOCKED_STACK_ID;
20import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
21import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
22import static android.app.ActivityManager.StackId.HOME_STACK_ID;
23import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
24import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
25import static android.content.pm.ActivityInfo.CONFIG_ORIENTATION;
26import static android.content.pm.ActivityInfo.CONFIG_SCREEN_LAYOUT;
27import static android.content.pm.ActivityInfo.CONFIG_SCREEN_SIZE;
28import static android.content.pm.ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
29import static android.content.pm.ActivityInfo.FLAG_RESUME_WHILE_PAUSING;
30import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS;
31import static android.content.res.Configuration.SCREENLAYOUT_UNDEFINED;
32import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ADD_REMOVE;
33import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
34import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_APP;
35import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CLEANUP;
36import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION;
37import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONTAINERS;
38import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKSCREEN;
39import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PAUSE;
40import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RELEASE;
41import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RESULTS;
42import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SAVED_STATE;
43import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SCREENSHOTS;
44import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
45import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
46import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
47import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
48import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TRANSITION;
49import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_USER_LEAVING;
50import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBILITY;
51import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_ADD_REMOVE;
52import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_APP;
53import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP;
54import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONFIGURATION;
55import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONTAINERS;
56import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PAUSE;
57import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RELEASE;
58import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RESULTS;
59import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SAVED_STATE;
60import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SCREENSHOTS;
61import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
62import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
63import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
64import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
65import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TRANSITION;
66import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_USER_LEAVING;
67import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBILITY;
68import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
69import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
70import static com.android.server.am.ActivityManagerService.LOCK_SCREEN_SHOWN;
71import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
72import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
73import static com.android.server.am.ActivityRecord.STARTING_WINDOW_REMOVED;
74import static com.android.server.am.ActivityRecord.STARTING_WINDOW_SHOWN;
75import static com.android.server.am.ActivityStackSupervisor.FindTaskResult;
76import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
77import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
78import static com.android.server.wm.AppTransition.TRANSIT_ACTIVITY_CLOSE;
79import static com.android.server.wm.AppTransition.TRANSIT_ACTIVITY_OPEN;
80import static com.android.server.wm.AppTransition.TRANSIT_NONE;
81import static com.android.server.wm.AppTransition.TRANSIT_TASK_CLOSE;
82import static com.android.server.wm.AppTransition.TRANSIT_TASK_OPEN;
83import static com.android.server.wm.AppTransition.TRANSIT_TASK_OPEN_BEHIND;
84import static com.android.server.wm.AppTransition.TRANSIT_TASK_TO_BACK;
85import static com.android.server.wm.AppTransition.TRANSIT_TASK_TO_FRONT;
86
87import android.app.Activity;
88import android.app.ActivityManager;
89import android.app.ActivityManager.RunningTaskInfo;
90import android.app.ActivityManager.StackId;
91import android.app.ActivityOptions;
92import android.app.AppGlobals;
93import android.app.IActivityController;
94import android.app.ResultInfo;
95import android.content.ComponentName;
96import android.content.Intent;
97import android.content.pm.ActivityInfo;
98import android.content.pm.ApplicationInfo;
99import android.content.res.Configuration;
100import android.graphics.Bitmap;
101import android.graphics.Point;
102import android.graphics.Rect;
103import android.net.Uri;
104import android.os.Binder;
105import android.os.Bundle;
106import android.os.Debug;
107import android.os.Handler;
108import android.os.IBinder;
109import android.os.Looper;
110import android.os.Message;
111import android.os.PersistableBundle;
112import android.os.RemoteException;
113import android.os.SystemClock;
114import android.os.Trace;
115import android.os.UserHandle;
116import android.service.voice.IVoiceInteractionSession;
117import android.util.ArraySet;
118import android.util.EventLog;
119import android.util.Log;
120import android.util.Slog;
121import android.view.Display;
122
123import com.android.internal.app.IVoiceInteractor;
124import com.android.internal.content.ReferrerIntent;
125import com.android.internal.os.BatteryStatsImpl;
126import com.android.server.Watchdog;
127import com.android.server.am.ActivityManagerService.ItemMatcher;
128import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
129import com.android.server.wm.TaskGroup;
130import com.android.server.wm.WindowManagerService;
131
132import java.io.FileDescriptor;
133import java.io.PrintWriter;
134import java.lang.ref.WeakReference;
135import java.util.ArrayList;
136import java.util.Iterator;
137import java.util.List;
138import java.util.Objects;
139import java.util.Set;
140
141/**
142 * State and management of a single stack of activities.
143 */
144final class ActivityStack {
145
146    private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStack" : TAG_AM;
147    private static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE;
148    private static final String TAG_APP = TAG + POSTFIX_APP;
149    private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
150    private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
151    private static final String TAG_CONTAINERS = TAG + POSTFIX_CONTAINERS;
152    private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
153    private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
154    private static final String TAG_RESULTS = TAG + POSTFIX_RESULTS;
155    private static final String TAG_SAVED_STATE = TAG + POSTFIX_SAVED_STATE;
156    private static final String TAG_SCREENSHOTS = TAG + POSTFIX_SCREENSHOTS;
157    private static final String TAG_STACK = TAG + POSTFIX_STACK;
158    private static final String TAG_STATES = TAG + POSTFIX_STATES;
159    private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
160    private static final String TAG_TASKS = TAG + POSTFIX_TASKS;
161    private static final String TAG_TRANSITION = TAG + POSTFIX_TRANSITION;
162    private static final String TAG_USER_LEAVING = TAG + POSTFIX_USER_LEAVING;
163    private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
164
165    private static final boolean VALIDATE_TOKENS = false;
166
167    // Ticks during which we check progress while waiting for an app to launch.
168    static final int LAUNCH_TICK = 500;
169
170    // How long we wait until giving up on the last activity to pause.  This
171    // is short because it directly impacts the responsiveness of starting the
172    // next activity.
173    static final int PAUSE_TIMEOUT = 500;
174
175    // How long we wait for the activity to tell us it has stopped before
176    // giving up.  This is a good amount of time because we really need this
177    // from the application in order to get its saved state.
178    static final int STOP_TIMEOUT = 10 * 1000;
179
180    // How long we wait until giving up on an activity telling us it has
181    // finished destroying itself.
182    static final int DESTROY_TIMEOUT = 10 * 1000;
183
184    // How long until we reset a task when the user returns to it.  Currently
185    // disabled.
186    static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
187
188    // How long between activity launches that we consider safe to not warn
189    // the user about an unexpected activity being launched on top.
190    static final long START_WARN_TIME = 5 * 1000;
191
192    // Set to false to disable the preview that is shown while a new activity
193    // is being started.
194    static final boolean SHOW_APP_STARTING_PREVIEW = true;
195
196    // How long to wait for all background Activities to redraw following a call to
197    // convertToTranslucent().
198    static final long TRANSLUCENT_CONVERSION_TIMEOUT = 2000;
199
200    // How many activities have to be scheduled to stop to force a stop pass.
201    private static final int MAX_STOPPING_TO_FORCE = 3;
202
203    enum ActivityState {
204        INITIALIZING,
205        RESUMED,
206        PAUSING,
207        PAUSED,
208        STOPPING,
209        STOPPED,
210        FINISHING,
211        DESTROYING,
212        DESTROYED
213    }
214
215    // Stack is not considered visible.
216    static final int STACK_INVISIBLE = 0;
217    // Stack is considered visible
218    static final int STACK_VISIBLE = 1;
219    // Stack is considered visible, but only becuase it has activity that is visible behind other
220    // activities and there is a specific combination of stacks.
221    static final int STACK_VISIBLE_ACTIVITY_BEHIND = 2;
222
223    /* The various modes for the method {@link #removeTask}. */
224    // Task is being completely removed from all stacks in the system.
225    static final int REMOVE_TASK_MODE_DESTROYING = 0;
226    // Task is being removed from this stack so we can add it to another stack. In the case we are
227    // moving we don't want to perform some operations on the task like removing it from window
228    // manager or recents.
229    static final int REMOVE_TASK_MODE_MOVING = 1;
230    // Similar to {@link #REMOVE_TASK_MODE_MOVING} and the task will be added to the top of its new
231    // stack and the new stack will be on top of all stacks.
232    static final int REMOVE_TASK_MODE_MOVING_TO_TOP = 2;
233
234    final ActivityManagerService mService;
235    final WindowManagerService mWindowManager;
236    private final RecentTasks mRecentTasks;
237
238    /**
239     * The back history of all previous (and possibly still
240     * running) activities.  It contains #TaskRecord objects.
241     */
242    private final ArrayList<TaskRecord> mTaskHistory = new ArrayList<>();
243
244    /**
245     * Used for validating app tokens with window manager.
246     */
247    final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<>();
248
249    /**
250     * List of running activities, sorted by recent usage.
251     * The first entry in the list is the least recently used.
252     * It contains HistoryRecord objects.
253     */
254    final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<>();
255
256    /**
257     * Animations that for the current transition have requested not to
258     * be considered for the transition animation.
259     */
260    final ArrayList<ActivityRecord> mNoAnimActivities = new ArrayList<>();
261
262    /**
263     * When we are in the process of pausing an activity, before starting the
264     * next one, this variable holds the activity that is currently being paused.
265     */
266    ActivityRecord mPausingActivity = null;
267
268    /**
269     * This is the last activity that we put into the paused state.  This is
270     * used to determine if we need to do an activity transition while sleeping,
271     * when we normally hold the top activity paused.
272     */
273    ActivityRecord mLastPausedActivity = null;
274
275    /**
276     * Activities that specify No History must be removed once the user navigates away from them.
277     * If the device goes to sleep with such an activity in the paused state then we save it here
278     * and finish it later if another activity replaces it on wakeup.
279     */
280    ActivityRecord mLastNoHistoryActivity = null;
281
282    /**
283     * Current activity that is resumed, or null if there is none.
284     */
285    ActivityRecord mResumedActivity = null;
286
287    /**
288     * This is the last activity that has been started.  It is only used to
289     * identify when multiple activities are started at once so that the user
290     * can be warned they may not be in the activity they think they are.
291     */
292    ActivityRecord mLastStartedActivity = null;
293
294    // The topmost Activity passed to convertToTranslucent(). When non-null it means we are
295    // waiting for all Activities in mUndrawnActivitiesBelowTopTranslucent to be removed as they
296    // are drawn. When the last member of mUndrawnActivitiesBelowTopTranslucent is removed the
297    // Activity in mTranslucentActivityWaiting is notified via
298    // Activity.onTranslucentConversionComplete(false). If a timeout occurs prior to the last
299    // background activity being drawn then the same call will be made with a true value.
300    ActivityRecord mTranslucentActivityWaiting = null;
301    private ArrayList<ActivityRecord> mUndrawnActivitiesBelowTopTranslucent = new ArrayList<>();
302
303    /**
304     * Set when we know we are going to be calling updateConfiguration()
305     * soon, so want to skip intermediate config checks.
306     */
307    boolean mConfigWillChange;
308
309    // Whether or not this stack covers the entire screen; by default stacks are fullscreen
310    boolean mFullscreen = true;
311    // Current bounds of the stack or null if fullscreen.
312    Rect mBounds = null;
313
314    boolean mUpdateBoundsDeferred;
315    boolean mUpdateBoundsDeferredCalled;
316    final Rect mDeferredBounds = new Rect();
317    final Rect mDeferredTaskBounds = new Rect();
318    final Rect mDeferredTaskInsetBounds = new Rect();
319
320    long mLaunchStartTime = 0;
321    long mFullyDrawnStartTime = 0;
322
323    int mCurrentUser;
324
325    final int mStackId;
326    final ActivityContainer mActivityContainer;
327    /** The other stacks, in order, on the attached display. Updated at attach/detach time. */
328    ArrayList<ActivityStack> mStacks;
329    /** The attached Display's unique identifier, or -1 if detached */
330    int mDisplayId;
331
332    /** Run all ActivityStacks through this */
333    final ActivityStackSupervisor mStackSupervisor;
334
335    private final LaunchingTaskPositioner mTaskPositioner;
336
337    static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
338    static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
339    static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
340    static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
341    static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
342    static final int TRANSLUCENT_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
343    static final int RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG =
344            ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
345
346    static class ScheduleDestroyArgs {
347        final ProcessRecord mOwner;
348        final String mReason;
349        ScheduleDestroyArgs(ProcessRecord owner, String reason) {
350            mOwner = owner;
351            mReason = reason;
352        }
353    }
354
355    final Handler mHandler;
356
357    final class ActivityStackHandler extends Handler {
358
359        ActivityStackHandler(Looper looper) {
360            super(looper);
361        }
362
363        @Override
364        public void handleMessage(Message msg) {
365            switch (msg.what) {
366                case PAUSE_TIMEOUT_MSG: {
367                    ActivityRecord r = (ActivityRecord)msg.obj;
368                    // We don't at this point know if the activity is fullscreen,
369                    // so we need to be conservative and assume it isn't.
370                    Slog.w(TAG, "Activity pause timeout for " + r);
371                    synchronized (mService) {
372                        if (r.app != null) {
373                            mService.logAppTooSlow(r.app, r.pauseTime, "pausing " + r);
374                        }
375                        activityPausedLocked(r.appToken, true);
376                    }
377                } break;
378                case LAUNCH_TICK_MSG: {
379                    ActivityRecord r = (ActivityRecord)msg.obj;
380                    synchronized (mService) {
381                        if (r.continueLaunchTickingLocked()) {
382                            mService.logAppTooSlow(r.app, r.launchTickTime, "launching " + r);
383                        }
384                    }
385                } break;
386                case DESTROY_TIMEOUT_MSG: {
387                    ActivityRecord r = (ActivityRecord)msg.obj;
388                    // We don't at this point know if the activity is fullscreen,
389                    // so we need to be conservative and assume it isn't.
390                    Slog.w(TAG, "Activity destroy timeout for " + r);
391                    synchronized (mService) {
392                        activityDestroyedLocked(r != null ? r.appToken : null, "destroyTimeout");
393                    }
394                } break;
395                case STOP_TIMEOUT_MSG: {
396                    ActivityRecord r = (ActivityRecord)msg.obj;
397                    // We don't at this point know if the activity is fullscreen,
398                    // so we need to be conservative and assume it isn't.
399                    Slog.w(TAG, "Activity stop timeout for " + r);
400                    synchronized (mService) {
401                        if (r.isInHistory()) {
402                            activityStoppedLocked(r, null, null, null);
403                        }
404                    }
405                } break;
406                case DESTROY_ACTIVITIES_MSG: {
407                    ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
408                    synchronized (mService) {
409                        destroyActivitiesLocked(args.mOwner, args.mReason);
410                    }
411                } break;
412                case TRANSLUCENT_TIMEOUT_MSG: {
413                    synchronized (mService) {
414                        notifyActivityDrawnLocked(null);
415                    }
416                } break;
417                case RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG: {
418                    synchronized (mService) {
419                        final ActivityRecord r = getVisibleBehindActivity();
420                        Slog.e(TAG, "Timeout waiting for cancelVisibleBehind player=" + r);
421                        if (r != null) {
422                            mService.killAppAtUsersRequest(r.app, null);
423                        }
424                    }
425                } break;
426            }
427        }
428    }
429
430    int numActivities() {
431        int count = 0;
432        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
433            count += mTaskHistory.get(taskNdx).mActivities.size();
434        }
435        return count;
436    }
437
438    ActivityStack(ActivityStackSupervisor.ActivityContainer activityContainer,
439            RecentTasks recentTasks) {
440        mActivityContainer = activityContainer;
441        mStackSupervisor = activityContainer.getOuter();
442        mService = mStackSupervisor.mService;
443        mHandler = new ActivityStackHandler(mService.mHandler.getLooper());
444        mWindowManager = mService.mWindowManager;
445        mStackId = activityContainer.mStackId;
446        mCurrentUser = mService.mUserController.getCurrentUserIdLocked();
447        mRecentTasks = recentTasks;
448        mTaskPositioner = mStackId == FREEFORM_WORKSPACE_STACK_ID
449                ? new LaunchingTaskPositioner() : null;
450    }
451
452    void attachDisplay(ActivityStackSupervisor.ActivityDisplay activityDisplay, boolean onTop) {
453        mDisplayId = activityDisplay.mDisplayId;
454        mStacks = activityDisplay.mStacks;
455        mBounds = mWindowManager.attachStack(mStackId, activityDisplay.mDisplayId, onTop);
456        mFullscreen = mBounds == null;
457        if (mTaskPositioner != null) {
458            mTaskPositioner.setDisplay(activityDisplay.mDisplay);
459            mTaskPositioner.configure(mBounds);
460        }
461
462        if (mStackId == DOCKED_STACK_ID) {
463            // If we created a docked stack we want to resize it so it resizes all other stacks
464            // in the system.
465            mStackSupervisor.resizeDockedStackLocked(
466                    mBounds, null, null, null, null, PRESERVE_WINDOWS);
467        }
468    }
469
470    void detachDisplay() {
471        mDisplayId = Display.INVALID_DISPLAY;
472        mStacks = null;
473        if (mTaskPositioner != null) {
474            mTaskPositioner.reset();
475        }
476        mWindowManager.detachStack(mStackId);
477        if (mStackId == DOCKED_STACK_ID) {
478            // If we removed a docked stack we want to resize it so it resizes all other stacks
479            // in the system to fullscreen.
480            mStackSupervisor.resizeDockedStackLocked(
481                    null, null, null, null, null, PRESERVE_WINDOWS);
482        }
483    }
484
485    public void getDisplaySize(Point out) {
486        mActivityContainer.mActivityDisplay.mDisplay.getSize(out);
487    }
488
489    /**
490     * Defers updating the bounds of the stack. If the stack was resized/repositioned while
491     * deferring, the bounds will update in {@link #continueUpdateBounds()}.
492     */
493    void deferUpdateBounds() {
494        if (!mUpdateBoundsDeferred) {
495            mUpdateBoundsDeferred = true;
496            mUpdateBoundsDeferredCalled = false;
497        }
498    }
499
500    /**
501     * Continues updating bounds after updates have been deferred. If there was a resize attempt
502     * between {@link #deferUpdateBounds()} and {@link #continueUpdateBounds()}, the stack will
503     * be resized to that bounds.
504     */
505    void continueUpdateBounds() {
506        final boolean wasDeferred = mUpdateBoundsDeferred;
507        mUpdateBoundsDeferred = false;
508        if (wasDeferred && mUpdateBoundsDeferredCalled) {
509            mStackSupervisor.resizeStackUncheckedLocked(this,
510                    mDeferredBounds.isEmpty() ? null : mDeferredBounds,
511                    mDeferredTaskBounds.isEmpty() ? null : mDeferredTaskBounds,
512                    mDeferredTaskInsetBounds.isEmpty() ? null : mDeferredTaskInsetBounds);
513        }
514    }
515
516    boolean updateBoundsAllowed(Rect bounds, Rect tempTaskBounds,
517            Rect tempTaskInsetBounds) {
518        if (!mUpdateBoundsDeferred) {
519            return true;
520        }
521        if (bounds != null) {
522            mDeferredBounds.set(bounds);
523        } else {
524            mDeferredBounds.setEmpty();
525        }
526        if (tempTaskBounds != null) {
527            mDeferredTaskBounds.set(tempTaskBounds);
528        } else {
529            mDeferredTaskBounds.setEmpty();
530        }
531        if (tempTaskInsetBounds != null) {
532            mDeferredTaskInsetBounds.set(tempTaskInsetBounds);
533        } else {
534            mDeferredTaskInsetBounds.setEmpty();
535        }
536        mUpdateBoundsDeferredCalled = true;
537        return false;
538    }
539
540    void setBounds(Rect bounds) {
541        mBounds = mFullscreen ? null : new Rect(bounds);
542        if (mTaskPositioner != null) {
543            mTaskPositioner.configure(bounds);
544        }
545    }
546
547    boolean okToShowLocked(ActivityRecord r) {
548        return mStackSupervisor.okToShowLocked(r);
549    }
550
551    final ActivityRecord topRunningActivityLocked() {
552        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
553            ActivityRecord r = mTaskHistory.get(taskNdx).topRunningActivityLocked();
554            if (r != null) {
555                return r;
556            }
557        }
558        return null;
559    }
560
561    final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
562        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
563            final TaskRecord task = mTaskHistory.get(taskNdx);
564            final ArrayList<ActivityRecord> activities = task.mActivities;
565            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
566                ActivityRecord r = activities.get(activityNdx);
567                if (!r.finishing && !r.delayedResume && r != notTop && okToShowLocked(r)) {
568                    return r;
569                }
570            }
571        }
572        return null;
573    }
574
575    /**
576     * This is a simplified version of topRunningActivityLocked that provides a number of
577     * optional skip-over modes.  It is intended for use with the ActivityController hook only.
578     *
579     * @param token If non-null, any history records matching this token will be skipped.
580     * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
581     *
582     * @return Returns the HistoryRecord of the next activity on the stack.
583     */
584    final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
585        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
586            TaskRecord task = mTaskHistory.get(taskNdx);
587            if (task.taskId == taskId) {
588                continue;
589            }
590            ArrayList<ActivityRecord> activities = task.mActivities;
591            for (int i = activities.size() - 1; i >= 0; --i) {
592                final ActivityRecord r = activities.get(i);
593                // Note: the taskId check depends on real taskId fields being non-zero
594                if (!r.finishing && (token != r.appToken) && okToShowLocked(r)) {
595                    return r;
596                }
597            }
598        }
599        return null;
600    }
601
602    final ActivityRecord topActivity() {
603        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
604            ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
605            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
606                final ActivityRecord r = activities.get(activityNdx);
607                if (!r.finishing) {
608                    return r;
609                }
610            }
611        }
612        return null;
613    }
614
615    final TaskRecord topTask() {
616        final int size = mTaskHistory.size();
617        if (size > 0) {
618            return mTaskHistory.get(size - 1);
619        }
620        return null;
621    }
622
623    TaskRecord taskForIdLocked(int id) {
624        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
625            final TaskRecord task = mTaskHistory.get(taskNdx);
626            if (task.taskId == id) {
627                return task;
628            }
629        }
630        return null;
631    }
632
633    ActivityRecord isInStackLocked(IBinder token) {
634        final ActivityRecord r = ActivityRecord.forTokenLocked(token);
635        return isInStackLocked(r);
636    }
637
638    ActivityRecord isInStackLocked(ActivityRecord r) {
639        if (r == null) {
640            return null;
641        }
642        final TaskRecord task = r.task;
643        if (task != null && task.stack != null
644                && task.mActivities.contains(r) && mTaskHistory.contains(task)) {
645            if (task.stack != this) Slog.w(TAG,
646                    "Illegal state! task does not point to stack it is in.");
647            return r;
648        }
649        return null;
650    }
651
652    final boolean updateLRUListLocked(ActivityRecord r) {
653        final boolean hadit = mLRUActivities.remove(r);
654        mLRUActivities.add(r);
655        return hadit;
656    }
657
658    final boolean isHomeStack() {
659        return mStackId == HOME_STACK_ID;
660    }
661
662    final boolean isDockedStack() {
663        return mStackId == DOCKED_STACK_ID;
664    }
665
666    final boolean isPinnedStack() {
667        return mStackId == PINNED_STACK_ID;
668    }
669
670    final boolean isOnHomeDisplay() {
671        return isAttached() &&
672                mActivityContainer.mActivityDisplay.mDisplayId == Display.DEFAULT_DISPLAY;
673    }
674
675    void moveToFront(String reason) {
676        moveToFront(reason, null);
677    }
678
679    /**
680     * @param reason The reason for moving the stack to the front.
681     * @param task If non-null, the task will be moved to the top of the stack.
682     * */
683    void moveToFront(String reason, TaskRecord task) {
684        if (!isAttached()) {
685            return;
686        }
687
688        mStacks.remove(this);
689        int addIndex = mStacks.size();
690
691        if (addIndex > 0) {
692            final ActivityStack topStack = mStacks.get(addIndex - 1);
693            if (StackId.isAlwaysOnTop(topStack.mStackId) && topStack != this) {
694                // If the top stack is always on top, we move this stack just below it.
695                addIndex--;
696            }
697        }
698
699        mStacks.add(addIndex, this);
700
701        // TODO(multi-display): Needs to also work if focus is moving to the non-home display.
702        if (isOnHomeDisplay()) {
703            mStackSupervisor.setFocusStackUnchecked(reason, this);
704        }
705        if (task != null) {
706            insertTaskAtTop(task, null);
707        } else {
708            task = topTask();
709        }
710        if (task != null) {
711            mWindowManager.moveTaskToTop(task.taskId);
712        }
713    }
714
715    boolean isFocusable() {
716        if (StackId.canReceiveKeys(mStackId)) {
717            return true;
718        }
719        // The stack isn't focusable. See if its top activity is focusable to force focus on the
720        // stack.
721        final ActivityRecord r = topRunningActivityLocked();
722        return r != null && r.isFocusable();
723    }
724
725    final boolean isAttached() {
726        return mStacks != null;
727    }
728
729    /**
730     * Returns the top activity in any existing task matching the given Intent in the input result.
731     * Returns null if no such task is found.
732     */
733    void findTaskLocked(ActivityRecord target, FindTaskResult result) {
734        Intent intent = target.intent;
735        ActivityInfo info = target.info;
736        ComponentName cls = intent.getComponent();
737        if (info.targetActivity != null) {
738            cls = new ComponentName(info.packageName, info.targetActivity);
739        }
740        final int userId = UserHandle.getUserId(info.applicationInfo.uid);
741        boolean isDocument = intent != null & intent.isDocument();
742        // If documentData is non-null then it must match the existing task data.
743        Uri documentData = isDocument ? intent.getData() : null;
744
745        if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + target + " in " + this);
746        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
747            final TaskRecord task = mTaskHistory.get(taskNdx);
748            if (task.voiceSession != null) {
749                // We never match voice sessions; those always run independently.
750                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": voice session");
751                continue;
752            }
753            if (task.userId != userId) {
754                // Looking for a different task.
755                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": different user");
756                continue;
757            }
758            final ActivityRecord r = task.getTopActivity();
759            if (r == null || r.finishing || r.userId != userId ||
760                    r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
761                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": mismatch root " + r);
762                continue;
763            }
764            if (r.mActivityType != target.mActivityType) {
765                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": mismatch activity type");
766                continue;
767            }
768
769            final Intent taskIntent = task.intent;
770            final Intent affinityIntent = task.affinityIntent;
771            final boolean taskIsDocument;
772            final Uri taskDocumentData;
773            if (taskIntent != null && taskIntent.isDocument()) {
774                taskIsDocument = true;
775                taskDocumentData = taskIntent.getData();
776            } else if (affinityIntent != null && affinityIntent.isDocument()) {
777                taskIsDocument = true;
778                taskDocumentData = affinityIntent.getData();
779            } else {
780                taskIsDocument = false;
781                taskDocumentData = null;
782            }
783
784            if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Comparing existing cls="
785                    + taskIntent.getComponent().flattenToShortString()
786                    + "/aff=" + r.task.rootAffinity + " to new cls="
787                    + intent.getComponent().flattenToShortString() + "/aff=" + info.taskAffinity);
788            // TODO Refactor to remove duplications. Check if logic can be simplified.
789            if (taskIntent != null && taskIntent.getComponent() != null &&
790                    taskIntent.getComponent().compareTo(cls) == 0 &&
791                    Objects.equals(documentData, taskDocumentData)) {
792                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!");
793                //dump();
794                if (DEBUG_TASKS) Slog.d(TAG_TASKS,
795                        "For Intent " + intent + " bringing to top: " + r.intent);
796                result.r = r;
797                result.matchedByRootAffinity = false;
798                break;
799            } else if (affinityIntent != null && affinityIntent.getComponent() != null &&
800                    affinityIntent.getComponent().compareTo(cls) == 0 &&
801                    Objects.equals(documentData, taskDocumentData)) {
802                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!");
803                //dump();
804                if (DEBUG_TASKS) Slog.d(TAG_TASKS,
805                        "For Intent " + intent + " bringing to top: " + r.intent);
806                result.r = r;
807                result.matchedByRootAffinity = false;
808                break;
809            } else if (!isDocument && !taskIsDocument
810                    && result.r == null && task.canMatchRootAffinity()) {
811                if (task.rootAffinity.equals(target.taskAffinity)) {
812                    if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching affinity candidate!");
813                    // It is possible for multiple tasks to have the same root affinity especially
814                    // if they are in separate stacks. We save off this candidate, but keep looking
815                    // to see if there is a better candidate.
816                    result.r = r;
817                    result.matchedByRootAffinity = true;
818                }
819            } else if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Not a match: " + task);
820        }
821    }
822
823    /**
824     * Returns the first activity (starting from the top of the stack) that
825     * is the same as the given activity.  Returns null if no such activity
826     * is found.
827     */
828    ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
829                                      boolean compareIntentFilters) {
830        ComponentName cls = intent.getComponent();
831        if (info.targetActivity != null) {
832            cls = new ComponentName(info.packageName, info.targetActivity);
833        }
834        final int userId = UserHandle.getUserId(info.applicationInfo.uid);
835
836        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
837            final TaskRecord task = mTaskHistory.get(taskNdx);
838            final boolean notCurrentUserTask =
839                    !mStackSupervisor.isCurrentProfileLocked(task.userId);
840            final ArrayList<ActivityRecord> activities = task.mActivities;
841
842            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
843                ActivityRecord r = activities.get(activityNdx);
844                if (notCurrentUserTask && (r.info.flags & FLAG_SHOW_FOR_ALL_USERS) == 0) {
845                    continue;
846                }
847                if (!r.finishing && r.userId == userId) {
848                    if (compareIntentFilters) {
849                        if (r.intent.filterEquals(intent)) {
850                            return r;
851                        }
852                    } else {
853                        if (r.intent.getComponent().equals(cls)) {
854                            return r;
855                        }
856                    }
857                }
858            }
859        }
860
861        return null;
862    }
863
864    /*
865     * Move the activities around in the stack to bring a user to the foreground.
866     */
867    final void switchUserLocked(int userId) {
868        if (mCurrentUser == userId) {
869            return;
870        }
871        mCurrentUser = userId;
872
873        // Move userId's tasks to the top.
874        int index = mTaskHistory.size();
875        for (int i = 0; i < index; ) {
876            final TaskRecord task = mTaskHistory.get(i);
877
878            // NOTE: If {@link TaskRecord#topRunningActivityLocked} return is not null then it is
879            // okay to show the activity when locked.
880            if (mStackSupervisor.isCurrentProfileLocked(task.userId)
881                    || task.topRunningActivityLocked() != null) {
882                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "switchUserLocked: stack=" + getStackId() +
883                        " moving " + task + " to top");
884                mTaskHistory.remove(i);
885                mTaskHistory.add(task);
886                --index;
887                // Use same value for i.
888            } else {
889                ++i;
890            }
891        }
892        if (VALIDATE_TOKENS) {
893            validateAppTokensLocked();
894        }
895    }
896
897    void minimalResumeActivityLocked(ActivityRecord r) {
898        r.state = ActivityState.RESUMED;
899        if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + r + " (starting new instance)"
900                + " callers=" + Debug.getCallers(5));
901        mResumedActivity = r;
902        r.task.touchActiveTime();
903        mRecentTasks.addLocked(r.task);
904        completeResumeLocked(r);
905        mStackSupervisor.checkReadyForSleepLocked();
906        setLaunchTime(r);
907        if (DEBUG_SAVED_STATE) Slog.i(TAG_SAVED_STATE,
908                "Launch completed; removing icicle of " + r.icicle);
909    }
910
911    void addRecentActivityLocked(ActivityRecord r) {
912        if (r != null) {
913            mRecentTasks.addLocked(r.task);
914            r.task.touchActiveTime();
915        }
916    }
917
918    private void startLaunchTraces(String packageName) {
919        if (mFullyDrawnStartTime != 0)  {
920            Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
921        }
922        Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching: " + packageName, 0);
923        Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
924    }
925
926    private void stopFullyDrawnTraceIfNeeded() {
927        if (mFullyDrawnStartTime != 0 && mLaunchStartTime == 0) {
928            Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
929            mFullyDrawnStartTime = 0;
930        }
931    }
932
933    void setLaunchTime(ActivityRecord r) {
934        if (r.displayStartTime == 0) {
935            r.fullyDrawnStartTime = r.displayStartTime = SystemClock.uptimeMillis();
936            if (r.task != null) {
937                r.task.isLaunching = true;
938            }
939            if (mLaunchStartTime == 0) {
940                startLaunchTraces(r.packageName);
941                mLaunchStartTime = mFullyDrawnStartTime = r.displayStartTime;
942            }
943        } else if (mLaunchStartTime == 0) {
944            startLaunchTraces(r.packageName);
945            mLaunchStartTime = mFullyDrawnStartTime = SystemClock.uptimeMillis();
946        }
947    }
948
949    void clearLaunchTime(ActivityRecord r) {
950        // Make sure that there is no activity waiting for this to launch.
951        if (mStackSupervisor.mWaitingActivityLaunched.isEmpty()) {
952            r.displayStartTime = r.fullyDrawnStartTime = 0;
953            if (r.task != null) {
954                r.task.isLaunching = false;
955            }
956        } else {
957            mStackSupervisor.removeTimeoutsForActivityLocked(r);
958            mStackSupervisor.scheduleIdleTimeoutLocked(r);
959        }
960    }
961
962    void awakeFromSleepingLocked() {
963        // Ensure activities are no longer sleeping.
964        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
965            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
966            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
967                activities.get(activityNdx).setSleeping(false);
968            }
969        }
970        if (mPausingActivity != null) {
971            Slog.d(TAG, "awakeFromSleepingLocked: previously pausing activity didn't pause");
972            activityPausedLocked(mPausingActivity.appToken, true);
973        }
974    }
975
976    void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
977        final String packageName = aInfo.packageName;
978        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
979            final List<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
980            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
981                if (packageName.equals(activities.get(activityNdx).packageName)) {
982                    activities.get(activityNdx).info.applicationInfo = aInfo;
983                }
984            }
985        }
986    }
987
988    /**
989     * @return true if something must be done before going to sleep.
990     */
991    boolean checkReadyForSleepLocked() {
992        if (mResumedActivity != null) {
993            // Still have something resumed; can't sleep until it is paused.
994            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep needs to pause " + mResumedActivity);
995            if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
996                    "Sleep => pause with userLeaving=false");
997            startPausingLocked(false, true, false, false);
998            return true;
999        }
1000        if (mPausingActivity != null) {
1001            // Still waiting for something to pause; can't sleep yet.
1002            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still waiting to pause " + mPausingActivity);
1003            return true;
1004        }
1005
1006        if (hasVisibleBehindActivity()) {
1007            // Stop visible behind activity before going to sleep.
1008            final ActivityRecord r = getVisibleBehindActivity();
1009            mStackSupervisor.mStoppingActivities.add(r);
1010            if (DEBUG_STATES) Slog.v(TAG_STATES, "Sleep still waiting to stop visible behind " + r);
1011            return true;
1012        }
1013
1014        return false;
1015    }
1016
1017    void goToSleep() {
1018        ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1019
1020        // Make sure any paused or stopped but visible activities are now sleeping.
1021        // This ensures that the activity's onStop() is called.
1022        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1023            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
1024            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1025                final ActivityRecord r = activities.get(activityNdx);
1026                if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED
1027                        || r.state == ActivityState.PAUSED || r.state == ActivityState.PAUSING) {
1028                    r.setSleeping(true);
1029                }
1030            }
1031        }
1032    }
1033
1034    public final Bitmap screenshotActivitiesLocked(ActivityRecord who) {
1035        if (DEBUG_SCREENSHOTS) Slog.d(TAG_SCREENSHOTS, "screenshotActivitiesLocked: " + who);
1036        if (who.noDisplay) {
1037            if (DEBUG_SCREENSHOTS) Slog.d(TAG_SCREENSHOTS, "\tNo display");
1038            return null;
1039        }
1040
1041        if (isHomeStack()) {
1042            // This is an optimization -- since we never show Home or Recents within Recents itself,
1043            // we can just go ahead and skip taking the screenshot if this is the home stack.
1044            if (DEBUG_SCREENSHOTS) Slog.d(TAG_SCREENSHOTS, "\tHome stack");
1045            return null;
1046        }
1047
1048        int w = mService.mThumbnailWidth;
1049        int h = mService.mThumbnailHeight;
1050        float scale = 1f;
1051        if (w > 0) {
1052            if (DEBUG_SCREENSHOTS) Slog.d(TAG_SCREENSHOTS, "\tTaking screenshot");
1053
1054            // When this flag is set, we currently take the fullscreen screenshot of the activity
1055            // but scaled to half the size.  This gives us a "good-enough" fullscreen thumbnail to
1056            // use within SystemUI while keeping memory usage low.
1057            if (ActivityManagerService.TAKE_FULLSCREEN_SCREENSHOTS) {
1058                w = h = -1;
1059                scale = mService.mFullscreenThumbnailScale;
1060            }
1061            return mWindowManager.screenshotApplications(who.appToken, Display.DEFAULT_DISPLAY,
1062                    w, h, scale);
1063        }
1064        Slog.e(TAG, "Invalid thumbnail dimensions: " + w + "x" + h);
1065        return null;
1066    }
1067
1068    /**
1069     * Start pausing the currently resumed activity.  It is an error to call this if there
1070     * is already an activity being paused or there is no resumed activity.
1071     *
1072     * @param userLeaving True if this should result in an onUserLeaving to the current activity.
1073     * @param uiSleeping True if this is happening with the user interface going to sleep (the
1074     * screen turning off).
1075     * @param resuming True if this is being called as part of resuming the top activity, so
1076     * we shouldn't try to instigate a resume here.
1077     * @param dontWait True if the caller does not want to wait for the pause to complete.  If
1078     * set to true, we will immediately complete the pause here before returning.
1079     * @return Returns true if an activity now is in the PAUSING state, and we are waiting for
1080     * it to tell us when it is done.
1081     */
1082    final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,
1083            boolean dontWait) {
1084        if (mPausingActivity != null) {
1085            Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity
1086                    + " state=" + mPausingActivity.state);
1087            if (!mService.isSleepingLocked()) {
1088                // Avoid recursion among check for sleep and complete pause during sleeping.
1089                // Because activity will be paused immediately after resume, just let pause
1090                // be completed by the order of activity paused from clients.
1091                completePauseLocked(false);
1092            }
1093        }
1094        ActivityRecord prev = mResumedActivity;
1095        if (prev == null) {
1096            if (!resuming) {
1097                Slog.wtf(TAG, "Trying to pause when nothing is resumed");
1098                mStackSupervisor.resumeFocusedStackTopActivityLocked();
1099            }
1100            return false;
1101        }
1102
1103        if (mActivityContainer.mParentActivity == null) {
1104            // Top level stack, not a child. Look for child stacks.
1105            mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait);
1106        }
1107
1108        if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSING: " + prev);
1109        else if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Start pausing: " + prev);
1110        mResumedActivity = null;
1111        mPausingActivity = prev;
1112        mLastPausedActivity = prev;
1113        mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1114                || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
1115        prev.state = ActivityState.PAUSING;
1116        prev.task.touchActiveTime();
1117        clearLaunchTime(prev);
1118        final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();
1119        if (mService.mHasRecents
1120                && (next == null || next.noDisplay || next.task != prev.task || uiSleeping)) {
1121            prev.mUpdateTaskThumbnailWhenHidden = true;
1122        }
1123        stopFullyDrawnTraceIfNeeded();
1124
1125        mService.updateCpuStats();
1126
1127        if (prev.app != null && prev.app.thread != null) {
1128            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
1129            try {
1130                EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
1131                        prev.userId, System.identityHashCode(prev),
1132                        prev.shortComponentName);
1133                mService.updateUsageStats(prev, false);
1134                prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
1135                        userLeaving, prev.configChangeFlags, dontWait);
1136            } catch (Exception e) {
1137                // Ignore exception, if process died other code will cleanup.
1138                Slog.w(TAG, "Exception thrown during pause", e);
1139                mPausingActivity = null;
1140                mLastPausedActivity = null;
1141                mLastNoHistoryActivity = null;
1142            }
1143        } else {
1144            mPausingActivity = null;
1145            mLastPausedActivity = null;
1146            mLastNoHistoryActivity = null;
1147        }
1148
1149        // If we are not going to sleep, we want to ensure the device is
1150        // awake until the next activity is started.
1151        if (!uiSleeping && !mService.isSleepingOrShuttingDownLocked()) {
1152            mStackSupervisor.acquireLaunchWakelock();
1153        }
1154
1155        if (mPausingActivity != null) {
1156            // Have the window manager pause its key dispatching until the new
1157            // activity has started.  If we're pausing the activity just because
1158            // the screen is being turned off and the UI is sleeping, don't interrupt
1159            // key dispatch; the same activity will pick it up again on wakeup.
1160            if (!uiSleeping) {
1161                prev.pauseKeyDispatchingLocked();
1162            } else if (DEBUG_PAUSE) {
1163                 Slog.v(TAG_PAUSE, "Key dispatch not paused for screen off");
1164            }
1165
1166            if (dontWait) {
1167                // If the caller said they don't want to wait for the pause, then complete
1168                // the pause now.
1169                completePauseLocked(false);
1170                return false;
1171
1172            } else {
1173                // Schedule a pause timeout in case the app doesn't respond.
1174                // We don't give it much time because this directly impacts the
1175                // responsiveness seen by the user.
1176                Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1177                msg.obj = prev;
1178                prev.pauseTime = SystemClock.uptimeMillis();
1179                mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1180                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Waiting for pause to complete...");
1181                return true;
1182            }
1183
1184        } else {
1185            // This activity failed to schedule the
1186            // pause, so just treat it as being paused now.
1187            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Activity not running, resuming next.");
1188            if (!resuming) {
1189                mStackSupervisor.resumeFocusedStackTopActivityLocked();
1190            }
1191            return false;
1192        }
1193    }
1194
1195    final void activityPausedLocked(IBinder token, boolean timeout) {
1196        if (DEBUG_PAUSE) Slog.v(TAG_PAUSE,
1197            "Activity paused: token=" + token + ", timeout=" + timeout);
1198
1199        final ActivityRecord r = isInStackLocked(token);
1200        if (r != null) {
1201            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
1202            if (mPausingActivity == r) {
1203                if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r
1204                        + (timeout ? " (due to timeout)" : " (pause complete)"));
1205                completePauseLocked(true);
1206                return;
1207            } else {
1208                EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
1209                        r.userId, System.identityHashCode(r), r.shortComponentName,
1210                        mPausingActivity != null
1211                            ? mPausingActivity.shortComponentName : "(none)");
1212                if (r.state == ActivityState.PAUSING) {
1213                    r.state = ActivityState.PAUSED;
1214                    if (r.finishing) {
1215                        if (DEBUG_PAUSE) Slog.v(TAG,
1216                                "Executing finish of failed to pause activity: " + r);
1217                        finishCurrentActivityLocked(r, FINISH_AFTER_VISIBLE, false);
1218                    }
1219                }
1220            }
1221        }
1222        mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1223    }
1224
1225    final void activityResumedLocked(IBinder token) {
1226        final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1227        if (DEBUG_SAVED_STATE) Slog.i(TAG_STATES, "Resumed activity; dropping state of: " + r);
1228        r.icicle = null;
1229        r.haveState = false;
1230    }
1231
1232    final void activityStoppedLocked(ActivityRecord r, Bundle icicle,
1233            PersistableBundle persistentState, CharSequence description) {
1234        if (r.state != ActivityState.STOPPING) {
1235            Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1236            mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1237            return;
1238        }
1239        if (persistentState != null) {
1240            r.persistentState = persistentState;
1241            mService.notifyTaskPersisterLocked(r.task, false);
1242        }
1243        if (DEBUG_SAVED_STATE) Slog.i(TAG_SAVED_STATE, "Saving icicle of " + r + ": " + icicle);
1244        if (icicle != null) {
1245            // If icicle is null, this is happening due to a timeout, so we
1246            // haven't really saved the state.
1247            r.icicle = icicle;
1248            r.haveState = true;
1249            r.launchCount = 0;
1250            r.updateThumbnailLocked(null, description);
1251        }
1252        if (!r.stopped) {
1253            if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to STOPPED: " + r + " (stop complete)");
1254            mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1255            r.stopped = true;
1256            r.state = ActivityState.STOPPED;
1257
1258            mWindowManager.notifyAppStopped(r.appToken, true);
1259
1260            if (getVisibleBehindActivity() == r) {
1261                mStackSupervisor.requestVisibleBehindLocked(r, false);
1262            }
1263            if (r.finishing) {
1264                r.clearOptionsLocked();
1265            } else {
1266                if (r.deferRelaunchUntilPaused) {
1267                    destroyActivityLocked(r, true, "stop-config");
1268                    mStackSupervisor.resumeFocusedStackTopActivityLocked();
1269                } else {
1270                    mStackSupervisor.updatePreviousProcessLocked(r);
1271                }
1272            }
1273        }
1274    }
1275
1276    private void completePauseLocked(boolean resumeNext) {
1277        ActivityRecord prev = mPausingActivity;
1278        if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Complete pause: " + prev);
1279
1280        if (prev != null) {
1281            final boolean wasStopping = prev.state == ActivityState.STOPPING;
1282            prev.state = ActivityState.PAUSED;
1283            if (prev.finishing) {
1284                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Executing finish of activity: " + prev);
1285                prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
1286            } else if (prev.app != null) {
1287                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueue pending stop if needed: " + prev
1288                        + " wasStopping=" + wasStopping + " visible=" + prev.visible);
1289                if (mStackSupervisor.mWaitingVisibleActivities.remove(prev)) {
1290                    if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG_PAUSE,
1291                            "Complete pause, no longer waiting: " + prev);
1292                }
1293                if (prev.deferRelaunchUntilPaused) {
1294                    // Complete the deferred relaunch that was waiting for pause to complete.
1295                    if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Re-launching after pause: " + prev);
1296                    relaunchActivityLocked(prev, prev.configChangeFlags, false,
1297                            prev.preserveWindowOnDeferredRelaunch);
1298                } else if (wasStopping) {
1299                    // We are also stopping, the stop request must have gone soon after the pause.
1300                    // We can't clobber it, because the stop confirmation will not be handled.
1301                    // We don't need to schedule another stop, we only need to let it happen.
1302                    prev.state = ActivityState.STOPPING;
1303                } else if ((!prev.visible && !hasVisibleBehindActivity())
1304                        || mService.isSleepingOrShuttingDownLocked()) {
1305                    // If we were visible then resumeTopActivities will release resources before
1306                    // stopping.
1307                    addToStopping(prev, true /* immediate */);
1308                }
1309            } else {
1310                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "App died during pause, not stopping: " + prev);
1311                prev = null;
1312            }
1313            // It is possible the activity was freezing the screen before it was paused.
1314            // In that case go ahead and remove the freeze this activity has on the screen
1315            // since it is no longer visible.
1316            prev.stopFreezingScreenLocked(true /*force*/);
1317            mPausingActivity = null;
1318        }
1319
1320        if (resumeNext) {
1321            final ActivityStack topStack = mStackSupervisor.getFocusedStack();
1322            if (!mService.isSleepingOrShuttingDownLocked()) {
1323                mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
1324            } else {
1325                mStackSupervisor.checkReadyForSleepLocked();
1326                ActivityRecord top = topStack.topRunningActivityLocked();
1327                if (top == null || (prev != null && top != prev)) {
1328                    // If there are no more activities available to run, do resume anyway to start
1329                    // something. Also if the top activity on the stack is not the just paused
1330                    // activity, we need to go ahead and resume it to ensure we complete an
1331                    // in-flight app switch.
1332                    mStackSupervisor.resumeFocusedStackTopActivityLocked();
1333                }
1334            }
1335        }
1336
1337        if (prev != null) {
1338            prev.resumeKeyDispatchingLocked();
1339
1340            if (prev.app != null && prev.cpuTimeAtResume > 0
1341                    && mService.mBatteryStatsService.isOnBattery()) {
1342                long diff = mService.mProcessCpuTracker.getCpuTimeForPid(prev.app.pid)
1343                        - prev.cpuTimeAtResume;
1344                if (diff > 0) {
1345                    BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1346                    synchronized (bsi) {
1347                        BatteryStatsImpl.Uid.Proc ps =
1348                                bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1349                                        prev.info.packageName);
1350                        if (ps != null) {
1351                            ps.addForegroundTimeLocked(diff);
1352                        }
1353                    }
1354                }
1355            }
1356            prev.cpuTimeAtResume = 0; // reset it
1357        }
1358
1359        // Notify when the task stack has changed, but only if visibilities changed (not just focus)
1360        if (mStackSupervisor.mAppVisibilitiesChangedSinceLastPause) {
1361            mService.notifyTaskStackChangedLocked();
1362            mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = false;
1363        }
1364
1365        mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1366    }
1367
1368    private void addToStopping(ActivityRecord r, boolean immediate) {
1369        if (!mStackSupervisor.mStoppingActivities.contains(r)) {
1370            mStackSupervisor.mStoppingActivities.add(r);
1371        }
1372
1373        // If we already have a few activities waiting to stop, then give up
1374        // on things going idle and start clearing them out. Or if r is the
1375        // last of activity of the last task the stack will be empty and must
1376        // be cleared immediately.
1377        boolean forceIdle = mStackSupervisor.mStoppingActivities.size() > MAX_STOPPING_TO_FORCE
1378                || (r.frontOfTask && mTaskHistory.size() <= 1);
1379
1380        if (immediate || forceIdle) {
1381            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Scheduling idle now: forceIdle="
1382                    + forceIdle + "immediate=" + immediate);
1383            mStackSupervisor.scheduleIdleLocked();
1384        } else {
1385            mStackSupervisor.checkReadyForSleepLocked();
1386        }
1387    }
1388
1389    /**
1390     * Once we know that we have asked an application to put an activity in
1391     * the resumed state (either by launching it or explicitly telling it),
1392     * this function updates the rest of our state to match that fact.
1393     */
1394    private void completeResumeLocked(ActivityRecord next) {
1395        next.visible = true;
1396        next.idle = false;
1397        next.results = null;
1398        next.newIntents = null;
1399        next.stopped = false;
1400
1401        if (next.isHomeActivity()) {
1402            ProcessRecord app = next.task.mActivities.get(0).app;
1403            if (app != null && app != mService.mHomeProcess) {
1404                mService.mHomeProcess = app;
1405            }
1406        }
1407
1408        if (next.nowVisible) {
1409            // We won't get a call to reportActivityVisibleLocked() so dismiss lockscreen now.
1410            mStackSupervisor.notifyActivityDrawnForKeyguard();
1411        }
1412
1413        // schedule an idle timeout in case the app doesn't do it for us.
1414        mStackSupervisor.scheduleIdleTimeoutLocked(next);
1415
1416        mStackSupervisor.reportResumedActivityLocked(next);
1417
1418        next.resumeKeyDispatchingLocked();
1419        mNoAnimActivities.clear();
1420
1421        // Mark the point when the activity is resuming
1422        // TODO: To be more accurate, the mark should be before the onCreate,
1423        //       not after the onResume. But for subsequent starts, onResume is fine.
1424        if (next.app != null) {
1425            next.cpuTimeAtResume = mService.mProcessCpuTracker.getCpuTimeForPid(next.app.pid);
1426        } else {
1427            next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1428        }
1429
1430        next.returningOptions = null;
1431
1432        if (getVisibleBehindActivity() == next) {
1433            // When resuming an activity, require it to call requestVisibleBehind() again.
1434            setVisibleBehindActivity(null);
1435        }
1436    }
1437
1438    private void setVisible(ActivityRecord r, boolean visible) {
1439        r.visible = visible;
1440        if (!visible && r.mUpdateTaskThumbnailWhenHidden) {
1441            r.updateThumbnailLocked(r.task.stack.screenshotActivitiesLocked(r), null);
1442            r.mUpdateTaskThumbnailWhenHidden = false;
1443        }
1444        mWindowManager.setAppVisibility(r.appToken, visible);
1445        final ArrayList<ActivityContainer> containers = r.mChildContainers;
1446        for (int containerNdx = containers.size() - 1; containerNdx >= 0; --containerNdx) {
1447            ActivityContainer container = containers.get(containerNdx);
1448            container.setVisible(visible);
1449        }
1450        mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = true;
1451    }
1452
1453    // Find the first visible activity above the passed activity and if it is translucent return it
1454    // otherwise return null;
1455    ActivityRecord findNextTranslucentActivity(ActivityRecord r) {
1456        TaskRecord task = r.task;
1457        if (task == null) {
1458            return null;
1459        }
1460
1461        ActivityStack stack = task.stack;
1462        if (stack == null) {
1463            return null;
1464        }
1465
1466        int stackNdx = mStacks.indexOf(stack);
1467
1468        ArrayList<TaskRecord> tasks = stack.mTaskHistory;
1469        int taskNdx = tasks.indexOf(task);
1470
1471        ArrayList<ActivityRecord> activities = task.mActivities;
1472        int activityNdx = activities.indexOf(r) + 1;
1473
1474        final int numStacks = mStacks.size();
1475        while (stackNdx < numStacks) {
1476            final ActivityStack historyStack = mStacks.get(stackNdx);
1477            tasks = historyStack.mTaskHistory;
1478            final int numTasks = tasks.size();
1479            while (taskNdx < numTasks) {
1480                final TaskRecord currentTask = tasks.get(taskNdx);
1481                activities = currentTask.mActivities;
1482                final int numActivities = activities.size();
1483                while (activityNdx < numActivities) {
1484                    final ActivityRecord activity = activities.get(activityNdx);
1485                    if (!activity.finishing) {
1486                        return historyStack.mFullscreen
1487                                && currentTask.mFullscreen && activity.fullscreen ? null : activity;
1488                    }
1489                    ++activityNdx;
1490                }
1491                activityNdx = 0;
1492                ++taskNdx;
1493            }
1494            taskNdx = 0;
1495            ++stackNdx;
1496        }
1497
1498        return null;
1499    }
1500
1501    ActivityStack getNextFocusableStackLocked() {
1502        ArrayList<ActivityStack> stacks = mStacks;
1503        final ActivityRecord parent = mActivityContainer.mParentActivity;
1504        if (parent != null) {
1505            stacks = parent.task.stack.mStacks;
1506        }
1507        if (stacks != null) {
1508            for (int i = stacks.size() - 1; i >= 0; --i) {
1509                ActivityStack stack = stacks.get(i);
1510                if (stack != this && stack.isFocusable()
1511                        && stack.getStackVisibilityLocked(null) != STACK_INVISIBLE) {
1512                    return stack;
1513                }
1514            }
1515        }
1516        return null;
1517    }
1518
1519    /** Returns true if the stack contains a fullscreen task. */
1520    private boolean hasFullscreenTask() {
1521        for (int i = mTaskHistory.size() - 1; i >= 0; --i) {
1522            final TaskRecord task = mTaskHistory.get(i);
1523            if (task.mFullscreen) {
1524                return true;
1525            }
1526        }
1527        return false;
1528    }
1529
1530    /**
1531     * Returns true if the stack is translucent and can have other contents visible behind it if
1532     * needed. A stack is considered translucent if it don't contain a visible or
1533     * starting (about to be visible) activity that is fullscreen (opaque).
1534     * @param starting The currently starting activity or null if there is none.
1535     * @param stackBehindId The id of the stack directly behind this one.
1536     */
1537    private boolean isStackTranslucent(ActivityRecord starting, int stackBehindId) {
1538        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1539            final TaskRecord task = mTaskHistory.get(taskNdx);
1540            final ArrayList<ActivityRecord> activities = task.mActivities;
1541            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1542                final ActivityRecord r = activities.get(activityNdx);
1543
1544                if (r.finishing) {
1545                    // We don't factor in finishing activities when determining translucency since
1546                    // they will be gone soon.
1547                    continue;
1548                }
1549
1550                if (!r.visible && r != starting) {
1551                    // Also ignore invisible activities that are not the currently starting
1552                    // activity (about to be visible).
1553                    continue;
1554                }
1555
1556                if (r.fullscreen) {
1557                    // Stack isn't translucent if it has at least one fullscreen activity
1558                    // that is visible.
1559                    return false;
1560                }
1561
1562                if (!isHomeStack() && r.frontOfTask
1563                        && task.isOverHomeStack() && stackBehindId != HOME_STACK_ID) {
1564                    // Stack isn't translucent if it's top activity should have the home stack
1565                    // behind it and the stack currently behind it isn't the home stack.
1566                    return false;
1567                }
1568            }
1569        }
1570        return true;
1571    }
1572
1573    /**
1574     * Returns stack's visibility: {@link #STACK_INVISIBLE}, {@link #STACK_VISIBLE} or
1575     * {@link #STACK_VISIBLE_ACTIVITY_BEHIND}.
1576     * @param starting The currently starting activity or null if there is none.
1577     */
1578    int getStackVisibilityLocked(ActivityRecord starting) {
1579        if (!isAttached()) {
1580            return STACK_INVISIBLE;
1581        }
1582
1583        if (mStackSupervisor.isFrontStack(this) || mStackSupervisor.isFocusedStack(this)) {
1584            return STACK_VISIBLE;
1585        }
1586
1587        final int stackIndex = mStacks.indexOf(this);
1588
1589        if (stackIndex == mStacks.size() - 1) {
1590            Slog.wtf(TAG,
1591                    "Stack=" + this + " isn't front stack but is at the top of the stack list");
1592            return STACK_INVISIBLE;
1593        }
1594
1595        final boolean isLockscreenShown = mService.mLockScreenShown == LOCK_SCREEN_SHOWN;
1596        if (isLockscreenShown && !StackId.isAllowedOverLockscreen(mStackId)) {
1597            return STACK_INVISIBLE;
1598        }
1599
1600        final ActivityStack focusedStack = mStackSupervisor.getFocusedStack();
1601        final int focusedStackId = focusedStack.mStackId;
1602
1603        if (mStackId == FULLSCREEN_WORKSPACE_STACK_ID
1604                && hasVisibleBehindActivity() && focusedStackId == HOME_STACK_ID
1605                && !focusedStack.topActivity().fullscreen) {
1606            // The fullscreen stack should be visible if it has a visible behind activity behind
1607            // the home stack that is translucent.
1608            return STACK_VISIBLE_ACTIVITY_BEHIND;
1609        }
1610
1611        if (mStackId == DOCKED_STACK_ID) {
1612            // Docked stack is always visible, except in the case where the top running activity
1613            // task in the focus stack doesn't support any form of resizing but we show it for the
1614            // home task even though it's not resizable.
1615            final ActivityRecord r = focusedStack.topRunningActivityLocked();
1616            final TaskRecord task = r != null ? r.task : null;
1617            return task == null || task.canGoInDockedStack() || task.isHomeTask() ? STACK_VISIBLE
1618                    : STACK_INVISIBLE;
1619        }
1620
1621        // Find the first stack behind focused stack that actually got something visible.
1622        int stackBehindFocusedIndex = mStacks.indexOf(focusedStack) - 1;
1623        while (stackBehindFocusedIndex >= 0 &&
1624                mStacks.get(stackBehindFocusedIndex).topRunningActivityLocked() == null) {
1625            stackBehindFocusedIndex--;
1626        }
1627        if ((focusedStackId == DOCKED_STACK_ID || focusedStackId == PINNED_STACK_ID)
1628                && stackIndex == stackBehindFocusedIndex) {
1629            // Stacks directly behind the docked or pinned stack are always visible.
1630            return STACK_VISIBLE;
1631        }
1632
1633        final int stackBehindFocusedId = (stackBehindFocusedIndex >= 0)
1634                ? mStacks.get(stackBehindFocusedIndex).mStackId : INVALID_STACK_ID;
1635
1636        if (focusedStackId == FULLSCREEN_WORKSPACE_STACK_ID
1637                && focusedStack.isStackTranslucent(starting, stackBehindFocusedId)) {
1638            // Stacks behind the fullscreen stack with a translucent activity are always
1639            // visible so they can act as a backdrop to the translucent activity.
1640            // For example, dialog activities
1641            if (stackIndex == stackBehindFocusedIndex) {
1642                return STACK_VISIBLE;
1643            }
1644            if (stackBehindFocusedIndex >= 0) {
1645                if ((stackBehindFocusedId == DOCKED_STACK_ID
1646                        || stackBehindFocusedId == PINNED_STACK_ID)
1647                        && stackIndex == (stackBehindFocusedIndex - 1)) {
1648                    // The stack behind the docked or pinned stack is also visible so we can have a
1649                    // complete backdrop to the translucent activity when the docked stack is up.
1650                    return STACK_VISIBLE;
1651                }
1652            }
1653        }
1654
1655        if (StackId.isStaticStack(mStackId)) {
1656            // Visibility of any static stack should have been determined by the conditions above.
1657            return STACK_INVISIBLE;
1658        }
1659
1660        for (int i = stackIndex + 1; i < mStacks.size(); i++) {
1661            final ActivityStack stack = mStacks.get(i);
1662
1663            if (!stack.mFullscreen && !stack.hasFullscreenTask()) {
1664                continue;
1665            }
1666
1667            if (!StackId.isDynamicStacksVisibleBehindAllowed(stack.mStackId)) {
1668                // These stacks can't have any dynamic stacks visible behind them.
1669                return STACK_INVISIBLE;
1670            }
1671
1672            if (!stack.isStackTranslucent(starting, INVALID_STACK_ID)) {
1673                return STACK_INVISIBLE;
1674            }
1675        }
1676
1677        return STACK_VISIBLE;
1678    }
1679
1680    final int rankTaskLayers(int baseLayer) {
1681        int layer = 0;
1682        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1683            final TaskRecord task = mTaskHistory.get(taskNdx);
1684            ActivityRecord r = task.topRunningActivityLocked();
1685            if (r == null || r.finishing || !r.visible) {
1686                task.mLayerRank = -1;
1687            } else {
1688                task.mLayerRank = baseLayer + layer++;
1689            }
1690        }
1691        return layer;
1692    }
1693
1694    /**
1695     * Make sure that all activities that need to be visible (that is, they
1696     * currently can be seen by the user) actually are.
1697     */
1698    final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
1699            boolean preserveWindows) {
1700        ActivityRecord top = topRunningActivityLocked();
1701        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "ensureActivitiesVisible behind " + top
1702                + " configChanges=0x" + Integer.toHexString(configChanges));
1703        if (top != null) {
1704            checkTranslucentActivityWaiting(top);
1705        }
1706
1707        // If the top activity is not fullscreen, then we need to
1708        // make sure any activities under it are now visible.
1709        boolean aboveTop = top != null;
1710        final int stackVisibility = getStackVisibilityLocked(starting);
1711        final boolean stackInvisible = stackVisibility != STACK_VISIBLE;
1712        final boolean stackVisibleBehind = stackVisibility == STACK_VISIBLE_ACTIVITY_BEHIND;
1713        boolean behindFullscreenActivity = stackInvisible;
1714        boolean resumeNextActivity = isFocusable() && (isInStackLocked(starting) == null);
1715        boolean behindTranslucentActivity = false;
1716        final ActivityRecord visibleBehind = getVisibleBehindActivity();
1717        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1718            final TaskRecord task = mTaskHistory.get(taskNdx);
1719            final ArrayList<ActivityRecord> activities = task.mActivities;
1720            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1721                final ActivityRecord r = activities.get(activityNdx);
1722                if (r.finishing) {
1723                    // Normally the screenshot will be taken in makeInvisible(). When an activity
1724                    // is finishing, we no longer change its visibility, but we still need to take
1725                    // the screenshots if startPausingLocked decided it should be taken.
1726                    if (r.mUpdateTaskThumbnailWhenHidden) {
1727                        r.updateThumbnailLocked(screenshotActivitiesLocked(r), null);
1728                        r.mUpdateTaskThumbnailWhenHidden = false;
1729                    }
1730                    continue;
1731                }
1732                final boolean isTop = r == top;
1733                if (aboveTop && !isTop) {
1734                    continue;
1735                }
1736                aboveTop = false;
1737
1738                if (shouldBeVisible(r, behindTranslucentActivity, stackVisibleBehind,
1739                        visibleBehind, behindFullscreenActivity)) {
1740                    if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Make visible? " + r
1741                            + " finishing=" + r.finishing + " state=" + r.state);
1742                    // First: if this is not the current activity being started, make
1743                    // sure it matches the current configuration.
1744                    if (r != starting) {
1745                        ensureActivityConfigurationLocked(r, 0, preserveWindows);
1746                    }
1747
1748                    if (r.app == null || r.app.thread == null) {
1749                        if (makeVisibleAndRestartIfNeeded(starting, configChanges, isTop,
1750                                resumeNextActivity, r)) {
1751                            if (activityNdx >= activities.size()) {
1752                                // Record may be removed if its process needs to restart.
1753                                activityNdx = activities.size() - 1;
1754                            } else {
1755                                resumeNextActivity = false;
1756                            }
1757                        }
1758                    } else if (r.visible) {
1759                        // If this activity is already visible, then there is nothing to do here.
1760                        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
1761                                "Skipping: already visible at " + r);
1762
1763                        if (handleAlreadyVisible(r)) {
1764                            resumeNextActivity = false;
1765                        }
1766                    } else {
1767                        makeVisibleIfNeeded(starting, r);
1768                    }
1769                    // Aggregate current change flags.
1770                    configChanges |= r.configChangeFlags;
1771                    behindFullscreenActivity = updateBehindFullscreen(stackInvisible,
1772                            behindFullscreenActivity, task, r);
1773                    if (behindFullscreenActivity && !r.fullscreen) {
1774                        behindTranslucentActivity = true;
1775                    }
1776                } else {
1777                    if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Make invisible? " + r
1778                            + " finishing=" + r.finishing + " state=" + r.state + " stackInvisible="
1779                            + stackInvisible + " behindFullscreenActivity="
1780                            + behindFullscreenActivity + " mLaunchTaskBehind="
1781                            + r.mLaunchTaskBehind);
1782                    makeInvisible(r, visibleBehind);
1783                }
1784            }
1785            if (mStackId == FREEFORM_WORKSPACE_STACK_ID) {
1786                // The visibility of tasks and the activities they contain in freeform stack are
1787                // determined individually unlike other stacks where the visibility or fullscreen
1788                // status of an activity in a previous task affects other.
1789                behindFullscreenActivity = stackVisibility == STACK_INVISIBLE;
1790            } else if (mStackId == HOME_STACK_ID) {
1791                if (task.isHomeTask()) {
1792                    if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Home task: at " + task
1793                            + " stackInvisible=" + stackInvisible
1794                            + " behindFullscreenActivity=" + behindFullscreenActivity);
1795                    // No other task in the home stack should be visible behind the home activity.
1796                    // Home activities is usually a translucent activity with the wallpaper behind
1797                    // them. However, when they don't have the wallpaper behind them, we want to
1798                    // show activities in the next application stack behind them vs. another
1799                    // task in the home stack like recents.
1800                    behindFullscreenActivity = true;
1801                } else if (task.isRecentsTask()
1802                        && task.getTaskToReturnTo() == APPLICATION_ACTIVITY_TYPE) {
1803                    if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
1804                            "Recents task returning to app: at " + task
1805                                    + " stackInvisible=" + stackInvisible
1806                                    + " behindFullscreenActivity=" + behindFullscreenActivity);
1807                    // We don't want any other tasks in the home stack visible if the recents
1808                    // activity is going to be returning to an application activity type.
1809                    // We do this to preserve the visible order the user used to get into the
1810                    // recents activity. The recents activity is normally translucent and if it
1811                    // doesn't have the wallpaper behind it the next activity in the home stack
1812                    // shouldn't be visible when the home stack is brought to the front to display
1813                    // the recents activity from an app.
1814                    behindFullscreenActivity = true;
1815                }
1816
1817            }
1818        }
1819
1820        if (mTranslucentActivityWaiting != null &&
1821                mUndrawnActivitiesBelowTopTranslucent.isEmpty()) {
1822            // Nothing is getting drawn or everything was already visible, don't wait for timeout.
1823            notifyActivityDrawnLocked(null);
1824        }
1825    }
1826
1827    /** Return true if the input activity should be made visible */
1828    private boolean shouldBeVisible(ActivityRecord r, boolean behindTranslucentActivity,
1829            boolean stackVisibleBehind, ActivityRecord visibleBehind,
1830            boolean behindFullscreenActivity) {
1831
1832        if (!okToShowLocked(r)
1833                || (mService.isSleepingOrShuttingDownLocked() && r.voiceSession == null)) {
1834            return false;
1835        }
1836
1837        // mLaunchingBehind: Activities launching behind are at the back of the task stack
1838        // but must be drawn initially for the animation as though they were visible.
1839        final boolean activityVisibleBehind =
1840                (behindTranslucentActivity || stackVisibleBehind) && visibleBehind == r;
1841
1842        boolean isVisible =
1843                !behindFullscreenActivity || r.mLaunchTaskBehind || activityVisibleBehind;
1844
1845        if (mService.mSupportsLeanbackOnly && isVisible && r.isRecentsActivity()) {
1846            // On devices that support leanback only (Android TV), Recents activity can only be
1847            // visible if the home stack is the focused stack or we are in split-screen mode.
1848            isVisible = mStackSupervisor.getStack(DOCKED_STACK_ID) != null
1849                    || mStackSupervisor.isFocusedStack(this);
1850        }
1851
1852        return isVisible;
1853    }
1854
1855    private void checkTranslucentActivityWaiting(ActivityRecord top) {
1856        if (mTranslucentActivityWaiting != top) {
1857            mUndrawnActivitiesBelowTopTranslucent.clear();
1858            if (mTranslucentActivityWaiting != null) {
1859                // Call the callback with a timeout indication.
1860                notifyActivityDrawnLocked(null);
1861                mTranslucentActivityWaiting = null;
1862            }
1863            mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG);
1864        }
1865    }
1866
1867    private boolean makeVisibleAndRestartIfNeeded(ActivityRecord starting, int configChanges,
1868            boolean isTop, boolean andResume, ActivityRecord r) {
1869        // We need to make sure the app is running if it's the top, or it is just made visible from
1870        // invisible. If the app is already visible, it must have died while it was visible. In this
1871        // case, we'll show the dead window but will not restart the app. Otherwise we could end up
1872        // thrashing.
1873        if (isTop || !r.visible) {
1874            // This activity needs to be visible, but isn't even running...
1875            // get it started and resume if no other stack in this stack is resumed.
1876            if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Start and freeze screen for " + r);
1877            if (r != starting) {
1878                r.startFreezingScreenLocked(r.app, configChanges);
1879            }
1880            if (!r.visible || r.mLaunchTaskBehind) {
1881                if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Starting and making visible: " + r);
1882                setVisible(r, true);
1883            }
1884            if (r != starting) {
1885                mStackSupervisor.startSpecificActivityLocked(r, andResume, false);
1886                return true;
1887            }
1888        }
1889        return false;
1890    }
1891
1892    private void makeInvisible(ActivityRecord r, ActivityRecord visibleBehind) {
1893        if (!r.visible) {
1894            if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Already invisible: " + r);
1895            return;
1896        }
1897        // Now for any activities that aren't visible to the user, make sure they no longer are
1898        // keeping the screen frozen.
1899        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Making invisible: " + r + " " + r.state);
1900        try {
1901            setVisible(r, false);
1902            switch (r.state) {
1903                case STOPPING:
1904                case STOPPED:
1905                    if (r.app != null && r.app.thread != null) {
1906                        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
1907                                "Scheduling invisibility: " + r);
1908                        r.app.thread.scheduleWindowVisibility(r.appToken, false);
1909                    }
1910                    break;
1911
1912                case INITIALIZING:
1913                case RESUMED:
1914                case PAUSING:
1915                case PAUSED:
1916                    // This case created for transitioning activities from
1917                    // translucent to opaque {@link Activity#convertToOpaque}.
1918                    if (visibleBehind == r) {
1919                        releaseBackgroundResources(r);
1920                    } else {
1921                        addToStopping(r, true /* immediate */);
1922                    }
1923                    break;
1924
1925                default:
1926                    break;
1927            }
1928        } catch (Exception e) {
1929            // Just skip on any failure; we'll make it visible when it next restarts.
1930            Slog.w(TAG, "Exception thrown making hidden: " + r.intent.getComponent(), e);
1931        }
1932    }
1933
1934    private boolean updateBehindFullscreen(boolean stackInvisible, boolean behindFullscreenActivity,
1935            TaskRecord task, ActivityRecord r) {
1936        if (r.fullscreen) {
1937            if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Fullscreen: at " + r
1938                        + " stackInvisible=" + stackInvisible
1939                        + " behindFullscreenActivity=" + behindFullscreenActivity);
1940            // At this point, nothing else needs to be shown in this task.
1941            behindFullscreenActivity = true;
1942        } else if (!isHomeStack() && r.frontOfTask && task.isOverHomeStack()) {
1943            if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Showing home: at " + r
1944                    + " stackInvisible=" + stackInvisible
1945                    + " behindFullscreenActivity=" + behindFullscreenActivity);
1946            behindFullscreenActivity = true;
1947        }
1948        return behindFullscreenActivity;
1949    }
1950
1951    private void makeVisibleIfNeeded(ActivityRecord starting, ActivityRecord r) {
1952
1953        // This activity is not currently visible, but is running. Tell it to become visible.
1954        if (r.state == ActivityState.RESUMED || r == starting) {
1955            if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY,
1956                    "Not making visible, r=" + r + " state=" + r.state + " starting=" + starting);
1957            return;
1958        }
1959
1960        // If this activity is paused, tell it to now show its window.
1961        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
1962                "Making visible and scheduling visibility: " + r);
1963        try {
1964            if (mTranslucentActivityWaiting != null) {
1965                r.updateOptionsLocked(r.returningOptions);
1966                mUndrawnActivitiesBelowTopTranslucent.add(r);
1967            }
1968            setVisible(r, true);
1969            r.sleeping = false;
1970            r.app.pendingUiClean = true;
1971            r.app.thread.scheduleWindowVisibility(r.appToken, true);
1972            // The activity may be waiting for stop, but that is no longer
1973            // appropriate for it.
1974            mStackSupervisor.mStoppingActivities.remove(r);
1975            mStackSupervisor.mGoingToSleepActivities.remove(r);
1976        } catch (Exception e) {
1977            // Just skip on any failure; we'll make it
1978            // visible when it next restarts.
1979            Slog.w(TAG, "Exception thrown making visibile: " + r.intent.getComponent(), e);
1980        }
1981        handleAlreadyVisible(r);
1982    }
1983
1984    private boolean handleAlreadyVisible(ActivityRecord r) {
1985        r.stopFreezingScreenLocked(false);
1986        try {
1987            if (r.returningOptions != null) {
1988                r.app.thread.scheduleOnNewActivityOptions(r.appToken, r.returningOptions);
1989            }
1990        } catch(RemoteException e) {
1991        }
1992        return r.state == ActivityState.RESUMED;
1993    }
1994
1995    void convertActivityToTranslucent(ActivityRecord r) {
1996        mTranslucentActivityWaiting = r;
1997        mUndrawnActivitiesBelowTopTranslucent.clear();
1998        mHandler.sendEmptyMessageDelayed(TRANSLUCENT_TIMEOUT_MSG, TRANSLUCENT_CONVERSION_TIMEOUT);
1999    }
2000
2001    void clearOtherAppTimeTrackers(AppTimeTracker except) {
2002        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2003            final TaskRecord task = mTaskHistory.get(taskNdx);
2004            final ArrayList<ActivityRecord> activities = task.mActivities;
2005            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2006                final ActivityRecord r = activities.get(activityNdx);
2007                if ( r.appTimeTracker != except) {
2008                    r.appTimeTracker = null;
2009                }
2010            }
2011        }
2012    }
2013
2014    /**
2015     * Called as activities below the top translucent activity are redrawn. When the last one is
2016     * redrawn notify the top activity by calling
2017     * {@link Activity#onTranslucentConversionComplete}.
2018     *
2019     * @param r The most recent background activity to be drawn. Or, if r is null then a timeout
2020     * occurred and the activity will be notified immediately.
2021     */
2022    void notifyActivityDrawnLocked(ActivityRecord r) {
2023        mActivityContainer.setDrawn();
2024        if ((r == null)
2025                || (mUndrawnActivitiesBelowTopTranslucent.remove(r) &&
2026                        mUndrawnActivitiesBelowTopTranslucent.isEmpty())) {
2027            // The last undrawn activity below the top has just been drawn. If there is an
2028            // opaque activity at the top, notify it that it can become translucent safely now.
2029            final ActivityRecord waitingActivity = mTranslucentActivityWaiting;
2030            mTranslucentActivityWaiting = null;
2031            mUndrawnActivitiesBelowTopTranslucent.clear();
2032            mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG);
2033
2034            if (waitingActivity != null) {
2035                mWindowManager.setWindowOpaque(waitingActivity.appToken, false);
2036                if (waitingActivity.app != null && waitingActivity.app.thread != null) {
2037                    try {
2038                        waitingActivity.app.thread.scheduleTranslucentConversionComplete(
2039                                waitingActivity.appToken, r != null);
2040                    } catch (RemoteException e) {
2041                    }
2042                }
2043            }
2044        }
2045    }
2046
2047    /** If any activities below the top running one are in the INITIALIZING state and they have a
2048     * starting window displayed then remove that starting window. It is possible that the activity
2049     * in this state will never resumed in which case that starting window will be orphaned. */
2050    void cancelInitializingActivities() {
2051        final ActivityRecord topActivity = topRunningActivityLocked();
2052        boolean aboveTop = true;
2053        // We don't want to clear starting window for activities that aren't behind fullscreen
2054        // activities as we need to display their starting window until they are done initializing.
2055        boolean behindFullscreenActivity = false;
2056        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2057            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2058            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2059                final ActivityRecord r = activities.get(activityNdx);
2060                if (aboveTop) {
2061                    if (r == topActivity) {
2062                        aboveTop = false;
2063                    }
2064                    behindFullscreenActivity |= r.fullscreen;
2065                    continue;
2066                }
2067
2068                if (r.state == ActivityState.INITIALIZING
2069                        && r.mStartingWindowState == STARTING_WINDOW_SHOWN
2070                        && behindFullscreenActivity) {
2071                    if (DEBUG_VISIBILITY) Slog.w(TAG_VISIBILITY,
2072                            "Found orphaned starting window " + r);
2073                    r.mStartingWindowState = STARTING_WINDOW_REMOVED;
2074                    mWindowManager.removeAppStartingWindow(r.appToken);
2075                }
2076
2077                behindFullscreenActivity |= r.fullscreen;
2078            }
2079        }
2080    }
2081
2082    /**
2083     * Ensure that the top activity in the stack is resumed.
2084     *
2085     * @param prev The previously resumed activity, for when in the process
2086     * of pausing; can be null to call from elsewhere.
2087     * @param options Activity options.
2088     *
2089     * @return Returns true if something is being resumed, or false if
2090     * nothing happened.
2091     *
2092     * NOTE: It is not safe to call this method directly as it can cause an activity in a
2093     *       non-focused stack to be resumed.
2094     *       Use {@link ActivityStackSupervisor#resumeFocusedStackTopActivityLocked} to resume the
2095     *       right activity for the current system state.
2096     */
2097    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
2098        if (mStackSupervisor.inResumeTopActivity) {
2099            // Don't even start recursing.
2100            return false;
2101        }
2102
2103        boolean result = false;
2104        try {
2105            // Protect against recursion.
2106            mStackSupervisor.inResumeTopActivity = true;
2107            if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
2108                mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
2109                mService.updateSleepIfNeededLocked();
2110            }
2111            result = resumeTopActivityInnerLocked(prev, options);
2112        } finally {
2113            mStackSupervisor.inResumeTopActivity = false;
2114        }
2115        return result;
2116    }
2117
2118    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
2119        if (DEBUG_LOCKSCREEN) mService.logLockScreen("");
2120
2121        if (!mService.mBooting && !mService.mBooted) {
2122            // Not ready yet!
2123            return false;
2124        }
2125
2126        ActivityRecord parent = mActivityContainer.mParentActivity;
2127        if ((parent != null && parent.state != ActivityState.RESUMED) ||
2128                !mActivityContainer.isAttachedLocked()) {
2129            // Do not resume this stack if its parent is not resumed.
2130            // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st.
2131            return false;
2132        }
2133
2134        mStackSupervisor.cancelInitializingActivities();
2135
2136        // Find the first activity that is not finishing.
2137        final ActivityRecord next = topRunningActivityLocked();
2138
2139        // Remember how we'll process this pause/resume situation, and ensure
2140        // that the state is reset however we wind up proceeding.
2141        final boolean userLeaving = mStackSupervisor.mUserLeaving;
2142        mStackSupervisor.mUserLeaving = false;
2143
2144        final TaskRecord prevTask = prev != null ? prev.task : null;
2145        if (next == null) {
2146            // There are no more activities!
2147            final String reason = "noMoreActivities";
2148            final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack()
2149                    ? HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
2150            if (!mFullscreen && adjustFocusToNextFocusableStackLocked(returnTaskType, reason)) {
2151                // Try to move focus to the next visible stack with a running activity if this
2152                // stack is not covering the entire screen.
2153                return mStackSupervisor.resumeFocusedStackTopActivityLocked(
2154                        mStackSupervisor.getFocusedStack(), prev, null);
2155            }
2156
2157            // Let's just start up the Launcher...
2158            ActivityOptions.abort(options);
2159            if (DEBUG_STATES) Slog.d(TAG_STATES,
2160                    "resumeTopActivityLocked: No more activities go home");
2161            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2162            // Only resume home if on home display
2163            return isOnHomeDisplay() &&
2164                    mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
2165        }
2166
2167        next.delayedResume = false;
2168
2169        // If the top activity is the resumed one, nothing to do.
2170        if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
2171                    mStackSupervisor.allResumedActivitiesComplete()) {
2172            // Make sure we have executed any pending transitions, since there
2173            // should be nothing left to do at this point.
2174            mWindowManager.executeAppTransition();
2175            mNoAnimActivities.clear();
2176            ActivityOptions.abort(options);
2177            if (DEBUG_STATES) Slog.d(TAG_STATES,
2178                    "resumeTopActivityLocked: Top activity resumed " + next);
2179            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2180            return false;
2181        }
2182
2183        final TaskRecord nextTask = next.task;
2184        if (prevTask != null && prevTask.stack == this &&
2185                prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
2186            if (DEBUG_STACK)  mStackSupervisor.validateTopActivitiesLocked();
2187            if (prevTask == nextTask) {
2188                prevTask.setFrontOfTask();
2189            } else if (prevTask != topTask()) {
2190                // This task is going away but it was supposed to return to the home stack.
2191                // Now the task above it has to return to the home task instead.
2192                final int taskNdx = mTaskHistory.indexOf(prevTask) + 1;
2193                mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE);
2194            } else if (!isOnHomeDisplay()) {
2195                return false;
2196            } else if (!isHomeStack()){
2197                if (DEBUG_STATES) Slog.d(TAG_STATES,
2198                        "resumeTopActivityLocked: Launching home next");
2199                final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
2200                        HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
2201                return isOnHomeDisplay() &&
2202                        mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "prevFinished");
2203            }
2204        }
2205
2206        // If we are sleeping, and there is no resumed activity, and the top
2207        // activity is paused, well that is the state we want.
2208        if (mService.isSleepingOrShuttingDownLocked()
2209                && mLastPausedActivity == next
2210                && mStackSupervisor.allPausedActivitiesComplete()) {
2211            // Make sure we have executed any pending transitions, since there
2212            // should be nothing left to do at this point.
2213            mWindowManager.executeAppTransition();
2214            mNoAnimActivities.clear();
2215            ActivityOptions.abort(options);
2216            if (DEBUG_STATES) Slog.d(TAG_STATES,
2217                    "resumeTopActivityLocked: Going to sleep and all paused");
2218            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2219            return false;
2220        }
2221
2222        // Make sure that the user who owns this activity is started.  If not,
2223        // we will just leave it as is because someone should be bringing
2224        // another user's activities to the top of the stack.
2225        if (!mService.mUserController.hasStartedUserState(next.userId)) {
2226            Slog.w(TAG, "Skipping resume of top activity " + next
2227                    + ": user " + next.userId + " is stopped");
2228            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2229            return false;
2230        }
2231
2232        // The activity may be waiting for stop, but that is no longer
2233        // appropriate for it.
2234        mStackSupervisor.mStoppingActivities.remove(next);
2235        mStackSupervisor.mGoingToSleepActivities.remove(next);
2236        next.sleeping = false;
2237        mStackSupervisor.mWaitingVisibleActivities.remove(next);
2238
2239        if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resuming " + next);
2240
2241        // If we are currently pausing an activity, then don't do anything until that is done.
2242        if (!mStackSupervisor.allPausedActivitiesComplete()) {
2243            if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
2244                    "resumeTopActivityLocked: Skip resume: some activity pausing.");
2245            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2246            return false;
2247        }
2248
2249        mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
2250
2251        // We need to start pausing the current activity so the top one can be resumed...
2252        final boolean dontWaitForPause = (next.info.flags & FLAG_RESUME_WHILE_PAUSING) != 0;
2253        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
2254        if (mResumedActivity != null) {
2255            if (DEBUG_STATES) Slog.d(TAG_STATES,
2256                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
2257            pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
2258        }
2259        if (pausing) {
2260            if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG_STATES,
2261                    "resumeTopActivityLocked: Skip resume: need to start pausing");
2262            // At this point we want to put the upcoming activity's process
2263            // at the top of the LRU list, since we know we will be needing it
2264            // very soon and it would be a waste to let it get killed if it
2265            // happens to be sitting towards the end.
2266            if (next.app != null && next.app.thread != null) {
2267                mService.updateLruProcessLocked(next.app, true, null);
2268            }
2269            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2270            return true;
2271        } else if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
2272                mStackSupervisor.allResumedActivitiesComplete()) {
2273            // It is possible for the activity to be resumed when we paused back stacks above if the
2274            // next activity doesn't have to wait for pause to complete.
2275            // So, nothing else to-do except:
2276            // Make sure we have executed any pending transitions, since there
2277            // should be nothing left to do at this point.
2278            mWindowManager.executeAppTransition();
2279            mNoAnimActivities.clear();
2280            ActivityOptions.abort(options);
2281            if (DEBUG_STATES) Slog.d(TAG_STATES,
2282                    "resumeTopActivityLocked: Top activity resumed (dontWaitForPause) " + next);
2283            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2284            return true;
2285        }
2286
2287        // If the most recent activity was noHistory but was only stopped rather
2288        // than stopped+finished because the device went to sleep, we need to make
2289        // sure to finish it as we're making a new activity topmost.
2290        if (mService.isSleepingLocked() && mLastNoHistoryActivity != null &&
2291                !mLastNoHistoryActivity.finishing) {
2292            if (DEBUG_STATES) Slog.d(TAG_STATES,
2293                    "no-history finish of " + mLastNoHistoryActivity + " on new resume");
2294            requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
2295                    null, "resume-no-history", false);
2296            mLastNoHistoryActivity = null;
2297        }
2298
2299        if (prev != null && prev != next) {
2300            if (!mStackSupervisor.mWaitingVisibleActivities.contains(prev)
2301                    && next != null && !next.nowVisible) {
2302                mStackSupervisor.mWaitingVisibleActivities.add(prev);
2303                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
2304                        "Resuming top, waiting visible to hide: " + prev);
2305            } else {
2306                // The next activity is already visible, so hide the previous
2307                // activity's windows right now so we can show the new one ASAP.
2308                // We only do this if the previous is finishing, which should mean
2309                // it is on top of the one being resumed so hiding it quickly
2310                // is good.  Otherwise, we want to do the normal route of allowing
2311                // the resumed activity to be shown so we can decide if the
2312                // previous should actually be hidden depending on whether the
2313                // new one is found to be full-screen or not.
2314                if (prev.finishing) {
2315                    mWindowManager.setAppVisibility(prev.appToken, false);
2316                    if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
2317                            "Not waiting for visible to hide: " + prev + ", waitingVisible="
2318                            + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
2319                            + ", nowVisible=" + next.nowVisible);
2320                } else {
2321                    if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
2322                            "Previous already visible but still waiting to hide: " + prev
2323                            + ", waitingVisible="
2324                            + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
2325                            + ", nowVisible=" + next.nowVisible);
2326                }
2327            }
2328        }
2329
2330        // Launching this app's activity, make sure the app is no longer
2331        // considered stopped.
2332        try {
2333            AppGlobals.getPackageManager().setPackageStoppedState(
2334                    next.packageName, false, next.userId); /* TODO: Verify if correct userid */
2335        } catch (RemoteException e1) {
2336        } catch (IllegalArgumentException e) {
2337            Slog.w(TAG, "Failed trying to unstop package "
2338                    + next.packageName + ": " + e);
2339        }
2340
2341        // We are starting up the next activity, so tell the window manager
2342        // that the previous one will be hidden soon.  This way it can know
2343        // to ignore it when computing the desired screen orientation.
2344        boolean anim = true;
2345        if (prev != null) {
2346            if (prev.finishing) {
2347                if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
2348                        "Prepare close transition: prev=" + prev);
2349                if (mNoAnimActivities.contains(prev)) {
2350                    anim = false;
2351                    mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
2352                } else {
2353                    mWindowManager.prepareAppTransition(prev.task == next.task
2354                            ? TRANSIT_ACTIVITY_CLOSE
2355                            : TRANSIT_TASK_CLOSE, false);
2356                }
2357                mWindowManager.setAppVisibility(prev.appToken, false);
2358            } else {
2359                if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
2360                        "Prepare open transition: prev=" + prev);
2361                if (mNoAnimActivities.contains(next)) {
2362                    anim = false;
2363                    mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
2364                } else {
2365                    mWindowManager.prepareAppTransition(prev.task == next.task
2366                            ? TRANSIT_ACTIVITY_OPEN
2367                            : next.mLaunchTaskBehind
2368                                    ? TRANSIT_TASK_OPEN_BEHIND
2369                                    : TRANSIT_TASK_OPEN, false);
2370                }
2371            }
2372        } else {
2373            if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare open transition: no previous");
2374            if (mNoAnimActivities.contains(next)) {
2375                anim = false;
2376                mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
2377            } else {
2378                mWindowManager.prepareAppTransition(TRANSIT_ACTIVITY_OPEN, false);
2379            }
2380        }
2381
2382        Bundle resumeAnimOptions = null;
2383        if (anim) {
2384            ActivityOptions opts = next.getOptionsForTargetActivityLocked();
2385            if (opts != null) {
2386                resumeAnimOptions = opts.toBundle();
2387            }
2388            next.applyOptionsLocked();
2389        } else {
2390            next.clearOptionsLocked();
2391        }
2392
2393        ActivityStack lastStack = mStackSupervisor.getLastStack();
2394        if (next.app != null && next.app.thread != null) {
2395            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resume running: " + next
2396                    + " stopped=" + next.stopped + " visible=" + next.visible);
2397
2398            // If the previous activity is translucent, force a visibility update of
2399            // the next activity, so that it's added to WM's opening app list, and
2400            // transition animation can be set up properly.
2401            // For example, pressing Home button with a translucent activity in focus.
2402            // Launcher is already visible in this case. If we don't add it to opening
2403            // apps, maybeUpdateTransitToWallpaper() will fail to identify this as a
2404            // TRANSIT_WALLPAPER_OPEN animation, and run some funny animation.
2405            final boolean lastActivityTranslucent = lastStack != null
2406                    && (!lastStack.mFullscreen
2407                    || (lastStack.mLastPausedActivity != null
2408                    && !lastStack.mLastPausedActivity.fullscreen));
2409
2410            // This activity is now becoming visible.
2411            if (!next.visible || next.stopped || lastActivityTranslucent) {
2412                mWindowManager.setAppVisibility(next.appToken, true);
2413            }
2414
2415            // schedule launch ticks to collect information about slow apps.
2416            next.startLaunchTickingLocked();
2417
2418            ActivityRecord lastResumedActivity =
2419                    lastStack == null ? null :lastStack.mResumedActivity;
2420            ActivityState lastState = next.state;
2421
2422            mService.updateCpuStats();
2423
2424            if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + next + " (in existing)");
2425            next.state = ActivityState.RESUMED;
2426            mResumedActivity = next;
2427            next.task.touchActiveTime();
2428            mRecentTasks.addLocked(next.task);
2429            mService.updateLruProcessLocked(next.app, true, null);
2430            updateLRUListLocked(next);
2431            mService.updateOomAdjLocked();
2432
2433            // Have the window manager re-evaluate the orientation of
2434            // the screen based on the new activity order.
2435            boolean notUpdated = true;
2436            if (mStackSupervisor.isFocusedStack(this)) {
2437                Configuration config = mWindowManager.updateOrientationFromAppTokens(
2438                        mService.mConfiguration,
2439                        next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
2440                if (config != null) {
2441                    next.frozenBeforeDestroy = true;
2442                }
2443                notUpdated = !mService.updateConfigurationLocked(config, next, false);
2444            }
2445
2446            if (notUpdated) {
2447                // The configuration update wasn't able to keep the existing
2448                // instance of the activity, and instead started a new one.
2449                // We should be all done, but let's just make sure our activity
2450                // is still at the top and schedule another run if something
2451                // weird happened.
2452                ActivityRecord nextNext = topRunningActivityLocked();
2453                if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_STATES,
2454                        "Activity config changed during resume: " + next
2455                        + ", new next: " + nextNext);
2456                if (nextNext != next) {
2457                    // Do over!
2458                    mStackSupervisor.scheduleResumeTopActivities();
2459                }
2460                if (mStackSupervisor.reportResumedActivityLocked(next)) {
2461                    mNoAnimActivities.clear();
2462                    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2463                    return true;
2464                }
2465                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2466                return false;
2467            }
2468
2469            try {
2470                // Deliver all pending results.
2471                ArrayList<ResultInfo> a = next.results;
2472                if (a != null) {
2473                    final int N = a.size();
2474                    if (!next.finishing && N > 0) {
2475                        if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
2476                                "Delivering results to " + next + ": " + a);
2477                        next.app.thread.scheduleSendResult(next.appToken, a);
2478                    }
2479                }
2480
2481                if (next.newIntents != null) {
2482                    next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
2483                }
2484
2485                // Well the app will no longer be stopped.
2486                // Clear app token stopped state in window manager if needed.
2487                mWindowManager.notifyAppStopped(next.appToken, false);
2488
2489                EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, next.userId,
2490                        System.identityHashCode(next), next.task.taskId, next.shortComponentName);
2491
2492                next.sleeping = false;
2493                mService.showUnsupportedZoomDialogIfNeededLocked(next);
2494                mService.showAskCompatModeDialogLocked(next);
2495                next.app.pendingUiClean = true;
2496                next.app.forceProcessStateUpTo(mService.mTopProcessState);
2497                next.clearOptionsLocked();
2498                next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
2499                        mService.isNextTransitionForward(), resumeAnimOptions);
2500
2501                mStackSupervisor.checkReadyForSleepLocked();
2502
2503                if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Resumed " + next);
2504            } catch (Exception e) {
2505                // Whoops, need to restart this activity!
2506                if (DEBUG_STATES) Slog.v(TAG_STATES, "Resume failed; resetting state to "
2507                        + lastState + ": " + next);
2508                next.state = lastState;
2509                if (lastStack != null) {
2510                    lastStack.mResumedActivity = lastResumedActivity;
2511                }
2512                Slog.i(TAG, "Restarting because process died: " + next);
2513                if (!next.hasBeenLaunched) {
2514                    next.hasBeenLaunched = true;
2515                } else  if (SHOW_APP_STARTING_PREVIEW && lastStack != null &&
2516                        mStackSupervisor.isFrontStack(lastStack)) {
2517                    next.showStartingWindow(null, true);
2518                }
2519                mStackSupervisor.startSpecificActivityLocked(next, true, false);
2520                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2521                return true;
2522            }
2523
2524            // From this point on, if something goes wrong there is no way
2525            // to recover the activity.
2526            try {
2527                completeResumeLocked(next);
2528            } catch (Exception e) {
2529                // If any exception gets thrown, toss away this
2530                // activity and try the next one.
2531                Slog.w(TAG, "Exception thrown during resume of " + next, e);
2532                requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
2533                        "resume-exception", true);
2534                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2535                return true;
2536            }
2537        } else {
2538            // Whoops, need to restart this activity!
2539            if (!next.hasBeenLaunched) {
2540                next.hasBeenLaunched = true;
2541            } else {
2542                if (SHOW_APP_STARTING_PREVIEW) {
2543                    next.showStartingWindow(null, true);
2544                }
2545                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
2546            }
2547            if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
2548            mStackSupervisor.startSpecificActivityLocked(next, true, true);
2549        }
2550
2551        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
2552        return true;
2553    }
2554
2555    private TaskRecord getNextTask(TaskRecord targetTask) {
2556        final int index = mTaskHistory.indexOf(targetTask);
2557        if (index >= 0) {
2558            final int numTasks = mTaskHistory.size();
2559            for (int i = index + 1; i < numTasks; ++i) {
2560                TaskRecord task = mTaskHistory.get(i);
2561                if (task.userId == targetTask.userId) {
2562                    return task;
2563                }
2564            }
2565        }
2566        return null;
2567    }
2568
2569    private void insertTaskAtPosition(TaskRecord task, int position) {
2570        if (position >= mTaskHistory.size()) {
2571            insertTaskAtTop(task, null);
2572            return;
2573        }
2574        // Calculate maximum possible position for this task.
2575        int maxPosition = mTaskHistory.size();
2576        if (!mStackSupervisor.isCurrentProfileLocked(task.userId)
2577                && task.topRunningActivityLocked() == null) {
2578            // Put non-current user tasks below current user tasks.
2579            while (maxPosition > 0) {
2580                final TaskRecord tmpTask = mTaskHistory.get(maxPosition - 1);
2581                if (!mStackSupervisor.isCurrentProfileLocked(tmpTask.userId)
2582                        || tmpTask.topRunningActivityLocked() == null) {
2583                    break;
2584                }
2585                maxPosition--;
2586            }
2587        }
2588        position = Math.min(position, maxPosition);
2589        mTaskHistory.remove(task);
2590        mTaskHistory.add(position, task);
2591        updateTaskMovement(task, true);
2592    }
2593
2594    private void insertTaskAtTop(TaskRecord task, ActivityRecord newActivity) {
2595        // If the moving task is over home stack, transfer its return type to next task
2596        if (task.isOverHomeStack()) {
2597            final TaskRecord nextTask = getNextTask(task);
2598            if (nextTask != null) {
2599                nextTask.setTaskToReturnTo(task.getTaskToReturnTo());
2600            }
2601        }
2602
2603        // If this is being moved to the top by another activity or being launched from the home
2604        // activity, set mTaskToReturnTo accordingly.
2605        if (isOnHomeDisplay()) {
2606            ActivityStack lastStack = mStackSupervisor.getLastStack();
2607            final boolean fromHome = lastStack.isHomeStack();
2608            if (!isHomeStack() && (fromHome || topTask() != task)) {
2609                int returnToType = APPLICATION_ACTIVITY_TYPE;
2610                if (fromHome && StackId.allowTopTaskToReturnHome(mStackId)) {
2611                    returnToType = lastStack.topTask() == null
2612                            ? HOME_ACTIVITY_TYPE : lastStack.topTask().taskType;
2613                }
2614                task.setTaskToReturnTo(returnToType);
2615            }
2616        } else {
2617            task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
2618        }
2619
2620        mTaskHistory.remove(task);
2621        // Now put task at top.
2622        int taskNdx = mTaskHistory.size();
2623        final boolean notShownWhenLocked =
2624                (newActivity != null && (newActivity.info.flags & FLAG_SHOW_FOR_ALL_USERS) == 0)
2625                || (newActivity == null && task.topRunningActivityLocked() == null);
2626        if (!mStackSupervisor.isCurrentProfileLocked(task.userId) && notShownWhenLocked) {
2627            // Put non-current user tasks below current user tasks.
2628            while (--taskNdx >= 0) {
2629                final TaskRecord tmpTask = mTaskHistory.get(taskNdx);
2630                if (!mStackSupervisor.isCurrentProfileLocked(tmpTask.userId)
2631                        || tmpTask.topRunningActivityLocked() == null) {
2632                    break;
2633                }
2634            }
2635            ++taskNdx;
2636        }
2637        mTaskHistory.add(taskNdx, task);
2638        updateTaskMovement(task, true);
2639    }
2640
2641    final void startActivityLocked(ActivityRecord r, boolean newTask, boolean keepCurTransition,
2642            ActivityOptions options) {
2643        TaskRecord rTask = r.task;
2644        final int taskId = rTask.taskId;
2645        // mLaunchTaskBehind tasks get placed at the back of the task stack.
2646        if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
2647            // Last activity in task had been removed or ActivityManagerService is reusing task.
2648            // Insert or replace.
2649            // Might not even be in.
2650            insertTaskAtTop(rTask, r);
2651            mWindowManager.moveTaskToTop(taskId);
2652        }
2653        TaskRecord task = null;
2654        if (!newTask) {
2655            // If starting in an existing task, find where that is...
2656            boolean startIt = true;
2657            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2658                task = mTaskHistory.get(taskNdx);
2659                if (task.getTopActivity() == null) {
2660                    // All activities in task are finishing.
2661                    continue;
2662                }
2663                if (task == r.task) {
2664                    // Here it is!  Now, if this is not yet visible to the
2665                    // user, then just add it without starting; it will
2666                    // get started when the user navigates back to it.
2667                    if (!startIt) {
2668                        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
2669                                + task, new RuntimeException("here").fillInStackTrace());
2670                        task.addActivityToTop(r);
2671                        r.putInHistory();
2672                        addConfigOverride(r, task);
2673                        if (VALIDATE_TOKENS) {
2674                            validateAppTokensLocked();
2675                        }
2676                        ActivityOptions.abort(options);
2677                        return;
2678                    }
2679                    break;
2680                } else if (task.numFullscreen > 0) {
2681                    startIt = false;
2682                }
2683            }
2684        }
2685
2686        // Place a new activity at top of stack, so it is next to interact
2687        // with the user.
2688
2689        // If we are not placing the new activity frontmost, we do not want
2690        // to deliver the onUserLeaving callback to the actual frontmost
2691        // activity
2692        if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
2693            mStackSupervisor.mUserLeaving = false;
2694            if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
2695                    "startActivity() behind front, mUserLeaving=false");
2696        }
2697
2698        task = r.task;
2699
2700        // Slot the activity into the history stack and proceed
2701        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
2702                new RuntimeException("here").fillInStackTrace());
2703        task.addActivityToTop(r);
2704        task.setFrontOfTask();
2705
2706        r.putInHistory();
2707        if (!isHomeStack() || numActivities() > 0) {
2708            // We want to show the starting preview window if we are
2709            // switching to a new task, or the next activity's process is
2710            // not currently running.
2711            boolean showStartingIcon = newTask;
2712            ProcessRecord proc = r.app;
2713            if (proc == null) {
2714                proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
2715            }
2716            if (proc == null || proc.thread == null) {
2717                showStartingIcon = true;
2718            }
2719            if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
2720                    "Prepare open transition: starting " + r);
2721            if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
2722                mWindowManager.prepareAppTransition(TRANSIT_NONE, keepCurTransition);
2723                mNoAnimActivities.add(r);
2724            } else {
2725                mWindowManager.prepareAppTransition(newTask
2726                        ? r.mLaunchTaskBehind
2727                                ? TRANSIT_TASK_OPEN_BEHIND
2728                                : TRANSIT_TASK_OPEN
2729                        : TRANSIT_ACTIVITY_OPEN, keepCurTransition);
2730                mNoAnimActivities.remove(r);
2731            }
2732            addConfigOverride(r, task);
2733            boolean doShow = true;
2734            if (newTask) {
2735                // Even though this activity is starting fresh, we still need
2736                // to reset it to make sure we apply affinities to move any
2737                // existing activities from other tasks in to it.
2738                // If the caller has requested that the target task be
2739                // reset, then do so.
2740                if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2741                    resetTaskIfNeededLocked(r, r);
2742                    doShow = topRunningNonDelayedActivityLocked(null) == r;
2743                }
2744            } else if (options != null && options.getAnimationType()
2745                    == ActivityOptions.ANIM_SCENE_TRANSITION) {
2746                doShow = false;
2747            }
2748            if (r.mLaunchTaskBehind) {
2749                // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we
2750                // tell WindowManager that r is visible even though it is at the back of the stack.
2751                mWindowManager.setAppVisibility(r.appToken, true);
2752                ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
2753            } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
2754                // Figure out if we are transitioning from another activity that is
2755                // "has the same starting icon" as the next one.  This allows the
2756                // window manager to keep the previous window it had previously
2757                // created, if it still had one.
2758                ActivityRecord prev = r.task.topRunningActivityWithStartingWindowLocked();
2759                if (prev != null) {
2760                    // We don't want to reuse the previous starting preview if:
2761                    // (1) The current activity is in a different task.
2762                    if (prev.task != r.task) {
2763                        prev = null;
2764                    }
2765                    // (2) The current activity is already displayed.
2766                    else if (prev.nowVisible) {
2767                        prev = null;
2768                    }
2769                }
2770                r.showStartingWindow(prev, showStartingIcon);
2771            }
2772        } else {
2773            // If this is the first activity, don't do any fancy animations,
2774            // because there is nothing for it to animate on top of.
2775            addConfigOverride(r, task);
2776            ActivityOptions.abort(options);
2777            options = null;
2778        }
2779        if (VALIDATE_TOKENS) {
2780            validateAppTokensLocked();
2781        }
2782    }
2783
2784    final void validateAppTokensLocked() {
2785        mValidateAppTokens.clear();
2786        mValidateAppTokens.ensureCapacity(numActivities());
2787        final int numTasks = mTaskHistory.size();
2788        for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) {
2789            TaskRecord task = mTaskHistory.get(taskNdx);
2790            final ArrayList<ActivityRecord> activities = task.mActivities;
2791            if (activities.isEmpty()) {
2792                continue;
2793            }
2794            TaskGroup group = new TaskGroup();
2795            group.taskId = task.taskId;
2796            mValidateAppTokens.add(group);
2797            final int numActivities = activities.size();
2798            for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
2799                final ActivityRecord r = activities.get(activityNdx);
2800                group.tokens.add(r.appToken);
2801            }
2802        }
2803        mWindowManager.validateAppTokens(mStackId, mValidateAppTokens);
2804    }
2805
2806    /**
2807     * Perform a reset of the given task, if needed as part of launching it.
2808     * Returns the new HistoryRecord at the top of the task.
2809     */
2810    /**
2811     * Helper method for #resetTaskIfNeededLocked.
2812     * We are inside of the task being reset...  we'll either finish this activity, push it out
2813     * for another task, or leave it as-is.
2814     * @param task The task containing the Activity (taskTop) that might be reset.
2815     * @param forceReset
2816     * @return An ActivityOptions that needs to be processed.
2817     */
2818    final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task, boolean forceReset) {
2819        ActivityOptions topOptions = null;
2820
2821        int replyChainEnd = -1;
2822        boolean canMoveOptions = true;
2823
2824        // We only do this for activities that are not the root of the task (since if we finish
2825        // the root, we may no longer have the task!).
2826        final ArrayList<ActivityRecord> activities = task.mActivities;
2827        final int numActivities = activities.size();
2828        final int rootActivityNdx = task.findEffectiveRootIndex();
2829        for (int i = numActivities - 1; i > rootActivityNdx; --i ) {
2830            ActivityRecord target = activities.get(i);
2831            if (target.frontOfTask)
2832                break;
2833
2834            final int flags = target.info.flags;
2835            final boolean finishOnTaskLaunch =
2836                    (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2837            final boolean allowTaskReparenting =
2838                    (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2839            final boolean clearWhenTaskReset =
2840                    (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2841
2842            if (!finishOnTaskLaunch
2843                    && !clearWhenTaskReset
2844                    && target.resultTo != null) {
2845                // If this activity is sending a reply to a previous
2846                // activity, we can't do anything with it now until
2847                // we reach the start of the reply chain.
2848                // XXX note that we are assuming the result is always
2849                // to the previous activity, which is almost always
2850                // the case but we really shouldn't count on.
2851                if (replyChainEnd < 0) {
2852                    replyChainEnd = i;
2853                }
2854            } else if (!finishOnTaskLaunch
2855                    && !clearWhenTaskReset
2856                    && allowTaskReparenting
2857                    && target.taskAffinity != null
2858                    && !target.taskAffinity.equals(task.affinity)) {
2859                // If this activity has an affinity for another
2860                // task, then we need to move it out of here.  We will
2861                // move it as far out of the way as possible, to the
2862                // bottom of the activity stack.  This also keeps it
2863                // correctly ordered with any activities we previously
2864                // moved.
2865                final TaskRecord targetTask;
2866                final ActivityRecord bottom =
2867                        !mTaskHistory.isEmpty() && !mTaskHistory.get(0).mActivities.isEmpty() ?
2868                                mTaskHistory.get(0).mActivities.get(0) : null;
2869                if (bottom != null && target.taskAffinity != null
2870                        && target.taskAffinity.equals(bottom.task.affinity)) {
2871                    // If the activity currently at the bottom has the
2872                    // same task affinity as the one we are moving,
2873                    // then merge it into the same task.
2874                    targetTask = bottom.task;
2875                    if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Start pushing activity " + target
2876                            + " out to bottom task " + bottom.task);
2877                } else {
2878                    targetTask = createTaskRecord(
2879                            mStackSupervisor.getNextTaskIdForUserLocked(target.userId),
2880                            target.info, null, null, null, false);
2881                    targetTask.affinityIntent = target.intent;
2882                    if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Start pushing activity " + target
2883                            + " out to new task " + target.task);
2884                }
2885
2886                setAppTask(target, targetTask);
2887
2888                boolean noOptions = canMoveOptions;
2889                final int start = replyChainEnd < 0 ? i : replyChainEnd;
2890                for (int srcPos = start; srcPos >= i; --srcPos) {
2891                    final ActivityRecord p = activities.get(srcPos);
2892                    if (p.finishing) {
2893                        continue;
2894                    }
2895
2896                    canMoveOptions = false;
2897                    if (noOptions && topOptions == null) {
2898                        topOptions = p.takeOptionsLocked();
2899                        if (topOptions != null) {
2900                            noOptions = false;
2901                        }
2902                    }
2903                    if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE,
2904                            "Removing activity " + p + " from task=" + task + " adding to task="
2905                            + targetTask + " Callers=" + Debug.getCallers(4));
2906                    if (DEBUG_TASKS) Slog.v(TAG_TASKS,
2907                            "Pushing next activity " + p + " out to target's task " + target.task);
2908                    p.setTask(targetTask, null);
2909                    targetTask.addActivityAtBottom(p);
2910
2911                    setAppTask(p, targetTask);
2912                }
2913
2914                mWindowManager.moveTaskToBottom(targetTask.taskId);
2915                if (VALIDATE_TOKENS) {
2916                    validateAppTokensLocked();
2917                }
2918
2919                replyChainEnd = -1;
2920            } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) {
2921                // If the activity should just be removed -- either
2922                // because it asks for it, or the task should be
2923                // cleared -- then finish it and anything that is
2924                // part of its reply chain.
2925                int end;
2926                if (clearWhenTaskReset) {
2927                    // In this case, we want to finish this activity
2928                    // and everything above it, so be sneaky and pretend
2929                    // like these are all in the reply chain.
2930                    end = activities.size() - 1;
2931                } else if (replyChainEnd < 0) {
2932                    end = i;
2933                } else {
2934                    end = replyChainEnd;
2935                }
2936                boolean noOptions = canMoveOptions;
2937                for (int srcPos = i; srcPos <= end; srcPos++) {
2938                    ActivityRecord p = activities.get(srcPos);
2939                    if (p.finishing) {
2940                        continue;
2941                    }
2942                    canMoveOptions = false;
2943                    if (noOptions && topOptions == null) {
2944                        topOptions = p.takeOptionsLocked();
2945                        if (topOptions != null) {
2946                            noOptions = false;
2947                        }
2948                    }
2949                    if (DEBUG_TASKS) Slog.w(TAG_TASKS,
2950                            "resetTaskIntendedTask: calling finishActivity on " + p);
2951                    if (finishActivityLocked(
2952                            p, Activity.RESULT_CANCELED, null, "reset-task", false)) {
2953                        end--;
2954                        srcPos--;
2955                    }
2956                }
2957                replyChainEnd = -1;
2958            } else {
2959                // If we were in the middle of a chain, well the
2960                // activity that started it all doesn't want anything
2961                // special, so leave it all as-is.
2962                replyChainEnd = -1;
2963            }
2964        }
2965
2966        return topOptions;
2967    }
2968
2969    /**
2970     * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given
2971     * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop.
2972     * @param affinityTask The task we are looking for an affinity to.
2973     * @param task Task that resetTaskIfNeededLocked.taskTop belongs to.
2974     * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked.
2975     * @param forceReset Flag passed in to resetTaskIfNeededLocked.
2976     */
2977    private int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task,
2978            boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) {
2979        int replyChainEnd = -1;
2980        final int taskId = task.taskId;
2981        final String taskAffinity = task.affinity;
2982
2983        final ArrayList<ActivityRecord> activities = affinityTask.mActivities;
2984        final int numActivities = activities.size();
2985        final int rootActivityNdx = affinityTask.findEffectiveRootIndex();
2986
2987        // Do not operate on or below the effective root Activity.
2988        for (int i = numActivities - 1; i > rootActivityNdx; --i) {
2989            ActivityRecord target = activities.get(i);
2990            if (target.frontOfTask)
2991                break;
2992
2993            final int flags = target.info.flags;
2994            boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2995            boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2996
2997            if (target.resultTo != null) {
2998                // If this activity is sending a reply to a previous
2999                // activity, we can't do anything with it now until
3000                // we reach the start of the reply chain.
3001                // XXX note that we are assuming the result is always
3002                // to the previous activity, which is almost always
3003                // the case but we really shouldn't count on.
3004                if (replyChainEnd < 0) {
3005                    replyChainEnd = i;
3006                }
3007            } else if (topTaskIsHigher
3008                    && allowTaskReparenting
3009                    && taskAffinity != null
3010                    && taskAffinity.equals(target.taskAffinity)) {
3011                // This activity has an affinity for our task. Either remove it if we are
3012                // clearing or move it over to our task.  Note that
3013                // we currently punt on the case where we are resetting a
3014                // task that is not at the top but who has activities above
3015                // with an affinity to it...  this is really not a normal
3016                // case, and we will need to later pull that task to the front
3017                // and usually at that point we will do the reset and pick
3018                // up those remaining activities.  (This only happens if
3019                // someone starts an activity in a new task from an activity
3020                // in a task that is not currently on top.)
3021                if (forceReset || finishOnTaskLaunch) {
3022                    final int start = replyChainEnd >= 0 ? replyChainEnd : i;
3023                    if (DEBUG_TASKS) Slog.v(TAG_TASKS,
3024                            "Finishing task at index " + start + " to " + i);
3025                    for (int srcPos = start; srcPos >= i; --srcPos) {
3026                        final ActivityRecord p = activities.get(srcPos);
3027                        if (p.finishing) {
3028                            continue;
3029                        }
3030                        finishActivityLocked(
3031                                p, Activity.RESULT_CANCELED, null, "move-affinity", false);
3032                    }
3033                } else {
3034                    if (taskInsertionPoint < 0) {
3035                        taskInsertionPoint = task.mActivities.size();
3036
3037                    }
3038
3039                    final int start = replyChainEnd >= 0 ? replyChainEnd : i;
3040                    if (DEBUG_TASKS) Slog.v(TAG_TASKS,
3041                            "Reparenting from task=" + affinityTask + ":" + start + "-" + i
3042                            + " to task=" + task + ":" + taskInsertionPoint);
3043                    for (int srcPos = start; srcPos >= i; --srcPos) {
3044                        final ActivityRecord p = activities.get(srcPos);
3045                        p.setTask(task, null);
3046                        task.addActivityAtIndex(taskInsertionPoint, p);
3047
3048                        if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE,
3049                                "Removing and adding activity " + p + " to stack at " + task
3050                                + " callers=" + Debug.getCallers(3));
3051                        if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Pulling activity " + p
3052                                + " from " + srcPos + " in to resetting task " + task);
3053                        setAppTask(p, task);
3054                    }
3055                    mWindowManager.moveTaskToTop(taskId);
3056                    if (VALIDATE_TOKENS) {
3057                        validateAppTokensLocked();
3058                    }
3059
3060                    // Now we've moved it in to place...  but what if this is
3061                    // a singleTop activity and we have put it on top of another
3062                    // instance of the same activity?  Then we drop the instance
3063                    // below so it remains singleTop.
3064                    if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
3065                        ArrayList<ActivityRecord> taskActivities = task.mActivities;
3066                        int targetNdx = taskActivities.indexOf(target);
3067                        if (targetNdx > 0) {
3068                            ActivityRecord p = taskActivities.get(targetNdx - 1);
3069                            if (p.intent.getComponent().equals(target.intent.getComponent())) {
3070                                finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace",
3071                                        false);
3072                            }
3073                        }
3074                    }
3075                }
3076
3077                replyChainEnd = -1;
3078            }
3079        }
3080        return taskInsertionPoint;
3081    }
3082
3083    final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
3084            ActivityRecord newActivity) {
3085        boolean forceReset =
3086                (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
3087        if (ACTIVITY_INACTIVE_RESET_TIME > 0
3088                && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
3089            if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
3090                forceReset = true;
3091            }
3092        }
3093
3094        final TaskRecord task = taskTop.task;
3095
3096        /** False until we evaluate the TaskRecord associated with taskTop. Switches to true
3097         * for remaining tasks. Used for later tasks to reparent to task. */
3098        boolean taskFound = false;
3099
3100        /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */
3101        ActivityOptions topOptions = null;
3102
3103        // Preserve the location for reparenting in the new task.
3104        int reparentInsertionPoint = -1;
3105
3106        for (int i = mTaskHistory.size() - 1; i >= 0; --i) {
3107            final TaskRecord targetTask = mTaskHistory.get(i);
3108
3109            if (targetTask == task) {
3110                topOptions = resetTargetTaskIfNeededLocked(task, forceReset);
3111                taskFound = true;
3112            } else {
3113                reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task,
3114                        taskFound, forceReset, reparentInsertionPoint);
3115            }
3116        }
3117
3118        int taskNdx = mTaskHistory.indexOf(task);
3119        if (taskNdx >= 0) {
3120            do {
3121                taskTop = mTaskHistory.get(taskNdx--).getTopActivity();
3122            } while (taskTop == null && taskNdx >= 0);
3123        }
3124
3125        if (topOptions != null) {
3126            // If we got some ActivityOptions from an activity on top that
3127            // was removed from the task, propagate them to the new real top.
3128            if (taskTop != null) {
3129                taskTop.updateOptionsLocked(topOptions);
3130            } else {
3131                topOptions.abort();
3132            }
3133        }
3134
3135        return taskTop;
3136    }
3137
3138    void sendActivityResultLocked(int callingUid, ActivityRecord r,
3139            String resultWho, int requestCode, int resultCode, Intent data) {
3140
3141        if (callingUid > 0) {
3142            mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
3143                    data, r.getUriPermissionsLocked(), r.userId);
3144        }
3145
3146        if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3147                + " : who=" + resultWho + " req=" + requestCode
3148                + " res=" + resultCode + " data=" + data);
3149        if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3150            try {
3151                ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3152                list.add(new ResultInfo(resultWho, requestCode,
3153                        resultCode, data));
3154                r.app.thread.scheduleSendResult(r.appToken, list);
3155                return;
3156            } catch (Exception e) {
3157                Slog.w(TAG, "Exception thrown sending result to " + r, e);
3158            }
3159        }
3160
3161        r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3162    }
3163
3164    private void adjustFocusedActivityLocked(ActivityRecord r, String reason) {
3165        if (!mStackSupervisor.isFocusedStack(this) || mService.mFocusedActivity != r) {
3166            return;
3167        }
3168
3169        final ActivityRecord next = topRunningActivityLocked();
3170        final String myReason = reason + " adjustFocus";
3171        if (next != r) {
3172            if (next != null && StackId.keepFocusInStackIfPossible(mStackId) && isFocusable()) {
3173                // For freeform, docked, and pinned stacks we always keep the focus within the
3174                // stack as long as there is a running activity in the stack that we can adjust
3175                // focus to.
3176                mService.setFocusedActivityLocked(next, myReason);
3177                return;
3178            } else {
3179                final TaskRecord task = r.task;
3180                if (r.frontOfTask && task == topTask() && task.isOverHomeStack()) {
3181                    final int taskToReturnTo = task.getTaskToReturnTo();
3182
3183                    // For non-fullscreen stack, we want to move the focus to the next visible
3184                    // stack to prevent the home screen from moving to the top and obscuring
3185                    // other visible stacks.
3186                    if (!mFullscreen
3187                            && adjustFocusToNextFocusableStackLocked(taskToReturnTo, myReason)) {
3188                        return;
3189                    }
3190                    // Move the home stack to the top if this stack is fullscreen or there is no
3191                    // other visible stack.
3192                    if (mStackSupervisor.moveHomeStackTaskToTop(taskToReturnTo, myReason)) {
3193                        // Activity focus was already adjusted. Nothing else to do...
3194                        return;
3195                    }
3196                }
3197            }
3198        }
3199
3200        mService.setFocusedActivityLocked(mStackSupervisor.topRunningActivityLocked(), myReason);
3201    }
3202
3203    private boolean adjustFocusToNextFocusableStackLocked(int taskToReturnTo, String reason) {
3204        final ActivityStack stack = getNextFocusableStackLocked();
3205        final String myReason = reason + " adjustFocusToNextFocusableStack";
3206        if (stack == null) {
3207            return false;
3208        }
3209
3210        final ActivityRecord top = stack.topRunningActivityLocked();
3211
3212        if (stack.isHomeStack() && (top == null || !top.visible)) {
3213            // If we will be focusing on the home stack next and its current top activity isn't
3214            // visible, then use the task return to value to determine the home task to display next.
3215            return mStackSupervisor.moveHomeStackTaskToTop(taskToReturnTo, reason);
3216        }
3217        return mService.setFocusedActivityLocked(top, myReason);
3218    }
3219
3220    final void stopActivityLocked(ActivityRecord r) {
3221        if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, "Stopping: " + r);
3222        if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3223                || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3224            if (!r.finishing) {
3225                if (!mService.isSleepingLocked()) {
3226                    if (DEBUG_STATES) Slog.d(TAG_STATES, "no-history finish of " + r);
3227                    if (requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
3228                            "stop-no-history", false)) {
3229                        // Activity was finished, no need to continue trying to schedule stop.
3230                        adjustFocusedActivityLocked(r, "stopActivityFinished");
3231                        r.resumeKeyDispatchingLocked();
3232                        return;
3233                    }
3234                } else {
3235                    if (DEBUG_STATES) Slog.d(TAG_STATES, "Not finishing noHistory " + r
3236                            + " on stop because we're just sleeping");
3237                }
3238            }
3239        }
3240
3241        if (r.app != null && r.app.thread != null) {
3242            adjustFocusedActivityLocked(r, "stopActivity");
3243            r.resumeKeyDispatchingLocked();
3244            try {
3245                r.stopped = false;
3246                if (DEBUG_STATES) Slog.v(TAG_STATES,
3247                        "Moving to STOPPING: " + r + " (stop requested)");
3248                r.state = ActivityState.STOPPING;
3249                if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
3250                        "Stopping visible=" + r.visible + " for " + r);
3251                if (!r.visible) {
3252                    mWindowManager.setAppVisibility(r.appToken, false);
3253                }
3254                EventLogTags.writeAmStopActivity(
3255                        r.userId, System.identityHashCode(r), r.shortComponentName);
3256                r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
3257                if (mService.isSleepingOrShuttingDownLocked()) {
3258                    r.setSleeping(true);
3259                }
3260                Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
3261                mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
3262            } catch (Exception e) {
3263                // Maybe just ignore exceptions here...  if the process
3264                // has crashed, our death notification will clean things
3265                // up.
3266                Slog.w(TAG, "Exception thrown during pause", e);
3267                // Just in case, assume it to be stopped.
3268                r.stopped = true;
3269                if (DEBUG_STATES) Slog.v(TAG_STATES, "Stop failed; moving to STOPPED: " + r);
3270                r.state = ActivityState.STOPPED;
3271                if (r.deferRelaunchUntilPaused) {
3272                    destroyActivityLocked(r, true, "stop-except");
3273                }
3274            }
3275        }
3276    }
3277
3278    /**
3279     * @return Returns true if the activity is being finished, false if for
3280     * some reason it is being left as-is.
3281     */
3282    final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3283            Intent resultData, String reason, boolean oomAdj) {
3284        ActivityRecord r = isInStackLocked(token);
3285        if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(TAG_STATES,
3286                "Finishing activity token=" + token + " r="
3287                + ", result=" + resultCode + ", data=" + resultData
3288                + ", reason=" + reason);
3289        if (r == null) {
3290            return false;
3291        }
3292
3293        finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
3294        return true;
3295    }
3296
3297    final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) {
3298        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3299            ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3300            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3301                ActivityRecord r = activities.get(activityNdx);
3302                if (r.resultTo == self && r.requestCode == requestCode) {
3303                    if ((r.resultWho == null && resultWho == null) ||
3304                        (r.resultWho != null && r.resultWho.equals(resultWho))) {
3305                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
3306                                false);
3307                    }
3308                }
3309            }
3310        }
3311        mService.updateOomAdjLocked();
3312    }
3313
3314    final TaskRecord finishTopRunningActivityLocked(ProcessRecord app, String reason) {
3315        ActivityRecord r = topRunningActivityLocked();
3316        TaskRecord finishedTask = null;
3317        if (r == null || r.app != app) {
3318            return null;
3319        }
3320        Slog.w(TAG, "  Force finishing activity "
3321                + r.intent.getComponent().flattenToShortString());
3322        int taskNdx = mTaskHistory.indexOf(r.task);
3323        int activityNdx = r.task.mActivities.indexOf(r);
3324        finishActivityLocked(r, Activity.RESULT_CANCELED, null, reason, false);
3325        finishedTask = r.task;
3326        // Also terminate any activities below it that aren't yet
3327        // stopped, to avoid a situation where one will get
3328        // re-start our crashing activity once it gets resumed again.
3329        --activityNdx;
3330        if (activityNdx < 0) {
3331            do {
3332                --taskNdx;
3333                if (taskNdx < 0) {
3334                    break;
3335                }
3336                activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1;
3337            } while (activityNdx < 0);
3338        }
3339        if (activityNdx >= 0) {
3340            r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx);
3341            if (r.state == ActivityState.RESUMED
3342                    || r.state == ActivityState.PAUSING
3343                    || r.state == ActivityState.PAUSED) {
3344                if (!r.isHomeActivity() || mService.mHomeProcess != r.app) {
3345                    Slog.w(TAG, "  Force finishing activity "
3346                            + r.intent.getComponent().flattenToShortString());
3347                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, reason, false);
3348                }
3349            }
3350        }
3351        return finishedTask;
3352    }
3353
3354    final void finishVoiceTask(IVoiceInteractionSession session) {
3355        IBinder sessionBinder = session.asBinder();
3356        boolean didOne = false;
3357        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3358            TaskRecord tr = mTaskHistory.get(taskNdx);
3359            if (tr.voiceSession != null && tr.voiceSession.asBinder() == sessionBinder) {
3360                for (int activityNdx = tr.mActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3361                    ActivityRecord r = tr.mActivities.get(activityNdx);
3362                    if (!r.finishing) {
3363                        finishActivityLocked(r, Activity.RESULT_CANCELED, null, "finish-voice",
3364                                false);
3365                        didOne = true;
3366                    }
3367                }
3368            } else {
3369                // Check if any of the activities are using voice
3370                for (int activityNdx = tr.mActivities.size() - 1; activityNdx >= 0; --activityNdx) {
3371                    ActivityRecord r = tr.mActivities.get(activityNdx);
3372                    if (r.voiceSession != null
3373                            && r.voiceSession.asBinder() == sessionBinder) {
3374                        // Inform of cancellation
3375                        r.clearVoiceSessionLocked();
3376                        try {
3377                            r.app.thread.scheduleLocalVoiceInteractionStarted((IBinder) r.appToken,
3378                                    null);
3379                        } catch (RemoteException re) {
3380                            // Ok
3381                        }
3382                        mService.finishRunningVoiceLocked();
3383                        break;
3384                    }
3385                }
3386            }
3387        }
3388
3389        if (didOne) {
3390            mService.updateOomAdjLocked();
3391        }
3392    }
3393
3394    final boolean finishActivityAffinityLocked(ActivityRecord r) {
3395        ArrayList<ActivityRecord> activities = r.task.mActivities;
3396        for (int index = activities.indexOf(r); index >= 0; --index) {
3397            ActivityRecord cur = activities.get(index);
3398            if (!Objects.equals(cur.taskAffinity, r.taskAffinity)) {
3399                break;
3400            }
3401            finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity", true);
3402        }
3403        return true;
3404    }
3405
3406    final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3407        // send the result
3408        ActivityRecord resultTo = r.resultTo;
3409        if (resultTo != null) {
3410            if (DEBUG_RESULTS) Slog.v(TAG_RESULTS, "Adding result to " + resultTo
3411                    + " who=" + r.resultWho + " req=" + r.requestCode
3412                    + " res=" + resultCode + " data=" + resultData);
3413            if (resultTo.userId != r.userId) {
3414                if (resultData != null) {
3415                    resultData.prepareToLeaveUser(r.userId);
3416                }
3417            }
3418            if (r.info.applicationInfo.uid > 0) {
3419                mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3420                        resultTo.packageName, resultData,
3421                        resultTo.getUriPermissionsLocked(), resultTo.userId);
3422            }
3423            resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3424                                     resultData);
3425            r.resultTo = null;
3426        }
3427        else if (DEBUG_RESULTS) Slog.v(TAG_RESULTS, "No result destination from " + r);
3428
3429        // Make sure this HistoryRecord is not holding on to other resources,
3430        // because clients have remote IPC references to this object so we
3431        // can't assume that will go away and want to avoid circular IPC refs.
3432        r.results = null;
3433        r.pendingResults = null;
3434        r.newIntents = null;
3435        r.icicle = null;
3436    }
3437
3438    /**
3439     * @return Returns true if this activity has been removed from the history
3440     * list, or false if it is still in the list and will be removed later.
3441     */
3442    final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
3443            String reason, boolean oomAdj) {
3444        if (r.finishing) {
3445            Slog.w(TAG, "Duplicate finish request for " + r);
3446            return false;
3447        }
3448
3449        r.makeFinishingLocked();
3450        final TaskRecord task = r.task;
3451        EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3452                r.userId, System.identityHashCode(r),
3453                task.taskId, r.shortComponentName, reason);
3454        final ArrayList<ActivityRecord> activities = task.mActivities;
3455        final int index = activities.indexOf(r);
3456        if (index < (activities.size() - 1)) {
3457            task.setFrontOfTask();
3458            if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3459                // If the caller asked that this activity (and all above it)
3460                // be cleared when the task is reset, don't lose that information,
3461                // but propagate it up to the next activity.
3462                ActivityRecord next = activities.get(index+1);
3463                next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3464            }
3465        }
3466
3467        r.pauseKeyDispatchingLocked();
3468
3469        adjustFocusedActivityLocked(r, "finishActivity");
3470
3471        finishActivityResultsLocked(r, resultCode, resultData);
3472
3473        final boolean endTask = index <= 0;
3474        final int transit = endTask ? TRANSIT_TASK_CLOSE : TRANSIT_ACTIVITY_CLOSE;
3475        if (mResumedActivity == r) {
3476
3477            if (DEBUG_VISIBILITY || DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
3478                    "Prepare close transition: finishing " + r);
3479            mWindowManager.prepareAppTransition(transit, false);
3480
3481            // Tell window manager to prepare for this one to be removed.
3482            mWindowManager.setAppVisibility(r.appToken, false);
3483
3484            if (mPausingActivity == null) {
3485                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Finish needs to pause: " + r);
3486                if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
3487                        "finish() => pause with userLeaving=false");
3488                startPausingLocked(false, false, false, false);
3489            }
3490
3491            if (endTask) {
3492                mStackSupervisor.removeLockedTaskLocked(task);
3493            }
3494        } else if (r.state != ActivityState.PAUSING) {
3495            // If the activity is PAUSING, we will complete the finish once
3496            // it is done pausing; else we can just directly finish it here.
3497            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Finish not pausing: " + r);
3498            if (r.visible) {
3499                mWindowManager.prepareAppTransition(transit, false);
3500                mWindowManager.setAppVisibility(r.appToken, false);
3501                mWindowManager.executeAppTransition();
3502                if (!mStackSupervisor.mWaitingVisibleActivities.contains(r)) {
3503                    mStackSupervisor.mWaitingVisibleActivities.add(r);
3504                }
3505            }
3506            return finishCurrentActivityLocked(r, (r.visible || r.nowVisible) ?
3507                    FINISH_AFTER_VISIBLE : FINISH_AFTER_PAUSE, oomAdj) == null;
3508        } else {
3509            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Finish waiting for pause of: " + r);
3510        }
3511
3512        return false;
3513    }
3514
3515    static final int FINISH_IMMEDIATELY = 0;
3516    static final int FINISH_AFTER_PAUSE = 1;
3517    static final int FINISH_AFTER_VISIBLE = 2;
3518
3519    final ActivityRecord finishCurrentActivityLocked(ActivityRecord r, int mode, boolean oomAdj) {
3520        // First things first: if this activity is currently visible,
3521        // and the resumed activity is not yet visible, then hold off on
3522        // finishing until the resumed one becomes visible.
3523
3524        final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();
3525
3526        if (mode == FINISH_AFTER_VISIBLE && (r.visible || r.nowVisible)
3527                && next != null && !next.nowVisible) {
3528            if (!mStackSupervisor.mStoppingActivities.contains(r)) {
3529                addToStopping(r, false /* immediate */);
3530            }
3531            if (DEBUG_STATES) Slog.v(TAG_STATES,
3532                    "Moving to STOPPING: "+ r + " (finish requested)");
3533            r.state = ActivityState.STOPPING;
3534            if (oomAdj) {
3535                mService.updateOomAdjLocked();
3536            }
3537            return r;
3538        }
3539
3540        // make sure the record is cleaned out of other places.
3541        mStackSupervisor.mStoppingActivities.remove(r);
3542        mStackSupervisor.mGoingToSleepActivities.remove(r);
3543        mStackSupervisor.mWaitingVisibleActivities.remove(r);
3544        if (mResumedActivity == r) {
3545            mResumedActivity = null;
3546        }
3547        final ActivityState prevState = r.state;
3548        if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to FINISHING: " + r);
3549        r.state = ActivityState.FINISHING;
3550
3551        if (mode == FINISH_IMMEDIATELY
3552                || (prevState == ActivityState.PAUSED
3553                    && (mode == FINISH_AFTER_PAUSE || mStackId == PINNED_STACK_ID))
3554                || prevState == ActivityState.STOPPED
3555                || prevState == ActivityState.INITIALIZING) {
3556            r.makeFinishingLocked();
3557            boolean activityRemoved = destroyActivityLocked(r, true, "finish-imm");
3558            if (activityRemoved) {
3559                mStackSupervisor.resumeFocusedStackTopActivityLocked();
3560            }
3561            if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS,
3562                    "destroyActivityLocked: finishCurrentActivityLocked r=" + r +
3563                    " destroy returned removed=" + activityRemoved);
3564            return activityRemoved ? null : r;
3565        }
3566
3567        // Need to go through the full pause cycle to get this
3568        // activity into the stopped state and then finish it.
3569        if (DEBUG_ALL) Slog.v(TAG, "Enqueueing pending finish: " + r);
3570        mStackSupervisor.mFinishingActivities.add(r);
3571        r.resumeKeyDispatchingLocked();
3572        mStackSupervisor.resumeFocusedStackTopActivityLocked();
3573        return r;
3574    }
3575
3576    void finishAllActivitiesLocked(boolean immediately) {
3577        boolean noActivitiesInStack = true;
3578        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3579            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3580            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3581                final ActivityRecord r = activities.get(activityNdx);
3582                noActivitiesInStack = false;
3583                if (r.finishing && !immediately) {
3584                    continue;
3585                }
3586                Slog.d(TAG, "finishAllActivitiesLocked: finishing " + r + " immediately");
3587                finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
3588            }
3589        }
3590        if (noActivitiesInStack) {
3591            mActivityContainer.onTaskListEmptyLocked();
3592        }
3593    }
3594
3595    final boolean shouldUpRecreateTaskLocked(ActivityRecord srec, String destAffinity) {
3596        // Basic case: for simple app-centric recents, we need to recreate
3597        // the task if the affinity has changed.
3598        if (srec == null || srec.task.affinity == null ||
3599                !srec.task.affinity.equals(destAffinity)) {
3600            return true;
3601        }
3602        // Document-centric case: an app may be split in to multiple documents;
3603        // they need to re-create their task if this current activity is the root
3604        // of a document, unless simply finishing it will return them to the the
3605        // correct app behind.
3606        if (srec.frontOfTask && srec.task != null && srec.task.getBaseIntent() != null
3607                && srec.task.getBaseIntent().isDocument()) {
3608            // Okay, this activity is at the root of its task.  What to do, what to do...
3609            if (srec.task.getTaskToReturnTo() != ActivityRecord.APPLICATION_ACTIVITY_TYPE) {
3610                // Finishing won't return to an application, so we need to recreate.
3611                return true;
3612            }
3613            // We now need to get the task below it to determine what to do.
3614            int taskIdx = mTaskHistory.indexOf(srec.task);
3615            if (taskIdx <= 0) {
3616                Slog.w(TAG, "shouldUpRecreateTask: task not in history for " + srec);
3617                return false;
3618            }
3619            if (taskIdx == 0) {
3620                // At the bottom of the stack, nothing to go back to.
3621                return true;
3622            }
3623            TaskRecord prevTask = mTaskHistory.get(taskIdx);
3624            if (!srec.task.affinity.equals(prevTask.affinity)) {
3625                // These are different apps, so need to recreate.
3626                return true;
3627            }
3628        }
3629        return false;
3630    }
3631
3632    final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode,
3633            Intent resultData) {
3634        final TaskRecord task = srec.task;
3635        final ArrayList<ActivityRecord> activities = task.mActivities;
3636        final int start = activities.indexOf(srec);
3637        if (!mTaskHistory.contains(task) || (start < 0)) {
3638            return false;
3639        }
3640        int finishTo = start - 1;
3641        ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo);
3642        boolean foundParentInTask = false;
3643        final ComponentName dest = destIntent.getComponent();
3644        if (start > 0 && dest != null) {
3645            for (int i = finishTo; i >= 0; i--) {
3646                ActivityRecord r = activities.get(i);
3647                if (r.info.packageName.equals(dest.getPackageName()) &&
3648                        r.info.name.equals(dest.getClassName())) {
3649                    finishTo = i;
3650                    parent = r;
3651                    foundParentInTask = true;
3652                    break;
3653                }
3654            }
3655        }
3656
3657        IActivityController controller = mService.mController;
3658        if (controller != null) {
3659            ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
3660            if (next != null) {
3661                // ask watcher if this is allowed
3662                boolean resumeOK = true;
3663                try {
3664                    resumeOK = controller.activityResuming(next.packageName);
3665                } catch (RemoteException e) {
3666                    mService.mController = null;
3667                    Watchdog.getInstance().setActivityController(null);
3668                }
3669
3670                if (!resumeOK) {
3671                    return false;
3672                }
3673            }
3674        }
3675        final long origId = Binder.clearCallingIdentity();
3676        for (int i = start; i > finishTo; i--) {
3677            ActivityRecord r = activities.get(i);
3678            requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
3679            // Only return the supplied result for the first activity finished
3680            resultCode = Activity.RESULT_CANCELED;
3681            resultData = null;
3682        }
3683
3684        if (parent != null && foundParentInTask) {
3685            final int parentLaunchMode = parent.info.launchMode;
3686            final int destIntentFlags = destIntent.getFlags();
3687            if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
3688                    parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
3689                    parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
3690                    (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3691                parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent,
3692                        srec.packageName);
3693            } else {
3694                try {
3695                    ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
3696                            destIntent.getComponent(), 0, srec.userId);
3697                    int res = mService.mActivityStarter.startActivityLocked(srec.app.thread,
3698                            destIntent, null /*ephemeralIntent*/, null, aInfo, null /*rInfo*/, null,
3699                            null, parent.appToken, null, 0, -1, parent.launchedFromUid,
3700                            parent.launchedFromPackage, -1, parent.launchedFromUid, 0, null,
3701                            false, true, null, null, null);
3702                    foundParentInTask = res == ActivityManager.START_SUCCESS;
3703                } catch (RemoteException e) {
3704                    foundParentInTask = false;
3705                }
3706                requestFinishActivityLocked(parent.appToken, resultCode,
3707                        resultData, "navigate-top", true);
3708            }
3709        }
3710        Binder.restoreCallingIdentity(origId);
3711        return foundParentInTask;
3712    }
3713    /**
3714     * Perform the common clean-up of an activity record.  This is called both
3715     * as part of destroyActivityLocked() (when destroying the client-side
3716     * representation) and cleaning things up as a result of its hosting
3717     * processing going away, in which case there is no remaining client-side
3718     * state to destroy so only the cleanup here is needed.
3719     *
3720     * Note: Call before #removeActivityFromHistoryLocked.
3721     */
3722    final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3723            boolean setState) {
3724        if (mResumedActivity == r) {
3725            mResumedActivity = null;
3726        }
3727        if (mPausingActivity == r) {
3728            mPausingActivity = null;
3729        }
3730        mService.resetFocusedActivityIfNeededLocked(r);
3731
3732        r.deferRelaunchUntilPaused = false;
3733        r.frozenBeforeDestroy = false;
3734
3735        if (setState) {
3736            if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to DESTROYED: " + r + " (cleaning up)");
3737            r.state = ActivityState.DESTROYED;
3738            if (DEBUG_APP) Slog.v(TAG_APP, "Clearing app during cleanUp for activity " + r);
3739            r.app = null;
3740        }
3741
3742        // Make sure this record is no longer in the pending finishes list.
3743        // This could happen, for example, if we are trimming activities
3744        // down to the max limit while they are still waiting to finish.
3745        mStackSupervisor.mFinishingActivities.remove(r);
3746        mStackSupervisor.mWaitingVisibleActivities.remove(r);
3747
3748        // Remove any pending results.
3749        if (r.finishing && r.pendingResults != null) {
3750            for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3751                PendingIntentRecord rec = apr.get();
3752                if (rec != null) {
3753                    mService.cancelIntentSenderLocked(rec, false);
3754                }
3755            }
3756            r.pendingResults = null;
3757        }
3758
3759        if (cleanServices) {
3760            cleanUpActivityServicesLocked(r);
3761        }
3762
3763        // Get rid of any pending idle timeouts.
3764        removeTimeoutsForActivityLocked(r);
3765        if (getVisibleBehindActivity() == r) {
3766            mStackSupervisor.requestVisibleBehindLocked(r, false);
3767        }
3768    }
3769
3770    private void removeTimeoutsForActivityLocked(ActivityRecord r) {
3771        mStackSupervisor.removeTimeoutsForActivityLocked(r);
3772        mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3773        mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
3774        mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3775        r.finishLaunchTickingLocked();
3776    }
3777
3778    private void removeActivityFromHistoryLocked(
3779            ActivityRecord r, TaskRecord oldTop, String reason) {
3780        mStackSupervisor.removeChildActivityContainers(r);
3781        finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
3782        r.makeFinishingLocked();
3783        if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE,
3784                "Removing activity " + r + " from stack callers=" + Debug.getCallers(5));
3785
3786        r.takeFromHistory();
3787        removeTimeoutsForActivityLocked(r);
3788        if (DEBUG_STATES) Slog.v(TAG_STATES,
3789                "Moving to DESTROYED: " + r + " (removed from history)");
3790        r.state = ActivityState.DESTROYED;
3791        if (DEBUG_APP) Slog.v(TAG_APP, "Clearing app during remove for activity " + r);
3792        r.app = null;
3793        mWindowManager.removeAppToken(r.appToken);
3794        if (VALIDATE_TOKENS) {
3795            validateAppTokensLocked();
3796        }
3797        final TaskRecord task = r.task;
3798        final TaskRecord topTask = oldTop != null ? oldTop : topTask();
3799        if (task != null && task.removeActivity(r)) {
3800            if (DEBUG_STACK) Slog.i(TAG_STACK,
3801                    "removeActivityFromHistoryLocked: last activity removed from " + this);
3802            if (mStackSupervisor.isFocusedStack(this) && task == topTask &&
3803                    task.isOverHomeStack()) {
3804                mStackSupervisor.moveHomeStackTaskToTop(task.getTaskToReturnTo(), reason);
3805            }
3806            removeTask(task, reason);
3807        }
3808        cleanUpActivityServicesLocked(r);
3809        r.removeUriPermissionsLocked();
3810    }
3811
3812    /**
3813     * Perform clean-up of service connections in an activity record.
3814     */
3815    final void cleanUpActivityServicesLocked(ActivityRecord r) {
3816        // Throw away any services that have been bound by this activity.
3817        if (r.connections != null) {
3818            Iterator<ConnectionRecord> it = r.connections.iterator();
3819            while (it.hasNext()) {
3820                ConnectionRecord c = it.next();
3821                mService.mServices.removeConnectionLocked(c, null, r);
3822            }
3823            r.connections = null;
3824        }
3825    }
3826
3827    final void scheduleDestroyActivities(ProcessRecord owner, String reason) {
3828        Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
3829        msg.obj = new ScheduleDestroyArgs(owner, reason);
3830        mHandler.sendMessage(msg);
3831    }
3832
3833    final void destroyActivitiesLocked(ProcessRecord owner, String reason) {
3834        boolean lastIsOpaque = false;
3835        boolean activityRemoved = false;
3836        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3837            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3838            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3839                final ActivityRecord r = activities.get(activityNdx);
3840                if (r.finishing) {
3841                    continue;
3842                }
3843                if (r.fullscreen) {
3844                    lastIsOpaque = true;
3845                }
3846                if (owner != null && r.app != owner) {
3847                    continue;
3848                }
3849                if (!lastIsOpaque) {
3850                    continue;
3851                }
3852                if (r.isDestroyable()) {
3853                    if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Destroying " + r + " in state " + r.state
3854                            + " resumed=" + mResumedActivity
3855                            + " pausing=" + mPausingActivity + " for reason " + reason);
3856                    if (destroyActivityLocked(r, true, reason)) {
3857                        activityRemoved = true;
3858                    }
3859                }
3860            }
3861        }
3862        if (activityRemoved) {
3863            mStackSupervisor.resumeFocusedStackTopActivityLocked();
3864        }
3865    }
3866
3867    final boolean safelyDestroyActivityLocked(ActivityRecord r, String reason) {
3868        if (r.isDestroyable()) {
3869            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
3870                    "Destroying " + r + " in state " + r.state + " resumed=" + mResumedActivity
3871                    + " pausing=" + mPausingActivity + " for reason " + reason);
3872            return destroyActivityLocked(r, true, reason);
3873        }
3874        return false;
3875    }
3876
3877    final int releaseSomeActivitiesLocked(ProcessRecord app, ArraySet<TaskRecord> tasks,
3878            String reason) {
3879        // Iterate over tasks starting at the back (oldest) first.
3880        if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
3881        int maxTasks = tasks.size() / 4;
3882        if (maxTasks < 1) {
3883            maxTasks = 1;
3884        }
3885        int numReleased = 0;
3886        for (int taskNdx = 0; taskNdx < mTaskHistory.size() && maxTasks > 0; taskNdx++) {
3887            final TaskRecord task = mTaskHistory.get(taskNdx);
3888            if (!tasks.contains(task)) {
3889                continue;
3890            }
3891            if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Looking for activities to release in " + task);
3892            int curNum = 0;
3893            final ArrayList<ActivityRecord> activities = task.mActivities;
3894            for (int actNdx = 0; actNdx < activities.size(); actNdx++) {
3895                final ActivityRecord activity = activities.get(actNdx);
3896                if (activity.app == app && activity.isDestroyable()) {
3897                    if (DEBUG_RELEASE) Slog.v(TAG_RELEASE, "Destroying " + activity
3898                            + " in state " + activity.state + " resumed=" + mResumedActivity
3899                            + " pausing=" + mPausingActivity + " for reason " + reason);
3900                    destroyActivityLocked(activity, true, reason);
3901                    if (activities.get(actNdx) != activity) {
3902                        // Was removed from list, back up so we don't miss the next one.
3903                        actNdx--;
3904                    }
3905                    curNum++;
3906                }
3907            }
3908            if (curNum > 0) {
3909                numReleased += curNum;
3910                maxTasks--;
3911                if (mTaskHistory.get(taskNdx) != task) {
3912                    // The entire task got removed, back up so we don't miss the next one.
3913                    taskNdx--;
3914                }
3915            }
3916        }
3917        if (DEBUG_RELEASE) Slog.d(TAG_RELEASE,
3918                "Done releasing: did " + numReleased + " activities");
3919        return numReleased;
3920    }
3921
3922    /**
3923     * Destroy the current CLIENT SIDE instance of an activity.  This may be
3924     * called both when actually finishing an activity, or when performing
3925     * a configuration switch where we destroy the current client-side object
3926     * but then create a new client-side object for this same HistoryRecord.
3927     */
3928    final boolean destroyActivityLocked(ActivityRecord r, boolean removeFromApp, String reason) {
3929        if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(TAG_SWITCH,
3930                "Removing activity from " + reason + ": token=" + r
3931                        + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3932        EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3933                r.userId, System.identityHashCode(r),
3934                r.task.taskId, r.shortComponentName, reason);
3935
3936        boolean removedFromHistory = false;
3937
3938        // If the activity is finishing, it's no longer considered in topRunningActivityLocked,
3939        // and cleanUpActivityLocked() may change focus to another activity (or task).
3940        // Get the current top task now, as removeActivityFromHistoryLocked() below need this
3941        // to decide whether to return to home stack after removal.
3942        final TaskRecord topTask = topTask();
3943
3944        cleanUpActivityLocked(r, false, false);
3945
3946        final boolean hadApp = r.app != null;
3947
3948        if (hadApp) {
3949            if (removeFromApp) {
3950                r.app.activities.remove(r);
3951                if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3952                    mService.mHeavyWeightProcess = null;
3953                    mService.mHandler.sendEmptyMessage(
3954                            ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3955                }
3956                if (r.app.activities.isEmpty()) {
3957                    // Update any services we are bound to that might care about whether
3958                    // their client may have activities.
3959                    mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
3960                    // No longer have activities, so update LRU list and oom adj.
3961                    mService.updateLruProcessLocked(r.app, false, null);
3962                    mService.updateOomAdjLocked();
3963                }
3964            }
3965
3966            boolean skipDestroy = false;
3967
3968            try {
3969                if (DEBUG_SWITCH) Slog.i(TAG_SWITCH, "Destroying: " + r);
3970                r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
3971                        r.configChangeFlags);
3972            } catch (Exception e) {
3973                // We can just ignore exceptions here...  if the process
3974                // has crashed, our death notification will clean things
3975                // up.
3976                //Slog.w(TAG, "Exception thrown during finish", e);
3977                if (r.finishing) {
3978                    removeActivityFromHistoryLocked(
3979                            r, topTask, reason + " exceptionInScheduleDestroy");
3980                    removedFromHistory = true;
3981                    skipDestroy = true;
3982                }
3983            }
3984
3985            r.nowVisible = false;
3986
3987            // If the activity is finishing, we need to wait on removing it
3988            // from the list to give it a chance to do its cleanup.  During
3989            // that time it may make calls back with its token so we need to
3990            // be able to find it on the list and so we don't want to remove
3991            // it from the list yet.  Otherwise, we can just immediately put
3992            // it in the destroyed state since we are not removing it from the
3993            // list.
3994            if (r.finishing && !skipDestroy) {
3995                if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to DESTROYING: " + r
3996                        + " (destroy requested)");
3997                r.state = ActivityState.DESTROYING;
3998                Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r);
3999                mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4000            } else {
4001                if (DEBUG_STATES) Slog.v(TAG_STATES,
4002                        "Moving to DESTROYED: " + r + " (destroy skipped)");
4003                r.state = ActivityState.DESTROYED;
4004                if (DEBUG_APP) Slog.v(TAG_APP, "Clearing app during destroy for activity " + r);
4005                r.app = null;
4006            }
4007        } else {
4008            // remove this record from the history.
4009            if (r.finishing) {
4010                removeActivityFromHistoryLocked(r, topTask, reason + " hadNoApp");
4011                removedFromHistory = true;
4012            } else {
4013                if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to DESTROYED: " + r + " (no app)");
4014                r.state = ActivityState.DESTROYED;
4015                if (DEBUG_APP) Slog.v(TAG_APP, "Clearing app during destroy for activity " + r);
4016                r.app = null;
4017            }
4018        }
4019
4020        r.configChangeFlags = 0;
4021
4022        if (!mLRUActivities.remove(r) && hadApp) {
4023            Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4024        }
4025
4026        return removedFromHistory;
4027    }
4028
4029    final void activityDestroyedLocked(IBinder token, String reason) {
4030        final long origId = Binder.clearCallingIdentity();
4031        try {
4032            ActivityRecord r = ActivityRecord.forTokenLocked(token);
4033            if (r != null) {
4034                mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
4035            }
4036            if (DEBUG_CONTAINERS) Slog.d(TAG_CONTAINERS, "activityDestroyedLocked: r=" + r);
4037
4038            if (isInStackLocked(r) != null) {
4039                if (r.state == ActivityState.DESTROYING) {
4040                    cleanUpActivityLocked(r, true, false);
4041                    removeActivityFromHistoryLocked(r, null, reason);
4042                }
4043            }
4044            mStackSupervisor.resumeFocusedStackTopActivityLocked();
4045        } finally {
4046            Binder.restoreCallingIdentity(origId);
4047        }
4048    }
4049
4050    void releaseBackgroundResources(ActivityRecord r) {
4051        if (hasVisibleBehindActivity() &&
4052                !mHandler.hasMessages(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG)) {
4053            if (r == topRunningActivityLocked()
4054                    && getStackVisibilityLocked(null) == STACK_VISIBLE) {
4055                // Don't release the top activity if it has requested to run behind the next
4056                // activity and the stack is currently visible.
4057                return;
4058            }
4059            if (DEBUG_STATES) Slog.d(TAG_STATES, "releaseBackgroundResources activtyDisplay=" +
4060                    mActivityContainer.mActivityDisplay + " visibleBehind=" + r + " app=" + r.app +
4061                    " thread=" + r.app.thread);
4062            if (r != null && r.app != null && r.app.thread != null) {
4063                try {
4064                    r.app.thread.scheduleCancelVisibleBehind(r.appToken);
4065                } catch (RemoteException e) {
4066                }
4067                mHandler.sendEmptyMessageDelayed(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG, 500);
4068            } else {
4069                Slog.e(TAG, "releaseBackgroundResources: activity " + r + " no longer running");
4070                backgroundResourcesReleased();
4071            }
4072        }
4073    }
4074
4075    final void backgroundResourcesReleased() {
4076        mHandler.removeMessages(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG);
4077        final ActivityRecord r = getVisibleBehindActivity();
4078        if (r != null) {
4079            mStackSupervisor.mStoppingActivities.add(r);
4080            setVisibleBehindActivity(null);
4081            mStackSupervisor.scheduleIdleTimeoutLocked(null);
4082        }
4083        mStackSupervisor.resumeFocusedStackTopActivityLocked();
4084    }
4085
4086    boolean hasVisibleBehindActivity() {
4087        return isAttached() && mActivityContainer.mActivityDisplay.hasVisibleBehindActivity();
4088    }
4089
4090    void setVisibleBehindActivity(ActivityRecord r) {
4091        if (isAttached()) {
4092            mActivityContainer.mActivityDisplay.setVisibleBehindActivity(r);
4093        }
4094    }
4095
4096    ActivityRecord getVisibleBehindActivity() {
4097        return isAttached() ? mActivityContainer.mActivityDisplay.mVisibleBehindActivity : null;
4098    }
4099
4100    private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
4101            ProcessRecord app, String listName) {
4102        int i = list.size();
4103        if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
4104            "Removing app " + app + " from list " + listName + " with " + i + " entries");
4105        while (i > 0) {
4106            i--;
4107            ActivityRecord r = list.get(i);
4108            if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "Record #" + i + " " + r);
4109            if (r.app == app) {
4110                if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "---> REMOVING this entry!");
4111                list.remove(i);
4112                removeTimeoutsForActivityLocked(r);
4113            }
4114        }
4115    }
4116
4117    boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4118        removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4119        removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app,
4120                "mStoppingActivities");
4121        removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app,
4122                "mGoingToSleepActivities");
4123        removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app,
4124                "mWaitingVisibleActivities");
4125        removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app,
4126                "mFinishingActivities");
4127
4128        boolean hasVisibleActivities = false;
4129
4130        // Clean out the history list.
4131        int i = numActivities();
4132        if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
4133                "Removing app " + app + " from history with " + i + " entries");
4134        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4135            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4136            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4137                final ActivityRecord r = activities.get(activityNdx);
4138                --i;
4139                if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
4140                        "Record #" + i + " " + r + ": app=" + r.app);
4141                if (r.app == app) {
4142                    if (r.visible) {
4143                        hasVisibleActivities = true;
4144                    }
4145                    final boolean remove;
4146                    if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
4147                        // Don't currently have state for the activity, or
4148                        // it is finishing -- always remove it.
4149                        remove = true;
4150                    } else if (!r.visible && r.launchCount > 2 &&
4151                            r.lastLaunchTime > (SystemClock.uptimeMillis() - 60000)) {
4152                        // We have launched this activity too many times since it was
4153                        // able to run, so give up and remove it.
4154                        // (Note if the activity is visible, we don't remove the record.
4155                        // We leave the dead window on the screen but the process will
4156                        // not be restarted unless user explicitly tap on it.)
4157                        remove = true;
4158                    } else {
4159                        // The process may be gone, but the activity lives on!
4160                        remove = false;
4161                    }
4162                    if (remove) {
4163                        if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) Slog.i(TAG_ADD_REMOVE,
4164                                "Removing activity " + r + " from stack at " + i
4165                                + ": haveState=" + r.haveState
4166                                + " stateNotNeeded=" + r.stateNotNeeded
4167                                + " finishing=" + r.finishing
4168                                + " state=" + r.state + " callers=" + Debug.getCallers(5));
4169                        if (!r.finishing) {
4170                            Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4171                            EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4172                                    r.userId, System.identityHashCode(r),
4173                                    r.task.taskId, r.shortComponentName,
4174                                    "proc died without state saved");
4175                            if (r.state == ActivityState.RESUMED) {
4176                                mService.updateUsageStats(r, false);
4177                            }
4178                        }
4179                    } else {
4180                        // We have the current state for this activity, so
4181                        // it can be restarted later when needed.
4182                        if (DEBUG_ALL) Slog.v(TAG, "Keeping entry, setting app to null");
4183                        if (DEBUG_APP) Slog.v(TAG_APP,
4184                                "Clearing app during removeHistory for activity " + r);
4185                        r.app = null;
4186                        // Set nowVisible to previous visible state. If the app was visible while
4187                        // it died, we leave the dead window on screen so it's basically visible.
4188                        // This is needed when user later tap on the dead window, we need to stop
4189                        // other apps when user transfers focus to the restarted activity.
4190                        r.nowVisible = r.visible;
4191                        if (!r.haveState) {
4192                            if (DEBUG_SAVED_STATE) Slog.i(TAG_SAVED_STATE,
4193                                    "App died, clearing saved state of " + r);
4194                            r.icicle = null;
4195                        }
4196                    }
4197                    cleanUpActivityLocked(r, true, true);
4198                    if (remove) {
4199                        removeActivityFromHistoryLocked(r, null, "appDied");
4200                    }
4201                }
4202            }
4203        }
4204
4205        return hasVisibleActivities;
4206    }
4207
4208    final void updateTransitLocked(int transit, ActivityOptions options) {
4209        if (options != null) {
4210            ActivityRecord r = topRunningActivityLocked();
4211            if (r != null && r.state != ActivityState.RESUMED) {
4212                r.updateOptionsLocked(options);
4213            } else {
4214                ActivityOptions.abort(options);
4215            }
4216        }
4217        mWindowManager.prepareAppTransition(transit, false);
4218    }
4219
4220    void updateTaskMovement(TaskRecord task, boolean toFront) {
4221        if (task.isPersistable) {
4222            task.mLastTimeMoved = System.currentTimeMillis();
4223            // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most
4224            // recently will be most negative, tasks sent to the bottom before that will be less
4225            // negative. Similarly for recent tasks moved to the top which will be most positive.
4226            if (!toFront) {
4227                task.mLastTimeMoved *= -1;
4228            }
4229        }
4230        mStackSupervisor.invalidateTaskLayers();
4231    }
4232
4233    void moveHomeStackTaskToTop(int homeStackTaskType) {
4234        final int top = mTaskHistory.size() - 1;
4235        for (int taskNdx = top; taskNdx >= 0; --taskNdx) {
4236            final TaskRecord task = mTaskHistory.get(taskNdx);
4237            if (task.taskType == homeStackTaskType) {
4238                if (DEBUG_TASKS || DEBUG_STACK) Slog.d(TAG_STACK,
4239                        "moveHomeStackTaskToTop: moving " + task);
4240                mTaskHistory.remove(taskNdx);
4241                mTaskHistory.add(top, task);
4242                updateTaskMovement(task, true);
4243                return;
4244            }
4245        }
4246    }
4247
4248    final void moveTaskToFrontLocked(TaskRecord tr, boolean noAnimation, ActivityOptions options,
4249            AppTimeTracker timeTracker, String reason) {
4250        if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "moveTaskToFront: " + tr);
4251
4252        final int numTasks = mTaskHistory.size();
4253        final int index = mTaskHistory.indexOf(tr);
4254        if (numTasks == 0 || index < 0)  {
4255            // nothing to do!
4256            if (noAnimation) {
4257                ActivityOptions.abort(options);
4258            } else {
4259                updateTransitLocked(TRANSIT_TASK_TO_FRONT, options);
4260            }
4261            return;
4262        }
4263
4264        if (timeTracker != null) {
4265            // The caller wants a time tracker associated with this task.
4266            for (int i = tr.mActivities.size() - 1; i >= 0; i--) {
4267                tr.mActivities.get(i).appTimeTracker = timeTracker;
4268            }
4269        }
4270
4271        // Shift all activities with this task up to the top
4272        // of the stack, keeping them in the same internal order.
4273        insertTaskAtTop(tr, null);
4274
4275        // Don't refocus if invisible to current user
4276        ActivityRecord top = tr.getTopActivity();
4277        if (!okToShowLocked(top)) {
4278            addRecentActivityLocked(top);
4279            ActivityOptions.abort(options);
4280            return;
4281        }
4282
4283        // Set focus to the top running activity of this stack.
4284        ActivityRecord r = topRunningActivityLocked();
4285        mService.setFocusedActivityLocked(r, reason);
4286
4287        if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to front transition: task=" + tr);
4288        if (noAnimation) {
4289            mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
4290            if (r != null) {
4291                mNoAnimActivities.add(r);
4292            }
4293            ActivityOptions.abort(options);
4294        } else {
4295            updateTransitLocked(TRANSIT_TASK_TO_FRONT, options);
4296        }
4297
4298        mStackSupervisor.resumeFocusedStackTopActivityLocked();
4299        EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId);
4300
4301        if (VALIDATE_TOKENS) {
4302            validateAppTokensLocked();
4303        }
4304    }
4305
4306    /**
4307     * Worker method for rearranging history stack. Implements the function of moving all
4308     * activities for a specific task (gathering them if disjoint) into a single group at the
4309     * bottom of the stack.
4310     *
4311     * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4312     * to premeptively cancel the move.
4313     *
4314     * @param taskId The taskId to collect and move to the bottom.
4315     * @return Returns true if the move completed, false if not.
4316     */
4317    final boolean moveTaskToBackLocked(int taskId) {
4318        final TaskRecord tr = taskForIdLocked(taskId);
4319        if (tr == null) {
4320            Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId);
4321            return false;
4322        }
4323
4324        Slog.i(TAG, "moveTaskToBack: " + tr);
4325        mStackSupervisor.removeLockedTaskLocked(tr);
4326
4327        // If we have a watcher, preflight the move before committing to it.  First check
4328        // for *other* available tasks, but if none are available, then try again allowing the
4329        // current task to be selected.
4330        if (mStackSupervisor.isFrontStack(this) && mService.mController != null) {
4331            ActivityRecord next = topRunningActivityLocked(null, taskId);
4332            if (next == null) {
4333                next = topRunningActivityLocked(null, 0);
4334            }
4335            if (next != null) {
4336                // ask watcher if this is allowed
4337                boolean moveOK = true;
4338                try {
4339                    moveOK = mService.mController.activityResuming(next.packageName);
4340                } catch (RemoteException e) {
4341                    mService.mController = null;
4342                    Watchdog.getInstance().setActivityController(null);
4343                }
4344                if (!moveOK) {
4345                    return false;
4346                }
4347            }
4348        }
4349
4350        if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to back transition: task=" + taskId);
4351
4352        if (mStackId == HOME_STACK_ID && topTask().isHomeTask()) {
4353            // For the case where we are moving the home task back and there is an activity visible
4354            // behind it on the fullscreen stack, we want to move the focus to the visible behind
4355            // activity to maintain order with what the user is seeing.
4356            final ActivityStack fullscreenStack =
4357                    mStackSupervisor.getStack(FULLSCREEN_WORKSPACE_STACK_ID);
4358            if (fullscreenStack != null && fullscreenStack.hasVisibleBehindActivity()) {
4359                final ActivityRecord visibleBehind = fullscreenStack.getVisibleBehindActivity();
4360                mService.setFocusedActivityLocked(visibleBehind, "moveTaskToBack");
4361                mStackSupervisor.resumeFocusedStackTopActivityLocked();
4362                return true;
4363            }
4364        }
4365
4366        boolean prevIsHome = false;
4367
4368        // If true, we should resume the home activity next if the task we are moving to the
4369        // back is over the home stack. We force to false if the task we are moving to back
4370        // is the home task and we don't want it resumed after moving to the back.
4371        final boolean canGoHome = !tr.isHomeTask() && tr.isOverHomeStack();
4372        if (canGoHome) {
4373            final TaskRecord nextTask = getNextTask(tr);
4374            if (nextTask != null) {
4375                nextTask.setTaskToReturnTo(tr.getTaskToReturnTo());
4376            } else {
4377                prevIsHome = true;
4378            }
4379        }
4380        mTaskHistory.remove(tr);
4381        mTaskHistory.add(0, tr);
4382        updateTaskMovement(tr, false);
4383
4384        // There is an assumption that moving a task to the back moves it behind the home activity.
4385        // We make sure here that some activity in the stack will launch home.
4386        int numTasks = mTaskHistory.size();
4387        for (int taskNdx = numTasks - 1; taskNdx >= 1; --taskNdx) {
4388            final TaskRecord task = mTaskHistory.get(taskNdx);
4389            if (task.isOverHomeStack()) {
4390                break;
4391            }
4392            if (taskNdx == 1) {
4393                // Set the last task before tr to go to home.
4394                task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
4395            }
4396        }
4397
4398        mWindowManager.prepareAppTransition(TRANSIT_TASK_TO_BACK, false);
4399        mWindowManager.moveTaskToBottom(taskId);
4400
4401        if (VALIDATE_TOKENS) {
4402            validateAppTokensLocked();
4403        }
4404
4405        final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null;
4406        if (prevIsHome || (task == tr && canGoHome) || (numTasks <= 1 && isOnHomeDisplay())) {
4407            if (!mService.mBooting && !mService.mBooted) {
4408                // Not ready yet!
4409                return false;
4410            }
4411            final int taskToReturnTo = tr.getTaskToReturnTo();
4412            tr.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
4413            return mStackSupervisor.resumeHomeStackTask(taskToReturnTo, null, "moveTaskToBack");
4414        }
4415
4416        mStackSupervisor.resumeFocusedStackTopActivityLocked();
4417        return true;
4418    }
4419
4420    static final void logStartActivity(int tag, ActivityRecord r,
4421            TaskRecord task) {
4422        final Uri data = r.intent.getData();
4423        final String strData = data != null ? data.toSafeString() : null;
4424
4425        EventLog.writeEvent(tag,
4426                r.userId, System.identityHashCode(r), task.taskId,
4427                r.shortComponentName, r.intent.getAction(),
4428                r.intent.getType(), strData, r.intent.getFlags());
4429    }
4430
4431    /**
4432     * Ensures all visible activities at or below the input activity have the right configuration.
4433     */
4434    void ensureVisibleActivitiesConfigurationLocked(ActivityRecord start, boolean preserveWindow) {
4435        if (start == null || !start.visible) {
4436            return;
4437        }
4438
4439        final TaskRecord startTask = start.task;
4440        boolean behindFullscreen = false;
4441        boolean updatedConfig = false;
4442
4443        for (int taskIndex = mTaskHistory.indexOf(startTask); taskIndex >= 0; --taskIndex) {
4444            final TaskRecord task = mTaskHistory.get(taskIndex);
4445            final ArrayList<ActivityRecord> activities = task.mActivities;
4446            int activityIndex =
4447                    (start.task == task) ? activities.indexOf(start) : activities.size() - 1;
4448            for (; activityIndex >= 0; --activityIndex) {
4449                final ActivityRecord r = activities.get(activityIndex);
4450                updatedConfig |= ensureActivityConfigurationLocked(r, 0, preserveWindow);
4451                if (r.fullscreen) {
4452                    behindFullscreen = true;
4453                    break;
4454                }
4455            }
4456            if (behindFullscreen) {
4457                break;
4458            }
4459        }
4460        if (updatedConfig) {
4461            // Ensure the resumed state of the focus activity if we updated the confiugaration of
4462            // any activity.
4463            mStackSupervisor.resumeFocusedStackTopActivityLocked();
4464        }
4465    }
4466
4467    /**
4468     * Make sure the given activity matches the current configuration. Returns false if the activity
4469     * had to be destroyed.  Returns true if the configuration is the same, or the activity will
4470     * remain running as-is for whatever reason. Ensures the HistoryRecord is updated with the
4471     * correct configuration and all other bookkeeping is handled.
4472     */
4473    boolean ensureActivityConfigurationLocked(
4474            ActivityRecord r, int globalChanges, boolean preserveWindow) {
4475        if (mConfigWillChange) {
4476            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4477                    "Skipping config check (will change): " + r);
4478            return true;
4479        }
4480
4481        if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4482                "Ensuring correct configuration: " + r);
4483
4484        // Short circuit: if the two configurations are equal (the common case), then there is
4485        // nothing to do.
4486        final Configuration newConfig = mService.mConfiguration;
4487        r.task.sanitizeOverrideConfiguration(newConfig);
4488        final Configuration taskConfig = r.task.mOverrideConfig;
4489        if (r.configuration.equals(newConfig)
4490                && r.taskConfigOverride.equals(taskConfig)
4491                && !r.forceNewConfig) {
4492            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4493                    "Configuration unchanged in " + r);
4494            return true;
4495        }
4496
4497        // We don't worry about activities that are finishing.
4498        if (r.finishing) {
4499            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4500                    "Configuration doesn't matter in finishing " + r);
4501            r.stopFreezingScreenLocked(false);
4502            return true;
4503        }
4504
4505        // Okay we now are going to make this activity have the new config.
4506        // But then we need to figure out how it needs to deal with that.
4507        final Configuration oldConfig = r.configuration;
4508        final Configuration oldTaskOverride = r.taskConfigOverride;
4509        r.configuration = newConfig;
4510        r.taskConfigOverride = taskConfig;
4511
4512        int taskChanges = getTaskConfigurationChanges(r, taskConfig, oldTaskOverride);
4513        final int changes = oldConfig.diff(newConfig) | taskChanges;
4514        if (changes == 0 && !r.forceNewConfig) {
4515            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4516                    "Configuration no differences in " + r);
4517            // There are no significant differences, so we won't relaunch but should still deliver
4518            // the new configuration to the client process.
4519            r.scheduleConfigurationChanged(taskConfig, true);
4520            return true;
4521        }
4522
4523        if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4524                "Configuration changes for " + r + " ; taskChanges="
4525                        + Configuration.configurationDiffToString(taskChanges) + ", allChanges="
4526                        + Configuration.configurationDiffToString(changes));
4527
4528        // If the activity isn't currently running, just leave the new
4529        // configuration and it will pick that up next time it starts.
4530        if (r.app == null || r.app.thread == null) {
4531            if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4532                    "Configuration doesn't matter not running " + r);
4533            r.stopFreezingScreenLocked(false);
4534            r.forceNewConfig = false;
4535            return true;
4536        }
4537
4538        // Figure out how to handle the changes between the configurations.
4539        if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4540                "Checking to restart " + r.info.name + ": changed=0x"
4541                + Integer.toHexString(changes) + ", handles=0x"
4542                + Integer.toHexString(r.info.getRealConfigChanged()) + ", newConfig=" + newConfig
4543                + ", taskConfig=" + taskConfig);
4544
4545        if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
4546            // Aha, the activity isn't handling the change, so DIE DIE DIE.
4547            r.configChangeFlags |= changes;
4548            r.startFreezingScreenLocked(r.app, globalChanges);
4549            r.forceNewConfig = false;
4550            preserveWindow &= isResizeOnlyChange(changes);
4551            if (r.app == null || r.app.thread == null) {
4552                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4553                        "Config is destroying non-running " + r);
4554                destroyActivityLocked(r, true, "config");
4555            } else if (r.state == ActivityState.PAUSING) {
4556                // A little annoying: we are waiting for this activity to finish pausing. Let's not
4557                // do anything now, but just flag that it needs to be restarted when done pausing.
4558                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4559                        "Config is skipping already pausing " + r);
4560                r.deferRelaunchUntilPaused = true;
4561                r.preserveWindowOnDeferredRelaunch = preserveWindow;
4562                return true;
4563            } else if (r.state == ActivityState.RESUMED) {
4564                // Try to optimize this case: the configuration is changing and we need to restart
4565                // the top, resumed activity. Instead of doing the normal handshaking, just say
4566                // "restart!".
4567                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4568                        "Config is relaunching resumed " + r);
4569
4570                if (DEBUG_STATES && !r.visible) {
4571                    Slog.v(TAG_STATES, "Config is relaunching resumed invisible activity " + r
4572                            + " called by " + Debug.getCallers(4));
4573                }
4574
4575                relaunchActivityLocked(r, r.configChangeFlags, true, preserveWindow);
4576            } else {
4577                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
4578                        "Config is relaunching non-resumed " + r);
4579                relaunchActivityLocked(r, r.configChangeFlags, false, preserveWindow);
4580            }
4581
4582            // All done...  tell the caller we weren't able to keep this activity around.
4583            return false;
4584        }
4585
4586        // Default case: the activity can handle this new configuration, so hand it over.
4587        // NOTE: We only forward the task override configuration as the system level configuration
4588        // changes is always sent to all processes when they happen so it can just use whatever
4589        // system level configuration it last got.
4590        r.scheduleConfigurationChanged(taskConfig, true);
4591        r.stopFreezingScreenLocked(false);
4592
4593        return true;
4594    }
4595
4596    private int getTaskConfigurationChanges(ActivityRecord record, Configuration taskConfig,
4597            Configuration oldTaskOverride) {
4598
4599        // If we went from full-screen to non-full-screen, make sure to use the correct
4600        // configuration task diff, so the diff stays as small as possible.
4601        if (Configuration.EMPTY.equals(oldTaskOverride)
4602                && !Configuration.EMPTY.equals(taskConfig)) {
4603            oldTaskOverride = record.task.extractOverrideConfig(record.configuration);
4604        }
4605
4606        // Conversely, do the same when going the other direction.
4607        if (Configuration.EMPTY.equals(taskConfig)
4608                && !Configuration.EMPTY.equals(oldTaskOverride)) {
4609            taskConfig = record.task.extractOverrideConfig(record.configuration);
4610        }
4611
4612        // Determine what has changed.  May be nothing, if this is a config
4613        // that has come back from the app after going idle.  In that case
4614        // we just want to leave the official config object now in the
4615        // activity and do nothing else.
4616        int taskChanges = oldTaskOverride.diff(taskConfig);
4617        // We don't want to use size changes if they don't cross boundaries that are important to
4618        // the app.
4619        if ((taskChanges & CONFIG_SCREEN_SIZE) != 0) {
4620            final boolean crosses = record.crossesHorizontalSizeThreshold(
4621                    oldTaskOverride.screenWidthDp, taskConfig.screenWidthDp)
4622                    || record.crossesVerticalSizeThreshold(
4623                    oldTaskOverride.screenHeightDp, taskConfig.screenHeightDp);
4624            if (!crosses) {
4625                taskChanges &= ~CONFIG_SCREEN_SIZE;
4626            }
4627        }
4628        if ((taskChanges & CONFIG_SMALLEST_SCREEN_SIZE) != 0) {
4629            final int oldSmallest = oldTaskOverride.smallestScreenWidthDp;
4630            final int newSmallest = taskConfig.smallestScreenWidthDp;
4631            if (!record.crossesSmallestSizeThreshold(oldSmallest, newSmallest)) {
4632                taskChanges &= ~CONFIG_SMALLEST_SCREEN_SIZE;
4633            }
4634        }
4635        return catchConfigChangesFromUnset(taskConfig, oldTaskOverride, taskChanges);
4636    }
4637
4638    private static int catchConfigChangesFromUnset(Configuration taskConfig,
4639            Configuration oldTaskOverride, int taskChanges) {
4640        if (taskChanges == 0) {
4641            // {@link Configuration#diff} doesn't catch changes from unset values.
4642            // Check for changes we care about.
4643            if (oldTaskOverride.orientation != taskConfig.orientation) {
4644                taskChanges |= CONFIG_ORIENTATION;
4645            }
4646            // We want to explicitly track situations where the size configuration goes from
4647            // undefined to defined. We don't care about crossing the threshold in that case,
4648            // because there is no threshold.
4649            final int oldHeight = oldTaskOverride.screenHeightDp;
4650            final int newHeight = taskConfig.screenHeightDp;
4651            final int undefinedHeight = Configuration.SCREEN_HEIGHT_DP_UNDEFINED;
4652            if ((oldHeight == undefinedHeight && newHeight != undefinedHeight)
4653                    || (oldHeight != undefinedHeight && newHeight == undefinedHeight)) {
4654                taskChanges |= CONFIG_SCREEN_SIZE;
4655            }
4656            final int oldWidth = oldTaskOverride.screenWidthDp;
4657            final int newWidth = taskConfig.screenWidthDp;
4658            final int undefinedWidth = Configuration.SCREEN_WIDTH_DP_UNDEFINED;
4659            if ((oldWidth == undefinedWidth && newWidth != undefinedWidth)
4660                    || (oldWidth != undefinedWidth && newWidth == undefinedWidth)) {
4661                taskChanges |= CONFIG_SCREEN_SIZE;
4662            }
4663            final int oldSmallest = oldTaskOverride.smallestScreenWidthDp;
4664            final int newSmallest = taskConfig.smallestScreenWidthDp;
4665            final int undefinedSmallest = Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED;
4666            if ((oldSmallest == undefinedSmallest && newSmallest != undefinedSmallest)
4667                    || (oldSmallest != undefinedSmallest && newSmallest == undefinedSmallest)) {
4668                taskChanges |= CONFIG_SMALLEST_SCREEN_SIZE;
4669            }
4670            final int oldLayout = oldTaskOverride.screenLayout;
4671            final int newLayout = taskConfig.screenLayout;
4672            if ((oldLayout == SCREENLAYOUT_UNDEFINED && newLayout != SCREENLAYOUT_UNDEFINED)
4673                || (oldLayout != SCREENLAYOUT_UNDEFINED && newLayout == SCREENLAYOUT_UNDEFINED)) {
4674                taskChanges |= CONFIG_SCREEN_LAYOUT;
4675            }
4676        }
4677        return taskChanges;
4678    }
4679
4680    private static boolean isResizeOnlyChange(int change) {
4681        return (change & ~(CONFIG_SCREEN_SIZE | CONFIG_SMALLEST_SCREEN_SIZE | CONFIG_ORIENTATION
4682                | CONFIG_SCREEN_LAYOUT)) == 0;
4683    }
4684
4685    private void relaunchActivityLocked(
4686            ActivityRecord r, int changes, boolean andResume, boolean preserveWindow) {
4687        if (mService.mSuppressResizeConfigChanges && preserveWindow) {
4688            r.configChangeFlags = 0;
4689            return;
4690        }
4691
4692        List<ResultInfo> results = null;
4693        List<ReferrerIntent> newIntents = null;
4694        if (andResume) {
4695            results = r.results;
4696            newIntents = r.newIntents;
4697        }
4698        if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
4699                "Relaunching: " + r + " with results=" + results + " newIntents=" + newIntents
4700                + " andResume=" + andResume + " preserveWindow=" + preserveWindow);
4701        EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4702                : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
4703                r.task.taskId, r.shortComponentName);
4704
4705        r.startFreezingScreenLocked(r.app, 0);
4706
4707        mStackSupervisor.removeChildActivityContainers(r);
4708
4709        try {
4710            if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_SWITCH,
4711                    "Moving to " + (andResume ? "RESUMED" : "PAUSED") + " Relaunching " + r
4712                    + " callers=" + Debug.getCallers(6));
4713            r.forceNewConfig = false;
4714            mStackSupervisor.activityRelaunchingLocked(r);
4715            r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents, changes,
4716                    !andResume, new Configuration(mService.mConfiguration),
4717                    new Configuration(r.task.mOverrideConfig), preserveWindow);
4718            // Note: don't need to call pauseIfSleepingLocked() here, because
4719            // the caller will only pass in 'andResume' if this activity is
4720            // currently resumed, which implies we aren't sleeping.
4721        } catch (RemoteException e) {
4722            if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_SWITCH, "Relaunch failed", e);
4723        }
4724
4725        if (andResume) {
4726            if (DEBUG_STATES) {
4727                Slog.d(TAG_STATES, "Resumed after relaunch " + r);
4728            }
4729            r.state = ActivityState.RESUMED;
4730            // Relaunch-resume could happen either when the app is already in the front,
4731            // or while it's being brought to front. In the latter case, it's marked RESUMED
4732            // but not yet visible (or stopped). We need to complete the resume here as the
4733            // code in resumeTopActivityInnerLocked to complete the resume might be skipped.
4734            if (!r.visible || r.stopped) {
4735                mWindowManager.setAppVisibility(r.appToken, true);
4736                completeResumeLocked(r);
4737            } else {
4738                r.results = null;
4739                r.newIntents = null;
4740            }
4741        } else {
4742            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4743            r.state = ActivityState.PAUSED;
4744        }
4745
4746        r.configChangeFlags = 0;
4747        r.deferRelaunchUntilPaused = false;
4748        r.preserveWindowOnDeferredRelaunch = false;
4749    }
4750
4751    boolean willActivityBeVisibleLocked(IBinder token) {
4752        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4753            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4754            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4755                final ActivityRecord r = activities.get(activityNdx);
4756                if (r.appToken == token) {
4757                    return true;
4758                }
4759                if (r.fullscreen && !r.finishing) {
4760                    return false;
4761                }
4762            }
4763        }
4764        final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4765        if (r == null) {
4766            return false;
4767        }
4768        if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false,"
4769                + " would have returned true for r=" + r);
4770        return !r.finishing;
4771    }
4772
4773    void closeSystemDialogsLocked() {
4774        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4775            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4776            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4777                final ActivityRecord r = activities.get(activityNdx);
4778                if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
4779                    finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true);
4780                }
4781            }
4782        }
4783    }
4784
4785    boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
4786            boolean doit, boolean evenPersistent, int userId) {
4787        boolean didSomething = false;
4788        TaskRecord lastTask = null;
4789        ComponentName homeActivity = null;
4790        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4791            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4792            int numActivities = activities.size();
4793            for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
4794                ActivityRecord r = activities.get(activityNdx);
4795                final boolean sameComponent =
4796                        (r.packageName.equals(packageName) && (filterByClasses == null
4797                                || filterByClasses.contains(r.realActivity.getClassName())))
4798                        || (packageName == null && r.userId == userId);
4799                if ((userId == UserHandle.USER_ALL || r.userId == userId)
4800                        && (sameComponent || r.task == lastTask)
4801                        && (r.app == null || evenPersistent || !r.app.persistent)) {
4802                    if (!doit) {
4803                        if (r.finishing) {
4804                            // If this activity is just finishing, then it is not
4805                            // interesting as far as something to stop.
4806                            continue;
4807                        }
4808                        return true;
4809                    }
4810                    if (r.isHomeActivity()) {
4811                        if (homeActivity != null && homeActivity.equals(r.realActivity)) {
4812                            Slog.i(TAG, "Skip force-stop again " + r);
4813                            continue;
4814                        } else {
4815                            homeActivity = r.realActivity;
4816                        }
4817                    }
4818                    didSomething = true;
4819                    Slog.i(TAG, "  Force finishing activity " + r);
4820                    if (sameComponent) {
4821                        if (r.app != null) {
4822                            r.app.removed = true;
4823                        }
4824                        r.app = null;
4825                    }
4826                    lastTask = r.task;
4827                    if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop",
4828                            true)) {
4829                        // r has been deleted from mActivities, accommodate.
4830                        --numActivities;
4831                        --activityNdx;
4832                    }
4833                }
4834            }
4835        }
4836        return didSomething;
4837    }
4838
4839    void getTasksLocked(List<RunningTaskInfo> list, int callingUid, boolean allowed) {
4840        boolean focusedStack = mStackSupervisor.getFocusedStack() == this;
4841        boolean topTask = true;
4842        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4843            final TaskRecord task = mTaskHistory.get(taskNdx);
4844            if (task.getTopActivity() == null) {
4845                continue;
4846            }
4847            ActivityRecord r = null;
4848            ActivityRecord top = null;
4849            ActivityRecord tmp;
4850            int numActivities = 0;
4851            int numRunning = 0;
4852            final ArrayList<ActivityRecord> activities = task.mActivities;
4853            if (!allowed && !task.isHomeTask() && task.effectiveUid != callingUid) {
4854                continue;
4855            }
4856            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4857                tmp = activities.get(activityNdx);
4858                if (tmp.finishing) {
4859                    continue;
4860                }
4861                r = tmp;
4862
4863                // Initialize state for next task if needed.
4864                if (top == null || (top.state == ActivityState.INITIALIZING)) {
4865                    top = r;
4866                    numActivities = numRunning = 0;
4867                }
4868
4869                // Add 'r' into the current task.
4870                numActivities++;
4871                if (r.app != null && r.app.thread != null) {
4872                    numRunning++;
4873                }
4874
4875                if (DEBUG_ALL) Slog.v(
4876                    TAG, r.intent.getComponent().flattenToShortString()
4877                    + ": task=" + r.task);
4878            }
4879
4880            RunningTaskInfo ci = new RunningTaskInfo();
4881            ci.id = task.taskId;
4882            ci.stackId = mStackId;
4883            ci.baseActivity = r.intent.getComponent();
4884            ci.topActivity = top.intent.getComponent();
4885            ci.lastActiveTime = task.lastActiveTime;
4886            if (focusedStack && topTask) {
4887                // Give the latest time to ensure foreground task can be sorted
4888                // at the first, because lastActiveTime of creating task is 0.
4889                ci.lastActiveTime = System.currentTimeMillis();
4890                topTask = false;
4891            }
4892
4893            if (top.task != null) {
4894                ci.description = top.task.lastDescription;
4895            }
4896            ci.numActivities = numActivities;
4897            ci.numRunning = numRunning;
4898            ci.isDockable = task.canGoInDockedStack();
4899            ci.resizeMode = task.mResizeMode;
4900            list.add(ci);
4901        }
4902    }
4903
4904    public void unhandledBackLocked() {
4905        final int top = mTaskHistory.size() - 1;
4906        if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, "Performing unhandledBack(): top activity at " + top);
4907        if (top >= 0) {
4908            final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
4909            int activityTop = activities.size() - 1;
4910            if (activityTop > 0) {
4911                finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
4912                        "unhandled-back", true);
4913            }
4914        }
4915    }
4916
4917    /**
4918     * Reset local parameters because an app's activity died.
4919     * @param app The app of the activity that died.
4920     * @return result from removeHistoryRecordsForAppLocked.
4921     */
4922    boolean handleAppDiedLocked(ProcessRecord app) {
4923        if (mPausingActivity != null && mPausingActivity.app == app) {
4924            if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG_PAUSE,
4925                    "App died while pausing: " + mPausingActivity);
4926            mPausingActivity = null;
4927        }
4928        if (mLastPausedActivity != null && mLastPausedActivity.app == app) {
4929            mLastPausedActivity = null;
4930            mLastNoHistoryActivity = null;
4931        }
4932
4933        return removeHistoryRecordsForAppLocked(app);
4934    }
4935
4936    void handleAppCrashLocked(ProcessRecord app) {
4937        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4938            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4939            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4940                final ActivityRecord r = activities.get(activityNdx);
4941                if (r.app == app) {
4942                    Slog.w(TAG, "  Force finishing activity "
4943                            + r.intent.getComponent().flattenToShortString());
4944                    // Force the destroy to skip right to removal.
4945                    r.app = null;
4946                    finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
4947                }
4948            }
4949        }
4950    }
4951
4952    boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
4953            boolean dumpClient, String dumpPackage, boolean needSep, String header) {
4954        boolean printed = false;
4955        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4956            final TaskRecord task = mTaskHistory.get(taskNdx);
4957            printed |= ActivityStackSupervisor.dumpHistoryList(fd, pw,
4958                    mTaskHistory.get(taskNdx).mActivities, "    ", "Hist", true, !dumpAll,
4959                    dumpClient, dumpPackage, needSep, header,
4960                    "    Task id #" + task.taskId + "\n" +
4961                    "    mFullscreen=" + task.mFullscreen + "\n" +
4962                    "    mBounds=" + task.mBounds + "\n" +
4963                    "    mMinWidth=" + task.mMinWidth + "\n" +
4964                    "    mMinHeight=" + task.mMinHeight + "\n" +
4965                    "    mLastNonFullscreenBounds=" + task.mLastNonFullscreenBounds);
4966            if (printed) {
4967                header = null;
4968            }
4969        }
4970        return printed;
4971    }
4972
4973    ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
4974        ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
4975
4976        if ("all".equals(name)) {
4977            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4978                activities.addAll(mTaskHistory.get(taskNdx).mActivities);
4979            }
4980        } else if ("top".equals(name)) {
4981            final int top = mTaskHistory.size() - 1;
4982            if (top >= 0) {
4983                final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities;
4984                int listTop = list.size() - 1;
4985                if (listTop >= 0) {
4986                    activities.add(list.get(listTop));
4987                }
4988            }
4989        } else {
4990            ItemMatcher matcher = new ItemMatcher();
4991            matcher.build(name);
4992
4993            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4994                for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) {
4995                    if (matcher.match(r1, r1.intent.getComponent())) {
4996                        activities.add(r1);
4997                    }
4998                }
4999            }
5000        }
5001
5002        return activities;
5003    }
5004
5005    ActivityRecord restartPackage(String packageName) {
5006        ActivityRecord starting = topRunningActivityLocked();
5007
5008        // All activities that came from the package must be
5009        // restarted as if there was a config change.
5010        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5011            final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
5012            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
5013                final ActivityRecord a = activities.get(activityNdx);
5014                if (a.info.packageName.equals(packageName)) {
5015                    a.forceNewConfig = true;
5016                    if (starting != null && a == starting && a.visible) {
5017                        a.startFreezingScreenLocked(starting.app,
5018                                CONFIG_SCREEN_LAYOUT);
5019                    }
5020                }
5021            }
5022        }
5023
5024        return starting;
5025    }
5026
5027    void removeTask(TaskRecord task, String reason) {
5028        removeTask(task, reason, REMOVE_TASK_MODE_DESTROYING);
5029    }
5030
5031    /**
5032     * Removes the input task from this stack.
5033     * @param task to remove.
5034     * @param reason for removal.
5035     * @param mode task removal mode. Either {@link #REMOVE_TASK_MODE_DESTROYING},
5036     *             {@link #REMOVE_TASK_MODE_MOVING}, {@link #REMOVE_TASK_MODE_MOVING_TO_TOP}.
5037     */
5038    void removeTask(TaskRecord task, String reason, int mode) {
5039        if (mode == REMOVE_TASK_MODE_DESTROYING) {
5040            mStackSupervisor.removeLockedTaskLocked(task);
5041            mWindowManager.removeTask(task.taskId);
5042            if (!StackId.persistTaskBounds(mStackId)) {
5043                // Reset current bounds for task whose bounds shouldn't be persisted so it uses
5044                // default configuration the next time it launches.
5045                task.updateOverrideConfiguration(null);
5046            }
5047        }
5048
5049        final ActivityRecord r = mResumedActivity;
5050        if (r != null && r.task == task) {
5051            mResumedActivity = null;
5052        }
5053
5054        final int taskNdx = mTaskHistory.indexOf(task);
5055        final int topTaskNdx = mTaskHistory.size() - 1;
5056        if (task.isOverHomeStack() && taskNdx < topTaskNdx) {
5057            final TaskRecord nextTask = mTaskHistory.get(taskNdx + 1);
5058            if (!nextTask.isOverHomeStack()) {
5059                nextTask.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
5060            }
5061        }
5062        mTaskHistory.remove(task);
5063        updateTaskMovement(task, true);
5064
5065        if (mode == REMOVE_TASK_MODE_DESTROYING && task.mActivities.isEmpty()) {
5066            // TODO: VI what about activity?
5067            final boolean isVoiceSession = task.voiceSession != null;
5068            if (isVoiceSession) {
5069                try {
5070                    task.voiceSession.taskFinished(task.intent, task.taskId);
5071                } catch (RemoteException e) {
5072                }
5073            }
5074            if (task.autoRemoveFromRecents() || isVoiceSession) {
5075                // Task creator asked to remove this when done, or this task was a voice
5076                // interaction, so it should not remain on the recent tasks list.
5077                mRecentTasks.remove(task);
5078                task.removedFromRecents();
5079            }
5080        }
5081
5082        if (mTaskHistory.isEmpty()) {
5083            if (DEBUG_STACK) Slog.i(TAG_STACK, "removeTask: removing stack=" + this);
5084            // We only need to adjust focused stack if this stack is in focus and we are not in the
5085            // process of moving the task to the top of the stack that will be focused.
5086            if (isOnHomeDisplay() && mode != REMOVE_TASK_MODE_MOVING_TO_TOP
5087                    && mStackSupervisor.isFocusedStack(this)) {
5088                String myReason = reason + " leftTaskHistoryEmpty";
5089                if (mFullscreen
5090                        || !adjustFocusToNextFocusableStackLocked(
5091                        task.getTaskToReturnTo(), myReason)) {
5092                    mStackSupervisor.moveHomeStackToFront(myReason);
5093                }
5094            }
5095            if (mStacks != null) {
5096                mStacks.remove(this);
5097                mStacks.add(0, this);
5098            }
5099            if (!isHomeStack()) {
5100                mActivityContainer.onTaskListEmptyLocked();
5101            }
5102        }
5103
5104        task.stack = null;
5105    }
5106
5107    TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
5108            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
5109            boolean toTop) {
5110        TaskRecord task = new TaskRecord(mService, taskId, info, intent, voiceSession,
5111                voiceInteractor);
5112        // add the task to stack first, mTaskPositioner might need the stack association
5113        addTask(task, toTop, "createTaskRecord");
5114        final boolean isLockscreenShown = mService.mLockScreenShown == LOCK_SCREEN_SHOWN;
5115        if (!layoutTaskInStack(task, info.windowLayout) && mBounds != null && task.isResizeable()
5116                && !isLockscreenShown) {
5117            task.updateOverrideConfiguration(mBounds);
5118        }
5119        return task;
5120    }
5121
5122    boolean layoutTaskInStack(TaskRecord task, ActivityInfo.WindowLayout windowLayout) {
5123        if (mTaskPositioner == null) {
5124            return false;
5125        }
5126        mTaskPositioner.updateDefaultBounds(task, mTaskHistory, windowLayout);
5127        return true;
5128    }
5129
5130    ArrayList<TaskRecord> getAllTasks() {
5131        return new ArrayList<>(mTaskHistory);
5132    }
5133
5134    void addTask(final TaskRecord task, final boolean toTop, String reason) {
5135        final ActivityStack prevStack = preAddTask(task, reason, toTop);
5136
5137        task.stack = this;
5138        if (toTop) {
5139            insertTaskAtTop(task, null);
5140        } else {
5141            mTaskHistory.add(0, task);
5142            updateTaskMovement(task, false);
5143        }
5144        postAddTask(task, prevStack);
5145    }
5146
5147    void positionTask(final TaskRecord task, int position) {
5148        final ActivityRecord topRunningActivity = task.topRunningActivityLocked();
5149        final boolean wasResumed = topRunningActivity == task.stack.mResumedActivity;
5150        final ActivityStack prevStack = preAddTask(task, "positionTask", !ON_TOP);
5151        task.stack = this;
5152        insertTaskAtPosition(task, position);
5153        postAddTask(task, prevStack);
5154        if (wasResumed) {
5155            if (mResumedActivity != null) {
5156                Log.wtf(TAG, "mResumedActivity was already set when moving mResumedActivity from"
5157                        + " other stack to this stack mResumedActivity=" + mResumedActivity
5158                        + " other mResumedActivity=" + topRunningActivity);
5159            }
5160            mResumedActivity = topRunningActivity;
5161        }
5162    }
5163
5164    private ActivityStack preAddTask(TaskRecord task, String reason, boolean toTop) {
5165        final ActivityStack prevStack = task.stack;
5166        if (prevStack != null && prevStack != this) {
5167            prevStack.removeTask(task, reason,
5168                    toTop ? REMOVE_TASK_MODE_MOVING_TO_TOP : REMOVE_TASK_MODE_MOVING);
5169        }
5170        return prevStack;
5171    }
5172
5173    private void postAddTask(TaskRecord task, ActivityStack prevStack) {
5174        if (prevStack != null) {
5175            mStackSupervisor.scheduleReportPictureInPictureModeChangedIfNeeded(task, prevStack);
5176        } else if (task.voiceSession != null) {
5177            try {
5178                task.voiceSession.taskStarted(task.intent, task.taskId);
5179            } catch (RemoteException e) {
5180            }
5181        }
5182    }
5183
5184    void addConfigOverride(ActivityRecord r, TaskRecord task) {
5185        final Rect bounds = task.updateOverrideConfigurationFromLaunchBounds();
5186        // TODO: VI deal with activity
5187        mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
5188                r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
5189                (r.info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0, r.userId, r.info.configChanges,
5190                task.voiceSession != null, r.mLaunchTaskBehind, bounds, task.mOverrideConfig,
5191                task.mResizeMode, r.isAlwaysFocusable(), task.isHomeTask(),
5192                r.appInfo.targetSdkVersion);
5193        r.taskConfigOverride = task.mOverrideConfig;
5194    }
5195
5196    void moveToFrontAndResumeStateIfNeeded(
5197            ActivityRecord r, boolean moveToFront, boolean setResume, String reason) {
5198        if (!moveToFront) {
5199            return;
5200        }
5201
5202        // If the activity owns the last resumed activity, transfer that together,
5203        // so that we don't resume the same activity again in the new stack.
5204        // Apps may depend on onResume()/onPause() being called in pairs.
5205        if (setResume) {
5206            mResumedActivity = r;
5207        }
5208        // Move the stack in which we are placing the activity to the front. The call will also
5209        // make sure the activity focus is set.
5210        moveToFront(reason);
5211    }
5212
5213    /**
5214     * Moves the input activity from its current stack to this one.
5215     * NOTE: The current task of the activity isn't moved to this stack. Instead a new task is
5216     * created on this stack which the activity is added to.
5217     * */
5218    void moveActivityToStack(ActivityRecord r) {
5219        final ActivityStack prevStack = r.task.stack;
5220        if (prevStack.mStackId == mStackId) {
5221            // You are already in the right stack silly...
5222            return;
5223        }
5224
5225        final boolean wasFocused = mStackSupervisor.isFocusedStack(prevStack)
5226                && (mStackSupervisor.topRunningActivityLocked() == r);
5227        final boolean wasResumed = wasFocused && (prevStack.mResumedActivity == r);
5228
5229        final TaskRecord task = createTaskRecord(
5230                mStackSupervisor.getNextTaskIdForUserLocked(r.userId),
5231                r.info, r.intent, null, null, true);
5232        r.setTask(task, null);
5233        task.addActivityToTop(r);
5234        setAppTask(r, task);
5235        mStackSupervisor.scheduleReportPictureInPictureModeChangedIfNeeded(task, prevStack);
5236        moveToFrontAndResumeStateIfNeeded(r, wasFocused, wasResumed, "moveActivityToStack");
5237        if (wasResumed) {
5238            prevStack.mResumedActivity = null;
5239        }
5240    }
5241
5242    private void setAppTask(ActivityRecord r, TaskRecord task) {
5243        final Rect bounds = task.updateOverrideConfigurationFromLaunchBounds();
5244        mWindowManager.setAppTask(r.appToken, task.taskId, mStackId, bounds, task.mOverrideConfig,
5245                task.mResizeMode, task.isHomeTask());
5246        r.taskConfigOverride = task.mOverrideConfig;
5247    }
5248
5249    public int getStackId() {
5250        return mStackId;
5251    }
5252
5253    @Override
5254    public String toString() {
5255        return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this))
5256                + " stackId=" + mStackId + ", " + mTaskHistory.size() + " tasks}";
5257    }
5258
5259    void onLockTaskPackagesUpdatedLocked() {
5260        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5261            mTaskHistory.get(taskNdx).setLockTaskAuth();
5262        }
5263    }
5264}
5265