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