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