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