OSDN Git Service

c09947c402fbac705f08ef366e7c617e73513ae2
[android-x86/frameworks-base.git] / services / core / java / com / android / server / am / ActivityRecord.java
1 /*
2  * Copyright (C) 2006 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 android.app.ActivityManager.ENABLE_TASK_SNAPSHOTS;
20 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
21 import static android.app.ActivityManager.StackId;
22 import static android.app.ActivityManager.StackId.ASSISTANT_STACK_ID;
23 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
24 import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
25 import static android.app.ActivityManager.StackId.HOME_STACK_ID;
26 import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
27 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
28 import static android.app.ActivityManager.TaskDescription.ATTR_TASKDESCRIPTION_PREFIX;
29 import static android.app.ActivityOptions.ANIM_CLIP_REVEAL;
30 import static android.app.ActivityOptions.ANIM_CUSTOM;
31 import static android.app.ActivityOptions.ANIM_SCALE_UP;
32 import static android.app.ActivityOptions.ANIM_SCENE_TRANSITION;
33 import static android.app.ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_DOWN;
34 import static android.app.ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_UP;
35 import static android.app.ActivityOptions.ANIM_THUMBNAIL_SCALE_DOWN;
36 import static android.app.ActivityOptions.ANIM_THUMBNAIL_SCALE_UP;
37 import static android.app.AppOpsManager.MODE_ALLOWED;
38 import static android.app.AppOpsManager.OP_PICTURE_IN_PICTURE;
39 import static android.content.Intent.ACTION_MAIN;
40 import static android.content.Intent.CATEGORY_HOME;
41 import static android.content.Intent.CATEGORY_LAUNCHER;
42 import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
43 import static android.content.Intent.FLAG_ACTIVITY_NO_HISTORY;
44 import static android.content.pm.ActivityInfo.CONFIG_APP_BOUNDS;
45 import static android.content.pm.ActivityInfo.CONFIG_ORIENTATION;
46 import static android.content.pm.ActivityInfo.CONFIG_ROTATION;
47 import static android.content.pm.ActivityInfo.CONFIG_SCREEN_LAYOUT;
48 import static android.content.pm.ActivityInfo.CONFIG_SCREEN_SIZE;
49 import static android.content.pm.ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
50 import static android.content.pm.ActivityInfo.CONFIG_UI_MODE;
51 import static android.content.pm.ActivityInfo.FLAG_ALWAYS_FOCUSABLE;
52 import static android.content.pm.ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
53 import static android.content.pm.ActivityInfo.FLAG_IMMERSIVE;
54 import static android.content.pm.ActivityInfo.FLAG_MULTIPROCESS;
55 import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS;
56 import static android.content.pm.ActivityInfo.FLAG_STATE_NOT_NEEDED;
57 import static android.content.pm.ActivityInfo.LAUNCH_MULTIPLE;
58 import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_INSTANCE;
59 import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TASK;
60 import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TOP;
61 import static android.content.pm.ActivityInfo.PERSIST_ACROSS_REBOOTS;
62 import static android.content.pm.ActivityInfo.PERSIST_ROOT_ONLY;
63 import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZEABLE;
64 import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE;
65 import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION;
66 import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
67 import static android.content.pm.ActivityInfo.FLAG_NO_HISTORY;
68 import static android.content.pm.ActivityInfo.isFixedOrientationLandscape;
69 import static android.content.pm.ActivityInfo.isFixedOrientationPortrait;
70 import static android.content.res.Configuration.EMPTY;
71 import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
72 import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
73 import static android.content.res.Configuration.UI_MODE_TYPE_MASK;
74 import static android.content.res.Configuration.UI_MODE_TYPE_VR_HEADSET;
75 import static android.os.Build.VERSION_CODES.HONEYCOMB;
76 import static android.os.Build.VERSION_CODES.O;
77 import static android.os.Process.SYSTEM_UID;
78 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
79 import static android.view.WindowManagerPolicy.NAV_BAR_LEFT;
80
81 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION;
82 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SAVED_STATE;
83 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SCREENSHOTS;
84 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STATES;
85 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
86 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_THUMBNAILS;
87 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBILITY;
88 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONFIGURATION;
89 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SAVED_STATE;
90 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SCREENSHOTS;
91 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
92 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
93 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_THUMBNAILS;
94 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBILITY;
95 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
96 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
97 import static com.android.server.am.ActivityManagerService.IS_USER_BUILD;
98 import static com.android.server.am.ActivityManagerService.TAKE_FULLSCREEN_SCREENSHOTS;
99 import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
100 import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
101 import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
102 import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
103 import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
104 import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
105 import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
106 import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
107 import static com.android.server.am.ActivityStack.LAUNCH_TICK;
108 import static com.android.server.am.ActivityStack.LAUNCH_TICK_MSG;
109 import static com.android.server.am.ActivityStack.PAUSE_TIMEOUT_MSG;
110 import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
111 import static com.android.server.am.ActivityStack.STOP_TIMEOUT_MSG;
112 import static com.android.server.am.EventLogTags.AM_ACTIVITY_FULLY_DRAWN_TIME;
113 import static com.android.server.am.EventLogTags.AM_ACTIVITY_LAUNCH_TIME;
114 import static com.android.server.am.EventLogTags.AM_RELAUNCH_ACTIVITY;
115 import static com.android.server.am.EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY;
116 import static com.android.server.am.TaskPersister.DEBUG;
117 import static com.android.server.am.TaskPersister.IMAGE_EXTENSION;
118 import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
119 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
120 import static org.xmlpull.v1.XmlPullParser.END_TAG;
121 import static org.xmlpull.v1.XmlPullParser.START_TAG;
122
123 import android.annotation.NonNull;
124 import android.app.ActivityManager.TaskDescription;
125 import android.app.ActivityOptions;
126 import android.app.PendingIntent;
127 import android.app.PictureInPictureParams;
128 import android.app.ResultInfo;
129 import android.content.ComponentName;
130 import android.content.Intent;
131 import android.content.pm.ActivityInfo;
132 import android.content.pm.ApplicationInfo;
133 import android.content.res.CompatibilityInfo;
134 import android.content.res.Configuration;
135 import android.graphics.Bitmap;
136 import android.graphics.GraphicBuffer;
137 import android.graphics.Rect;
138 import android.os.Build;
139 import android.os.Bundle;
140 import android.os.Debug;
141 import android.os.IBinder;
142 import android.os.Message;
143 import android.os.PersistableBundle;
144 import android.os.Process;
145 import android.os.RemoteException;
146 import android.os.SystemClock;
147 import android.os.Trace;
148 import android.os.UserHandle;
149 import android.service.voice.IVoiceInteractionSession;
150 import android.util.EventLog;
151 import android.util.Log;
152 import android.util.MergedConfiguration;
153 import android.util.Slog;
154 import android.util.TimeUtils;
155 import android.view.AppTransitionAnimationSpec;
156 import android.view.IAppTransitionAnimationSpecsFuture;
157 import android.view.IApplicationToken;
158 import android.view.WindowManager.LayoutParams;
159
160 import com.android.internal.annotations.VisibleForTesting;
161 import com.android.internal.app.ResolverActivity;
162 import com.android.internal.content.ReferrerIntent;
163 import com.android.internal.util.XmlUtils;
164 import com.android.server.AttributeCache;
165 import com.android.server.AttributeCache.Entry;
166 import com.android.server.am.ActivityStack.ActivityState;
167 import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
168 import com.android.server.wm.AppWindowContainerController;
169 import com.android.server.wm.AppWindowContainerListener;
170 import com.android.server.wm.TaskWindowContainerController;
171
172 import org.xmlpull.v1.XmlPullParser;
173 import org.xmlpull.v1.XmlPullParserException;
174 import org.xmlpull.v1.XmlSerializer;
175
176 import java.io.File;
177 import java.io.IOException;
178 import java.io.PrintWriter;
179 import java.lang.ref.WeakReference;
180 import java.util.ArrayList;
181 import java.util.Arrays;
182 import java.util.HashSet;
183 import java.util.List;
184 import java.util.Objects;
185
186 /**
187  * An entry in the history stack, representing an activity.
188  */
189 final class ActivityRecord extends ConfigurationContainer implements AppWindowContainerListener {
190     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityRecord" : TAG_AM;
191     private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
192     private static final String TAG_SAVED_STATE = TAG + POSTFIX_SAVED_STATE;
193     private static final String TAG_SCREENSHOTS = TAG + POSTFIX_SCREENSHOTS;
194     private static final String TAG_STATES = TAG + POSTFIX_STATES;
195     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
196     private static final String TAG_THUMBNAILS = TAG + POSTFIX_THUMBNAILS;
197     private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
198
199     private static final boolean SHOW_ACTIVITY_START_TIME = true;
200     private static final String RECENTS_PACKAGE_NAME = "com.android.systemui.recents";
201
202     private static final String ATTR_ID = "id";
203     private static final String TAG_INTENT = "intent";
204     private static final String ATTR_USERID = "user_id";
205     private static final String TAG_PERSISTABLEBUNDLE = "persistable_bundle";
206     private static final String ATTR_LAUNCHEDFROMUID = "launched_from_uid";
207     private static final String ATTR_LAUNCHEDFROMPACKAGE = "launched_from_package";
208     private static final String ATTR_RESOLVEDTYPE = "resolved_type";
209     private static final String ATTR_COMPONENTSPECIFIED = "component_specified";
210     static final String ACTIVITY_ICON_SUFFIX = "_activity_icon_";
211
212     final ActivityManagerService service; // owner
213     final IApplicationToken.Stub appToken; // window manager token
214     AppWindowContainerController mWindowContainerController;
215     final ActivityInfo info; // all about me
216     final ApplicationInfo appInfo; // information about activity's app
217     final int launchedFromPid; // always the pid who started the activity.
218     final int launchedFromUid; // always the uid who started the activity.
219     final String launchedFromPackage; // always the package who started the activity.
220     final int userId;          // Which user is this running for?
221     final Intent intent;    // the original intent that generated us
222     final ComponentName realActivity;  // the intent component, or target of an alias.
223     final String shortComponentName; // the short component name of the intent
224     final String resolvedType; // as per original caller;
225     final String packageName; // the package implementing intent's component
226     final String processName; // process where this component wants to run
227     final String taskAffinity; // as per ActivityInfo.taskAffinity
228     final boolean stateNotNeeded; // As per ActivityInfo.flags
229     boolean fullscreen; // covers the full screen?
230     final boolean noDisplay;  // activity is not displayed?
231     private final boolean componentSpecified;  // did caller specify an explicit component?
232     final boolean rootVoiceInteraction;  // was this the root activity of a voice interaction?
233
234     static final int APPLICATION_ACTIVITY_TYPE = 0;
235     static final int HOME_ACTIVITY_TYPE = 1;
236     static final int RECENTS_ACTIVITY_TYPE = 2;
237     static final int ASSISTANT_ACTIVITY_TYPE = 3;
238     int mActivityType;
239
240     private CharSequence nonLocalizedLabel;  // the label information from the package mgr.
241     private int labelRes;           // the label information from the package mgr.
242     private int icon;               // resource identifier of activity's icon.
243     private int logo;               // resource identifier of activity's logo.
244     private int theme;              // resource identifier of activity's theme.
245     private int realTheme;          // actual theme resource we will use, never 0.
246     private int windowFlags;        // custom window flags for preview window.
247     private TaskRecord task;        // the task this is in.
248     private long createTime = System.currentTimeMillis();
249     long displayStartTime;  // when we started launching this activity
250     long fullyDrawnStartTime; // when we started launching this activity
251     private long startTime;         // last time this activity was started
252     long lastVisibleTime;   // last time this activity became visible
253     long cpuTimeAtResume;   // the cpu time of host process at the time of resuming activity
254     long pauseTime;         // last time we started pausing the activity
255     long launchTickTime;    // base time for launch tick messages
256     // Last configuration reported to the activity in the client process.
257     private MergedConfiguration mLastReportedConfiguration;
258     private int mLastReportedDisplayId;
259     private boolean mLastReportedMultiWindowMode;
260     private boolean mLastReportedPictureInPictureMode;
261     CompatibilityInfo compat;// last used compatibility mode
262     ActivityRecord resultTo; // who started this entry, so will get our reply
263     final String resultWho; // additional identifier for use by resultTo.
264     final int requestCode;  // code given by requester (resultTo)
265     ArrayList<ResultInfo> results; // pending ActivityResult objs we have received
266     HashSet<WeakReference<PendingIntentRecord>> pendingResults; // all pending intents for this act
267     ArrayList<ReferrerIntent> newIntents; // any pending new intents for single-top mode
268     ActivityOptions pendingOptions; // most recently given options
269     ActivityOptions returningOptions; // options that are coming back via convertToTranslucent
270     AppTimeTracker appTimeTracker; // set if we are tracking the time in this app/task/activity
271     HashSet<ConnectionRecord> connections; // All ConnectionRecord we hold
272     UriPermissionOwner uriPermissions; // current special URI access perms.
273     ProcessRecord app;      // if non-null, hosting application
274     ActivityState state;    // current state we are in
275     Bundle  icicle;         // last saved activity state
276     PersistableBundle persistentState; // last persistently saved activity state
277     boolean frontOfTask;    // is this the root activity of its task?
278     boolean launchFailed;   // set if a launched failed, to abort on 2nd try
279     boolean haveState;      // have we gotten the last activity state?
280     boolean stopped;        // is activity pause finished?
281     boolean delayedResume;  // not yet resumed because of stopped app switches?
282     boolean finishing;      // activity in pending finish list?
283     boolean deferRelaunchUntilPaused;   // relaunch of activity is being deferred until pause is
284                                         // completed
285     boolean preserveWindowOnDeferredRelaunch; // activity windows are preserved on deferred relaunch
286     int configChangeFlags;  // which config values have changed
287     private boolean keysPaused;     // has key dispatching been paused for it?
288     int launchMode;         // the launch mode activity attribute.
289     boolean visible;        // does this activity's window need to be shown?
290     boolean visibleIgnoringKeyguard; // is this activity visible, ignoring the fact that Keyguard
291                                      // might hide this activity?
292     private boolean mDeferHidingClient; // If true we told WM to defer reporting to the client
293                                         // process that it is hidden.
294     boolean sleeping;       // have we told the activity to sleep?
295     boolean nowVisible;     // is this activity's window visible?
296     boolean idle;           // has the activity gone idle?
297     boolean hasBeenLaunched;// has this activity ever been launched?
298     boolean frozenBeforeDestroy;// has been frozen but not yet destroyed.
299     boolean immersive;      // immersive mode (don't interrupt if possible)
300     boolean forceNewConfig; // force re-create with new config next time
301     boolean supportsPictureInPictureWhilePausing;  // This flag is set by the system to indicate
302         // that the activity can enter picture in picture while pausing (ie. only when another
303         // task is brought to front or started)
304     PictureInPictureParams pictureInPictureArgs = new PictureInPictureParams.Builder().build();
305         // The PiP params used when deferring the entering of picture-in-picture.
306     int launchCount;        // count of launches since last state
307     long lastLaunchTime;    // time of last launch of this activity
308     ComponentName requestedVrComponent; // the requested component for handling VR mode.
309     ArrayList<ActivityContainer> mChildContainers = new ArrayList<>();
310
311     String stringName;      // for caching of toString().
312
313     private boolean inHistory;  // are we in the history stack?
314     final ActivityStackSupervisor mStackSupervisor;
315
316     static final int STARTING_WINDOW_NOT_SHOWN = 0;
317     static final int STARTING_WINDOW_SHOWN = 1;
318     static final int STARTING_WINDOW_REMOVED = 2;
319     int mStartingWindowState = STARTING_WINDOW_NOT_SHOWN;
320     boolean mTaskOverlay = false; // Task is always on-top of other activities in the task.
321
322     boolean mUpdateTaskThumbnailWhenHidden;
323     ActivityContainer mInitialActivityContainer;
324
325     TaskDescription taskDescription; // the recents information for this activity
326     boolean mLaunchTaskBehind; // this activity is actively being launched with
327         // ActivityOptions.setLaunchTaskBehind, will be cleared once launch is completed.
328
329     // These configurations are collected from application's resources based on size-sensitive
330     // qualifiers. For example, layout-w800dp will be added to mHorizontalSizeConfigurations as 800
331     // and drawable-sw400dp will be added to both as 400.
332     private int[] mVerticalSizeConfigurations;
333     private int[] mHorizontalSizeConfigurations;
334     private int[] mSmallestSizeConfigurations;
335
336     boolean pendingVoiceInteractionStart;   // Waiting for activity-invoked voice session
337     IVoiceInteractionSession voiceSession;  // Voice interaction session for this activity
338
339     // A hint to override the window specified rotation animation, or -1
340     // to use the window specified value. We use this so that
341     // we can select the right animation in the cases of starting
342     // windows, where the app hasn't had time to set a value
343     // on the window.
344     int mRotationAnimationHint = -1;
345
346     // The bounds of this activity. Mainly used for aspect-ratio compatibility.
347     // TODO(b/36505427): Every level on ConfigurationContainer now has bounds information, which
348     // directly affects the configuration. We should probably move this into that class and have it
349     // handle calculating override configuration from the bounds.
350     private final Rect mBounds = new Rect();
351
352     /**
353      * Temp configs used in {@link #ensureActivityConfigurationLocked(int, boolean)}
354      */
355     private final Configuration mTmpConfig = new Configuration();
356     private final Rect mTmpBounds = new Rect();
357
358     private static String startingWindowStateToString(int state) {
359         switch (state) {
360             case STARTING_WINDOW_NOT_SHOWN:
361                 return "STARTING_WINDOW_NOT_SHOWN";
362             case STARTING_WINDOW_SHOWN:
363                 return "STARTING_WINDOW_SHOWN";
364             case STARTING_WINDOW_REMOVED:
365                 return "STARTING_WINDOW_REMOVED";
366             default:
367                 return "unknown state=" + state;
368         }
369     }
370
371     void dump(PrintWriter pw, String prefix) {
372         final long now = SystemClock.uptimeMillis();
373         pw.print(prefix); pw.print("packageName="); pw.print(packageName);
374                 pw.print(" processName="); pw.println(processName);
375         pw.print(prefix); pw.print("launchedFromUid="); pw.print(launchedFromUid);
376                 pw.print(" launchedFromPackage="); pw.print(launchedFromPackage);
377                 pw.print(" userId="); pw.println(userId);
378         pw.print(prefix); pw.print("app="); pw.println(app);
379         pw.print(prefix); pw.println(intent.toInsecureStringWithClip());
380         pw.print(prefix); pw.print("frontOfTask="); pw.print(frontOfTask);
381                 pw.print(" task="); pw.println(task);
382         pw.print(prefix); pw.print("taskAffinity="); pw.println(taskAffinity);
383         pw.print(prefix); pw.print("realActivity=");
384                 pw.println(realActivity.flattenToShortString());
385         if (appInfo != null) {
386             pw.print(prefix); pw.print("baseDir="); pw.println(appInfo.sourceDir);
387             if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) {
388                 pw.print(prefix); pw.print("resDir="); pw.println(appInfo.publicSourceDir);
389             }
390             pw.print(prefix); pw.print("dataDir="); pw.println(appInfo.dataDir);
391             if (appInfo.splitSourceDirs != null) {
392                 pw.print(prefix); pw.print("splitDir=");
393                         pw.println(Arrays.toString(appInfo.splitSourceDirs));
394             }
395         }
396         pw.print(prefix); pw.print("stateNotNeeded="); pw.print(stateNotNeeded);
397                 pw.print(" componentSpecified="); pw.print(componentSpecified);
398                 pw.print(" mActivityType="); pw.println(mActivityType);
399         if (rootVoiceInteraction) {
400             pw.print(prefix); pw.print("rootVoiceInteraction="); pw.println(rootVoiceInteraction);
401         }
402         pw.print(prefix); pw.print("compat="); pw.print(compat);
403                 pw.print(" labelRes=0x"); pw.print(Integer.toHexString(labelRes));
404                 pw.print(" icon=0x"); pw.print(Integer.toHexString(icon));
405                 pw.print(" theme=0x"); pw.println(Integer.toHexString(theme));
406         pw.println(prefix + "mLastReportedConfigurations:");
407         mLastReportedConfiguration.dump(pw, prefix + " ");
408
409         pw.print(prefix); pw.print("CurrentConfiguration="); pw.println(getConfiguration());
410         if (!getOverrideConfiguration().equals(EMPTY)) {
411             pw.println(prefix + "OverrideConfiguration=" + getOverrideConfiguration());
412         }
413         if (!mBounds.isEmpty()) {
414             pw.println(prefix + "mBounds=" + mBounds);
415         }
416         if (resultTo != null || resultWho != null) {
417             pw.print(prefix); pw.print("resultTo="); pw.print(resultTo);
418                     pw.print(" resultWho="); pw.print(resultWho);
419                     pw.print(" resultCode="); pw.println(requestCode);
420         }
421         if (taskDescription != null) {
422             final String iconFilename = taskDescription.getIconFilename();
423             if (iconFilename != null || taskDescription.getLabel() != null ||
424                     taskDescription.getPrimaryColor() != 0) {
425                 pw.print(prefix); pw.print("taskDescription:");
426                         pw.print(" iconFilename="); pw.print(taskDescription.getIconFilename());
427                         pw.print(" label=\""); pw.print(taskDescription.getLabel());
428                                 pw.print("\"");
429                         pw.print(" primaryColor=");
430                         pw.println(Integer.toHexString(taskDescription.getPrimaryColor()));
431                         pw.print(prefix + " backgroundColor=");
432                         pw.println(Integer.toHexString(taskDescription.getBackgroundColor()));
433                         pw.print(prefix + " statusBarColor=");
434                         pw.println(Integer.toHexString(taskDescription.getStatusBarColor()));
435                         pw.print(prefix + " navigationBarColor=");
436                         pw.println(Integer.toHexString(taskDescription.getNavigationBarColor()));
437             }
438             if (iconFilename == null && taskDescription.getIcon() != null) {
439                 pw.print(prefix); pw.println("taskDescription contains Bitmap");
440             }
441         }
442         if (results != null) {
443             pw.print(prefix); pw.print("results="); pw.println(results);
444         }
445         if (pendingResults != null && pendingResults.size() > 0) {
446             pw.print(prefix); pw.println("Pending Results:");
447             for (WeakReference<PendingIntentRecord> wpir : pendingResults) {
448                 PendingIntentRecord pir = wpir != null ? wpir.get() : null;
449                 pw.print(prefix); pw.print("  - ");
450                 if (pir == null) {
451                     pw.println("null");
452                 } else {
453                     pw.println(pir);
454                     pir.dump(pw, prefix + "    ");
455                 }
456             }
457         }
458         if (newIntents != null && newIntents.size() > 0) {
459             pw.print(prefix); pw.println("Pending New Intents:");
460             for (int i=0; i<newIntents.size(); i++) {
461                 Intent intent = newIntents.get(i);
462                 pw.print(prefix); pw.print("  - ");
463                 if (intent == null) {
464                     pw.println("null");
465                 } else {
466                     pw.println(intent.toShortString(false, true, false, true));
467                 }
468             }
469         }
470         if (pendingOptions != null) {
471             pw.print(prefix); pw.print("pendingOptions="); pw.println(pendingOptions);
472         }
473         if (appTimeTracker != null) {
474             appTimeTracker.dumpWithHeader(pw, prefix, false);
475         }
476         if (uriPermissions != null) {
477             uriPermissions.dump(pw, prefix);
478         }
479         pw.print(prefix); pw.print("launchFailed="); pw.print(launchFailed);
480                 pw.print(" launchCount="); pw.print(launchCount);
481                 pw.print(" lastLaunchTime=");
482                 if (lastLaunchTime == 0) pw.print("0");
483                 else TimeUtils.formatDuration(lastLaunchTime, now, pw);
484                 pw.println();
485         pw.print(prefix); pw.print("haveState="); pw.print(haveState);
486                 pw.print(" icicle="); pw.println(icicle);
487         pw.print(prefix); pw.print("state="); pw.print(state);
488                 pw.print(" stopped="); pw.print(stopped);
489                 pw.print(" delayedResume="); pw.print(delayedResume);
490                 pw.print(" finishing="); pw.println(finishing);
491         pw.print(prefix); pw.print("keysPaused="); pw.print(keysPaused);
492                 pw.print(" inHistory="); pw.print(inHistory);
493                 pw.print(" visible="); pw.print(visible);
494                 pw.print(" sleeping="); pw.print(sleeping);
495                 pw.print(" idle="); pw.print(idle);
496                 pw.print(" mStartingWindowState=");
497                 pw.println(startingWindowStateToString(mStartingWindowState));
498         pw.print(prefix); pw.print("fullscreen="); pw.print(fullscreen);
499                 pw.print(" noDisplay="); pw.print(noDisplay);
500                 pw.print(" immersive="); pw.print(immersive);
501                 pw.print(" launchMode="); pw.println(launchMode);
502         pw.print(prefix); pw.print("frozenBeforeDestroy="); pw.print(frozenBeforeDestroy);
503                 pw.print(" forceNewConfig="); pw.println(forceNewConfig);
504         pw.print(prefix); pw.print("mActivityType=");
505                 pw.println(activityTypeToString(mActivityType));
506         if (requestedVrComponent != null) {
507             pw.print(prefix);
508             pw.print("requestedVrComponent=");
509             pw.println(requestedVrComponent);
510         }
511         if (displayStartTime != 0 || startTime != 0) {
512             pw.print(prefix); pw.print("displayStartTime=");
513                     if (displayStartTime == 0) pw.print("0");
514                     else TimeUtils.formatDuration(displayStartTime, now, pw);
515                     pw.print(" startTime=");
516                     if (startTime == 0) pw.print("0");
517                     else TimeUtils.formatDuration(startTime, now, pw);
518                     pw.println();
519         }
520         final boolean waitingVisible =
521                 mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(this);
522         if (lastVisibleTime != 0 || waitingVisible || nowVisible) {
523             pw.print(prefix); pw.print("waitingVisible="); pw.print(waitingVisible);
524                     pw.print(" nowVisible="); pw.print(nowVisible);
525                     pw.print(" lastVisibleTime=");
526                     if (lastVisibleTime == 0) pw.print("0");
527                     else TimeUtils.formatDuration(lastVisibleTime, now, pw);
528                     pw.println();
529         }
530         if (mDeferHidingClient) {
531             pw.println(prefix + "mDeferHidingClient=" + mDeferHidingClient);
532         }
533         if (deferRelaunchUntilPaused || configChangeFlags != 0) {
534             pw.print(prefix); pw.print("deferRelaunchUntilPaused="); pw.print(deferRelaunchUntilPaused);
535                     pw.print(" configChangeFlags=");
536                     pw.println(Integer.toHexString(configChangeFlags));
537         }
538         if (connections != null) {
539             pw.print(prefix); pw.print("connections="); pw.println(connections);
540         }
541         if (info != null) {
542             pw.println(prefix + "resizeMode=" + ActivityInfo.resizeModeToString(info.resizeMode));
543             pw.println(prefix + "mLastReportedMultiWindowMode=" + mLastReportedMultiWindowMode
544                     + " mLastReportedPictureInPictureMode=" + mLastReportedPictureInPictureMode);
545             if (info.supportsPictureInPicture()) {
546                 pw.println(prefix + "supportsPictureInPicture=" + info.supportsPictureInPicture());
547                 pw.println(prefix + "supportsPictureInPictureWhilePausing: "
548                         + supportsPictureInPictureWhilePausing);
549             }
550             if (info.maxAspectRatio != 0) {
551                 pw.println(prefix + "maxAspectRatio=" + info.maxAspectRatio);
552             }
553         }
554     }
555
556     private boolean crossesHorizontalSizeThreshold(int firstDp, int secondDp) {
557         return crossesSizeThreshold(mHorizontalSizeConfigurations, firstDp, secondDp);
558     }
559
560     private boolean crossesVerticalSizeThreshold(int firstDp, int secondDp) {
561         return crossesSizeThreshold(mVerticalSizeConfigurations, firstDp, secondDp);
562     }
563
564     private boolean crossesSmallestSizeThreshold(int firstDp, int secondDp) {
565         return crossesSizeThreshold(mSmallestSizeConfigurations, firstDp, secondDp);
566     }
567
568     /**
569      * The purpose of this method is to decide whether the activity needs to be relaunched upon
570      * changing its size. In most cases the activities don't need to be relaunched, if the resize
571      * is small, all the activity content has to do is relayout itself within new bounds. There are
572      * cases however, where the activity's content would be completely changed in the new size and
573      * the full relaunch is required.
574      *
575      * The activity will report to us vertical and horizontal thresholds after which a relaunch is
576      * required. These thresholds are collected from the application resource qualifiers. For
577      * example, if application has layout-w600dp resource directory, then it needs a relaunch when
578      * we resize from width of 650dp to 550dp, as it crosses the 600dp threshold. However, if
579      * it resizes width from 620dp to 700dp, it won't be relaunched as it stays on the same side
580      * of the threshold.
581      */
582     private static boolean crossesSizeThreshold(int[] thresholds, int firstDp,
583             int secondDp) {
584         if (thresholds == null) {
585             return false;
586         }
587         for (int i = thresholds.length - 1; i >= 0; i--) {
588             final int threshold = thresholds[i];
589             if ((firstDp < threshold && secondDp >= threshold)
590                     || (firstDp >= threshold && secondDp < threshold)) {
591                 return true;
592             }
593         }
594         return false;
595     }
596
597     void setSizeConfigurations(int[] horizontalSizeConfiguration,
598             int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
599         mHorizontalSizeConfigurations = horizontalSizeConfiguration;
600         mVerticalSizeConfigurations = verticalSizeConfigurations;
601         mSmallestSizeConfigurations = smallestSizeConfigurations;
602     }
603
604     private void scheduleActivityMovedToDisplay(int displayId, Configuration config) {
605         if (app == null || app.thread == null) {
606             if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.w(TAG,
607                     "Can't report activity moved to display - client not running, activityRecord="
608                             + this + ", displayId=" + displayId);
609             return;
610         }
611         try {
612             if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
613                     "Reporting activity moved to display" + ", activityRecord=" + this
614                             + ", displayId=" + displayId + ", config=" + config);
615
616             app.thread.scheduleActivityMovedToDisplay(appToken, displayId,
617                     new Configuration(config));
618         } catch (RemoteException e) {
619             // If process died, whatever.
620         }
621     }
622
623     private void scheduleConfigurationChanged(Configuration config) {
624         if (app == null || app.thread == null) {
625             if (DEBUG_CONFIGURATION) Slog.w(TAG,
626                     "Can't report activity configuration update - client not running"
627                             + ", activityRecord=" + this);
628             return;
629         }
630         try {
631             if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + this + ", config: "
632                     + config);
633
634             app.thread.scheduleActivityConfigurationChanged(appToken, new Configuration(config));
635         } catch (RemoteException e) {
636             // If process died, whatever.
637         }
638     }
639
640     void updateMultiWindowMode() {
641         if (task == null || task.getStack() == null || app == null || app.thread == null) {
642             return;
643         }
644
645         // An activity is considered to be in multi-window mode if its task isn't fullscreen.
646         final boolean inMultiWindowMode = !task.mFullscreen;
647         if (inMultiWindowMode != mLastReportedMultiWindowMode) {
648             mLastReportedMultiWindowMode = inMultiWindowMode;
649             scheduleMultiWindowModeChanged(getConfiguration());
650         }
651     }
652
653     private void scheduleMultiWindowModeChanged(Configuration overrideConfig) {
654         try {
655             app.thread.scheduleMultiWindowModeChanged(appToken, mLastReportedMultiWindowMode,
656                     overrideConfig);
657         } catch (Exception e) {
658             // If process died, I don't care.
659         }
660     }
661
662     void updatePictureInPictureMode(Rect targetStackBounds) {
663         if (task == null || task.getStack() == null || app == null || app.thread == null) {
664             return;
665         }
666
667         final boolean inPictureInPictureMode = (task.getStackId() == PINNED_STACK_ID) &&
668                 (targetStackBounds != null);
669         if (inPictureInPictureMode != mLastReportedPictureInPictureMode) {
670             // Picture-in-picture mode changes also trigger a multi-window mode change as well, so
671             // update that here in order
672             mLastReportedPictureInPictureMode = inPictureInPictureMode;
673             mLastReportedMultiWindowMode = inPictureInPictureMode;
674             final Configuration newConfig = task.computeNewOverrideConfigurationForBounds(
675                     targetStackBounds, null);
676             schedulePictureInPictureModeChanged(newConfig);
677             scheduleMultiWindowModeChanged(newConfig);
678         }
679     }
680
681     private void schedulePictureInPictureModeChanged(Configuration overrideConfig) {
682         try {
683             app.thread.schedulePictureInPictureModeChanged(appToken,
684                     mLastReportedPictureInPictureMode,
685                     overrideConfig);
686         } catch (Exception e) {
687             // If process died, no one cares.
688         }
689     }
690
691     boolean isFreeform() {
692         return task != null && task.getStackId() == FREEFORM_WORKSPACE_STACK_ID;
693     }
694
695     @Override
696     protected int getChildCount() {
697         // {@link ActivityRecord} is a leaf node and has no children.
698         return 0;
699     }
700
701     @Override
702     protected ConfigurationContainer getChildAt(int index) {
703         return null;
704     }
705
706     @Override
707     protected ConfigurationContainer getParent() {
708         return getTask();
709     }
710
711     TaskRecord getTask() {
712         return task;
713     }
714
715     /**
716      * Sets reference to the {@link TaskRecord} the {@link ActivityRecord} will treat as its parent.
717      * Note that this does not actually add the {@link ActivityRecord} as a {@link TaskRecord}
718      * children. However, this method will clean up references to this {@link ActivityRecord} in
719      * {@link ActivityStack}.
720      * @param task The new parent {@link TaskRecord}.
721      */
722     void setTask(TaskRecord task) {
723         setTask(task, false /*reparenting*/);
724     }
725
726     /**
727      * This method should only be called by {@link TaskRecord#removeActivity(ActivityRecord)}.
728      */
729     void setTask(TaskRecord task, boolean reparenting) {
730         // Do nothing if the {@link TaskRecord} is the same as the current {@link getTask}.
731         if (task != null && task == getTask()) {
732             return;
733         }
734
735         final ActivityStack stack = getStack();
736
737         // If the new {@link TaskRecord} is from a different {@link ActivityStack}, remove this
738         // {@link ActivityRecord} from its current {@link ActivityStack}.
739         if (!reparenting && stack != null && (task == null || stack != task.getStack())) {
740             stack.onActivityRemovedFromStack(this);
741         }
742
743         this.task = task;
744
745         if (!reparenting) {
746             onParentChanged();
747         }
748     }
749
750     static class Token extends IApplicationToken.Stub {
751         private final WeakReference<ActivityRecord> weakActivity;
752
753         Token(ActivityRecord activity) {
754             weakActivity = new WeakReference<>(activity);
755         }
756
757         private static ActivityRecord tokenToActivityRecordLocked(Token token) {
758             if (token == null) {
759                 return null;
760             }
761             ActivityRecord r = token.weakActivity.get();
762             if (r == null || r.getStack() == null) {
763                 return null;
764             }
765             return r;
766         }
767
768         @Override
769         public String toString() {
770             StringBuilder sb = new StringBuilder(128);
771             sb.append("Token{");
772             sb.append(Integer.toHexString(System.identityHashCode(this)));
773             sb.append(' ');
774             sb.append(weakActivity.get());
775             sb.append('}');
776             return sb.toString();
777         }
778     }
779
780     static ActivityRecord forTokenLocked(IBinder token) {
781         try {
782             return Token.tokenToActivityRecordLocked((Token)token);
783         } catch (ClassCastException e) {
784             Slog.w(TAG, "Bad activity token: " + token, e);
785             return null;
786         }
787     }
788
789     boolean isResolverActivity() {
790         return ResolverActivity.class.getName().equals(realActivity.getClassName());
791     }
792
793     ActivityRecord(ActivityManagerService _service, ProcessRecord _caller, int _launchedFromPid,
794             int _launchedFromUid, String _launchedFromPackage, Intent _intent, String _resolvedType,
795             ActivityInfo aInfo, Configuration _configuration,
796             ActivityRecord _resultTo, String _resultWho, int _reqCode,
797             boolean _componentSpecified, boolean _rootVoiceInteraction,
798             ActivityStackSupervisor supervisor,
799             ActivityContainer container, ActivityOptions options, ActivityRecord sourceRecord) {
800         service = _service;
801         appToken = new Token(this);
802         info = aInfo;
803         launchedFromPid = _launchedFromPid;
804         launchedFromUid = _launchedFromUid;
805         launchedFromPackage = _launchedFromPackage;
806         userId = UserHandle.getUserId(aInfo.applicationInfo.uid);
807         intent = _intent;
808         shortComponentName = _intent.getComponent().flattenToShortString();
809         resolvedType = _resolvedType;
810         componentSpecified = _componentSpecified;
811         rootVoiceInteraction = _rootVoiceInteraction;
812         mLastReportedConfiguration = new MergedConfiguration(_configuration);
813         resultTo = _resultTo;
814         resultWho = _resultWho;
815         requestCode = _reqCode;
816         state = INITIALIZING;
817         frontOfTask = false;
818         launchFailed = false;
819         stopped = false;
820         delayedResume = false;
821         finishing = false;
822         deferRelaunchUntilPaused = false;
823         keysPaused = false;
824         inHistory = false;
825         visible = false;
826         nowVisible = false;
827         idle = false;
828         hasBeenLaunched = false;
829         mStackSupervisor = supervisor;
830         mInitialActivityContainer = container;
831
832         mRotationAnimationHint = aInfo.rotationAnimation;
833
834         if (options != null) {
835             pendingOptions = options;
836             mLaunchTaskBehind = pendingOptions.getLaunchTaskBehind();
837
838             final int rotationAnimation = pendingOptions.getRotationAnimationHint();
839             // Only override manifest supplied option if set.
840             if (rotationAnimation >= 0) {
841                 mRotationAnimationHint = rotationAnimation;
842             }
843             PendingIntent usageReport = pendingOptions.getUsageTimeReport();
844             if (usageReport != null) {
845                 appTimeTracker = new AppTimeTracker(usageReport);
846             }
847         }
848
849         // This starts out true, since the initial state of an activity is that we have everything,
850         // and we shouldn't never consider it lacking in state to be removed if it dies.
851         haveState = true;
852
853         // If the class name in the intent doesn't match that of the target, this is
854         // probably an alias. We have to create a new ComponentName object to keep track
855         // of the real activity name, so that FLAG_ACTIVITY_CLEAR_TOP is handled properly.
856         if (aInfo.targetActivity == null
857                 || (aInfo.targetActivity.equals(_intent.getComponent().getClassName())
858                 && (aInfo.launchMode == LAUNCH_MULTIPLE
859                 || aInfo.launchMode == LAUNCH_SINGLE_TOP))) {
860             realActivity = _intent.getComponent();
861         } else {
862             realActivity = new ComponentName(aInfo.packageName, aInfo.targetActivity);
863         }
864         taskAffinity = aInfo.taskAffinity;
865         stateNotNeeded = (aInfo.flags & FLAG_STATE_NOT_NEEDED) != 0;
866         appInfo = aInfo.applicationInfo;
867         nonLocalizedLabel = aInfo.nonLocalizedLabel;
868         labelRes = aInfo.labelRes;
869         if (nonLocalizedLabel == null && labelRes == 0) {
870             ApplicationInfo app = aInfo.applicationInfo;
871             nonLocalizedLabel = app.nonLocalizedLabel;
872             labelRes = app.labelRes;
873         }
874         icon = aInfo.getIconResource();
875         logo = aInfo.getLogoResource();
876         theme = aInfo.getThemeResource();
877         realTheme = theme;
878         if (realTheme == 0) {
879             realTheme = aInfo.applicationInfo.targetSdkVersion < HONEYCOMB
880                     ? android.R.style.Theme : android.R.style.Theme_Holo;
881         }
882         if ((aInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
883             windowFlags |= LayoutParams.FLAG_HARDWARE_ACCELERATED;
884         }
885         if ((aInfo.flags & FLAG_MULTIPROCESS) != 0 && _caller != null
886                 && (aInfo.applicationInfo.uid == SYSTEM_UID
887                     || aInfo.applicationInfo.uid == _caller.info.uid)) {
888             processName = _caller.processName;
889         } else {
890             processName = aInfo.processName;
891         }
892
893         if ((aInfo.flags & FLAG_EXCLUDE_FROM_RECENTS) != 0) {
894             intent.addFlags(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
895         }
896
897         packageName = aInfo.applicationInfo.packageName;
898         launchMode = aInfo.launchMode;
899
900         Entry ent = AttributeCache.instance().get(packageName,
901                 realTheme, com.android.internal.R.styleable.Window, userId);
902         fullscreen = ent != null && !ActivityInfo.isTranslucentOrFloating(ent.array);
903         noDisplay = ent != null && ent.array.getBoolean(
904                 com.android.internal.R.styleable.Window_windowNoDisplay, false);
905
906         setActivityType(_componentSpecified, _launchedFromUid, _intent, options, sourceRecord);
907
908         immersive = (aInfo.flags & FLAG_IMMERSIVE) != 0;
909
910         requestedVrComponent = (aInfo.requestedVrComponent == null) ?
911                 null : ComponentName.unflattenFromString(aInfo.requestedVrComponent);
912     }
913
914     AppWindowContainerController getWindowContainerController() {
915         return mWindowContainerController;
916     }
917
918     void createWindowContainer() {
919         if (mWindowContainerController != null) {
920             throw new IllegalArgumentException("Window container=" + mWindowContainerController
921                     + " already created for r=" + this);
922         }
923
924         inHistory = true;
925
926         final TaskWindowContainerController taskController = task.getWindowContainerController();
927
928         // TODO(b/36505427): Maybe this call should be moved inside updateOverrideConfiguration()
929         task.updateOverrideConfigurationFromLaunchBounds();
930         // Make sure override configuration is up-to-date before using to create window controller.
931         updateOverrideConfiguration();
932
933         mWindowContainerController = new AppWindowContainerController(taskController, appToken,
934                 this, Integer.MAX_VALUE /* add on top */, info.screenOrientation, fullscreen,
935                 (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0, info.configChanges,
936                 task.voiceSession != null, mLaunchTaskBehind, isAlwaysFocusable(),
937                 appInfo.targetSdkVersion, mRotationAnimationHint,
938                 ActivityManagerService.getInputDispatchingTimeoutLocked(this) * 1000000L,
939                 getOverrideConfiguration(), mBounds);
940
941         task.addActivityToTop(this);
942
943         // When an activity is started directly into a split-screen fullscreen stack, we need to
944         // update the initial multi-window modes so that the callbacks are scheduled correctly when
945         // the user leaves that mode.
946         mLastReportedMultiWindowMode = !task.mFullscreen;
947         mLastReportedPictureInPictureMode = (task.getStackId() == PINNED_STACK_ID);
948
949         onOverrideConfigurationSent();
950     }
951
952     void removeWindowContainer() {
953         // Resume key dispatching if it is currently paused before we remove the container.
954         resumeKeyDispatchingLocked();
955
956         mWindowContainerController.removeContainer(getDisplayId());
957         mWindowContainerController = null;
958     }
959
960     /**
961      * Reparents this activity into {@param newTask} at the provided {@param position}.  The caller
962      * should ensure that the {@param newTask} is not already the parent of this activity.
963      */
964     void reparent(TaskRecord newTask, int position, String reason) {
965         final TaskRecord prevTask = task;
966         if (prevTask == newTask) {
967             throw new IllegalArgumentException(reason + ": task=" + newTask
968                     + " is already the parent of r=" + this);
969         }
970
971         // TODO: Ensure that we do not directly reparent activities across stacks, as that may leave
972         //       the stacks in strange states. For now, we should use Task.reparent() to ensure that
973         //       the stack is left in an OK state.
974         if (prevTask != null && newTask != null && prevTask.getStack() != newTask.getStack()) {
975             throw new IllegalArgumentException(reason + ": task=" + newTask
976                     + " is in a different stack (" + newTask.getStackId() + ") than the parent of"
977                     + " r=" + this + " (" + prevTask.getStackId() + ")");
978         }
979
980         // Must reparent first in window manager
981         mWindowContainerController.reparent(newTask.getWindowContainerController(), position);
982
983         // Remove the activity from the old task and add it to the new task.
984         prevTask.removeActivity(this, true /*reparenting*/);
985
986         newTask.addActivityAtIndex(position, this);
987     }
988
989     private boolean isHomeIntent(Intent intent) {
990         return ACTION_MAIN.equals(intent.getAction())
991                 && intent.hasCategory(CATEGORY_HOME)
992                 && intent.getCategories().size() == 1
993                 && intent.getData() == null
994                 && intent.getType() == null;
995     }
996
997     static boolean isMainIntent(Intent intent) {
998         return ACTION_MAIN.equals(intent.getAction())
999                 && intent.hasCategory(CATEGORY_LAUNCHER)
1000                 && intent.getCategories().size() == 1
1001                 && intent.getData() == null
1002                 && intent.getType() == null;
1003     }
1004
1005     private boolean canLaunchHomeActivity(int uid, ActivityRecord sourceRecord) {
1006         if (uid == Process.myUid() || uid == 0) {
1007             // System process can launch home activity.
1008             return true;
1009         }
1010         // Resolver activity can launch home activity.
1011         return sourceRecord != null && sourceRecord.isResolverActivity();
1012     }
1013
1014     /**
1015      * @return whether the given package name can launch an assist activity.
1016      */
1017     private boolean canLaunchAssistActivity(String packageName) {
1018         if (service.mAssistUtils == null) {
1019             return false;
1020         }
1021
1022         final ComponentName assistComponent = service.mAssistUtils.getActiveServiceComponentName();
1023         if (assistComponent != null) {
1024             return assistComponent.getPackageName().equals(packageName);
1025         }
1026         return false;
1027     }
1028
1029     private void setActivityType(boolean componentSpecified, int launchedFromUid, Intent intent,
1030             ActivityOptions options, ActivityRecord sourceRecord) {
1031         if ((!componentSpecified || canLaunchHomeActivity(launchedFromUid, sourceRecord))
1032                 && isHomeIntent(intent) && !isResolverActivity()) {
1033             // This sure looks like a home activity!
1034             mActivityType = HOME_ACTIVITY_TYPE;
1035
1036             if (info.resizeMode == RESIZE_MODE_FORCE_RESIZEABLE
1037                     || info.resizeMode == RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION) {
1038                 // We only allow home activities to be resizeable if they explicitly requested it.
1039                 info.resizeMode = RESIZE_MODE_UNRESIZEABLE;
1040             }
1041         } else if (realActivity.getClassName().contains(RECENTS_PACKAGE_NAME)) {
1042             mActivityType = RECENTS_ACTIVITY_TYPE;
1043         } else if (options != null && options.getLaunchStackId() == ASSISTANT_STACK_ID
1044                 && canLaunchAssistActivity(launchedFromPackage)) {
1045             mActivityType = ASSISTANT_ACTIVITY_TYPE;
1046         } else {
1047             mActivityType = APPLICATION_ACTIVITY_TYPE;
1048         }
1049     }
1050
1051     void setTaskToAffiliateWith(TaskRecord taskToAffiliateWith) {
1052         if (launchMode != LAUNCH_SINGLE_INSTANCE && launchMode != LAUNCH_SINGLE_TASK) {
1053             task.setTaskToAffiliateWith(taskToAffiliateWith);
1054         }
1055     }
1056
1057     /**
1058      * @return Stack value from current task, null if there is no task.
1059      */
1060     <T extends ActivityStack> T getStack() {
1061         return task != null ? (T) task.getStack() : null;
1062     }
1063
1064     int getStackId() {
1065         return getStack() != null ? getStack().mStackId : INVALID_STACK_ID;
1066     }
1067
1068     boolean changeWindowTranslucency(boolean toOpaque) {
1069         if (fullscreen == toOpaque) {
1070             return false;
1071         }
1072
1073         // Keep track of the number of fullscreen activities in this task.
1074         task.numFullscreen += toOpaque ? +1 : -1;
1075
1076         fullscreen = toOpaque;
1077         return true;
1078     }
1079
1080     void takeFromHistory() {
1081         if (inHistory) {
1082             inHistory = false;
1083             if (task != null && !finishing) {
1084                 task = null;
1085             }
1086             clearOptionsLocked();
1087         }
1088     }
1089
1090     boolean isInHistory() {
1091         return inHistory;
1092     }
1093
1094     boolean isInStackLocked() {
1095         final ActivityStack stack = getStack();
1096         return stack != null && stack.isInStackLocked(this) != null;
1097     }
1098
1099     boolean isHomeActivity() {
1100         return mActivityType == HOME_ACTIVITY_TYPE;
1101     }
1102
1103     boolean isRecentsActivity() {
1104         return mActivityType == RECENTS_ACTIVITY_TYPE;
1105     }
1106
1107     boolean isAssistantActivity() {
1108         return mActivityType == ASSISTANT_ACTIVITY_TYPE;
1109     }
1110
1111     boolean isApplicationActivity() {
1112         return mActivityType == APPLICATION_ACTIVITY_TYPE;
1113     }
1114
1115     boolean isPersistable() {
1116         return (info.persistableMode == PERSIST_ROOT_ONLY ||
1117                 info.persistableMode == PERSIST_ACROSS_REBOOTS) &&
1118                 (intent == null ||
1119                         (intent.getFlags() & FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0);
1120     }
1121
1122     boolean isFocusable() {
1123         return StackId.canReceiveKeys(task.getStackId()) || isAlwaysFocusable();
1124     }
1125
1126     boolean isResizeable() {
1127         return ActivityInfo.isResizeableMode(info.resizeMode) || info.supportsPictureInPicture();
1128     }
1129
1130     /**
1131      * @return whether this activity is non-resizeable or forced to be resizeable
1132      */
1133     boolean isNonResizableOrForcedResizable() {
1134         return info.resizeMode != RESIZE_MODE_RESIZEABLE
1135                 && info.resizeMode != RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION;
1136     }
1137
1138     /**
1139      * @return whether this activity supports PiP multi-window and can be put in the pinned stack.
1140      */
1141     boolean supportsPictureInPicture() {
1142         return service.mSupportsPictureInPicture && !isHomeActivity()
1143                 && info.supportsPictureInPicture();
1144     }
1145
1146     /**
1147      * @return whether this activity supports split-screen multi-window and can be put in the docked
1148      *         stack.
1149      */
1150     boolean supportsSplitScreen() {
1151         // An activity can not be docked even if it is considered resizeable because it only
1152         // supports picture-in-picture mode but has a non-resizeable resizeMode
1153         return service.mSupportsSplitScreenMultiWindow && supportsResizeableMultiWindow();
1154     }
1155
1156     /**
1157      * @return whether this activity supports freeform multi-window and can be put in the freeform
1158      *         stack.
1159      */
1160     boolean supportsFreeform() {
1161         return service.mSupportsFreeformWindowManagement && supportsResizeableMultiWindow();
1162     }
1163
1164     /**
1165      * @return whether this activity supports non-PiP multi-window.
1166      */
1167     private boolean supportsResizeableMultiWindow() {
1168         return service.mSupportsMultiWindow && !isHomeActivity()
1169                 && (ActivityInfo.isResizeableMode(info.resizeMode)
1170                         || service.mForceResizableActivities);
1171     }
1172
1173     /**
1174      * Check whether this activity can be launched on the specified display.
1175      * @param displayId Target display id.
1176      * @return {@code true} if either it is the default display or this activity is resizeable and
1177      *         can be put a secondary screen.
1178      */
1179     boolean canBeLaunchedOnDisplay(int displayId) {
1180         return service.mStackSupervisor.canPlaceEntityOnDisplay(displayId,
1181                 supportsResizeableMultiWindow());
1182     }
1183
1184     /**
1185      * @param beforeStopping Whether this check is for an auto-enter-pip operation, that is to say
1186      *         the activity has requested to enter PiP when it would otherwise be stopped.
1187      *
1188      * @return whether this activity is currently allowed to enter PIP, throwing an exception if
1189      *         the activity is not currently visible and {@param noThrow} is not set.
1190      */
1191     boolean checkEnterPictureInPictureState(String caller, boolean noThrow, boolean beforeStopping) {
1192         if (!supportsPictureInPicture()) {
1193             return false;
1194         }
1195
1196         // Check app-ops and see if PiP is supported for this package
1197         if (!checkEnterPictureInPictureAppOpsState()) {
1198             return false;
1199         }
1200
1201         // Check to see if we are in VR mode, and disallow PiP if so
1202         if (service.shouldDisableNonVrUiLocked()) {
1203             return false;
1204         }
1205
1206         boolean isKeyguardLocked = service.isKeyguardLocked();
1207         boolean isCurrentAppLocked = mStackSupervisor.getLockTaskModeState() != LOCK_TASK_MODE_NONE;
1208         boolean hasPinnedStack = mStackSupervisor.getStack(PINNED_STACK_ID) != null;
1209         // Don't return early if !isNotLocked, since we want to throw an exception if the activity
1210         // is in an incorrect state
1211         boolean isNotLockedOrOnKeyguard = !isKeyguardLocked && !isCurrentAppLocked;
1212
1213         // We don't allow auto-PiP when something else is already pipped.
1214         if (beforeStopping && hasPinnedStack) {
1215             return false;
1216         }
1217
1218         switch (state) {
1219             case RESUMED:
1220                 // When visible, allow entering PiP if the app is not locked.  If it is over the
1221                 // keyguard, then we will prompt to unlock in the caller before entering PiP.
1222                 return !isCurrentAppLocked &&
1223                         (supportsPictureInPictureWhilePausing || !beforeStopping);
1224             case PAUSING:
1225             case PAUSED:
1226                 // When pausing, then only allow enter PiP as in the resume state, and in addition,
1227                 // require that there is not an existing PiP activity and that the current system
1228                 // state supports entering PiP
1229                 return isNotLockedOrOnKeyguard && !hasPinnedStack
1230                         && supportsPictureInPictureWhilePausing;
1231             case STOPPING:
1232                 // When stopping in a valid state, then only allow enter PiP as in the pause state.
1233                 // Otherwise, fall through to throw an exception if the caller is trying to enter
1234                 // PiP in an invalid stopping state.
1235                 if (supportsPictureInPictureWhilePausing) {
1236                     return isNotLockedOrOnKeyguard && !hasPinnedStack;
1237                 }
1238             default:
1239                 if (noThrow) {
1240                     return false;
1241                 } else {
1242                     throw new IllegalStateException(caller
1243                             + ": Current activity is not visible (state=" + state.name() + ") "
1244                             + "r=" + this);
1245                 }
1246         }
1247     }
1248
1249     /**
1250      * @return Whether AppOps allows this package to enter picture-in-picture.
1251      */
1252     private boolean checkEnterPictureInPictureAppOpsState() {
1253         try {
1254             return service.getAppOpsService().checkOperation(OP_PICTURE_IN_PICTURE,
1255                     appInfo.uid, packageName) == MODE_ALLOWED;
1256         } catch (RemoteException e) {
1257             // Local call
1258         }
1259         return false;
1260     }
1261
1262     boolean isAlwaysFocusable() {
1263         return (info.flags & FLAG_ALWAYS_FOCUSABLE) != 0;
1264     }
1265
1266     /**
1267      * @return true if the activity contains windows that have
1268      *         {@link LayoutParams#FLAG_SHOW_WHEN_LOCKED} set
1269      */
1270     boolean hasShowWhenLockedWindows() {
1271         return service.mWindowManager.containsShowWhenLockedWindow(appToken);
1272     }
1273
1274     /**
1275      * @return true if the activity contains windows that have
1276      *         {@link LayoutParams#FLAG_DISMISS_KEYGUARD} set
1277      */
1278     boolean hasDismissKeyguardWindows() {
1279         return service.mWindowManager.containsDismissKeyguardWindow(appToken);
1280     }
1281
1282     void makeFinishingLocked() {
1283         if (!finishing) {
1284             final ActivityStack stack = getStack();
1285             if (stack != null && this == stack.getVisibleBehindActivity()) {
1286                 // A finishing activity should not remain as visible in the background
1287                 mStackSupervisor.requestVisibleBehindLocked(this, false);
1288             }
1289             finishing = true;
1290             if (stopped) {
1291                 clearOptionsLocked();
1292             }
1293
1294             if (service != null) {
1295                 service.mTaskChangeNotificationController.notifyTaskStackChanged();
1296             }
1297         }
1298     }
1299
1300     UriPermissionOwner getUriPermissionsLocked() {
1301         if (uriPermissions == null) {
1302             uriPermissions = new UriPermissionOwner(service, this);
1303         }
1304         return uriPermissions;
1305     }
1306
1307     void addResultLocked(ActivityRecord from, String resultWho,
1308             int requestCode, int resultCode,
1309             Intent resultData) {
1310         ActivityResult r = new ActivityResult(from, resultWho,
1311                 requestCode, resultCode, resultData);
1312         if (results == null) {
1313             results = new ArrayList<ResultInfo>();
1314         }
1315         results.add(r);
1316     }
1317
1318     void removeResultsLocked(ActivityRecord from, String resultWho,
1319             int requestCode) {
1320         if (results != null) {
1321             for (int i=results.size()-1; i>=0; i--) {
1322                 ActivityResult r = (ActivityResult)results.get(i);
1323                 if (r.mFrom != from) continue;
1324                 if (r.mResultWho == null) {
1325                     if (resultWho != null) continue;
1326                 } else {
1327                     if (!r.mResultWho.equals(resultWho)) continue;
1328                 }
1329                 if (r.mRequestCode != requestCode) continue;
1330
1331                 results.remove(i);
1332             }
1333         }
1334     }
1335
1336     private void addNewIntentLocked(ReferrerIntent intent) {
1337         if (newIntents == null) {
1338             newIntents = new ArrayList<>();
1339         }
1340         newIntents.add(intent);
1341     }
1342
1343     /**
1344      * Deliver a new Intent to an existing activity, so that its onNewIntent()
1345      * method will be called at the proper time.
1346      */
1347     final void deliverNewIntentLocked(int callingUid, Intent intent, String referrer) {
1348         // The activity now gets access to the data associated with this Intent.
1349         service.grantUriPermissionFromIntentLocked(callingUid, packageName,
1350                 intent, getUriPermissionsLocked(), userId);
1351         final ReferrerIntent rintent = new ReferrerIntent(intent, referrer);
1352         boolean unsent = true;
1353         final ActivityStack stack = getStack();
1354         final boolean isTopActivityInStack =
1355                 stack != null && stack.topRunningActivityLocked() == this;
1356         final boolean isTopActivityWhileSleeping =
1357                 service.isSleepingLocked() && isTopActivityInStack;
1358
1359         // We want to immediately deliver the intent to the activity if:
1360         // - It is currently resumed or paused. i.e. it is currently visible to the user and we want
1361         //   the user to see the visual effects caused by the intent delivery now.
1362         // - The device is sleeping and it is the top activity behind the lock screen (b/6700897).
1363         if ((state == RESUMED || state == PAUSED
1364                 || isTopActivityWhileSleeping) && app != null && app.thread != null) {
1365             try {
1366                 ArrayList<ReferrerIntent> ar = new ArrayList<>(1);
1367                 ar.add(rintent);
1368                 app.thread.scheduleNewIntent(
1369                         ar, appToken, state == PAUSED /* andPause */);
1370                 unsent = false;
1371             } catch (RemoteException e) {
1372                 Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
1373             } catch (NullPointerException e) {
1374                 Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
1375             }
1376         }
1377         if (unsent) {
1378             addNewIntentLocked(rintent);
1379         }
1380     }
1381
1382     void updateOptionsLocked(ActivityOptions options) {
1383         if (options != null) {
1384             if (pendingOptions != null) {
1385                 pendingOptions.abort();
1386             }
1387             pendingOptions = options;
1388         }
1389     }
1390
1391     void applyOptionsLocked() {
1392         if (pendingOptions != null
1393                 && pendingOptions.getAnimationType() != ANIM_SCENE_TRANSITION) {
1394             final int animationType = pendingOptions.getAnimationType();
1395             switch (animationType) {
1396                 case ANIM_CUSTOM:
1397                     service.mWindowManager.overridePendingAppTransition(
1398                             pendingOptions.getPackageName(),
1399                             pendingOptions.getCustomEnterResId(),
1400                             pendingOptions.getCustomExitResId(),
1401                             pendingOptions.getOnAnimationStartListener());
1402                     break;
1403                 case ANIM_CLIP_REVEAL:
1404                     service.mWindowManager.overridePendingAppTransitionClipReveal(
1405                             pendingOptions.getStartX(), pendingOptions.getStartY(),
1406                             pendingOptions.getWidth(), pendingOptions.getHeight());
1407                     if (intent.getSourceBounds() == null) {
1408                         intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1409                                 pendingOptions.getStartY(),
1410                                 pendingOptions.getStartX()+pendingOptions.getWidth(),
1411                                 pendingOptions.getStartY()+pendingOptions.getHeight()));
1412                     }
1413                     break;
1414                 case ANIM_SCALE_UP:
1415                     service.mWindowManager.overridePendingAppTransitionScaleUp(
1416                             pendingOptions.getStartX(), pendingOptions.getStartY(),
1417                             pendingOptions.getWidth(), pendingOptions.getHeight());
1418                     if (intent.getSourceBounds() == null) {
1419                         intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1420                                 pendingOptions.getStartY(),
1421                                 pendingOptions.getStartX()+pendingOptions.getWidth(),
1422                                 pendingOptions.getStartY()+pendingOptions.getHeight()));
1423                     }
1424                     break;
1425                 case ANIM_THUMBNAIL_SCALE_UP:
1426                 case ANIM_THUMBNAIL_SCALE_DOWN:
1427                     final boolean scaleUp = (animationType == ANIM_THUMBNAIL_SCALE_UP);
1428                     final GraphicBuffer buffer = pendingOptions.getThumbnail();
1429                     service.mWindowManager.overridePendingAppTransitionThumb(buffer,
1430                             pendingOptions.getStartX(), pendingOptions.getStartY(),
1431                             pendingOptions.getOnAnimationStartListener(),
1432                             scaleUp);
1433                     if (intent.getSourceBounds() == null && buffer != null) {
1434                         intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1435                                 pendingOptions.getStartY(),
1436                                 pendingOptions.getStartX() + buffer.getWidth(),
1437                                 pendingOptions.getStartY() + buffer.getHeight()));
1438                     }
1439                     break;
1440                 case ANIM_THUMBNAIL_ASPECT_SCALE_UP:
1441                 case ANIM_THUMBNAIL_ASPECT_SCALE_DOWN:
1442                     final AppTransitionAnimationSpec[] specs = pendingOptions.getAnimSpecs();
1443                     final IAppTransitionAnimationSpecsFuture specsFuture =
1444                             pendingOptions.getSpecsFuture();
1445                     if (specsFuture != null) {
1446                         service.mWindowManager.overridePendingAppTransitionMultiThumbFuture(
1447                                 specsFuture, pendingOptions.getOnAnimationStartListener(),
1448                                 animationType == ANIM_THUMBNAIL_ASPECT_SCALE_UP);
1449                     } else if (animationType == ANIM_THUMBNAIL_ASPECT_SCALE_DOWN
1450                             && specs != null) {
1451                         service.mWindowManager.overridePendingAppTransitionMultiThumb(
1452                                 specs, pendingOptions.getOnAnimationStartListener(),
1453                                 pendingOptions.getAnimationFinishedListener(), false);
1454                     } else {
1455                         service.mWindowManager.overridePendingAppTransitionAspectScaledThumb(
1456                                 pendingOptions.getThumbnail(),
1457                                 pendingOptions.getStartX(), pendingOptions.getStartY(),
1458                                 pendingOptions.getWidth(), pendingOptions.getHeight(),
1459                                 pendingOptions.getOnAnimationStartListener(),
1460                                 (animationType == ANIM_THUMBNAIL_ASPECT_SCALE_UP));
1461                         if (intent.getSourceBounds() == null) {
1462                             intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1463                                     pendingOptions.getStartY(),
1464                                     pendingOptions.getStartX() + pendingOptions.getWidth(),
1465                                     pendingOptions.getStartY() + pendingOptions.getHeight()));
1466                         }
1467                     }
1468                     break;
1469                 default:
1470                     Slog.e(TAG, "applyOptionsLocked: Unknown animationType=" + animationType);
1471                     break;
1472             }
1473             pendingOptions = null;
1474         }
1475     }
1476
1477     ActivityOptions getOptionsForTargetActivityLocked() {
1478         return pendingOptions != null ? pendingOptions.forTargetActivity() : null;
1479     }
1480
1481     void clearOptionsLocked() {
1482         if (pendingOptions != null) {
1483             pendingOptions.abort();
1484             pendingOptions = null;
1485         }
1486     }
1487
1488     ActivityOptions takeOptionsLocked() {
1489         ActivityOptions opts = pendingOptions;
1490         pendingOptions = null;
1491         return opts;
1492     }
1493
1494     void removeUriPermissionsLocked() {
1495         if (uriPermissions != null) {
1496             uriPermissions.removeUriPermissionsLocked();
1497             uriPermissions = null;
1498         }
1499     }
1500
1501     void pauseKeyDispatchingLocked() {
1502         if (!keysPaused) {
1503             keysPaused = true;
1504             mWindowContainerController.pauseKeyDispatching();
1505         }
1506     }
1507
1508     void resumeKeyDispatchingLocked() {
1509         if (keysPaused) {
1510             keysPaused = false;
1511             mWindowContainerController.resumeKeyDispatching();
1512         }
1513     }
1514
1515     void updateThumbnailLocked(Bitmap newThumbnail, CharSequence description) {
1516         if (newThumbnail != null) {
1517             if (DEBUG_THUMBNAILS) Slog.i(TAG_THUMBNAILS,
1518                     "Setting thumbnail of " + this + " to " + newThumbnail);
1519             boolean thumbnailUpdated = task.setLastThumbnailLocked(newThumbnail);
1520             if (thumbnailUpdated && isPersistable()) {
1521                 service.notifyTaskPersisterLocked(task, false);
1522             }
1523         }
1524         task.lastDescription = description;
1525     }
1526
1527     final Bitmap screenshotActivityLocked() {
1528         if (DEBUG_SCREENSHOTS) Slog.d(TAG_SCREENSHOTS, "screenshotActivityLocked: " + this);
1529
1530         if (ENABLE_TASK_SNAPSHOTS) {
1531             // No need to screenshot if snapshots are enabled.
1532             if (DEBUG_SCREENSHOTS) Slog.d(TAG_SCREENSHOTS,
1533                     "\tSnapshots are enabled, abort taking screenshot");
1534             return null;
1535         }
1536
1537         if (noDisplay) {
1538             if (DEBUG_SCREENSHOTS) Slog.d(TAG_SCREENSHOTS, "\tNo display");
1539             return null;
1540         }
1541
1542         final ActivityStack stack = getStack();
1543         if (stack.isHomeOrRecentsStack()) {
1544             // This is an optimization -- since we never show Home or Recents within Recents itself,
1545             // we can just go ahead and skip taking the screenshot if this is the home stack.
1546             if (DEBUG_SCREENSHOTS) Slog.d(TAG_SCREENSHOTS, stack.getStackId() == HOME_STACK_ID ?
1547                         "\tHome stack" : "\tRecents stack");
1548             return null;
1549         }
1550
1551         int w = service.mThumbnailWidth;
1552         int h = service.mThumbnailHeight;
1553
1554         if (w <= 0) {
1555             Slog.e(TAG, "\tInvalid thumbnail dimensions: " + w + "x" + h);
1556             return null;
1557         }
1558
1559         if (stack.mStackId == DOCKED_STACK_ID && mStackSupervisor.mIsDockMinimized) {
1560             // When the docked stack is minimized its app windows are cropped significantly so any
1561             // screenshot taken will not display the apps contain. So, we avoid taking a screenshot
1562             // in that case.
1563             if (DEBUG_SCREENSHOTS) Slog.e(TAG, "\tIn minimized docked stack");
1564             return null;
1565         }
1566
1567         float scale = 0;
1568         if (DEBUG_SCREENSHOTS) Slog.d(TAG_SCREENSHOTS, "\tTaking screenshot");
1569
1570         // When this flag is set, we currently take the fullscreen screenshot of the activity but
1571         // scaled to half the size. This gives us a "good-enough" fullscreen thumbnail to use within
1572         // SystemUI while keeping memory usage low.
1573         if (TAKE_FULLSCREEN_SCREENSHOTS) {
1574             w = h = -1;
1575             scale = service.mFullscreenThumbnailScale;
1576         }
1577
1578         return mWindowContainerController.screenshotApplications(getDisplayId(), w, h, scale);
1579     }
1580
1581     void setDeferHidingClient(boolean deferHidingClient) {
1582         if (mDeferHidingClient == deferHidingClient) {
1583             return;
1584         }
1585         mDeferHidingClient = deferHidingClient;
1586         if (!mDeferHidingClient && !visible) {
1587             // Hiding the client is no longer deferred and the app isn't visible still, go ahead and
1588             // update the visibility.
1589             setVisibility(false);
1590         }
1591     }
1592
1593     void setVisibility(boolean visible) {
1594         mWindowContainerController.setVisibility(visible, mDeferHidingClient);
1595         mStackSupervisor.mActivityMetricsLogger.notifyVisibilityChanged(this, visible);
1596     }
1597
1598     // TODO: Look into merging with #setVisibility()
1599     void setVisible(boolean newVisible) {
1600         visible = newVisible;
1601         mDeferHidingClient = !visible && mDeferHidingClient;
1602         if (!visible && mUpdateTaskThumbnailWhenHidden) {
1603             updateThumbnailLocked(screenshotActivityLocked(), null /* description */);
1604             mUpdateTaskThumbnailWhenHidden = false;
1605         }
1606         setVisibility(visible);
1607         final ArrayList<ActivityContainer> containers = mChildContainers;
1608         for (int containerNdx = containers.size() - 1; containerNdx >= 0; --containerNdx) {
1609             final ActivityContainer container = containers.get(containerNdx);
1610             container.setVisible(visible);
1611         }
1612         mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = true;
1613     }
1614
1615     void notifyAppResumed(boolean wasStopped) {
1616         mWindowContainerController.notifyAppResumed(wasStopped);
1617     }
1618
1619     void notifyUnknownVisibilityLaunched() {
1620         mWindowContainerController.notifyUnknownVisibilityLaunched();
1621     }
1622
1623     /**
1624      * @return true if the input activity should be made visible, ignoring any effect Keyguard
1625      * might have on the visibility
1626      *
1627      * @see {@link ActivityStack#checkKeyguardVisibility}
1628      */
1629     boolean shouldBeVisibleIgnoringKeyguard(boolean behindTranslucentActivity,
1630             boolean stackVisibleBehind, ActivityRecord visibleBehind,
1631             boolean behindFullscreenActivity) {
1632         if (!okToShowLocked()) {
1633             return false;
1634         }
1635
1636         // mLaunchingBehind: Activities launching behind are at the back of the task stack
1637         // but must be drawn initially for the animation as though they were visible.
1638         final boolean activityVisibleBehind =
1639                 (behindTranslucentActivity || stackVisibleBehind) && visibleBehind == this;
1640
1641         boolean isVisible =
1642                 !behindFullscreenActivity || mLaunchTaskBehind || activityVisibleBehind;
1643
1644         if (service.mSupportsLeanbackOnly && isVisible && isRecentsActivity()) {
1645             // On devices that support leanback only (Android TV), Recents activity can only be
1646             // visible if the home stack is the focused stack or we are in split-screen mode.
1647             isVisible = mStackSupervisor.getStack(DOCKED_STACK_ID) != null
1648                     || mStackSupervisor.isFocusedStack(getStack());
1649         }
1650
1651         return isVisible;
1652     }
1653
1654     void makeVisibleIfNeeded(ActivityRecord starting) {
1655         // This activity is not currently visible, but is running. Tell it to become visible.
1656         if (state == RESUMED || this == starting) {
1657             if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY,
1658                     "Not making visible, r=" + this + " state=" + state + " starting=" + starting);
1659             return;
1660         }
1661
1662         // If this activity is paused, tell it to now show its window.
1663         if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
1664                 "Making visible and scheduling visibility: " + this);
1665         final ActivityStack stack = getStack();
1666         try {
1667             if (stack.mTranslucentActivityWaiting != null) {
1668                 updateOptionsLocked(returningOptions);
1669                 stack.mUndrawnActivitiesBelowTopTranslucent.add(this);
1670             }
1671             setVisible(true);
1672             sleeping = false;
1673             app.pendingUiClean = true;
1674             app.thread.scheduleWindowVisibility(appToken, true /* showWindow */);
1675             // The activity may be waiting for stop, but that is no longer appropriate for it.
1676             mStackSupervisor.mStoppingActivities.remove(this);
1677             mStackSupervisor.mGoingToSleepActivities.remove(this);
1678         } catch (Exception e) {
1679             // Just skip on any failure; we'll make it visible when it next restarts.
1680             Slog.w(TAG, "Exception thrown making visibile: " + intent.getComponent(), e);
1681         }
1682         handleAlreadyVisible();
1683     }
1684
1685     boolean handleAlreadyVisible() {
1686         stopFreezingScreenLocked(false);
1687         try {
1688             if (returningOptions != null) {
1689                 app.thread.scheduleOnNewActivityOptions(appToken, returningOptions.toBundle());
1690             }
1691         } catch(RemoteException e) {
1692         }
1693         return state == RESUMED;
1694     }
1695
1696     static void activityResumedLocked(IBinder token) {
1697         final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1698         if (DEBUG_SAVED_STATE) Slog.i(TAG_STATES, "Resumed activity; dropping state of: " + r);
1699         if (r != null) {
1700             r.icicle = null;
1701             r.haveState = false;
1702         }
1703     }
1704
1705     /**
1706      * Once we know that we have asked an application to put an activity in the resumed state
1707      * (either by launching it or explicitly telling it), this function updates the rest of our
1708      * state to match that fact.
1709      */
1710     void completeResumeLocked() {
1711         final boolean wasVisible = visible;
1712         visible = true;
1713         if (!wasVisible) {
1714             // Visibility has changed, so take a note of it so we call the TaskStackChangedListener
1715             mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = true;
1716         }
1717         idle = false;
1718         results = null;
1719         newIntents = null;
1720         stopped = false;
1721
1722         if (isHomeActivity()) {
1723             ProcessRecord app = task.mActivities.get(0).app;
1724             if (app != null && app != service.mHomeProcess) {
1725                 service.mHomeProcess = app;
1726             }
1727         }
1728
1729         if (nowVisible) {
1730             // We won't get a call to reportActivityVisibleLocked() so dismiss lockscreen now.
1731             mStackSupervisor.reportActivityVisibleLocked(this);
1732         }
1733
1734         // Schedule an idle timeout in case the app doesn't do it for us.
1735         mStackSupervisor.scheduleIdleTimeoutLocked(this);
1736
1737         mStackSupervisor.reportResumedActivityLocked(this);
1738
1739         resumeKeyDispatchingLocked();
1740         final ActivityStack stack = getStack();
1741         stack.mNoAnimActivities.clear();
1742
1743         // Mark the point when the activity is resuming
1744         // TODO: To be more accurate, the mark should be before the onCreate,
1745         //       not after the onResume. But for subsequent starts, onResume is fine.
1746         if (app != null) {
1747             cpuTimeAtResume = service.mProcessCpuTracker.getCpuTimeForPid(app.pid);
1748         } else {
1749             cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1750         }
1751
1752         returningOptions = null;
1753
1754         if (stack.getVisibleBehindActivity() == this) {
1755             // When resuming an activity, require it to call requestVisibleBehind() again.
1756             stack.setVisibleBehindActivity(null /* ActivityRecord */);
1757         }
1758         mStackSupervisor.checkReadyForSleepLocked();
1759     }
1760
1761     final void activityStoppedLocked(Bundle newIcicle, PersistableBundle newPersistentState,
1762             CharSequence description) {
1763         final ActivityStack stack = getStack();
1764         if (state != STOPPING) {
1765             Slog.i(TAG, "Activity reported stop, but no longer stopping: " + this);
1766             stack.mHandler.removeMessages(STOP_TIMEOUT_MSG, this);
1767             return;
1768         }
1769         if (newPersistentState != null) {
1770             persistentState = newPersistentState;
1771             service.notifyTaskPersisterLocked(task, false);
1772         }
1773         if (DEBUG_SAVED_STATE) Slog.i(TAG_SAVED_STATE, "Saving icicle of " + this + ": " + icicle);
1774
1775         if (newIcicle != null) {
1776             // If icicle is null, this is happening due to a timeout, so we haven't really saved
1777             // the state.
1778             icicle = newIcicle;
1779             haveState = true;
1780             launchCount = 0;
1781             updateThumbnailLocked(null /* newThumbnail */, description);
1782         }
1783         if (!stopped) {
1784             if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to STOPPED: " + this + " (stop complete)");
1785             stack.mHandler.removeMessages(STOP_TIMEOUT_MSG, this);
1786             stopped = true;
1787             state = STOPPED;
1788
1789             mWindowContainerController.notifyAppStopped();
1790
1791             if (stack.getVisibleBehindActivity() == this) {
1792                 mStackSupervisor.requestVisibleBehindLocked(this, false /* visible */);
1793             }
1794             if (finishing) {
1795                 clearOptionsLocked();
1796             } else {
1797                 if (deferRelaunchUntilPaused) {
1798                     stack.destroyActivityLocked(this, true /* removeFromApp */, "stop-config");
1799                     mStackSupervisor.resumeFocusedStackTopActivityLocked();
1800                 } else {
1801                     mStackSupervisor.updatePreviousProcessLocked(this);
1802                 }
1803             }
1804         }
1805     }
1806
1807     void startLaunchTickingLocked() {
1808         if (IS_USER_BUILD) {
1809             return;
1810         }
1811         if (launchTickTime == 0) {
1812             launchTickTime = SystemClock.uptimeMillis();
1813             continueLaunchTickingLocked();
1814         }
1815     }
1816
1817     boolean continueLaunchTickingLocked() {
1818         if (launchTickTime == 0) {
1819             return false;
1820         }
1821
1822         final ActivityStack stack = getStack();
1823         if (stack == null) {
1824             return false;
1825         }
1826
1827         Message msg = stack.mHandler.obtainMessage(LAUNCH_TICK_MSG, this);
1828         stack.mHandler.removeMessages(LAUNCH_TICK_MSG);
1829         stack.mHandler.sendMessageDelayed(msg, LAUNCH_TICK);
1830         return true;
1831     }
1832
1833     void finishLaunchTickingLocked() {
1834         launchTickTime = 0;
1835         final ActivityStack stack = getStack();
1836         if (stack != null) {
1837             stack.mHandler.removeMessages(LAUNCH_TICK_MSG);
1838         }
1839     }
1840
1841     // IApplicationToken
1842
1843     public boolean mayFreezeScreenLocked(ProcessRecord app) {
1844         // Only freeze the screen if this activity is currently attached to
1845         // an application, and that application is not blocked or unresponding.
1846         // In any other case, we can't count on getting the screen unfrozen,
1847         // so it is best to leave as-is.
1848         return app != null && !app.crashing && !app.notResponding;
1849     }
1850
1851     public void startFreezingScreenLocked(ProcessRecord app, int configChanges) {
1852         if (mayFreezeScreenLocked(app)) {
1853             mWindowContainerController.startFreezingScreen(configChanges);
1854         }
1855     }
1856
1857     public void stopFreezingScreenLocked(boolean force) {
1858         if (force || frozenBeforeDestroy) {
1859             frozenBeforeDestroy = false;
1860             mWindowContainerController.stopFreezingScreen(force);
1861         }
1862     }
1863
1864     public void reportFullyDrawnLocked() {
1865         final long curTime = SystemClock.uptimeMillis();
1866         if (displayStartTime != 0) {
1867             reportLaunchTimeLocked(curTime);
1868         }
1869         final ActivityStack stack = getStack();
1870         if (fullyDrawnStartTime != 0 && stack != null) {
1871             final long thisTime = curTime - fullyDrawnStartTime;
1872             final long totalTime = stack.mFullyDrawnStartTime != 0
1873                     ? (curTime - stack.mFullyDrawnStartTime) : thisTime;
1874             if (SHOW_ACTIVITY_START_TIME) {
1875                 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
1876                 EventLog.writeEvent(AM_ACTIVITY_FULLY_DRAWN_TIME,
1877                         userId, System.identityHashCode(this), shortComponentName,
1878                         thisTime, totalTime);
1879                 StringBuilder sb = service.mStringBuilder;
1880                 sb.setLength(0);
1881                 sb.append("Fully drawn ");
1882                 sb.append(shortComponentName);
1883                 sb.append(": ");
1884                 TimeUtils.formatDuration(thisTime, sb);
1885                 if (thisTime != totalTime) {
1886                     sb.append(" (total ");
1887                     TimeUtils.formatDuration(totalTime, sb);
1888                     sb.append(")");
1889                 }
1890                 Log.i(TAG, sb.toString());
1891             }
1892             if (totalTime > 0) {
1893                 //service.mUsageStatsService.noteFullyDrawnTime(realActivity, (int) totalTime);
1894             }
1895             stack.mFullyDrawnStartTime = 0;
1896         }
1897         fullyDrawnStartTime = 0;
1898     }
1899
1900     private void reportLaunchTimeLocked(final long curTime) {
1901         final ActivityStack stack = getStack();
1902         if (stack == null) {
1903             return;
1904         }
1905         final long thisTime = curTime - displayStartTime;
1906         final long totalTime = stack.mLaunchStartTime != 0
1907                 ? (curTime - stack.mLaunchStartTime) : thisTime;
1908         if (SHOW_ACTIVITY_START_TIME) {
1909             Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER, "launching: " + packageName, 0);
1910             EventLog.writeEvent(AM_ACTIVITY_LAUNCH_TIME,
1911                     userId, System.identityHashCode(this), shortComponentName,
1912                     thisTime, totalTime);
1913             StringBuilder sb = service.mStringBuilder;
1914             sb.setLength(0);
1915             sb.append("Displayed ");
1916             sb.append(shortComponentName);
1917             sb.append(": ");
1918             TimeUtils.formatDuration(thisTime, sb);
1919             if (thisTime != totalTime) {
1920                 sb.append(" (total ");
1921                 TimeUtils.formatDuration(totalTime, sb);
1922                 sb.append(")");
1923             }
1924             Log.i(TAG, sb.toString());
1925         }
1926         mStackSupervisor.reportActivityLaunchedLocked(false, this, thisTime, totalTime);
1927         if (totalTime > 0) {
1928             //service.mUsageStatsService.noteLaunchTime(realActivity, (int)totalTime);
1929         }
1930         displayStartTime = 0;
1931         stack.mLaunchStartTime = 0;
1932     }
1933
1934     @Override
1935     public void onStartingWindowDrawn(long timestamp) {
1936         synchronized (service) {
1937             mStackSupervisor.mActivityMetricsLogger.notifyStartingWindowDrawn(
1938                     getStackId(), timestamp);
1939         }
1940     }
1941
1942     @Override
1943     public void onWindowsDrawn(long timestamp) {
1944         synchronized (service) {
1945             mStackSupervisor.mActivityMetricsLogger.notifyWindowsDrawn(getStackId(), timestamp);
1946             if (displayStartTime != 0) {
1947                 reportLaunchTimeLocked(timestamp);
1948             }
1949             mStackSupervisor.sendWaitingVisibleReportLocked(this);
1950             startTime = 0;
1951             finishLaunchTickingLocked();
1952             if (task != null) {
1953                 task.hasBeenVisible = true;
1954             }
1955         }
1956     }
1957
1958     @Override
1959     public void onWindowsVisible() {
1960         synchronized (service) {
1961             mStackSupervisor.reportActivityVisibleLocked(this);
1962             if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "windowsVisibleLocked(): " + this);
1963             if (!nowVisible) {
1964                 nowVisible = true;
1965                 lastVisibleTime = SystemClock.uptimeMillis();
1966                 if (idle || mStackSupervisor.isStoppingNoHistoryActivity()) {
1967                     // If this activity was already idle or there is an activity that must be
1968                     // stopped immediately after visible, then we now need to make sure we perform
1969                     // the full stop of any activities that are waiting to do so. This is because
1970                     // we won't do that while they are still waiting for this one to become visible.
1971                     final int size = mStackSupervisor.mActivitiesWaitingForVisibleActivity.size();
1972                     if (size > 0) {
1973                         for (int i = 0; i < size; i++) {
1974                             final ActivityRecord r =
1975                                     mStackSupervisor.mActivitiesWaitingForVisibleActivity.get(i);
1976                             if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "Was waiting for visible: " + r);
1977                         }
1978                         mStackSupervisor.mActivitiesWaitingForVisibleActivity.clear();
1979                         mStackSupervisor.scheduleIdleLocked();
1980                     }
1981                 } else {
1982                     // Instead of doing the full stop routine here, let's just hide any activities
1983                     // we now can, and let them stop when the normal idle happens.
1984                     mStackSupervisor.processStoppingActivitiesLocked(null /* idleActivity */,
1985                             false /* remove */, true /* processPausingActivities */);
1986                 }
1987                 service.scheduleAppGcsLocked();
1988             }
1989         }
1990     }
1991
1992     @Override
1993     public void onWindowsGone() {
1994         synchronized (service) {
1995             if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "windowsGone(): " + this);
1996             nowVisible = false;
1997         }
1998     }
1999
2000     @Override
2001     public boolean keyDispatchingTimedOut(String reason, int windowPid) {
2002         ActivityRecord anrActivity;
2003         ProcessRecord anrApp;
2004         boolean windowFromSameProcessAsActivity;
2005         synchronized (service) {
2006             anrActivity = getWaitingHistoryRecordLocked();
2007             anrApp = app;
2008             windowFromSameProcessAsActivity =
2009                     app == null || app.pid == windowPid || windowPid == -1;
2010         }
2011         if (windowFromSameProcessAsActivity) {
2012             return service.inputDispatchingTimedOut(anrApp, anrActivity, this, false, reason);
2013         } else {
2014             // In this case another process added windows using this activity token. So, we call the
2015             // generic service input dispatch timed out method so that the right process is blamed.
2016             return service.inputDispatchingTimedOut(windowPid, false /* aboveSystem */, reason) < 0;
2017         }
2018     }
2019
2020     private ActivityRecord getWaitingHistoryRecordLocked() {
2021         // First find the real culprit...  if this activity is waiting for
2022         // another activity to start or has stopped, then the key dispatching
2023         // timeout should not be caused by this.
2024         if (mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(this) || stopped) {
2025             final ActivityStack stack = mStackSupervisor.getFocusedStack();
2026             // Try to use the one which is closest to top.
2027             ActivityRecord r = stack.mResumedActivity;
2028             if (r == null) {
2029                 r = stack.mPausingActivity;
2030             }
2031             if (r != null) {
2032                 return r;
2033             }
2034         }
2035         return this;
2036     }
2037
2038     /** Checks whether the activity should be shown for current user. */
2039     public boolean okToShowLocked() {
2040         return (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0
2041                 || (mStackSupervisor.isCurrentProfileLocked(userId)
2042                 && !service.mUserController.isUserStoppingOrShuttingDownLocked(userId));
2043     }
2044
2045     /**
2046      * This method will return true if the activity is either visible, is becoming visible, is
2047      * currently pausing, or is resumed.
2048      */
2049     public boolean isInterestingToUserLocked() {
2050         return visible || nowVisible || state == PAUSING ||
2051                 state == RESUMED;
2052     }
2053
2054     void setSleeping(boolean _sleeping) {
2055         setSleeping(_sleeping, false);
2056     }
2057
2058     void setSleeping(boolean _sleeping, boolean force) {
2059         if (!force && sleeping == _sleeping) {
2060             return;
2061         }
2062         if (app != null && app.thread != null) {
2063             try {
2064                 app.thread.scheduleSleeping(appToken, _sleeping);
2065                 if (_sleeping && !mStackSupervisor.mGoingToSleepActivities.contains(this)) {
2066                     mStackSupervisor.mGoingToSleepActivities.add(this);
2067                 }
2068                 sleeping = _sleeping;
2069             } catch (RemoteException e) {
2070                 Slog.w(TAG, "Exception thrown when sleeping: " + intent.getComponent(), e);
2071             }
2072         }
2073     }
2074
2075     static int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
2076         final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2077         if (r == null) {
2078             return INVALID_TASK_ID;
2079         }
2080         final TaskRecord task = r.task;
2081         final int activityNdx = task.mActivities.indexOf(r);
2082         if (activityNdx < 0 || (onlyRoot && activityNdx > task.findEffectiveRootIndex())) {
2083             return INVALID_TASK_ID;
2084         }
2085         return task.taskId;
2086     }
2087
2088     static ActivityRecord isInStackLocked(IBinder token) {
2089         final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2090         return (r != null) ? r.getStack().isInStackLocked(r) : null;
2091     }
2092
2093     static ActivityStack getStackLocked(IBinder token) {
2094         final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2095         if (r != null) {
2096             return r.getStack();
2097         }
2098         return null;
2099     }
2100
2101     /**
2102      * @return display id to which this record is attached, -1 if not attached.
2103      */
2104     int getDisplayId() {
2105         final ActivityStack stack = getStack();
2106         if (stack == null) {
2107             return -1;
2108         }
2109         return stack.mDisplayId;
2110     }
2111
2112     final boolean isDestroyable() {
2113         if (finishing || app == null || state == DESTROYING
2114                 || state == DESTROYED) {
2115             // This would be redundant.
2116             return false;
2117         }
2118         final ActivityStack stack = getStack();
2119         if (stack == null || this == stack.mResumedActivity || this == stack.mPausingActivity
2120                 || !haveState || !stopped) {
2121             // We're not ready for this kind of thing.
2122             return false;
2123         }
2124         if (visible) {
2125             // The user would notice this!
2126             return false;
2127         }
2128         return true;
2129     }
2130
2131     private static String createImageFilename(long createTime, int taskId) {
2132         return String.valueOf(taskId) + ACTIVITY_ICON_SUFFIX + createTime +
2133                 IMAGE_EXTENSION;
2134     }
2135
2136     void setTaskDescription(TaskDescription _taskDescription) {
2137         Bitmap icon;
2138         if (_taskDescription.getIconFilename() == null &&
2139                 (icon = _taskDescription.getIcon()) != null) {
2140             final String iconFilename = createImageFilename(createTime, task.taskId);
2141             final File iconFile = new File(TaskPersister.getUserImagesDir(task.userId),
2142                     iconFilename);
2143             final String iconFilePath = iconFile.getAbsolutePath();
2144             service.mRecentTasks.saveImage(icon, iconFilePath);
2145             _taskDescription.setIconFilename(iconFilePath);
2146         }
2147         taskDescription = _taskDescription;
2148     }
2149
2150     void setVoiceSessionLocked(IVoiceInteractionSession session) {
2151         voiceSession = session;
2152         pendingVoiceInteractionStart = false;
2153     }
2154
2155     void clearVoiceSessionLocked() {
2156         voiceSession = null;
2157         pendingVoiceInteractionStart = false;
2158     }
2159
2160     void showStartingWindow(ActivityRecord prev, boolean newTask, boolean taskSwitch) {
2161         showStartingWindow(prev, newTask, taskSwitch, false /* fromRecents */);
2162     }
2163
2164     void showStartingWindow(ActivityRecord prev, boolean newTask, boolean taskSwitch,
2165             boolean fromRecents) {
2166         if (mWindowContainerController == null) {
2167             return;
2168         }
2169         if (mTaskOverlay) {
2170             // We don't show starting window for overlay activities.
2171             return;
2172         }
2173
2174         final CompatibilityInfo compatInfo =
2175                 service.compatibilityInfoForPackageLocked(info.applicationInfo);
2176         final boolean shown = mWindowContainerController.addStartingWindow(packageName, theme,
2177                 compatInfo, nonLocalizedLabel, labelRes, icon, logo, windowFlags,
2178                 prev != null ? prev.appToken : null, newTask, taskSwitch, isProcessRunning(),
2179                 allowTaskSnapshot(),
2180                 state.ordinal() >= RESUMED.ordinal() && state.ordinal() <= STOPPED.ordinal(),
2181                 fromRecents);
2182         if (shown) {
2183             mStartingWindowState = STARTING_WINDOW_SHOWN;
2184         }
2185     }
2186
2187     void removeOrphanedStartingWindow(boolean behindFullscreenActivity) {
2188         if (mStartingWindowState == STARTING_WINDOW_SHOWN && behindFullscreenActivity) {
2189             if (DEBUG_VISIBILITY) Slog.w(TAG_VISIBILITY, "Found orphaned starting window " + this);
2190             mStartingWindowState = STARTING_WINDOW_REMOVED;
2191             mWindowContainerController.removeHiddenStartingWindow();
2192         }
2193     }
2194
2195     int getRequestedOrientation() {
2196         return mWindowContainerController.getOrientation();
2197     }
2198
2199     void setRequestedOrientation(int requestedOrientation) {
2200         if (ActivityInfo.isFixedOrientation(requestedOrientation) && !fullscreen
2201                 && appInfo.targetSdkVersion > O) {
2202             throw new IllegalStateException("Only fullscreen activities can request orientation");
2203         }
2204
2205         final int displayId = getDisplayId();
2206         final Configuration displayConfig =
2207                 mStackSupervisor.getDisplayOverrideConfiguration(displayId);
2208
2209         final Configuration config = mWindowContainerController.setOrientation(requestedOrientation,
2210                 displayId, displayConfig, mayFreezeScreenLocked(app));
2211         if (config != null) {
2212             frozenBeforeDestroy = true;
2213             if (!service.updateDisplayOverrideConfigurationLocked(config, this,
2214                     false /* deferResume */, displayId)) {
2215                 mStackSupervisor.resumeFocusedStackTopActivityLocked();
2216             }
2217         }
2218         service.mTaskChangeNotificationController.notifyActivityRequestedOrientationChanged(
2219                 task.taskId, requestedOrientation);
2220     }
2221
2222     void setDisablePreviewScreenshots(boolean disable) {
2223         mWindowContainerController.setDisablePreviewScreenshots(disable);
2224     }
2225
2226     /**
2227      * Set the last reported global configuration to the client. Should be called whenever a new
2228      * global configuration is sent to the client for this activity.
2229      */
2230     void setLastReportedGlobalConfiguration(@NonNull Configuration config) {
2231         mLastReportedConfiguration.setGlobalConfiguration(config);
2232     }
2233
2234     /**
2235      * Set the last reported configuration to the client. Should be called whenever
2236      * a new merged configuration is sent to the client for this activity.
2237      */
2238     void setLastReportedConfiguration(@NonNull MergedConfiguration config) {
2239         mLastReportedConfiguration.setTo(config);
2240     }
2241
2242     /** Call when override config was sent to the Window Manager to update internal records. */
2243     // TODO(b/36505427): Why do we set last reported based on sending the config to WM? Seems like
2244     // we should only set this when we actually report to the activity which is what the method
2245     // setLastReportedMergedOverrideConfiguration() does. Investigate if this is really needed.
2246     void onOverrideConfigurationSent() {
2247         mLastReportedConfiguration.setOverrideConfiguration(getMergedOverrideConfiguration());
2248     }
2249
2250     @Override
2251     void onOverrideConfigurationChanged(Configuration newConfig) {
2252         final Configuration currentConfig = getOverrideConfiguration();
2253         if (currentConfig.equals(newConfig)) {
2254             return;
2255         }
2256         super.onOverrideConfigurationChanged(newConfig);
2257         if (mWindowContainerController == null) {
2258             return;
2259         }
2260         mWindowContainerController.onOverrideConfigurationChanged(newConfig, mBounds);
2261         // TODO(b/36505427): Can we consolidate the call points of onOverrideConfigurationSent()
2262         // to just use this method instead?
2263         onOverrideConfigurationSent();
2264     }
2265
2266     // TODO(b/36505427): Consider moving this method and similar ones to ConfigurationContainer.
2267     private void updateOverrideConfiguration() {
2268         mTmpConfig.unset();
2269         computeBounds(mTmpBounds);
2270         if (mTmpBounds.equals(mBounds)) {
2271             final ActivityStack stack = getStack();
2272             if (!mBounds.isEmpty() || task == null || stack == null || !task.mFullscreen) {
2273                 // We don't want to influence the override configuration here if our task is in
2274                 // multi-window mode or there is a bounds specified to calculate the override
2275                 // config. In both of this cases the app should be compatible with whatever the
2276                 // current configuration is or will be.
2277                 return;
2278             }
2279
2280             // Currently limited to the top activity for now to avoid situations where non-top
2281             // visible activity and top might have conflicting requests putting the non-top activity
2282             // windows in an odd state.
2283             final ActivityRecord top = mStackSupervisor.topRunningActivityLocked();
2284             final Configuration parentConfig = getParent().getConfiguration();
2285             if (top != this || isConfigurationCompatible(parentConfig)) {
2286                 onOverrideConfigurationChanged(mTmpConfig);
2287             } else if (isConfigurationCompatible(
2288                     mLastReportedConfiguration.getMergedConfiguration())) {
2289                 onOverrideConfigurationChanged(mLastReportedConfiguration.getMergedConfiguration());
2290             }
2291             return;
2292         }
2293
2294         mBounds.set(mTmpBounds);
2295         // Bounds changed...update configuration to match.
2296         if (!mBounds.isEmpty()) {
2297             task.computeOverrideConfiguration(mTmpConfig, mBounds, null /* insetBounds */,
2298                     false /* overrideWidth */, false /* overrideHeight */);
2299         }
2300         onOverrideConfigurationChanged(mTmpConfig);
2301     }
2302
2303     /** Returns true if the configuration is compatible with this activity. */
2304     boolean isConfigurationCompatible(Configuration config) {
2305         final int orientation = mWindowContainerController != null
2306                 ? mWindowContainerController.getOrientation() : info.screenOrientation;
2307         if (isFixedOrientationPortrait(orientation)
2308                 && config.orientation != ORIENTATION_PORTRAIT) {
2309             return false;
2310         }
2311         if (isFixedOrientationLandscape(orientation)
2312                 && config.orientation != ORIENTATION_LANDSCAPE) {
2313             return false;
2314         }
2315         return true;
2316     }
2317
2318     /**
2319      * Computes the bounds to fit the Activity within the bounds of the {@link Configuration}.
2320      */
2321     // TODO(b/36505427): Consider moving this method and similar ones to ConfigurationContainer.
2322     private void computeBounds(Rect outBounds) {
2323         outBounds.setEmpty();
2324         final float maxAspectRatio = info.maxAspectRatio;
2325         final ActivityStack stack = getStack();
2326         if (task == null || stack == null || !task.mFullscreen || maxAspectRatio == 0
2327                 || isInVrUiMode(getConfiguration())) {
2328             // We don't set override configuration if that activity task isn't fullscreen. I.e. the
2329             // activity is in multi-window mode. Or, there isn't a max aspect ratio specified for
2330             // the activity. This is indicated by an empty {@link outBounds}. We also don't set it
2331             // if we are in VR mode.
2332             return;
2333         }
2334
2335         // We must base this on the parent configuration, because we set our override
2336         // configuration's appBounds based on the result of this method. If we used our own
2337         // configuration, it would be influenced by past invocations.
2338         final Configuration configuration = getParent().getConfiguration();
2339         final int containingAppWidth = configuration.appBounds.width();
2340         final int containingAppHeight = configuration.appBounds.height();
2341         int maxActivityWidth = containingAppWidth;
2342         int maxActivityHeight = containingAppHeight;
2343
2344         if (containingAppWidth < containingAppHeight) {
2345             // Width is the shorter side, so we use that to figure-out what the max. height
2346             // should be given the aspect ratio.
2347             maxActivityHeight = (int) ((maxActivityWidth * maxAspectRatio) + 0.5f);
2348         } else {
2349             // Height is the shorter side, so we use that to figure-out what the max. width
2350             // should be given the aspect ratio.
2351             maxActivityWidth = (int) ((maxActivityHeight * maxAspectRatio) + 0.5f);
2352         }
2353
2354         if (containingAppWidth <= maxActivityWidth && containingAppHeight <= maxActivityHeight) {
2355             // The display matches or is less than the activity aspect ratio, so nothing else to do.
2356             // Return the existing bounds. If this method is running for the first time,
2357             // {@link mBounds} will be empty (representing no override). If the method has run
2358             // before, then effect of {@link mBounds} will already have been applied to the
2359             // value returned from {@link getConfiguration}. Refer to
2360             // {@link TaskRecord#computeOverrideConfiguration}.
2361             outBounds.set(mBounds);
2362             return;
2363         }
2364
2365         // Compute configuration based on max supported width and height.
2366         outBounds.set(0, 0, maxActivityWidth, maxActivityHeight);
2367         // Position the activity frame on the opposite side of the nav bar.
2368         final int navBarPosition = service.mWindowManager.getNavBarPosition();
2369         final int left = navBarPosition == NAV_BAR_LEFT
2370                 ? configuration.appBounds.right - outBounds.width() : 0;
2371         outBounds.offsetTo(left, 0 /* top */);
2372     }
2373
2374     /** Get bounds of the activity. */
2375     @VisibleForTesting
2376     Rect getBounds() {
2377         return new Rect(mBounds);
2378     }
2379
2380     /**
2381      * Make sure the given activity matches the current configuration. Returns false if the activity
2382      * had to be destroyed.  Returns true if the configuration is the same, or the activity will
2383      * remain running as-is for whatever reason. Ensures the HistoryRecord is updated with the
2384      * correct configuration and all other bookkeeping is handled.
2385      */
2386     boolean ensureActivityConfigurationLocked(int globalChanges, boolean preserveWindow) {
2387         final ActivityStack stack = getStack();
2388         if (stack.mConfigWillChange) {
2389             if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2390                     "Skipping config check (will change): " + this);
2391             return true;
2392         }
2393
2394         // We don't worry about activities that are finishing.
2395         if (finishing) {
2396             if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2397                     "Configuration doesn't matter in finishing " + this);
2398             stopFreezingScreenLocked(false);
2399             return true;
2400         }
2401
2402         // Skip updating configuration for activity that are stopping or stopped.
2403         if (state == STOPPING || state == STOPPED) {
2404             if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2405                     "Skipping config check stopped or stopping: " + this);
2406             return true;
2407         }
2408
2409         // TODO: We should add ActivityRecord.shouldBeVisible() that checks if the activity should
2410         // be visible based on the stack, task, and lockscreen state and use that here instead. The
2411         // method should be based on the logic in ActivityStack.ensureActivitiesVisibleLocked().
2412         // Skip updating configuration for activity is a stack that shouldn't be visible.
2413         if (stack.shouldBeVisible(null /* starting */) == STACK_INVISIBLE) {
2414             if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2415                     "Skipping config check invisible stack: " + this);
2416             return true;
2417         }
2418
2419         if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2420                 "Ensuring correct configuration: " + this);
2421
2422         final int newDisplayId = getDisplayId();
2423         final boolean displayChanged = mLastReportedDisplayId != newDisplayId;
2424         if (displayChanged) {
2425             mLastReportedDisplayId = newDisplayId;
2426         }
2427         // TODO(b/36505427): Is there a better place to do this?
2428         updateOverrideConfiguration();
2429
2430         // Short circuit: if the two full configurations are equal (the common case), then there is
2431         // nothing to do.  We test the full configuration instead of the global and merged override
2432         // configurations because there are cases (like moving a task to the pinned stack) where
2433         // the combine configurations are equal, but would otherwise differ in the override config
2434         mTmpConfig.setTo(mLastReportedConfiguration.getMergedConfiguration());
2435         if (getConfiguration().equals(mTmpConfig) && !forceNewConfig && !displayChanged) {
2436             if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2437                     "Configuration & display unchanged in " + this);
2438             return true;
2439         }
2440
2441         // Okay we now are going to make this activity have the new config.
2442         // But then we need to figure out how it needs to deal with that.
2443
2444         // Find changes between last reported merged configuration and the current one. This is used
2445         // to decide whether to relaunch an activity or just report a configuration change.
2446         final int changes = getConfigurationChanges(mTmpConfig);
2447
2448         // Update last reported values.
2449         final Configuration newMergedOverrideConfig = getMergedOverrideConfiguration();
2450         mLastReportedConfiguration.setConfiguration(service.getGlobalConfiguration(),
2451                 newMergedOverrideConfig);
2452
2453         if (changes == 0 && !forceNewConfig) {
2454             if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2455                     "Configuration no differences in " + this);
2456             // There are no significant differences, so we won't relaunch but should still deliver
2457             // the new configuration to the client process.
2458             if (displayChanged) {
2459                 scheduleActivityMovedToDisplay(newDisplayId, newMergedOverrideConfig);
2460             } else {
2461                 scheduleConfigurationChanged(newMergedOverrideConfig);
2462             }
2463             return true;
2464         }
2465
2466         if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2467                 "Configuration changes for " + this + ", allChanges="
2468                         + Configuration.configurationDiffToString(changes));
2469
2470         // If the activity isn't currently running, just leave the new configuration and it will
2471         // pick that up next time it starts.
2472         if (app == null || app.thread == null) {
2473             if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2474                     "Configuration doesn't matter not running " + this);
2475             stopFreezingScreenLocked(false);
2476             forceNewConfig = false;
2477             return true;
2478         }
2479
2480         // Figure out how to handle the changes between the configurations.
2481         if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2482                 "Checking to restart " + info.name + ": changed=0x"
2483                         + Integer.toHexString(changes) + ", handles=0x"
2484                         + Integer.toHexString(info.getRealConfigChanged())
2485                         + ", mLastReportedConfiguration=" + mLastReportedConfiguration);
2486
2487         if (shouldRelaunchLocked(changes, mTmpConfig) || forceNewConfig) {
2488             // Aha, the activity isn't handling the change, so DIE DIE DIE.
2489             configChangeFlags |= changes;
2490             startFreezingScreenLocked(app, globalChanges);
2491             forceNewConfig = false;
2492             preserveWindow &= isResizeOnlyChange(changes);
2493             if (app == null || app.thread == null) {
2494                 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2495                         "Config is destroying non-running " + this);
2496                 stack.destroyActivityLocked(this, true, "config");
2497             } else if (state == PAUSING) {
2498                 // A little annoying: we are waiting for this activity to finish pausing. Let's not
2499                 // do anything now, but just flag that it needs to be restarted when done pausing.
2500                 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2501                         "Config is skipping already pausing " + this);
2502                 deferRelaunchUntilPaused = true;
2503                 preserveWindowOnDeferredRelaunch = preserveWindow;
2504                 return true;
2505             } else if (state == RESUMED) {
2506                 // Try to optimize this case: the configuration is changing and we need to restart
2507                 // the top, resumed activity. Instead of doing the normal handshaking, just say
2508                 // "restart!".
2509                 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2510                         "Config is relaunching resumed " + this);
2511
2512                 if (DEBUG_STATES && !visible) {
2513                     Slog.v(TAG_STATES, "Config is relaunching resumed invisible activity " + this
2514                             + " called by " + Debug.getCallers(4));
2515                 }
2516
2517                 relaunchActivityLocked(true /* andResume */, preserveWindow);
2518             } else {
2519                 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
2520                         "Config is relaunching non-resumed " + this);
2521                 relaunchActivityLocked(false /* andResume */, preserveWindow);
2522             }
2523
2524             // All done...  tell the caller we weren't able to keep this activity around.
2525             return false;
2526         }
2527
2528         // Default case: the activity can handle this new configuration, so hand it over.
2529         // NOTE: We only forward the override configuration as the system level configuration
2530         // changes is always sent to all processes when they happen so it can just use whatever
2531         // system level configuration it last got.
2532         if (displayChanged) {
2533             scheduleActivityMovedToDisplay(newDisplayId, newMergedOverrideConfig);
2534         } else {
2535             scheduleConfigurationChanged(newMergedOverrideConfig);
2536         }
2537         stopFreezingScreenLocked(false);
2538
2539         return true;
2540     }
2541
2542     /**
2543      * When assessing a configuration change, decide if the changes flags and the new configurations
2544      * should cause the Activity to relaunch.
2545      *
2546      * @param changes the changes due to the given configuration.
2547      * @param changesConfig the configuration that was used to calculate the given changes via a
2548      *        call to getConfigurationChanges.
2549      */
2550     private boolean shouldRelaunchLocked(int changes, Configuration changesConfig) {
2551         int configChanged = info.getRealConfigChanged();
2552         boolean onlyVrUiModeChanged = onlyVrUiModeChanged(changes, changesConfig);
2553
2554         // Override for apps targeting pre-O sdks
2555         // If a device is in VR mode, and we're transitioning into VR ui mode, add ignore ui mode
2556         // to the config change.
2557         // For O and later, apps will be required to add configChanges="uimode" to their manifest.
2558         if (appInfo.targetSdkVersion < O
2559                 && requestedVrComponent != null
2560                 && onlyVrUiModeChanged) {
2561             configChanged |= CONFIG_UI_MODE;
2562         }
2563
2564         return (changes&(~configChanged)) != 0;
2565     }
2566
2567     /**
2568      * Returns true if the configuration change is solely due to the UI mode switching into or out
2569      * of UI_MODE_TYPE_VR_HEADSET.
2570      */
2571     private boolean onlyVrUiModeChanged(int changes, Configuration lastReportedConfig) {
2572         final Configuration currentConfig = getConfiguration();
2573         return changes == CONFIG_UI_MODE && (isInVrUiMode(currentConfig)
2574             != isInVrUiMode(lastReportedConfig));
2575     }
2576
2577     private int getConfigurationChanges(Configuration lastReportedConfig) {
2578         // Determine what has changed.  May be nothing, if this is a config that has come back from
2579         // the app after going idle.  In that case we just want to leave the official config object
2580         // now in the activity and do nothing else.
2581         final Configuration currentConfig = getConfiguration();
2582         int changes = lastReportedConfig.diff(currentConfig);
2583         // We don't want to use size changes if they don't cross boundaries that are important to
2584         // the app.
2585         if ((changes & CONFIG_SCREEN_SIZE) != 0) {
2586             final boolean crosses = crossesHorizontalSizeThreshold(lastReportedConfig.screenWidthDp,
2587                     currentConfig.screenWidthDp)
2588                     || crossesVerticalSizeThreshold(lastReportedConfig.screenHeightDp,
2589                     currentConfig.screenHeightDp);
2590             if (!crosses) {
2591                 changes &= ~CONFIG_SCREEN_SIZE;
2592             }
2593         }
2594         if ((changes & CONFIG_SMALLEST_SCREEN_SIZE) != 0) {
2595             final int oldSmallest = lastReportedConfig.smallestScreenWidthDp;
2596             final int newSmallest = currentConfig.smallestScreenWidthDp;
2597             if (!crossesSmallestSizeThreshold(oldSmallest, newSmallest)) {
2598                 changes &= ~CONFIG_SMALLEST_SCREEN_SIZE;
2599             }
2600         }
2601         // We don't want rotation to cause relaunches.
2602         if ((changes & CONFIG_ROTATION) != 0) {
2603             changes &= ~CONFIG_ROTATION;
2604         }
2605
2606         // We don't want app bound changes to cause relaunches.
2607         if ((changes & CONFIG_APP_BOUNDS) != 0) {
2608             changes &= ~CONFIG_APP_BOUNDS;
2609         }
2610
2611         return changes;
2612     }
2613
2614     private static boolean isResizeOnlyChange(int change) {
2615         return (change & ~(CONFIG_SCREEN_SIZE | CONFIG_SMALLEST_SCREEN_SIZE | CONFIG_ORIENTATION
2616                 | CONFIG_SCREEN_LAYOUT)) == 0;
2617     }
2618
2619     void relaunchActivityLocked(boolean andResume, boolean preserveWindow) {
2620         if (service.mSuppressResizeConfigChanges && preserveWindow) {
2621             configChangeFlags = 0;
2622             return;
2623         }
2624
2625         List<ResultInfo> pendingResults = null;
2626         List<ReferrerIntent> pendingNewIntents = null;
2627         if (andResume) {
2628             pendingResults = results;
2629             pendingNewIntents = newIntents;
2630         }
2631         if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
2632                 "Relaunching: " + this + " with results=" + pendingResults
2633                         + " newIntents=" + pendingNewIntents + " andResume=" + andResume
2634                         + " preserveWindow=" + preserveWindow);
2635         EventLog.writeEvent(andResume ? AM_RELAUNCH_RESUME_ACTIVITY
2636                         : AM_RELAUNCH_ACTIVITY, userId, System.identityHashCode(this),
2637                 task.taskId, shortComponentName);
2638
2639         startFreezingScreenLocked(app, 0);
2640
2641         mStackSupervisor.removeChildActivityContainers(this);
2642
2643         try {
2644             if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_SWITCH,
2645                     "Moving to " + (andResume ? "RESUMED" : "PAUSED") + " Relaunching " + this
2646                             + " callers=" + Debug.getCallers(6));
2647             forceNewConfig = false;
2648             mStackSupervisor.activityRelaunchingLocked(this);
2649             app.thread.scheduleRelaunchActivity(appToken, pendingResults, pendingNewIntents,
2650                     configChangeFlags, !andResume,
2651                     new Configuration(service.getGlobalConfiguration()),
2652                     new Configuration(getMergedOverrideConfiguration()), preserveWindow);
2653             // Note: don't need to call pauseIfSleepingLocked() here, because the caller will only
2654             // pass in 'andResume' if this activity is currently resumed, which implies we aren't
2655             // sleeping.
2656         } catch (RemoteException e) {
2657             if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_SWITCH, "Relaunch failed", e);
2658         }
2659
2660         if (andResume) {
2661             if (DEBUG_STATES) {
2662                 Slog.d(TAG_STATES, "Resumed after relaunch " + this);
2663             }
2664             results = null;
2665             newIntents = null;
2666             service.showUnsupportedZoomDialogIfNeededLocked(this);
2667             service.showAskCompatModeDialogLocked(this);
2668         } else {
2669             service.mHandler.removeMessages(PAUSE_TIMEOUT_MSG, this);
2670             state = PAUSED;
2671             // if the app is relaunched when it's stopped, and we're not resuming,
2672             // put it back into stopped state.
2673             if (stopped) {
2674                 getStack().addToStopping(this, true /* scheduleIdle */, false /* idleDelayed */);
2675             }
2676         }
2677
2678         configChangeFlags = 0;
2679         deferRelaunchUntilPaused = false;
2680         preserveWindowOnDeferredRelaunch = false;
2681     }
2682
2683     private boolean isProcessRunning() {
2684         ProcessRecord proc = app;
2685         if (proc == null) {
2686             proc = service.mProcessNames.get(processName, info.applicationInfo.uid);
2687         }
2688         return proc != null && proc.thread != null;
2689     }
2690
2691     /**
2692      * @return Whether a task snapshot starting window may be shown.
2693      */
2694     private boolean allowTaskSnapshot() {
2695         if (newIntents == null) {
2696             return true;
2697         }
2698
2699         // Restrict task snapshot starting window to launcher start, or there is no intent at all
2700         // (eg. task being brought to front). If the intent is something else, likely the app is
2701         // going to show some specific page or view, instead of what's left last time.
2702         for (int i = newIntents.size() - 1; i >= 0; i--) {
2703             final Intent intent = newIntents.get(i);
2704             if (intent != null && !ActivityRecord.isMainIntent(intent)) {
2705                 return false;
2706             }
2707         }
2708         return true;
2709     }
2710
2711     /**
2712      * Returns {@code true} if the associated activity has the no history flag set on it.
2713      * {@code false} otherwise.
2714      */
2715     boolean isNoHistory() {
2716         return (intent.getFlags() & FLAG_ACTIVITY_NO_HISTORY) != 0
2717                 || (info.flags & FLAG_NO_HISTORY) != 0;
2718     }
2719
2720     void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException {
2721         out.attribute(null, ATTR_ID, String.valueOf(createTime));
2722         out.attribute(null, ATTR_LAUNCHEDFROMUID, String.valueOf(launchedFromUid));
2723         if (launchedFromPackage != null) {
2724             out.attribute(null, ATTR_LAUNCHEDFROMPACKAGE, launchedFromPackage);
2725         }
2726         if (resolvedType != null) {
2727             out.attribute(null, ATTR_RESOLVEDTYPE, resolvedType);
2728         }
2729         out.attribute(null, ATTR_COMPONENTSPECIFIED, String.valueOf(componentSpecified));
2730         out.attribute(null, ATTR_USERID, String.valueOf(userId));
2731
2732         if (taskDescription != null) {
2733             taskDescription.saveToXml(out);
2734         }
2735
2736         out.startTag(null, TAG_INTENT);
2737         intent.saveToXml(out);
2738         out.endTag(null, TAG_INTENT);
2739
2740         if (isPersistable() && persistentState != null) {
2741             out.startTag(null, TAG_PERSISTABLEBUNDLE);
2742             persistentState.saveToXml(out);
2743             out.endTag(null, TAG_PERSISTABLEBUNDLE);
2744         }
2745     }
2746
2747     static ActivityRecord restoreFromXml(XmlPullParser in,
2748             ActivityStackSupervisor stackSupervisor) throws IOException, XmlPullParserException {
2749         Intent intent = null;
2750         PersistableBundle persistentState = null;
2751         int launchedFromUid = 0;
2752         String launchedFromPackage = null;
2753         String resolvedType = null;
2754         boolean componentSpecified = false;
2755         int userId = 0;
2756         long createTime = -1;
2757         final int outerDepth = in.getDepth();
2758         TaskDescription taskDescription = new TaskDescription();
2759
2760         for (int attrNdx = in.getAttributeCount() - 1; attrNdx >= 0; --attrNdx) {
2761             final String attrName = in.getAttributeName(attrNdx);
2762             final String attrValue = in.getAttributeValue(attrNdx);
2763             if (DEBUG) Slog.d(TaskPersister.TAG,
2764                         "ActivityRecord: attribute name=" + attrName + " value=" + attrValue);
2765             if (ATTR_ID.equals(attrName)) {
2766                 createTime = Long.parseLong(attrValue);
2767             } else if (ATTR_LAUNCHEDFROMUID.equals(attrName)) {
2768                 launchedFromUid = Integer.parseInt(attrValue);
2769             } else if (ATTR_LAUNCHEDFROMPACKAGE.equals(attrName)) {
2770                 launchedFromPackage = attrValue;
2771             } else if (ATTR_RESOLVEDTYPE.equals(attrName)) {
2772                 resolvedType = attrValue;
2773             } else if (ATTR_COMPONENTSPECIFIED.equals(attrName)) {
2774                 componentSpecified = Boolean.parseBoolean(attrValue);
2775             } else if (ATTR_USERID.equals(attrName)) {
2776                 userId = Integer.parseInt(attrValue);
2777             } else if (attrName.startsWith(ATTR_TASKDESCRIPTION_PREFIX)) {
2778                 taskDescription.restoreFromXml(attrName, attrValue);
2779             } else {
2780                 Log.d(TAG, "Unknown ActivityRecord attribute=" + attrName);
2781             }
2782         }
2783
2784         int event;
2785         while (((event = in.next()) != END_DOCUMENT) &&
2786                 (event != END_TAG || in.getDepth() >= outerDepth)) {
2787             if (event == START_TAG) {
2788                 final String name = in.getName();
2789                 if (DEBUG)
2790                         Slog.d(TaskPersister.TAG, "ActivityRecord: START_TAG name=" + name);
2791                 if (TAG_INTENT.equals(name)) {
2792                     intent = Intent.restoreFromXml(in);
2793                     if (DEBUG)
2794                             Slog.d(TaskPersister.TAG, "ActivityRecord: intent=" + intent);
2795                 } else if (TAG_PERSISTABLEBUNDLE.equals(name)) {
2796                     persistentState = PersistableBundle.restoreFromXml(in);
2797                     if (DEBUG) Slog.d(TaskPersister.TAG,
2798                             "ActivityRecord: persistentState=" + persistentState);
2799                 } else {
2800                     Slog.w(TAG, "restoreActivity: unexpected name=" + name);
2801                     XmlUtils.skipCurrentTag(in);
2802                 }
2803             }
2804         }
2805
2806         if (intent == null) {
2807             throw new XmlPullParserException("restoreActivity error intent=" + intent);
2808         }
2809
2810         final ActivityManagerService service = stackSupervisor.mService;
2811         final ActivityInfo aInfo = stackSupervisor.resolveActivity(intent, resolvedType, 0, null,
2812                 userId);
2813         if (aInfo == null) {
2814             throw new XmlPullParserException("restoreActivity resolver error. Intent=" + intent +
2815                     " resolvedType=" + resolvedType);
2816         }
2817         final ActivityRecord r = new ActivityRecord(service, null /* caller */,
2818                 0 /* launchedFromPid */, launchedFromUid, launchedFromPackage, intent, resolvedType,
2819                 aInfo, service.getConfiguration(), null /* resultTo */, null /* resultWho */,
2820                 0 /* reqCode */, componentSpecified, false /* rootVoiceInteraction */,
2821                 stackSupervisor, null /* container */, null /* options */, null /* sourceRecord */);
2822
2823         r.persistentState = persistentState;
2824         r.taskDescription = taskDescription;
2825         r.createTime = createTime;
2826
2827         return r;
2828     }
2829
2830     private static String activityTypeToString(int type) {
2831         switch (type) {
2832             case APPLICATION_ACTIVITY_TYPE: return "APPLICATION_ACTIVITY_TYPE";
2833             case HOME_ACTIVITY_TYPE: return "HOME_ACTIVITY_TYPE";
2834             case RECENTS_ACTIVITY_TYPE: return "RECENTS_ACTIVITY_TYPE";
2835             case ASSISTANT_ACTIVITY_TYPE: return "ASSISTANT_ACTIVITY_TYPE";
2836             default: return Integer.toString(type);
2837         }
2838     }
2839
2840     private static boolean isInVrUiMode(Configuration config) {
2841         return (config.uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_VR_HEADSET;
2842     }
2843
2844     int getUid() {
2845         return info.applicationInfo.uid;
2846     }
2847
2848     @Override
2849     public String toString() {
2850         if (stringName != null) {
2851             return stringName + " t" + (task == null ? INVALID_TASK_ID : task.taskId) +
2852                     (finishing ? " f}" : "}");
2853         }
2854         StringBuilder sb = new StringBuilder(128);
2855         sb.append("ActivityRecord{");
2856         sb.append(Integer.toHexString(System.identityHashCode(this)));
2857         sb.append(" u");
2858         sb.append(userId);
2859         sb.append(' ');
2860         sb.append(intent.getComponent().flattenToShortString());
2861         stringName = sb.toString();
2862         return toString();
2863     }
2864 }