OSDN Git Service

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