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