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