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