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