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