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