OSDN Git Service

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