1 /*
2  * Copyright (C) 2018 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.wm;
18 
19 import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20 import static android.Manifest.permission.CHANGE_CONFIGURATION;
21 import static android.Manifest.permission.CONTROL_KEYGUARD;
22 import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
23 import static android.Manifest.permission.DETECT_SCREEN_CAPTURE;
24 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
25 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
26 import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
27 import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
28 import static android.Manifest.permission.MANAGE_ACTIVITY_TASKS;
29 import static android.Manifest.permission.MANAGE_GAME_ACTIVITY;
30 import static android.Manifest.permission.READ_FRAME_BUFFER;
31 import static android.Manifest.permission.REMOVE_TASKS;
32 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
33 import static android.Manifest.permission.STOP_APP_SWITCHES;
34 import static android.app.ActivityManager.DROP_CLOSE_SYSTEM_DIALOGS;
35 import static android.app.ActivityManager.LOCK_DOWN_CLOSE_SYSTEM_DIALOGS;
36 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
37 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
38 import static android.app.ActivityTaskManager.INVALID_TASK_ID;
39 import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
40 import static android.app.WindowConfiguration.ACTIVITY_TYPE_DREAM;
41 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
42 import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
43 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
44 import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
45 import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
46 import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47 import static android.content.pm.PackageManager.FEATURE_CANT_SAVE_STATE;
48 import static android.content.pm.PackageManager.FEATURE_COMPANION_DEVICE_SETUP;
49 import static android.content.pm.PackageManager.FEATURE_EXPANDED_PICTURE_IN_PICTURE;
50 import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
51 import static android.content.pm.PackageManager.FEATURE_LEANBACK;
52 import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
53 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
54 import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55 import static android.os.InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
56 import static android.os.Process.FIRST_APPLICATION_UID;
57 import static android.os.Process.SYSTEM_UID;
58 import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
59 import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60 import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_NON_RESIZABLE_MULTI_WINDOW;
61 import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
62 import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
63 import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
64 import static android.provider.Settings.System.FONT_SCALE;
65 import static android.service.controls.flags.Flags.homePanelDream;
66 import static android.view.Display.DEFAULT_DISPLAY;
67 import static android.view.Display.INVALID_DISPLAY;
68 import static android.view.WindowManager.TRANSIT_CHANGE;
69 import static android.view.WindowManager.TRANSIT_PIP;
70 import static android.view.WindowManager.TRANSIT_TO_FRONT;
71 import static android.view.WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_TO_LAUNCHER_CLEAR_SNAPSHOT;
72 import static android.window.TransitionInfo.FLAG_IN_TASK_WITH_EMBEDDED_ACTIVITY;
73 
74 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_CONFIGURATION;
75 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_DREAM;
76 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_FOCUS;
77 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_IMMERSIVE;
78 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_LOCKTASK;
79 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_TASKS;
80 import static com.android.sdksandbox.flags.Flags.sandboxActivitySdkBasedContext;
81 import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
82 import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
83 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
84 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
85 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
86 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
87 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
88 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
89 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
90 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
91 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
92 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
93 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
94 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
95 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
96 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
97 import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
98 import static com.android.server.am.EventLogTags.writeConfigurationChanged;
99 import static com.android.server.am.StackTracesDumpHelper.ANR_TRACE_DIR;
100 import static com.android.server.am.StackTracesDumpHelper.dumpStackTraces;
101 import static com.android.server.wm.ActivityInterceptorCallback.MAINLINE_FIRST_ORDERED_ID;
102 import static com.android.server.wm.ActivityInterceptorCallback.MAINLINE_LAST_ORDERED_ID;
103 import static com.android.server.wm.ActivityInterceptorCallback.SYSTEM_FIRST_ORDERED_ID;
104 import static com.android.server.wm.ActivityInterceptorCallback.SYSTEM_LAST_ORDERED_ID;
105 import static com.android.server.wm.ActivityRecord.State.DESTROYED;
106 import static com.android.server.wm.ActivityRecord.State.DESTROYING;
107 import static com.android.server.wm.ActivityRecord.State.FINISHING;
108 import static com.android.server.wm.ActivityRecord.State.PAUSING;
109 import static com.android.server.wm.ActivityRecord.State.RESUMED;
110 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ACTIVITY_STARTS;
111 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
112 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_ROOT_TASK;
113 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
114 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
115 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
116 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
117 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
118 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
119 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
120 import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
121 import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
122 import static com.android.server.wm.ActivityTaskSupervisor.DEFER_RESUME;
123 import static com.android.server.wm.ActivityTaskSupervisor.ON_TOP;
124 import static com.android.server.wm.ActivityTaskSupervisor.REMOVE_FROM_RECENTS;
125 import static com.android.server.wm.BackgroundActivityStartController.BalVerdict;
126 import static com.android.server.wm.LockTaskController.LOCK_TASK_AUTH_DONT_LOCK;
127 import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
128 import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
129 import static com.android.server.wm.RootWindowContainer.MATCH_ATTACHED_TASK_ONLY;
130 import static com.android.server.wm.RootWindowContainer.MATCH_ATTACHED_TASK_OR_RECENT_TASKS;
131 import static com.android.server.wm.Task.REPARENT_KEEP_ROOT_TASK_AT_FRONT;
132 import static com.android.server.wm.WindowManagerService.MY_PID;
133 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_NORMAL;
134 
135 import android.Manifest;
136 import android.annotation.IntDef;
137 import android.annotation.NonNull;
138 import android.annotation.Nullable;
139 import android.annotation.UserIdInt;
140 import android.app.ActivityManager;
141 import android.app.ActivityManagerInternal;
142 import android.app.ActivityOptions;
143 import android.app.ActivityTaskManager;
144 import android.app.ActivityTaskManager.RootTaskInfo;
145 import android.app.ActivityThread;
146 import android.app.AlertDialog;
147 import android.app.AnrController;
148 import android.app.AppGlobals;
149 import android.app.AppOpsManager;
150 import android.app.BackgroundStartPrivileges;
151 import android.app.Dialog;
152 import android.app.IActivityClientController;
153 import android.app.IActivityController;
154 import android.app.IActivityTaskManager;
155 import android.app.IAppTask;
156 import android.app.IApplicationThread;
157 import android.app.IAssistDataReceiver;
158 import android.app.INotificationManager;
159 import android.app.IScreenCaptureObserver;
160 import android.app.ITaskStackListener;
161 import android.app.Notification;
162 import android.app.NotificationManager;
163 import android.app.PendingIntent;
164 import android.app.PictureInPictureParams;
165 import android.app.PictureInPictureUiState;
166 import android.app.ProfilerInfo;
167 import android.app.WaitResult;
168 import android.app.admin.DevicePolicyCache;
169 import android.app.admin.DeviceStateCache;
170 import android.app.assist.ActivityId;
171 import android.app.assist.AssistContent;
172 import android.app.assist.AssistStructure;
173 import android.app.compat.CompatChanges;
174 import android.app.sdksandbox.sandboxactivity.SdkSandboxActivityAuthority;
175 import android.app.usage.UsageStatsManagerInternal;
176 import android.content.ActivityNotFoundException;
177 import android.content.ComponentName;
178 import android.content.ContentResolver;
179 import android.content.Context;
180 import android.content.DialogInterface;
181 import android.content.IIntentSender;
182 import android.content.Intent;
183 import android.content.LocusId;
184 import android.content.pm.ActivityInfo;
185 import android.content.pm.ApplicationInfo;
186 import android.content.pm.ConfigurationInfo;
187 import android.content.pm.FeatureInfo;
188 import android.content.pm.IPackageManager;
189 import android.content.pm.PackageManager;
190 import android.content.pm.PackageManagerInternal;
191 import android.content.pm.ParceledListSlice;
192 import android.content.pm.ResolveInfo;
193 import android.content.res.CompatibilityInfo;
194 import android.content.res.Configuration;
195 import android.content.res.Resources;
196 import android.database.ContentObserver;
197 import android.graphics.Bitmap;
198 import android.graphics.Point;
199 import android.graphics.Rect;
200 import android.net.Uri;
201 import android.os.Binder;
202 import android.os.Build;
203 import android.os.Bundle;
204 import android.os.FactoryTest;
205 import android.os.FileUtils;
206 import android.os.Handler;
207 import android.os.IBinder;
208 import android.os.IUserManager;
209 import android.os.LocaleList;
210 import android.os.Looper;
211 import android.os.Message;
212 import android.os.Parcel;
213 import android.os.PowerManager;
214 import android.os.PowerManagerInternal;
215 import android.os.Process;
216 import android.os.RemoteCallback;
217 import android.os.RemoteException;
218 import android.os.ServiceManager;
219 import android.os.StrictMode;
220 import android.os.SystemClock;
221 import android.os.SystemProperties;
222 import android.os.Trace;
223 import android.os.UpdateLock;
224 import android.os.UserHandle;
225 import android.os.UserManager;
226 import android.os.WorkSource;
227 import android.provider.Settings;
228 import android.service.dreams.DreamActivity;
229 import android.service.voice.IVoiceInteractionSession;
230 import android.service.voice.VoiceInteractionManagerInternal;
231 import android.sysprop.DisplayProperties;
232 import android.telecom.TelecomManager;
233 import android.text.format.TimeMigrationUtils;
234 import android.util.ArrayMap;
235 import android.util.ArraySet;
236 import android.util.IntArray;
237 import android.util.Log;
238 import android.util.Slog;
239 import android.util.SparseArray;
240 import android.util.TimeUtils;
241 import android.util.proto.ProtoOutputStream;
242 import android.view.Display;
243 import android.view.IRecentsAnimationRunner;
244 import android.view.RemoteAnimationAdapter;
245 import android.view.RemoteAnimationDefinition;
246 import android.view.WindowManager;
247 import android.window.BackAnimationAdapter;
248 import android.window.BackNavigationInfo;
249 import android.window.IWindowOrganizerController;
250 import android.window.SplashScreenView.SplashScreenViewParcelable;
251 import android.window.TaskSnapshot;
252 
253 import com.android.internal.R;
254 import com.android.internal.annotations.GuardedBy;
255 import com.android.internal.annotations.VisibleForTesting;
256 import com.android.internal.app.IVoiceInteractor;
257 import com.android.internal.app.ProcessMap;
258 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
259 import com.android.internal.notification.SystemNotificationChannels;
260 import com.android.internal.os.TransferPipe;
261 import com.android.internal.policy.AttributeCache;
262 import com.android.internal.policy.KeyguardDismissCallback;
263 import com.android.internal.protolog.common.ProtoLog;
264 import com.android.internal.util.ArrayUtils;
265 import com.android.internal.util.FastPrintWriter;
266 import com.android.internal.util.FrameworkStatsLog;
267 import com.android.internal.util.function.pooled.PooledLambda;
268 import com.android.server.LocalManagerRegistry;
269 import com.android.server.LocalServices;
270 import com.android.server.SystemConfig;
271 import com.android.server.SystemService;
272 import com.android.server.SystemServiceManager;
273 import com.android.server.UiThread;
274 import com.android.server.Watchdog;
275 import com.android.server.am.ActivityManagerService;
276 import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
277 import com.android.server.am.AppTimeTracker;
278 import com.android.server.am.AssistDataRequester;
279 import com.android.server.am.BaseErrorDialog;
280 import com.android.server.am.PendingIntentController;
281 import com.android.server.am.PendingIntentRecord;
282 import com.android.server.am.UserState;
283 import com.android.server.firewall.IntentFirewall;
284 import com.android.server.grammaticalinflection.GrammaticalInflectionManagerInternal;
285 import com.android.server.pm.UserManagerService;
286 import com.android.server.policy.PermissionPolicyInternal;
287 import com.android.server.sdksandbox.SdkSandboxManagerLocal;
288 import com.android.server.statusbar.StatusBarManagerInternal;
289 import com.android.server.uri.NeededUriGrants;
290 import com.android.server.uri.UriGrantsManagerInternal;
291 import com.android.server.wallpaper.WallpaperManagerInternal;
292 import com.android.wm.shell.Flags;
293 
294 import java.io.BufferedReader;
295 import java.io.File;
296 import java.io.FileDescriptor;
297 import java.io.FileOutputStream;
298 import java.io.FileReader;
299 import java.io.IOException;
300 import java.io.PrintWriter;
301 import java.io.StringWriter;
302 import java.lang.annotation.ElementType;
303 import java.lang.annotation.Retention;
304 import java.lang.annotation.RetentionPolicy;
305 import java.lang.annotation.Target;
306 import java.lang.ref.WeakReference;
307 import java.text.DateFormat;
308 import java.util.ArrayList;
309 import java.util.Arrays;
310 import java.util.Collection;
311 import java.util.Collections;
312 import java.util.Date;
313 import java.util.HashSet;
314 import java.util.List;
315 import java.util.Locale;
316 import java.util.Map;
317 import java.util.Objects;
318 import java.util.Set;
319 
320 /**
321  * System service for managing activities and their containers (task, displays,... ).
322  *
323  * {@hide}
324  */
325 public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
326     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
327     static final String TAG_ROOT_TASK = TAG + POSTFIX_ROOT_TASK;
328     static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
329 
330     // How long we wait until we timeout on key dispatching during instrumentation.
331     static final long INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MILLIS = 60 * 1000;
332     // How long we permit background activity starts after an activity in the process
333     // started or finished.
334     static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
335 
336     /**
337      * The duration to keep a process in animating state (top scheduling group) when the
338      * wakefulness is dozing (unlocking) or changing from awake to doze or sleep (locking).
339      */
340     private static final long DOZE_ANIMATING_STATE_RETAIN_TIME_MS = 2000;
341 
342     /** Used to indicate that an app transition should be animated. */
343     static final boolean ANIMATE = true;
344 
345     /** Hardware-reported OpenGLES version. */
346     final int GL_ES_VERSION;
347 
348     public static final String DUMP_ACTIVITIES_CMD = "activities";
349     public static final String DUMP_ACTIVITIES_SHORT_CMD = "a";
350     public static final String DUMP_LASTANR_CMD = "lastanr";
351     public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces";
352     public static final String DUMP_STARTER_CMD = "starter";
353     public static final String DUMP_CONTAINERS_CMD = "containers";
354     public static final String DUMP_RECENTS_CMD = "recents";
355     public static final String DUMP_RECENTS_SHORT_CMD = "r";
356     public static final String DUMP_TOP_RESUMED_ACTIVITY = "top-resumed";
357     public static final String DUMP_VISIBLE_ACTIVITIES = "visible";
358 
359     /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
360     public static final int RELAUNCH_REASON_NONE = 0;
361     /** This activity is being relaunched due to windowing mode change. */
362     public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
363     /** This activity is being relaunched due to a free-resize operation. */
364     public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
365 
366     Context mContext;
367 
368     /**
369      * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
370      * change at runtime. Use mContext for non-UI purposes.
371      */
372     private final Context mUiContext;
373     final ActivityThread mSystemThread;
374     H mH;
375     UiHandler mUiHandler;
376     ActivityManagerInternal mAmInternal;
377     UriGrantsManagerInternal mUgmInternal;
378     private PackageManagerInternal mPmInternal;
379     /** The cached sys ui service component name from package manager. */
380     private ComponentName mSysUiServiceComponent;
381     private PermissionPolicyInternal mPermissionPolicyInternal;
382     private StatusBarManagerInternal mStatusBarManagerInternal;
383     private WallpaperManagerInternal mWallpaperManagerInternal;
384     @VisibleForTesting
385     final ActivityTaskManagerInternal mInternal;
386     private PowerManagerInternal mPowerManagerInternal;
387     private UsageStatsManagerInternal mUsageStatsInternal;
388 
389     GrammaticalInflectionManagerInternal mGrammaticalManagerInternal;
390     PendingIntentController mPendingIntentController;
391     IntentFirewall mIntentFirewall;
392 
393     final VisibleActivityProcessTracker mVisibleActivityProcessTracker;
394 
395     /** The starting activities which are waiting for their processes to attach. */
396     final ArrayList<ActivityRecord> mStartingProcessActivities = new ArrayList<>();
397 
398     /* Global service lock used by the package the owns this service. */
399     final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
400     /**
401      * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
402      * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
403      * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
404      *
405      * @see WindowManagerThreadPriorityBooster
406      */
407     final Object mGlobalLockWithoutBoost = mGlobalLock;
408     ActivityTaskSupervisor mTaskSupervisor;
409     ActivityClientController mActivityClientController;
410     RootWindowContainer mRootWindowContainer;
411     WindowManagerService mWindowManager;
412     private UserManagerService mUserManager;
413     private AppOpsManager mAppOpsManager;
414     /** All active uids in the system. */
415     final MirrorActiveUids mActiveUids = new MirrorActiveUids();
416     /** All processes currently running that might have a window organized by name. */
417     final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
418     /** All processes we currently have running mapped by pid and uid */
419     final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
420     /** This is the process holding what we currently consider to be the "home" activity. */
421     volatile WindowProcessController mHomeProcess;
422     /** The currently running heavy-weight process, if any. */
423     volatile WindowProcessController mHeavyWeightProcess;
424     boolean mHasHeavyWeightFeature;
425     boolean mHasLeanbackFeature;
426     boolean mHasCompanionDeviceSetupFeature;
427     /** The process of the top most activity. */
428     volatile WindowProcessController mTopApp;
429     /** The process showing UI while the device is dozing. */
430     volatile WindowProcessController mVisibleDozeUiProcess;
431     /**
432      * This is the process holding the activity the user last visited that is in a different process
433      * from the one they are currently in.
434      */
435     volatile WindowProcessController mPreviousProcess;
436     /** The time at which the previous process was last visible. */
437     private long mPreviousProcessVisibleTime;
438 
439     /** It is set from keyguard-going-away to set-keyguard-shown. */
440     static final int DEMOTE_TOP_REASON_DURING_UNLOCKING = 1;
441     /** It is set if legacy recents animation is running. */
442     static final int DEMOTE_TOP_REASON_ANIMATING_RECENTS = 1 << 1;
443 
444     @Retention(RetentionPolicy.SOURCE)
445     @IntDef({
446             DEMOTE_TOP_REASON_DURING_UNLOCKING,
447             DEMOTE_TOP_REASON_ANIMATING_RECENTS,
448     })
449     @interface DemoteTopReason {}
450 
451     /**
452      * If non-zero, getTopProcessState() will
453      * return {@link ActivityManager#PROCESS_STATE_IMPORTANT_FOREGROUND} to avoid top app from
454      * preempting CPU while another process is running an important animation.
455      */
456     @DemoteTopReason
457     volatile int mDemoteTopAppReasons;
458 
459     /** List of intents that were used to start the most recent tasks. */
460     private RecentTasks mRecentTasks;
461     /** State of external calls telling us if the device is awake or asleep. */
462     private boolean mKeyguardShown = false;
463 
464     // VoiceInteraction session ID that changes for each new request except when
465     // being called for multi-window assist in a single session.
466     private int mViSessionId = 1000;
467 
468     // How long to wait in getAssistContextExtras for the activity and foreground services
469     // to respond with the result.
470     private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
471 
472     // How long top wait when going through the modern assist (which doesn't need to block
473     // on getting this result before starting to launch its UI).
474     private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
475 
476     // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
477     private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
478 
479     private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
480 
481     // Keeps track of the active voice interaction service component, notified from
482     // VoiceInteractionManagerService
483     ComponentName mActiveVoiceInteractionServiceComponent;
484 
485     // A map userId and all its companion app uids
486     private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
487 
488     VrController mVrController;
489     KeyguardController mKeyguardController;
490     private final ClientLifecycleManager mLifecycleManager;
491 
492     final BackNavigationController mBackNavigationController;
493 
494     private TaskChangeNotificationController mTaskChangeNotificationController;
495     /** The controller for all operations related to locktask. */
496     private LockTaskController mLockTaskController;
497     private ActivityStartController mActivityStartController;
498     private SparseArray<ActivityInterceptorCallback> mActivityInterceptorCallbacks =
499             new SparseArray<>();
500     PackageConfigPersister mPackageConfigPersister;
501 
502     boolean mSuppressResizeConfigChanges;
503 
504     final UpdateConfigurationResult mTmpUpdateConfigurationResult =
505             new UpdateConfigurationResult();
506 
507     // TODO(b/258618073): Remove this and make the related methods return whether config is changed.
508     static final class UpdateConfigurationResult {
509         // Configuration changes that were updated.
510         int changes;
511         // If the activity was relaunched to match the new configuration.
512         boolean activityRelaunched;
513         boolean mIsUpdating;
514     }
515 
516     /** Current sequencing integer of the configuration, for skipping old configurations. */
517     private int mConfigurationSeq;
518 
519     /** Current sequencing integer of the asset changes, for skipping old resources overlays. */
520     private int mGlobalAssetsSeq;
521 
522     // To cache the list of supported system locales
523     private String[] mSupportedSystemLocales = null;
524 
525     /**
526      * Temp object used when global and/or display override configuration is updated. It is also
527      * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
528      * anyone...
529      */
530     private Configuration mTempConfig = new Configuration();
531 
532     /**
533      * Whether normal application switches are allowed; a call to {@link #stopAppSwitches()
534      * disables this.
535      */
536     private volatile int mAppSwitchesState = APP_SWITCH_ALLOW;
537 
538     // The duration of resuming foreground app switch from disallow.
539     private static final long RESUME_FG_APP_SWITCH_MS = 500;
540 
541     /** App switch is not allowed. */
542     static final int APP_SWITCH_DISALLOW = 0;
543 
544     /** App switch is allowed only if the activity launch was requested by a foreground app. */
545     static final int APP_SWITCH_FG_ONLY = 1;
546 
547     /** App switch is allowed. */
548     static final int APP_SWITCH_ALLOW = 2;
549 
550     @IntDef({
551             APP_SWITCH_DISALLOW,
552             APP_SWITCH_FG_ONLY,
553             APP_SWITCH_ALLOW,
554     })
555     @Retention(RetentionPolicy.SOURCE)
556     @interface AppSwitchState {}
557 
558     /**
559      * Last stop app switches time, apps finished before this time cannot start background activity
560      * even if they are in grace period.
561      */
562     private volatile long mLastStopAppSwitchesTime;
563 
564     @GuardedBy("itself")
565     private final List<AnrController> mAnrController = new ArrayList<>();
566     IActivityController mController = null;
567     boolean mControllerIsAMonkey = false;
568 
569     final int mFactoryTest;
570 
571     /** Used to control how we initialize the service. */
572     ComponentName mTopComponent;
573     String mTopAction = Intent.ACTION_MAIN;
574     String mTopData;
575 
576     /** Profiling app information. */
577     String mProfileApp = null;
578     WindowProcessController mProfileProc = null;
579     ProfilerInfo mProfilerInfo = null;
580 
581     /**
582      * Dump of the activity state at the time of the last ANR. Cleared after
583      * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
584      */
585     String mLastANRState;
586 
587     /**
588      * Used to retain an update lock when the foreground activity is in
589      * immersive mode.
590      */
591     private final UpdateLock mUpdateLock = new UpdateLock("immersive");
592 
593     /**
594      * Packages that are being allowed to perform unrestricted app switches.  Mapping is
595      * User -> Type -> uid.
596      */
597     final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
598 
599     /** The dimensions of the thumbnails in the Recents UI. */
600     private int mThumbnailWidth;
601     private int mThumbnailHeight;
602 
603     /**
604      * Flag that indicates if multi-window is enabled.
605      *
606      * For any particular form of multi-window to be enabled, generic multi-window must be enabled
607      * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
608      * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
609      * At least one of the forms of multi-window must be enabled in order for this flag to be
610      * initialized to 'true'.
611      *
612      * @see #mSupportsSplitScreenMultiWindow
613      * @see #mSupportsFreeformWindowManagement
614      * @see #mSupportsPictureInPicture
615      * @see #mSupportsMultiDisplay
616      */
617     boolean mSupportsMultiWindow;
618     boolean mSupportsSplitScreenMultiWindow;
619     boolean mSupportsFreeformWindowManagement;
620     boolean mSupportsPictureInPicture;
621     boolean mSupportsExpandedPictureInPicture;
622     boolean mSupportsMultiDisplay;
623     boolean mForceResizableActivities;
624 
625     /** Development option to enable non resizable in multi window. */
626     // TODO(b/176061101) change the default value to false.
627     boolean mDevEnableNonResizableMultiWindow;
628 
629     /**
630      * Whether the device supports non-resizable in multi windowing modes.
631      * -1: The device doesn't support non-resizable in multi windowing modes.
632      *  0: The device supports non-resizable in multi windowing modes only if this is a large
633      *     screen (smallest width >= {@link WindowManager#LARGE_SCREEN_SMALLEST_SCREEN_WIDTH_DP}).
634      *  1: The device always supports non-resizable in multi windowing modes.
635      */
636     int mSupportsNonResizableMultiWindow;
637 
638     /**
639      * Whether the device checks activity min width/height to determine if it can be shown in multi
640      * windowing modes.
641      * -1: The device ignores activity min width/height when determining if it can be shown in multi
642      *     windowing modes.
643      *  0: If it is a small screen (smallest width <
644      *     {@link WindowManager#LARGE_SCREEN_SMALLEST_SCREEN_WIDTH_DP}),
645      *     the device compares the activity min width/height with the min multi windowing modes
646      *     dimensions {@link #mMinPercentageMultiWindowSupportHeight} the device supports to
647      *     determine whether the activity can be shown in multi windowing modes
648      *  1: The device always compare the activity min width/height with the min multi windowing
649      *     modes dimensions {@link #mMinPercentageMultiWindowSupportHeight} the device supports to
650      *     determine whether it can be shown in multi windowing modes.
651      */
652     int mRespectsActivityMinWidthHeightMultiWindow;
653 
654     /**
655      * This value is only used when the device checks activity min height to determine if it
656      * can be shown in multi windowing modes.
657      * If the activity min height is greater than this percentage of the display height in portrait,
658      * it will not be allowed to be shown in multi windowing modes.
659      * The value should be between [0 - 1].
660      */
661     float mMinPercentageMultiWindowSupportHeight;
662 
663     /**
664      * This value is only used when the device checks activity min width to determine if it
665      * can be shown in multi windowing modes.
666      * If the activity min width is greater than this percentage of the display width in landscape,
667      * it will not be allowed to be shown in multi windowing modes.
668      * The value should be between [0 - 1].
669      */
670     float mMinPercentageMultiWindowSupportWidth;
671 
672     final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers =
673             Collections.synchronizedList(new ArrayList<>());
674 
675     // VR Vr2d Display Id.
676     int mVr2dDisplayId = INVALID_DISPLAY;
677 
678     /**
679      * Set while we are wanting to sleep, to prevent any
680      * activities from being started/resumed.
681      *
682      * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
683      *
684      * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
685      * while in the sleep state until there is a pending transition out of sleep, in which case
686      * mSleeping is set to false, and remains false while awake.
687      *
688      * Whether mSleeping can quickly toggled between true/false without the device actually
689      * display changing states is undefined.
690      */
691     private volatile boolean mSleeping;
692 
693     /**
694      * The mActiveDreamComponent state is set by the {@link DreamManagerService} when it receives a
695      * request to start/stop the dream. It is set to the active dream shortly before the
696      * {@link DreamService} is started. It is set to null after the {@link DreamService} is stopped.
697      */
698     @Nullable
699     private volatile ComponentName mActiveDreamComponent;
700 
701     /**
702      * The process state used for processes that are running the top activities.
703      * This changes between TOP and TOP_SLEEPING to following mSleeping.
704      */
705     volatile int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
706 
707     /** Whether to keep higher priority to launch app while device is sleeping. */
708     private volatile boolean mRetainPowerModeAndTopProcessState;
709 
710     /** The timeout to restore power mode if {@link #mRetainPowerModeAndTopProcessState} is set. */
711     private static final long POWER_MODE_UNKNOWN_VISIBILITY_TIMEOUT_MS = 1000;
712 
713     @Retention(RetentionPolicy.SOURCE)
714     @IntDef({
715             POWER_MODE_REASON_START_ACTIVITY,
716             POWER_MODE_REASON_CHANGE_DISPLAY,
717             POWER_MODE_REASON_UNKNOWN_VISIBILITY,
718             POWER_MODE_REASON_ALL,
719     })
720     @interface PowerModeReason {}
721 
722     static final int POWER_MODE_REASON_START_ACTIVITY = 1 << 0;
723     static final int POWER_MODE_REASON_CHANGE_DISPLAY = 1 << 1;
724     /** @see UnknownAppVisibilityController */
725     static final int POWER_MODE_REASON_UNKNOWN_VISIBILITY = 1 << 2;
726     /**
727      * This can only be used by {@link #endPowerMode(int)}. Excluding UNKNOWN_VISIBILITY because
728      * that is guarded by a timeout while keyguard is locked.
729      */
730     static final int POWER_MODE_REASON_ALL = (1 << 2) - 1;
731 
732     /** The reasons to apply power modes. */
733     @PowerModeReason
734     private int mPowerModeReasons;
735 
736     @Retention(RetentionPolicy.SOURCE)
737     @IntDef({
738             LAYOUT_REASON_CONFIG_CHANGED,
739             LAYOUT_REASON_VISIBILITY_CHANGED,
740     })
741     @interface LayoutReason {
742     }
743 
744     static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
745     static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
746 
747     /** The reasons to perform surface placement. */
748     @LayoutReason
749     private int mLayoutReasons;
750 
751     // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
752     // automatically. Important for devices without direct input devices.
753     private boolean mShowDialogs = true;
754 
755     /** Set if we are shutting down the system, similar to sleeping. */
756     volatile boolean mShuttingDown;
757 
758     /**
759      * We want to hold a wake lock while running a voice interaction session, since
760      * this may happen with the screen off and we need to keep the CPU running to
761      * be able to continue to interact with the user.
762      */
763     PowerManager.WakeLock mVoiceWakeLock;
764 
765     /**
766      * Set while we are running a voice interaction. This overrides sleeping while it is active.
767      */
768     IVoiceInteractionSession mRunningVoice;
769 
770     /**
771      * The last resumed activity. This is identical to the current resumed activity most
772      * of the time but could be different when we're pausing one activity before we resume
773      * another activity.
774      */
775     ActivityRecord mLastResumedActivity;
776 
777     /**
778      * The activity that is currently being traced as the active resumed activity.
779      *
780      * @see #updateResumedAppTrace
781      */
782     @Nullable
783     private ActivityRecord mTracedResumedActivity;
784 
785     /** If non-null, we are tracking the time the user spends in the currently focused app. */
786     AppTimeTracker mCurAppTimeTracker;
787 
788     AppWarnings mAppWarnings;
789 
790     /**
791      * Packages that the user has asked to have run in screen size
792      * compatibility mode instead of filling the screen.
793      */
794     CompatModePackages mCompatModePackages;
795 
796     private SettingObserver mSettingsObserver;
797 
798     WindowOrganizerController mWindowOrganizerController;
799     TaskOrganizerController mTaskOrganizerController;
800     TaskFragmentOrganizerController mTaskFragmentOrganizerController;
801 
802     @Nullable
803     private BackgroundActivityStartCallback mBackgroundActivityStartCallback;
804 
805     private int[] mAccessibilityServiceUids = new int[0];
806 
807     private int mDeviceOwnerUid = Process.INVALID_UID;
808 
809     private Set<Integer> mProfileOwnerUids = new ArraySet<Integer>();
810 
811     private final class SettingObserver extends ContentObserver {
812         private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
813         private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
814         private final Uri mFontWeightAdjustmentUri = Settings.Secure.getUriFor(
815                 Settings.Secure.FONT_WEIGHT_ADJUSTMENT);
816 
SettingObserver()817         SettingObserver() {
818             super(mH);
819             final ContentResolver resolver = mContext.getContentResolver();
820             resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
821             resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
822                     UserHandle.USER_ALL);
823             resolver.registerContentObserver(
824                     mFontWeightAdjustmentUri, false, this, UserHandle.USER_ALL);
825         }
826 
827         @Override
onChange(boolean selfChange, Collection<Uri> uris, int flags, @UserIdInt int userId)828         public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
829                 @UserIdInt int userId) {
830             for (Uri uri : uris) {
831                 if (mFontScaleUri.equals(uri)) {
832                     updateFontScaleIfNeeded(userId);
833                 } else if (mHideErrorDialogsUri.equals(uri)) {
834                     synchronized (mGlobalLock) {
835                         updateShouldShowDialogsLocked(getGlobalConfiguration());
836                     }
837                 } else if (mFontWeightAdjustmentUri.equals(uri)) {
838                     updateFontWeightAdjustmentIfNeeded(userId);
839                 }
840             }
841         }
842     }
843 
844     /** Indicates that the method may be invoked frequently or is sensitive to performance. */
845     @Target(ElementType.METHOD)
846     @Retention(RetentionPolicy.SOURCE)
847     @interface HotPath {
848         int NONE = 0;
849         int OOM_ADJUSTMENT = 1;
850         int LRU_UPDATE = 2;
851         int PROCESS_CHANGE = 3;
852         int START_SERVICE = 4;
853 
caller()854         int caller() default NONE;
855     }
856 
857     private final Runnable mUpdateOomAdjRunnable = new Runnable() {
858         @Override
859         public void run() {
860             mAmInternal.updateOomAdj(ActivityManagerInternal.OOM_ADJ_REASON_ACTIVITY);
861         }
862     };
863 
864     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
ActivityTaskManagerService(Context context)865     public ActivityTaskManagerService(Context context) {
866         mContext = context;
867         mFactoryTest = FactoryTest.getMode();
868         mSystemThread = ActivityThread.currentActivityThread();
869         mUiContext = mSystemThread.getSystemUiContext();
870         mLifecycleManager = new ClientLifecycleManager();
871         mVisibleActivityProcessTracker = new VisibleActivityProcessTracker(this);
872         mInternal = new LocalService();
873         GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
874         mWindowOrganizerController = new WindowOrganizerController(this);
875         mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
876         mTaskFragmentOrganizerController =
877                 mWindowOrganizerController.mTaskFragmentOrganizerController;
878         mBackNavigationController = new BackNavigationController();
879     }
880 
onSystemReady()881     public void onSystemReady() {
882         synchronized (mGlobalLock) {
883             final PackageManager pm = mContext.getPackageManager();
884             mHasHeavyWeightFeature = pm.hasSystemFeature(FEATURE_CANT_SAVE_STATE);
885             mHasLeanbackFeature = pm.hasSystemFeature(FEATURE_LEANBACK);
886             mHasCompanionDeviceSetupFeature = pm.hasSystemFeature(FEATURE_COMPANION_DEVICE_SETUP);
887             mVrController.onSystemReady();
888             mRecentTasks.onSystemReadyLocked();
889             mTaskSupervisor.onSystemReady();
890             mActivityClientController.onSystemReady();
891             mAppWarnings.onSystemReady();
892             // TODO(b/258792202) Cleanup once ASM is ready to launch
893             ActivitySecurityModelFeatureFlags.initialize(mContext.getMainExecutor());
894             mGrammaticalManagerInternal = LocalServices.getService(
895                     GrammaticalInflectionManagerInternal.class);
896         }
897     }
898 
onInitPowerManagement()899     public void onInitPowerManagement() {
900         synchronized (mGlobalLock) {
901             mTaskSupervisor.initPowerManagement();
902             final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
903             mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
904             mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
905             mVoiceWakeLock.setReferenceCounted(false);
906         }
907     }
908 
installSystemProviders()909     public void installSystemProviders() {
910         mSettingsObserver = new SettingObserver();
911     }
912 
retrieveSettings(ContentResolver resolver)913     public void retrieveSettings(ContentResolver resolver) {
914         final boolean freeformWindowManagement =
915                 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
916                         || Settings.Global.getInt(
917                         resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
918 
919         final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
920         final boolean supportsPictureInPicture = supportsMultiWindow &&
921                 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
922         final boolean supportsExpandedPictureInPicture =
923                 supportsPictureInPicture && mContext.getPackageManager().hasSystemFeature(
924                         FEATURE_EXPANDED_PICTURE_IN_PICTURE);
925         final boolean supportsSplitScreenMultiWindow =
926                 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
927         final boolean supportsMultiDisplay = mContext.getPackageManager()
928                 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
929         final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
930         final boolean forceResizable = Settings.Global.getInt(
931                 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
932         final boolean devEnableNonResizableMultiWindow = Settings.Global.getInt(
933                 resolver, DEVELOPMENT_ENABLE_NON_RESIZABLE_MULTI_WINDOW, 0) != 0;
934         final int supportsNonResizableMultiWindow = mContext.getResources().getInteger(
935                 com.android.internal.R.integer.config_supportsNonResizableMultiWindow);
936         final int respectsActivityMinWidthHeightMultiWindow = mContext.getResources().getInteger(
937                 com.android.internal.R.integer.config_respectsActivityMinWidthHeightMultiWindow);
938         final float minPercentageMultiWindowSupportHeight = mContext.getResources().getFloat(
939                 com.android.internal.R.dimen.config_minPercentageMultiWindowSupportHeight);
940         final float minPercentageMultiWindowSupportWidth = mContext.getResources().getFloat(
941                 com.android.internal.R.dimen.config_minPercentageMultiWindowSupportWidth);
942 
943         // Transfer any global setting for forcing RTL layout, into a System Property
944         DisplayProperties.debug_force_rtl(forceRtl);
945 
946         final Configuration configuration = new Configuration();
947         Settings.System.getConfiguration(resolver, configuration);
948         if (forceRtl) {
949             // This will take care of setting the correct layout direction flags
950             configuration.setLayoutDirection(configuration.locale);
951         }
952 
953         configuration.setGrammaticalGender(
954                 mGrammaticalManagerInternal.mergedFinalSystemGrammaticalGender());
955 
956         synchronized (mGlobalLock) {
957             mForceResizableActivities = forceResizable;
958             mDevEnableNonResizableMultiWindow = devEnableNonResizableMultiWindow;
959             mSupportsNonResizableMultiWindow = supportsNonResizableMultiWindow;
960             mRespectsActivityMinWidthHeightMultiWindow = respectsActivityMinWidthHeightMultiWindow;
961             mMinPercentageMultiWindowSupportHeight = minPercentageMultiWindowSupportHeight;
962             mMinPercentageMultiWindowSupportWidth = minPercentageMultiWindowSupportWidth;
963             final boolean multiWindowFormEnabled = freeformWindowManagement
964                     || supportsSplitScreenMultiWindow
965                     || supportsPictureInPicture
966                     || supportsMultiDisplay;
967             if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
968                 mSupportsMultiWindow = true;
969                 mSupportsFreeformWindowManagement = freeformWindowManagement;
970                 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
971                 mSupportsPictureInPicture = supportsPictureInPicture;
972                 mSupportsExpandedPictureInPicture = supportsExpandedPictureInPicture;
973                 mSupportsMultiDisplay = supportsMultiDisplay;
974             } else {
975                 mSupportsMultiWindow = false;
976                 mSupportsFreeformWindowManagement = false;
977                 mSupportsSplitScreenMultiWindow = false;
978                 mSupportsPictureInPicture = false;
979                 mSupportsExpandedPictureInPicture = false;
980                 mSupportsMultiDisplay = false;
981             }
982             mWindowManager.mRoot.onSettingsRetrieved();
983             // This happens before any activities are started, so we can change global configuration
984             // in-place.
985             updateConfigurationLocked(configuration, null, true);
986             final Configuration globalConfig = getGlobalConfiguration();
987             ProtoLog.v(WM_DEBUG_CONFIGURATION, "Initial config: %s", globalConfig);
988 
989             // Load resources only after the current configuration has been set.
990             final Resources res = mContext.getResources();
991             mThumbnailWidth = res.getDimensionPixelSize(
992                     com.android.internal.R.dimen.thumbnail_width);
993             mThumbnailHeight = res.getDimensionPixelSize(
994                     com.android.internal.R.dimen.thumbnail_height);
995         }
996     }
997 
getGlobalLock()998     public WindowManagerGlobalLock getGlobalLock() {
999         return mGlobalLock;
1000     }
1001 
1002     /** For test purpose only. */
1003     @VisibleForTesting
getAtmInternal()1004     public ActivityTaskManagerInternal getAtmInternal() {
1005         return mInternal;
1006     }
1007 
initialize(IntentFirewall intentFirewall, PendingIntentController intentController, Looper looper)1008     public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
1009             Looper looper) {
1010         mH = new H(looper);
1011         mUiHandler = new UiHandler();
1012         mIntentFirewall = intentFirewall;
1013         final File systemDir = SystemServiceManager.ensureSystemDir();
1014         mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
1015         mCompatModePackages = new CompatModePackages(this, systemDir, mH);
1016         mPendingIntentController = intentController;
1017         mTaskSupervisor = createTaskSupervisor();
1018         mActivityClientController = new ActivityClientController(this);
1019 
1020         mTaskChangeNotificationController =
1021                 new TaskChangeNotificationController(mTaskSupervisor, mH);
1022         mLockTaskController = new LockTaskController(mContext, mTaskSupervisor, mH,
1023                 mTaskChangeNotificationController);
1024         mActivityStartController = new ActivityStartController(this);
1025         setRecentTasks(new RecentTasks(this, mTaskSupervisor));
1026         mVrController = new VrController(mGlobalLock);
1027         mKeyguardController = mTaskSupervisor.getKeyguardController();
1028         mPackageConfigPersister = new PackageConfigPersister(mTaskSupervisor.mPersisterQueue, this);
1029     }
1030 
onActivityManagerInternalAdded()1031     public void onActivityManagerInternalAdded() {
1032         synchronized (mGlobalLock) {
1033             mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
1034             mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
1035         }
1036     }
1037 
increaseConfigurationSeqLocked()1038     int increaseConfigurationSeqLocked() {
1039         mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
1040         return mConfigurationSeq;
1041     }
1042 
createTaskSupervisor()1043     protected ActivityTaskSupervisor createTaskSupervisor() {
1044         final ActivityTaskSupervisor supervisor = new ActivityTaskSupervisor(this,
1045                 mH.getLooper());
1046         supervisor.initialize();
1047         return supervisor;
1048     }
1049 
createAppWarnings( Context uiContext, Handler handler, Handler uiHandler, File systemDir)1050     protected AppWarnings createAppWarnings(
1051             Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
1052         return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
1053     }
1054 
setWindowManager(WindowManagerService wm)1055     public void setWindowManager(WindowManagerService wm) {
1056         synchronized (mGlobalLock) {
1057             mWindowManager = wm;
1058             mRootWindowContainer = wm.mRoot;
1059             mWindowOrganizerController.mTransitionController.setWindowManager(wm);
1060             mLifecycleManager.setWindowManager(wm);
1061             mTempConfig.setToDefaults();
1062             mTempConfig.setLocales(LocaleList.getDefault());
1063             mConfigurationSeq = mTempConfig.seq = 1;
1064             mRootWindowContainer.onConfigurationChanged(mTempConfig);
1065             mLockTaskController.setWindowManager(wm);
1066             mTaskSupervisor.setWindowManager(wm);
1067             mRootWindowContainer.setWindowManager(wm);
1068             mBackNavigationController.setWindowManager(wm);
1069         }
1070     }
1071 
setUsageStatsManager(UsageStatsManagerInternal usageStatsManager)1072     public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
1073         synchronized (mGlobalLock) {
1074             mUsageStatsInternal = usageStatsManager;
1075         }
1076     }
1077 
getUiContext()1078     Context getUiContext() {
1079         return mUiContext;
1080     }
1081 
getUserManager()1082     UserManagerService getUserManager() {
1083         if (mUserManager == null) {
1084             IBinder b = ServiceManager.getService(Context.USER_SERVICE);
1085             mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
1086         }
1087         return mUserManager;
1088     }
1089 
getAppOpsManager()1090     AppOpsManager getAppOpsManager() {
1091         if (mAppOpsManager == null) {
1092             mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
1093         }
1094         return mAppOpsManager;
1095     }
1096 
hasUserRestriction(String restriction, int userId)1097     boolean hasUserRestriction(String restriction, int userId) {
1098         return getUserManager().hasUserRestriction(restriction, userId);
1099     }
1100 
hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage)1101     boolean hasSystemAlertWindowPermission(int callingUid, int callingPid,
1102             String callingPackage) {
1103         final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
1104                 callingUid, callingPackage, /* featureId */ null, "");
1105         if (mode == AppOpsManager.MODE_DEFAULT) {
1106             return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
1107                     == PERMISSION_GRANTED;
1108         }
1109         return mode == AppOpsManager.MODE_ALLOWED;
1110     }
1111 
1112     @VisibleForTesting
setRecentTasks(RecentTasks recentTasks)1113     protected void setRecentTasks(RecentTasks recentTasks) {
1114         mRecentTasks = recentTasks;
1115         mTaskSupervisor.setRecentTasks(recentTasks);
1116     }
1117 
getRecentTasks()1118     RecentTasks getRecentTasks() {
1119         return mRecentTasks;
1120     }
1121 
getLifecycleManager()1122     ClientLifecycleManager getLifecycleManager() {
1123         return mLifecycleManager;
1124     }
1125 
getActivityStartController()1126     ActivityStartController getActivityStartController() {
1127         return mActivityStartController;
1128     }
1129 
getTaskChangeNotificationController()1130     TaskChangeNotificationController getTaskChangeNotificationController() {
1131         return mTaskChangeNotificationController;
1132     }
1133 
getLockTaskController()1134     LockTaskController getLockTaskController() {
1135         return mLockTaskController;
1136     }
1137 
getTransitionController()1138     TransitionController getTransitionController() {
1139         return mWindowOrganizerController.getTransitionController();
1140     }
1141 
1142     /**
1143      * Return the global configuration used by the process corresponding to the input pid. This is
1144      * usually the global configuration with some overrides specific to that process.
1145      */
getGlobalConfigurationForCallingPid()1146     private Configuration getGlobalConfigurationForCallingPid() {
1147         final int pid = Binder.getCallingPid();
1148         if (pid == MY_PID || pid < 0) {
1149             return getGlobalConfiguration();
1150         }
1151         final WindowProcessController app = mProcessMap.getProcess(pid);
1152         return app != null ? app.getConfiguration() : getGlobalConfiguration();
1153     }
1154 
1155     /**
1156      * Return the device configuration info used by the process corresponding to the input pid.
1157      * The value is consistent with the global configuration for the process.
1158      */
1159     @Override
getDeviceConfigurationInfo()1160     public ConfigurationInfo getDeviceConfigurationInfo() {
1161         ConfigurationInfo config = new ConfigurationInfo();
1162         synchronized (mGlobalLock) {
1163             final Configuration globalConfig = getGlobalConfigurationForCallingPid();
1164             config.reqTouchScreen = globalConfig.touchscreen;
1165             config.reqKeyboardType = globalConfig.keyboard;
1166             config.reqNavigation = globalConfig.navigation;
1167             if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
1168                     || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
1169                 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
1170             }
1171             if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
1172                     && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
1173                 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
1174             }
1175             config.reqGlEsVersion = GL_ES_VERSION;
1176         }
1177         return config;
1178     }
1179 
1180     @Nullable
getBackgroundActivityStartCallback()1181     public BackgroundActivityStartCallback getBackgroundActivityStartCallback() {
1182         return mBackgroundActivityStartCallback;
1183     }
1184 
getActivityInterceptorCallbacks()1185     SparseArray<ActivityInterceptorCallback> getActivityInterceptorCallbacks() {
1186         return mActivityInterceptorCallbacks;
1187     }
1188 
start()1189     private void start() {
1190         LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
1191     }
1192 
1193     public static final class Lifecycle extends SystemService {
1194         private final ActivityTaskManagerService mService;
1195 
Lifecycle(Context context)1196         public Lifecycle(Context context) {
1197             super(context);
1198             mService = new ActivityTaskManagerService(context);
1199         }
1200 
1201         @Override
onStart()1202         public void onStart() {
1203             publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
1204             mService.start();
1205         }
1206 
1207         @Override
onUserUnlocked(@onNull TargetUser user)1208         public void onUserUnlocked(@NonNull TargetUser user) {
1209             synchronized (mService.getGlobalLock()) {
1210                 mService.mTaskSupervisor.onUserUnlocked(user.getUserIdentifier());
1211             }
1212         }
1213 
1214         @Override
onUserStopped(@onNull TargetUser user)1215         public void onUserStopped(@NonNull TargetUser user) {
1216             synchronized (mService.getGlobalLock()) {
1217                 mService.mTaskSupervisor.mLaunchParamsPersister
1218                         .onCleanupUser(user.getUserIdentifier());
1219             }
1220         }
1221 
getService()1222         public ActivityTaskManagerService getService() {
1223             return mService;
1224         }
1225     }
1226 
1227     @Override
startActivity(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)1228     public final int startActivity(IApplicationThread caller, String callingPackage,
1229             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1230             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1231             Bundle bOptions) {
1232         return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1233                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
1234                 UserHandle.getCallingUserId());
1235     }
1236 
1237     @Override
startActivities(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions, int userId)1238     public final int startActivities(IApplicationThread caller, String callingPackage,
1239             String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1240             Bundle bOptions, int userId) {
1241         assertPackageMatchesCallingUid(callingPackage);
1242         final String reason = "startActivities";
1243         enforceNotIsolatedCaller(reason);
1244         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
1245         // TODO: Switch to user app stacks here.
1246         return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1247                 callingFeatureId, intents, resolvedTypes, resultTo,
1248                 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1249                 null /* originatingPendingIntent */, BackgroundStartPrivileges.NONE);
1250     }
1251 
1252     @Override
startActivityAsUser(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)1253     public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1254             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1255             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1256             Bundle bOptions, int userId) {
1257         return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1258                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1259                 true /*validateIncomingUser*/);
1260     }
1261 
isSdkSandboxActivityIntent(Context context, Intent intent)1262     static boolean isSdkSandboxActivityIntent(Context context, Intent intent) {
1263         return intent != null
1264                 && (sandboxActivitySdkBasedContext()
1265                         ? SdkSandboxActivityAuthority.isSdkSandboxActivityIntent(context, intent)
1266                         : intent.isSandboxActivity(context));
1267     }
1268 
startActivityAsUser(IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser)1269     private int startActivityAsUser(IApplicationThread caller, String callingPackage,
1270             @Nullable String callingFeatureId, Intent intent, String resolvedType,
1271             IBinder resultTo, String resultWho, int requestCode, int startFlags,
1272             ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
1273         final SafeActivityOptions opts = SafeActivityOptions.fromBundle(bOptions);
1274 
1275         assertPackageMatchesCallingUid(callingPackage);
1276         enforceNotIsolatedCaller("startActivityAsUser");
1277 
1278         if (isSdkSandboxActivityIntent(mContext, intent)) {
1279             SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager(
1280                     SdkSandboxManagerLocal.class);
1281             sdkSandboxManagerLocal.enforceAllowedToHostSandboxedActivity(
1282                     intent, Binder.getCallingUid(), callingPackage
1283             );
1284         }
1285 
1286         if (Process.isSdkSandboxUid(Binder.getCallingUid())) {
1287             SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager(
1288                     SdkSandboxManagerLocal.class);
1289             if (sdkSandboxManagerLocal == null) {
1290                 throw new IllegalStateException("SdkSandboxManagerLocal not found when starting"
1291                         + " an activity from an SDK sandbox uid.");
1292             }
1293             sdkSandboxManagerLocal.enforceAllowedToStartActivity(intent);
1294         }
1295 
1296         userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
1297                 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1298 
1299         // TODO: Switch to user app stacks here.
1300         return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
1301                 .setCaller(caller)
1302                 .setCallingPackage(callingPackage)
1303                 .setCallingFeatureId(callingFeatureId)
1304                 .setResolvedType(resolvedType)
1305                 .setResultTo(resultTo)
1306                 .setResultWho(resultWho)
1307                 .setRequestCode(requestCode)
1308                 .setStartFlags(startFlags)
1309                 .setProfilerInfo(profilerInfo)
1310                 .setActivityOptions(opts)
1311                 .setUserId(userId)
1312                 .execute();
1313     }
1314 
1315     @Override
startActivityIntentSender(IApplicationThread caller, IIntentSender target, IBinder allowlistToken, Intent fillInIntent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions)1316     public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1317             IBinder allowlistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
1318             String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1319         enforceNotIsolatedCaller("startActivityIntentSender");
1320         if (fillInIntent != null) {
1321             // Refuse possible leaked file descriptors
1322             if (fillInIntent.hasFileDescriptors()) {
1323                 throw new IllegalArgumentException("File descriptors passed in Intent");
1324             }
1325             // Remove existing mismatch flag so it can be properly updated later
1326             fillInIntent.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH);
1327         }
1328 
1329         if (!(target instanceof PendingIntentRecord)) {
1330             throw new IllegalArgumentException("Bad PendingIntent object");
1331         }
1332 
1333         PendingIntentRecord pir = (PendingIntentRecord) target;
1334 
1335         synchronized (mGlobalLock) {
1336             // If this is coming from the currently resumed activity, it is
1337             // effectively saying that app switches are allowed at this point.
1338             final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
1339             if (topFocusedRootTask != null && topFocusedRootTask.getTopResumedActivity() != null
1340                     && topFocusedRootTask.getTopResumedActivity().info.applicationInfo.uid
1341                     == Binder.getCallingUid()) {
1342                 mAppSwitchesState = APP_SWITCH_ALLOW;
1343             }
1344         }
1345         return pir.sendInner(caller, 0, fillInIntent, resolvedType, allowlistToken, null, null,
1346                 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
1347     }
1348 
1349     @Override
startNextMatchingActivity(IBinder callingActivity, Intent intent, Bundle bOptions)1350     public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1351             Bundle bOptions) {
1352         // Refuse possible leaked file descriptors
1353         if (intent != null && intent.hasFileDescriptors()) {
1354             throw new IllegalArgumentException("File descriptors passed in Intent");
1355         }
1356         SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1357 
1358         synchronized (mGlobalLock) {
1359             final ActivityRecord r = ActivityRecord.isInRootTaskLocked(callingActivity);
1360             if (r == null) {
1361                 SafeActivityOptions.abort(options);
1362                 return false;
1363             }
1364             if (!r.attachedToProcess()) {
1365                 // The caller is not running...  d'oh!
1366                 SafeActivityOptions.abort(options);
1367                 return false;
1368             }
1369             intent = new Intent(intent);
1370             // Remove existing mismatch flag so it can be properly updated later
1371             intent.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH);
1372             // The caller is not allowed to change the data.
1373             intent.setDataAndType(r.intent.getData(), r.intent.getType());
1374             // And we are resetting to find the next component...
1375             intent.setComponent(null);
1376 
1377             final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1378 
1379             final int userId = UserHandle.getCallingUserId();
1380             ActivityInfo aInfo = null;
1381             try {
1382                 List<ResolveInfo> resolves =
1383                         AppGlobals.getPackageManager().queryIntentActivities(
1384                                 intent, r.resolvedType,
1385                                 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1386                                 userId).getList();
1387 
1388                 // Look for the original activity in the list...
1389                 final int N = resolves != null ? resolves.size() : 0;
1390                 for (int i = 0; i < N; i++) {
1391                     ResolveInfo rInfo = resolves.get(i);
1392                     if (rInfo.activityInfo.packageName.equals(r.packageName)
1393                             && rInfo.activityInfo.name.equals(r.info.name)) {
1394                         // We found the current one...  the next matching is
1395                         // after it.
1396                         i++;
1397                         if (i < N) {
1398                             aInfo = resolves.get(i).activityInfo;
1399                         }
1400                         if (debug) {
1401                             Slog.v(TAG, "Next matching activity: found current " + r.packageName
1402                                     + "/" + r.info.name);
1403                             Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1404                                     ? "null" : aInfo.packageName + "/" + aInfo.name));
1405                         }
1406                         break;
1407                     }
1408                 }
1409             } catch (RemoteException e) {
1410             }
1411 
1412             if (aInfo == null) {
1413                 // Nobody who is next!
1414                 SafeActivityOptions.abort(options);
1415                 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1416                 return false;
1417             }
1418 
1419             intent.setComponent(new ComponentName(
1420                     aInfo.applicationInfo.packageName, aInfo.name));
1421             intent.setFlags(intent.getFlags() & ~(Intent.FLAG_ACTIVITY_FORWARD_RESULT
1422                     | Intent.FLAG_ACTIVITY_CLEAR_TOP
1423                     | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
1424                     | FLAG_ACTIVITY_NEW_TASK));
1425 
1426             // Okay now we need to start the new activity, replacing the currently running activity.
1427             // This is a little tricky because we want to start the new one as if the current one is
1428             // finished, but not finish the current one first so that there is no flicker.
1429             // And thus...
1430             final boolean wasFinishing = r.finishing;
1431             r.finishing = true;
1432 
1433             // Propagate reply information over to the new activity.
1434             final ActivityRecord resultTo = r.resultTo;
1435             final String resultWho = r.resultWho;
1436             final int requestCode = r.requestCode;
1437             r.resultTo = null;
1438             if (resultTo != null) {
1439                 resultTo.removeResultsLocked(r, resultWho, requestCode);
1440             }
1441 
1442             final int origCallingUid = Binder.getCallingUid();
1443             final int origCallingPid = Binder.getCallingPid();
1444             final long origId = Binder.clearCallingIdentity();
1445             // TODO(b/64750076): Check if calling pid should really be -1.
1446             try {
1447                 if (options == null) {
1448                     options = new SafeActivityOptions(ActivityOptions.makeBasic());
1449                 }
1450 
1451                 // Fixes b/230492947 b/337726734
1452                 // Prevents background activity launch through #startNextMatchingActivity
1453                 // launchedFromUid of the calling activity represents the app that launches it.
1454                 // It may have BAL privileges (i.e. the Launcher App). Using its identity to
1455                 // launch to launch next matching activity causes BAL.
1456                 // Change the realCallingUid to the calling activity's uid.
1457                 // In ActivityStarter, when caller is set, the callingUid and callingPid are
1458                 // ignored. So now both callingUid and realCallingUid is set to the caller app.
1459                 final int res = getActivityStartController()
1460                         .obtainStarter(intent, "startNextMatchingActivity")
1461                         .setCaller(r.app.getThread())
1462                         .setResolvedType(r.resolvedType)
1463                         .setActivityInfo(aInfo)
1464                         .setResultTo(resultTo != null ? resultTo.token : null)
1465                         .setResultWho(resultWho)
1466                         .setRequestCode(requestCode)
1467                         .setCallingPid(-1)
1468                         .setCallingUid(r.launchedFromUid)
1469                         .setCallingPackage(r.launchedFromPackage)
1470                         .setCallingFeatureId(r.launchedFromFeatureId)
1471                         .setRealCallingPid(origCallingPid)
1472                         .setRealCallingUid(origCallingUid)
1473                         .setActivityOptions(options)
1474                         .setUserId(userId)
1475                         .execute();
1476                 r.finishing = wasFinishing;
1477                 return res == ActivityManager.START_SUCCESS;
1478             } finally {
1479                 Binder.restoreCallingIdentity(origId);
1480             }
1481         }
1482     }
1483 
isDreaming()1484     boolean isDreaming() {
1485         return mActiveDreamComponent != null;
1486     }
1487 
canLaunchDreamActivity(String packageName)1488     boolean canLaunchDreamActivity(String packageName) {
1489         if (mActiveDreamComponent == null || packageName == null) {
1490             ProtoLog.e(WM_DEBUG_DREAM, "Cannot launch dream activity due to invalid state. "
1491                     + "dream component: %s packageName: %s", mActiveDreamComponent, packageName);
1492             return false;
1493         }
1494         if (packageName.equals(mActiveDreamComponent.getPackageName())) {
1495             return true;
1496         }
1497         ProtoLog.e(WM_DEBUG_DREAM,
1498                 "Dream packageName does not match active dream. Package %s does not match %s",
1499                 packageName, String.valueOf(mActiveDreamComponent));
1500         return false;
1501     }
1502 
startDreamActivityInternal(@onNull Intent intent, int callingUid, int callingPid)1503     private IAppTask startDreamActivityInternal(@NonNull Intent intent, int callingUid,
1504             int callingPid) {
1505         final ActivityInfo a = new ActivityInfo();
1506         a.theme = com.android.internal.R.style.Theme_Dream;
1507         a.exported = true;
1508         a.name = DreamActivity.class.getName();
1509         a.enabled = true;
1510         a.persistableMode = ActivityInfo.PERSIST_NEVER;
1511         a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1512         a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1513         a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | ActivityInfo.FLAG_SHOW_WHEN_LOCKED;
1514         a.configChanges = 0xffffffff;
1515 
1516         if (homePanelDream()) {
1517             a.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
1518             a.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_ALWAYS;
1519         } else {
1520             a.resizeMode = RESIZE_MODE_UNRESIZEABLE;
1521             a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1522         }
1523 
1524         final ActivityOptions options = ActivityOptions.makeBasic();
1525         options.setLaunchActivityType(ACTIVITY_TYPE_DREAM);
1526 
1527         synchronized (mGlobalLock) {
1528             final WindowProcessController process = mProcessMap.getProcess(callingPid);
1529 
1530             a.packageName = process.mInfo.packageName;
1531             a.applicationInfo = process.mInfo;
1532             a.processName = process.mName;
1533             a.uiOptions = process.mInfo.uiOptions;
1534             a.taskAffinity = "android:" + a.packageName + "/dream";
1535 
1536 
1537             final ActivityRecord[] outActivity = new ActivityRecord[1];
1538             getActivityStartController().obtainStarter(intent, "dream")
1539                     .setCallingUid(callingUid)
1540                     .setCallingPid(callingPid)
1541                     .setCallingPackage(intent.getPackage())
1542                     .setActivityInfo(a)
1543                     .setActivityOptions(createSafeActivityOptionsWithBalAllowed(options))
1544                     .setOutActivity(outActivity)
1545                     // To start the dream from background, we need to start it from a persistent
1546                     // system process. Here we set the real calling uid to the system server uid
1547                     .setRealCallingUid(Binder.getCallingUid())
1548                     .setBackgroundStartPrivileges(BackgroundStartPrivileges.ALLOW_BAL)
1549                     .execute();
1550 
1551             final ActivityRecord started = outActivity[0];
1552             final IAppTask appTask = started == null ? null :
1553                     new AppTaskImpl(this, started.getTask().mTaskId, callingUid);
1554             return appTask;
1555         }
1556     }
1557 
1558     @Override
startActivityAndWait(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)1559     public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1560             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1561             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1562             Bundle bOptions, int userId) {
1563         assertPackageMatchesCallingUid(callingPackage);
1564         final WaitResult res = new WaitResult();
1565         enforceNotIsolatedCaller("startActivityAndWait");
1566         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1567                 userId, "startActivityAndWait");
1568         // TODO: Switch to user app stacks here.
1569         getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1570                 .setCaller(caller)
1571                 .setCallingPackage(callingPackage)
1572                 .setCallingFeatureId(callingFeatureId)
1573                 .setResolvedType(resolvedType)
1574                 .setResultTo(resultTo)
1575                 .setResultWho(resultWho)
1576                 .setRequestCode(requestCode)
1577                 .setStartFlags(startFlags)
1578                 .setActivityOptions(bOptions)
1579                 .setUserId(userId)
1580                 .setProfilerInfo(profilerInfo)
1581                 .setWaitResult(res)
1582                 .execute();
1583         return res;
1584     }
1585 
1586     @Override
startActivityWithConfig(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, Configuration config, Bundle bOptions, int userId)1587     public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1588             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1589             String resultWho, int requestCode, int startFlags, Configuration config,
1590             Bundle bOptions, int userId) {
1591         assertPackageMatchesCallingUid(callingPackage);
1592         enforceNotIsolatedCaller("startActivityWithConfig");
1593         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1594                 "startActivityWithConfig");
1595         // TODO: Switch to user app stacks here.
1596         return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1597                 .setCaller(caller)
1598                 .setCallingPackage(callingPackage)
1599                 .setCallingFeatureId(callingFeatureId)
1600                 .setResolvedType(resolvedType)
1601                 .setResultTo(resultTo)
1602                 .setResultWho(resultWho)
1603                 .setRequestCode(requestCode)
1604                 .setStartFlags(startFlags)
1605                 .setGlobalConfiguration(config)
1606                 .setActivityOptions(bOptions)
1607                 .setUserId(userId)
1608                 .execute();
1609     }
1610 
1611     @Override
startActivityAsCaller(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity, int userId)1612     public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1613             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1614             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions,
1615             boolean ignoreTargetSecurity, int userId) {
1616         // This is very dangerous -- it allows you to perform a start activity (including
1617         // permission grants) as any app that may launch one of your own activities.  So we only
1618         // allow this in two cases:
1619         // 1)  The calling process holds the signature permission START_ACTIVITY_AS_CALLER
1620         //
1621         // 2) The calling process is an activity belonging to the package "android" which is
1622         //    running as UID_SYSTEM or as the target UID (the activity which started the activity
1623         //    calling this method).
1624 
1625         final ActivityRecord sourceRecord;
1626         final int targetUid;
1627         final String targetPackage;
1628         final String targetFeatureId;
1629         final boolean isResolver;
1630         synchronized (mGlobalLock) {
1631             if (resultTo == null) {
1632                 throw new SecurityException("Must be called from an activity");
1633             }
1634 
1635             sourceRecord = ActivityRecord.isInAnyTask(resultTo);
1636             if (sourceRecord == null) {
1637                 throw new SecurityException("Called with bad activity token: " + resultTo);
1638             }
1639             if (sourceRecord.app == null) {
1640                 throw new SecurityException("Called without a process attached to activity");
1641             }
1642 
1643             if (checkCallingPermission(Manifest.permission.START_ACTIVITY_AS_CALLER)
1644                     != PERMISSION_GRANTED) {
1645                 // Whether called directly or from a delegate, the source activity must be from the
1646                 // android package.
1647                 if (!sourceRecord.info.packageName.equals("android")) {
1648                     throw new SecurityException("Must be called from an activity that is "
1649                             + "declared in the android package");
1650                 }
1651                 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
1652                     // This is still okay, as long as this activity is running under the
1653                     // uid of the original calling activity.
1654                     if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
1655                         throw new SecurityException(
1656                                 "Calling activity in uid " + sourceRecord.app.mUid
1657                                         + " must be system uid or original calling uid "
1658                                         + sourceRecord.launchedFromUid);
1659                     }
1660                 }
1661             }
1662             if (ignoreTargetSecurity) {
1663                 if (intent.getComponent() == null) {
1664                     throw new SecurityException(
1665                             "Component must be specified with ignoreTargetSecurity");
1666                 }
1667                 if (intent.getSelector() != null) {
1668                     throw new SecurityException(
1669                             "Selector not allowed with ignoreTargetSecurity");
1670                 }
1671             }
1672             targetUid = sourceRecord.launchedFromUid;
1673             targetPackage = sourceRecord.launchedFromPackage;
1674             targetFeatureId = sourceRecord.launchedFromFeatureId;
1675             isResolver = sourceRecord.isResolverOrChildActivity();
1676         }
1677 
1678         if (userId == UserHandle.USER_NULL) {
1679             userId = UserHandle.getUserId(sourceRecord.app.mUid);
1680         }
1681 
1682         // TODO: Switch to user app stacks here.
1683         try {
1684             return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
1685                     .setCallingUid(targetUid)
1686                     .setCallingPackage(targetPackage)
1687                     .setCallingFeatureId(targetFeatureId)
1688                     .setResolvedType(resolvedType)
1689                     .setResultTo(resultTo)
1690                     .setResultWho(resultWho)
1691                     .setRequestCode(requestCode)
1692                     .setStartFlags(startFlags)
1693                     .setActivityOptions(createSafeActivityOptionsWithBalAllowed(bOptions))
1694                     .setUserId(userId)
1695                     .setIgnoreTargetSecurity(ignoreTargetSecurity)
1696                     .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1697                     // The target may well be in the background, which would normally prevent it
1698                     // from starting an activity. Here we definitely want the start to succeed.
1699                     .setBackgroundStartPrivileges(BackgroundStartPrivileges.ALLOW_BAL)
1700                     .execute();
1701         } catch (SecurityException e) {
1702             // XXX need to figure out how to propagate to original app.
1703             // A SecurityException here is generally actually a fault of the original
1704             // calling activity (such as a fairly granting permissions), so propagate it
1705             // back to them.
1706             /*
1707             StringBuilder msg = new StringBuilder();
1708             msg.append("While launching");
1709             msg.append(intent.toString());
1710             msg.append(": ");
1711             msg.append(e.getMessage());
1712             */
1713             throw e;
1714         }
1715     }
1716 
handleIncomingUser(int callingPid, int callingUid, int userId, String name)1717     int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1718         return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1719                 ALLOW_NON_FULL, name, null /* callerPackage */);
1720     }
1721 
1722     @Override
startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid, int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session, IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)1723     public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1724             int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
1725             IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1726             Bundle bOptions, int userId) {
1727         assertPackageMatchesCallingUid(callingPackage);
1728         mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
1729         if (session == null || interactor == null) {
1730             throw new NullPointerException("null session or interactor");
1731         }
1732         userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
1733         // TODO: Switch to user app stacks here.
1734         return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
1735                 .setCallingUid(callingUid)
1736                 .setCallingPackage(callingPackage)
1737                 .setCallingFeatureId(callingFeatureId)
1738                 .setResolvedType(resolvedType)
1739                 .setVoiceSession(session)
1740                 .setVoiceInteractor(interactor)
1741                 .setStartFlags(startFlags)
1742                 .setProfilerInfo(profilerInfo)
1743                 .setActivityOptions(createSafeActivityOptionsWithBalAllowed(bOptions))
1744                 .setUserId(userId)
1745                 .setBackgroundStartPrivileges(BackgroundStartPrivileges.ALLOW_BAL)
1746                 .execute();
1747     }
1748 
1749     @Override
getVoiceInteractorPackageName(IBinder callingVoiceInteractor)1750     public String getVoiceInteractorPackageName(IBinder callingVoiceInteractor) {
1751         return LocalServices.getService(VoiceInteractionManagerInternal.class)
1752                 .getVoiceInteractorPackageName(callingVoiceInteractor);
1753     }
1754 
1755     @Override
startAssistantActivity(String callingPackage, @NonNull String callingFeatureId, int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions, int userId)1756     public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1757             int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1758             int userId) {
1759         assertPackageMatchesCallingUid(callingPackage);
1760         mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1761         userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
1762 
1763         final long origId = Binder.clearCallingIdentity();
1764         try {
1765             return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
1766                     .setCallingUid(callingUid)
1767                     .setCallingPackage(callingPackage)
1768                     .setCallingFeatureId(callingFeatureId)
1769                     .setResolvedType(resolvedType)
1770                     .setActivityOptions(createSafeActivityOptionsWithBalAllowed(bOptions))
1771                     .setUserId(userId)
1772                     .setBackgroundStartPrivileges(BackgroundStartPrivileges.ALLOW_BAL)
1773                     .execute();
1774         } finally {
1775             Binder.restoreCallingIdentity(origId);
1776         }
1777     }
1778 
1779     /**
1780      * Start the recents activity to perform the recents animation.
1781      *
1782      * @param intent                 The intent to start the recents activity.
1783      * @param eventTime              When the (touch) event is triggered to start recents activity.
1784      * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1785      */
1786     @Override
startRecentsActivity(Intent intent, long eventTime, @Nullable IRecentsAnimationRunner recentsAnimationRunner)1787     public void startRecentsActivity(Intent intent, long eventTime,
1788             @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
1789         enforceTaskPermission("startRecentsActivity()");
1790         final int callingPid = Binder.getCallingPid();
1791         final int callingUid = Binder.getCallingUid();
1792         final long origId = Binder.clearCallingIdentity();
1793         try {
1794             synchronized (mGlobalLock) {
1795                 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1796                 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
1797                 final int recentsUid = mRecentTasks.getRecentsComponentUid();
1798                 final WindowProcessController caller = getProcessController(callingPid, callingUid);
1799 
1800                 // Start a new recents animation
1801                 final RecentsAnimation anim = new RecentsAnimation(this, mTaskSupervisor,
1802                         getActivityStartController(), mWindowManager, intent, recentsComponent,
1803                         recentsFeatureId, recentsUid, caller);
1804                 if (recentsAnimationRunner == null) {
1805                     anim.preloadRecentsActivity();
1806                 } else {
1807                     anim.startRecentsActivity(recentsAnimationRunner, eventTime);
1808                 }
1809             }
1810         } finally {
1811             Binder.restoreCallingIdentity(origId);
1812         }
1813     }
1814 
1815     @Override
startActivityFromRecents(int taskId, Bundle bOptions)1816     public final int startActivityFromRecents(int taskId, Bundle bOptions) {
1817         mAmInternal.enforceCallingPermission(START_TASKS_FROM_RECENTS,
1818                 "startActivityFromRecents()");
1819 
1820         final int callingPid = Binder.getCallingPid();
1821         final int callingUid = Binder.getCallingUid();
1822         final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1823         final long origId = Binder.clearCallingIdentity();
1824         try {
1825             return mTaskSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1826                     safeOptions);
1827         } finally {
1828             Binder.restoreCallingIdentity(origId);
1829         }
1830     }
1831 
1832     @Override
startActivityFromGameSession(IApplicationThread caller, String callingPackage, String callingFeatureId, int callingPid, int callingUid, Intent intent, int taskId, int userId)1833     public int startActivityFromGameSession(IApplicationThread caller, String callingPackage,
1834             String callingFeatureId, int callingPid, int callingUid, Intent intent, int taskId,
1835             int userId) {
1836         if (checkCallingPermission(MANAGE_GAME_ACTIVITY) != PERMISSION_GRANTED) {
1837             final String msg = "Permission Denial: startActivityFromGameSession() from pid="
1838                     + Binder.getCallingPid()
1839                     + ", uid=" + Binder.getCallingUid()
1840                     + " requires " + MANAGE_GAME_ACTIVITY;
1841             Slog.w(TAG, msg);
1842             throw new SecurityException(msg);
1843         }
1844         assertPackageMatchesCallingUid(callingPackage);
1845 
1846         final ActivityOptions activityOptions = ActivityOptions.makeBasic();
1847         activityOptions.setLaunchTaskId(taskId);
1848 
1849         userId = handleIncomingUser(callingPid, callingUid, userId, "startActivityFromGameSession");
1850 
1851         final long origId = Binder.clearCallingIdentity();
1852         try {
1853             return getActivityStartController()
1854                     .obtainStarter(intent, "startActivityFromGameSession")
1855                     .setCaller(caller)
1856                     .setCallingUid(callingUid)
1857                     .setCallingPid(callingPid)
1858                     .setCallingPackage(intent.getPackage())
1859                     .setCallingFeatureId(callingFeatureId)
1860                     .setUserId(userId)
1861                     .setActivityOptions(activityOptions.toBundle())
1862                     .setRealCallingUid(Binder.getCallingUid())
1863                     .execute();
1864         } finally {
1865             Binder.restoreCallingIdentity(origId);
1866         }
1867     }
1868 
1869     @Override
startBackNavigation( RemoteCallback navigationObserver, BackAnimationAdapter adapter)1870     public BackNavigationInfo startBackNavigation(
1871             RemoteCallback navigationObserver, BackAnimationAdapter adapter) {
1872         mAmInternal.enforceCallingPermission(START_TASKS_FROM_RECENTS,
1873                 "startBackNavigation()");
1874         final long origId = Binder.clearCallingIdentity();
1875         try {
1876             return mBackNavigationController.startBackNavigation(navigationObserver, adapter);
1877         } finally {
1878             Binder.restoreCallingIdentity(origId);
1879         }
1880     }
1881 
1882     /**
1883      * Public API to check if the client is allowed to start an activity on specified display.
1884      *
1885      * If the target display is private or virtual, some restrictions will apply.
1886      *
1887      * @param displayId    Target display id.
1888      * @param intent       Intent used to launch the activity.
1889      * @param resolvedType The MIME type of the intent.
1890      * @param userId       The id of the user for whom the call is made.
1891      * @return {@code true} if a call to start an activity on the target display should succeed and
1892      * no {@link SecurityException} will be thrown, {@code false} otherwise.
1893      */
1894     @Override
isActivityStartAllowedOnDisplay(int displayId, Intent intent, String resolvedType, int userId)1895     public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1896             String resolvedType, int userId) {
1897         final int callingUid = Binder.getCallingUid();
1898         final int callingPid = Binder.getCallingPid();
1899         final long origId = Binder.clearCallingIdentity();
1900 
1901         try {
1902             // Collect information about the target of the Intent.
1903             final ActivityInfo aInfo = resolveActivityInfoForIntent(intent, resolvedType, userId,
1904                     callingUid, callingPid);
1905 
1906             synchronized (mGlobalLock) {
1907                 return mTaskSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1908                         aInfo);
1909             }
1910         } finally {
1911             Binder.restoreCallingIdentity(origId);
1912         }
1913     }
1914 
resolveActivityInfoForIntent(Intent intent, String resolvedType, int userId, int callingUid, int callingPid)1915     ActivityInfo resolveActivityInfoForIntent(Intent intent, String resolvedType,
1916             int userId, int callingUid, int callingPid) {
1917         ActivityInfo aInfo = mTaskSupervisor.resolveActivity(intent, resolvedType,
1918                 0 /* startFlags */, null /* profilerInfo */, userId,
1919                 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1920                         UserHandle.USER_NULL), callingPid);
1921         return mAmInternal.getActivityInfoForUser(aInfo, userId);
1922     }
1923 
1924     @Override
getActivityClientController()1925     public IActivityClientController getActivityClientController() {
1926         return mActivityClientController;
1927     }
1928 
applyUpdateLockStateLocked(ActivityRecord r)1929     void applyUpdateLockStateLocked(ActivityRecord r) {
1930         // Modifications to the UpdateLock state are done on our handler, outside
1931         // the activity manager's locks.  The new state is determined based on the
1932         // state *now* of the relevant activity record.  The object is passed to
1933         // the handler solely for logging detail, not to be consulted/modified.
1934         final boolean nextState = r != null && r.immersive;
1935         mH.post(() -> {
1936             if (mUpdateLock.isHeld() != nextState) {
1937                 ProtoLog.d(WM_DEBUG_IMMERSIVE, "Applying new update lock state '%s' for %s",
1938                         nextState, r);
1939                 if (nextState) {
1940                     mUpdateLock.acquire();
1941                 } else {
1942                     mUpdateLock.release();
1943                 }
1944             }
1945         });
1946     }
1947 
1948     @Override
isTopActivityImmersive()1949     public boolean isTopActivityImmersive() {
1950         enforceNotIsolatedCaller("isTopActivityImmersive");
1951         synchronized (mGlobalLock) {
1952             final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
1953             if (topFocusedRootTask == null) {
1954                 return false;
1955             }
1956 
1957             final ActivityRecord r = topFocusedRootTask.topRunningActivity();
1958             return r != null && r.immersive;
1959         }
1960     }
1961 
1962     @Override
getFrontActivityScreenCompatMode()1963     public int getFrontActivityScreenCompatMode() {
1964         enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
1965         synchronized (mGlobalLock) {
1966             final Task rootTask = getTopDisplayFocusedRootTask();
1967             final ActivityRecord r = rootTask != null ? rootTask.topRunningActivity() : null;
1968             if (r == null) {
1969                 return ActivityManager.COMPAT_MODE_UNKNOWN;
1970             }
1971             return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
1972         }
1973     }
1974 
1975     @Override
setFrontActivityScreenCompatMode(int mode)1976     public void setFrontActivityScreenCompatMode(int mode) {
1977         mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
1978                 "setFrontActivityScreenCompatMode");
1979         ApplicationInfo ai;
1980         synchronized (mGlobalLock) {
1981             final Task rootTask = getTopDisplayFocusedRootTask();
1982             final ActivityRecord r = rootTask != null ? rootTask.topRunningActivity() : null;
1983             if (r == null) {
1984                 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1985                 return;
1986             }
1987             ai = r.info.applicationInfo;
1988             mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
1989         }
1990     }
1991 
1992 
1993     @Override
getFocusedRootTaskInfo()1994     public RootTaskInfo getFocusedRootTaskInfo() throws RemoteException {
1995         enforceTaskPermission("getFocusedRootTaskInfo()");
1996         final long ident = Binder.clearCallingIdentity();
1997         try {
1998             synchronized (mGlobalLock) {
1999                 Task focusedRootTask = getTopDisplayFocusedRootTask();
2000                 if (focusedRootTask != null) {
2001                     return mRootWindowContainer.getRootTaskInfo(focusedRootTask.mTaskId);
2002                 }
2003                 return null;
2004             }
2005         } finally {
2006             Binder.restoreCallingIdentity(ident);
2007         }
2008     }
2009 
2010     @Override
setFocusedRootTask(int taskId)2011     public void setFocusedRootTask(int taskId) {
2012         enforceTaskPermission("setFocusedRootTask()");
2013         ProtoLog.d(WM_DEBUG_FOCUS, "setFocusedRootTask: taskId=%d", taskId);
2014         final long callingId = Binder.clearCallingIdentity();
2015         try {
2016             synchronized (mGlobalLock) {
2017                 final Task task = mRootWindowContainer.getRootTask(taskId);
2018                 if (task == null) {
2019                     Slog.w(TAG, "setFocusedRootTask: No task with id=" + taskId);
2020                     return;
2021                 }
2022                 final ActivityRecord r = task.topRunningActivity();
2023                 if (r != null && r.moveFocusableActivityToTop("setFocusedRootTask")) {
2024                     mRootWindowContainer.resumeFocusedTasksTopActivities();
2025                 }
2026             }
2027         } finally {
2028             Binder.restoreCallingIdentity(callingId);
2029         }
2030     }
2031 
2032     @Override
setFocusedTask(int taskId)2033     public void setFocusedTask(int taskId) {
2034         enforceTaskPermission("setFocusedTask()");
2035         final long callingId = Binder.clearCallingIdentity();
2036         try {
2037             synchronized (mGlobalLock) {
2038                 setFocusedTask(taskId, null /* touchedActivity */);
2039             }
2040         } finally {
2041             Binder.restoreCallingIdentity(callingId);
2042         }
2043     }
2044 
2045     @Override
focusTopTask(int displayId)2046     public void focusTopTask(int displayId) {
2047         enforceTaskPermission("focusTopTask()");
2048         final long callingId = Binder.clearCallingIdentity();
2049         try {
2050             synchronized (mGlobalLock) {
2051                 final DisplayContent dc = mRootWindowContainer.getDisplayContent(displayId);
2052                 if (dc == null) return;
2053                 final Task task = dc.getTask((t) -> t.isLeafTask() && t.isTopActivityFocusable(),
2054                         true /*  traverseTopToBottom */);
2055                 if (task == null) return;
2056                 setFocusedTask(task.mTaskId, null /* touchedActivity */);
2057             }
2058         } finally {
2059             Binder.restoreCallingIdentity(callingId);
2060         }
2061     }
2062 
setFocusedTask(int taskId, ActivityRecord touchedActivity)2063     void setFocusedTask(int taskId, ActivityRecord touchedActivity) {
2064         ProtoLog.d(WM_DEBUG_FOCUS, "setFocusedTask: taskId=%d touchedActivity=%s", taskId,
2065                 touchedActivity);
2066         final Task task = mRootWindowContainer.anyTaskForId(taskId, MATCH_ATTACHED_TASK_ONLY);
2067         if (task == null) {
2068             return;
2069         }
2070         final ActivityRecord r = task.topRunningActivityLocked();
2071         if (r == null) {
2072             return;
2073         }
2074 
2075         if ((touchedActivity == null || r == touchedActivity) && r.isState(RESUMED)
2076                 && r == mRootWindowContainer.getTopResumedActivity()) {
2077             setLastResumedActivityUncheckLocked(r, "setFocusedTask-alreadyTop");
2078             return;
2079         }
2080         final Transition transition = (getTransitionController().isCollecting()
2081                 || !getTransitionController().isShellTransitionsEnabled()) ? null
2082                 : getTransitionController().createTransition(TRANSIT_TO_FRONT);
2083         if (transition != null) {
2084             // Set ready before doing anything. If order does change, then that will set it unready
2085             // so that we wait for the new lifecycles to complete.
2086             transition.setReady(task, true /* ready */);
2087         }
2088         final boolean movedToTop = r.moveFocusableActivityToTop("setFocusedTask");
2089         if (movedToTop) {
2090             if (transition != null) {
2091                 getTransitionController().requestStartTransition(
2092                         transition, null /* startTask */, null /* remote */, null /* display */);
2093             }
2094             mRootWindowContainer.resumeFocusedTasksTopActivities();
2095         } else if (touchedActivity != null && touchedActivity.isFocusable()) {
2096             final TaskFragment parent = touchedActivity.getTaskFragment();
2097             if (parent != null && parent.isEmbedded()) {
2098                 // Set the focused app directly if the focused window is currently embedded
2099                 final DisplayContent displayContent = touchedActivity.getDisplayContent();
2100                 displayContent.setFocusedApp(touchedActivity);
2101                 mWindowManager.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL,
2102                         true /* updateInputWindows */);
2103             }
2104         }
2105         if (transition != null && !movedToTop) {
2106             // No order changes and focus-changes, alone, aren't captured in transitions.
2107             transition.abort();
2108         }
2109     }
2110 
2111     @Override
removeTask(int taskId)2112     public boolean removeTask(int taskId) {
2113         mAmInternal.enforceCallingPermission(REMOVE_TASKS, "removeTask()");
2114         synchronized (mGlobalLock) {
2115             final long ident = Binder.clearCallingIdentity();
2116             try {
2117                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2118                         MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
2119                 if (task == null) {
2120                     Slog.w(TAG, "removeTask: No task remove with id=" + taskId);
2121                     return false;
2122                 }
2123 
2124                 if (task.isLeafTask()) {
2125                     mTaskSupervisor.removeTask(task, true, REMOVE_FROM_RECENTS, "remove-task");
2126                 } else {
2127                     mTaskSupervisor.removeRootTask(task);
2128                 }
2129                 return true;
2130             } finally {
2131                 Binder.restoreCallingIdentity(ident);
2132             }
2133         }
2134     }
2135 
2136     @Override
removeAllVisibleRecentTasks()2137     public void removeAllVisibleRecentTasks() {
2138         mAmInternal.enforceCallingPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2139         synchronized (mGlobalLock) {
2140             final long ident = Binder.clearCallingIdentity();
2141             try {
2142                 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
2143             } finally {
2144                 Binder.restoreCallingIdentity(ident);
2145             }
2146         }
2147     }
2148 
2149     @Override
getTaskBounds(int taskId)2150     public Rect getTaskBounds(int taskId) {
2151         enforceTaskPermission("getTaskBounds()");
2152         final long ident = Binder.clearCallingIdentity();
2153         Rect rect = new Rect();
2154         try {
2155             synchronized (mGlobalLock) {
2156                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2157                         MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
2158                 if (task == null) {
2159                     Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2160                     return rect;
2161                 }
2162                 if (task.getParent() != null) {
2163                     rect.set(task.getBounds());
2164                 } else if (task.mLastNonFullscreenBounds != null) {
2165                     rect.set(task.mLastNonFullscreenBounds);
2166                 }
2167             }
2168         } finally {
2169             Binder.restoreCallingIdentity(ident);
2170         }
2171         return rect;
2172     }
2173 
2174     /**
2175      * Sets the locusId for a particular activity.
2176      *
2177      * @param locusId the locusId to set.
2178      * @param appToken the ActivityRecord's appToken.
2179      */
setLocusId(LocusId locusId, IBinder appToken)2180     public void setLocusId(LocusId locusId, IBinder appToken) {
2181         synchronized (mGlobalLock) {
2182             final ActivityRecord r = ActivityRecord.isInRootTaskLocked(appToken);
2183             if (r != null) {
2184                 r.setLocusId(locusId);
2185             }
2186         }
2187     }
2188 
collectGrants(Intent intent, ActivityRecord target)2189     NeededUriGrants collectGrants(Intent intent, ActivityRecord target) {
2190         if (target != null) {
2191             return mUgmInternal.checkGrantUriPermissionFromIntent(intent,
2192                     Binder.getCallingUid(), target.packageName, target.mUserId);
2193         } else {
2194             return null;
2195         }
2196     }
2197 
2198     @Override
unhandledBack()2199     public void unhandledBack() {
2200         mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
2201                 "unhandledBack()");
2202 
2203         synchronized (mGlobalLock) {
2204             final long origId = Binder.clearCallingIdentity();
2205             try {
2206                 final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
2207                 if (topFocusedRootTask != null) {
2208                     topFocusedRootTask.unhandledBackLocked();
2209                 }
2210             } finally {
2211                 Binder.restoreCallingIdentity(origId);
2212             }
2213         }
2214     }
2215 
2216     /**
2217      * TODO: Add mController hook
2218      */
2219     @Override
moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)2220     public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2221             int flags, Bundle bOptions) {
2222         mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
2223                 "moveTaskToFront()");
2224 
2225         ProtoLog.d(WM_DEBUG_TASKS, "moveTaskToFront: moving taskId=%d", taskId);
2226         synchronized (mGlobalLock) {
2227             moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2228                     SafeActivityOptions.fromBundle(bOptions));
2229         }
2230     }
2231 
moveTaskToFrontLocked(@ullable IApplicationThread appThread, @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options)2232     void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2233             @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options) {
2234         final int callingPid = Binder.getCallingPid();
2235         final int callingUid = Binder.getCallingUid();
2236         assertPackageMatchesCallingUid(callingPackage);
2237 
2238         final long origId = Binder.clearCallingIdentity();
2239         WindowProcessController callerApp = null;
2240         if (appThread != null) {
2241             callerApp = getProcessController(appThread);
2242         }
2243         final BackgroundActivityStartController balController =
2244                 mTaskSupervisor.getBackgroundActivityLaunchController();
2245         final BalVerdict balVerdict = balController.checkBackgroundActivityStart(
2246                 callingUid,
2247                 callingPid,
2248                 callingPackage,
2249                 -1,
2250                 -1,
2251                 callerApp,
2252                 null,
2253                 BackgroundStartPrivileges.NONE,
2254                 null,
2255                 null,
2256                 null);
2257         if (balVerdict.blocks() && !isBackgroundActivityStartsEnabled()) {
2258             Slog.w(TAG, "moveTaskToFront blocked: " + balVerdict);
2259             return;
2260         }
2261         if (DEBUG_ACTIVITY_STARTS) {
2262             Slog.d(TAG, "moveTaskToFront allowed: " + balVerdict);
2263         }
2264         try {
2265             final Task task = mRootWindowContainer.anyTaskForId(taskId);
2266             if (task == null) {
2267                 ProtoLog.d(WM_DEBUG_TASKS, "Could not find task for id: %d", taskId);
2268                 SafeActivityOptions.abort(options);
2269                 return;
2270             }
2271             if (getLockTaskController().isLockTaskModeViolation(task)) {
2272                 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
2273                 SafeActivityOptions.abort(options);
2274                 return;
2275             }
2276             ActivityOptions realOptions = options != null
2277                     ? options.getOptions(mTaskSupervisor)
2278                     : null;
2279             mTaskSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2280                     false /* forceNonResizable */);
2281         } finally {
2282             Binder.restoreCallingIdentity(origId);
2283         }
2284     }
2285 
2286     /**
2287      * Return true if callingUid is system, or packageName belongs to that callingUid.
2288      */
isSameApp(int callingUid, @Nullable String packageName)2289     private boolean isSameApp(int callingUid, @Nullable String packageName) {
2290         if (callingUid != 0 && callingUid != SYSTEM_UID) {
2291             return mPmInternal.isSameApp(packageName, callingUid, UserHandle.getUserId(callingUid));
2292         }
2293         return true;
2294     }
2295 
2296     /**
2297      * Checks that the provided package name matches the current calling UID, throws a security
2298      * exception if it doesn't.
2299      */
assertPackageMatchesCallingUid(@ullable String packageName)2300     void assertPackageMatchesCallingUid(@Nullable String packageName) {
2301         final int callingUid = Binder.getCallingUid();
2302         if (isSameApp(callingUid, packageName)) {
2303             return;
2304         }
2305         final String msg = "Permission Denial: package=" + packageName
2306                 + " does not belong to uid=" + callingUid;
2307         Slog.w(TAG, msg);
2308         throw new SecurityException(msg);
2309     }
2310 
2311     /**
2312      * Return true if app switching is allowed.
2313      */
getBalAppSwitchesState()2314     @AppSwitchState int getBalAppSwitchesState() {
2315         return mAppSwitchesState;
2316     }
2317 
2318     /** Register an {@link AnrController} to control the ANR dialog behavior */
registerAnrController(AnrController controller)2319     public void registerAnrController(AnrController controller) {
2320         synchronized (mAnrController) {
2321             mAnrController.add(controller);
2322         }
2323     }
2324 
2325     /** Unregister an {@link AnrController} */
unregisterAnrController(AnrController controller)2326     public void unregisterAnrController(AnrController controller) {
2327         synchronized (mAnrController) {
2328             mAnrController.remove(controller);
2329         }
2330     }
2331 
2332     /**
2333      * @return the controller with the max ANR delay from all registered
2334      * {@link AnrController} instances
2335      */
2336     @Nullable
getAnrController(ApplicationInfo info)2337     public AnrController getAnrController(ApplicationInfo info) {
2338         if (info == null || info.packageName == null) {
2339             return null;
2340         }
2341 
2342         final ArrayList<AnrController> controllers;
2343         synchronized (mAnrController) {
2344             controllers = new ArrayList<>(mAnrController);
2345         }
2346 
2347         final String packageName = info.packageName;
2348         final int uid = info.uid;
2349         long maxDelayMs = 0;
2350         AnrController controllerWithMaxDelay = null;
2351 
2352         for (AnrController controller : controllers) {
2353             long delayMs = controller.getAnrDelayMillis(packageName, uid);
2354             if (delayMs > 0 && delayMs > maxDelayMs) {
2355                 controllerWithMaxDelay = controller;
2356                 maxDelayMs = delayMs;
2357             }
2358         }
2359 
2360         return controllerWithMaxDelay;
2361     }
2362 
2363     @Override
setActivityController(IActivityController controller, boolean imAMonkey)2364     public void setActivityController(IActivityController controller, boolean imAMonkey) {
2365         mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2366                 "setActivityController()");
2367         synchronized (mGlobalLock) {
2368             mController = controller;
2369             mControllerIsAMonkey = imAMonkey;
2370             Watchdog.getInstance().setActivityController(controller);
2371         }
2372     }
2373 
isControllerAMonkey()2374     public boolean isControllerAMonkey() {
2375         synchronized (mGlobalLock) {
2376             return mController != null && mControllerIsAMonkey;
2377         }
2378     }
2379 
2380     /**
2381      * Gets info of running tasks up to the given number.
2382      *
2383      * @param maxNum the maximum number of task info returned by this method. If the total number of
2384      *               running tasks is larger than it then there is no guarantee which task will be
2385      *               left out.
2386      * @return a list of {@link ActivityManager.RunningTaskInfo} with up to {@code maxNum} items
2387      */
getTasks(int maxNum)2388     public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2389         return getTasks(maxNum, false /* filterForVisibleRecents */, false /* keepIntentExtra */,
2390                 INVALID_DISPLAY);
2391     }
2392 
2393     /**
2394      * @param filterOnlyVisibleRecents whether to filter the tasks based on whether they would ever
2395      *                                 be visible in the recent task list in systemui
2396      */
getTasks(int maxNum, boolean filterOnlyVisibleRecents, boolean keepIntentExtra)2397     public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum,
2398             boolean filterOnlyVisibleRecents, boolean keepIntentExtra) {
2399         return getTasks(maxNum, filterOnlyVisibleRecents, keepIntentExtra, INVALID_DISPLAY);
2400     }
2401 
2402     /**
2403      * @param displayId the target display id, or {@link INVALID_DISPLAY} not to filter by displayId
2404      */
2405     @Override
getTasks(int maxNum, boolean filterOnlyVisibleRecents, boolean keepIntentExtra, int displayId)2406     public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum,
2407             boolean filterOnlyVisibleRecents, boolean keepIntentExtra, int displayId) {
2408         final int callingUid = Binder.getCallingUid();
2409         final int callingPid = Binder.getCallingPid();
2410 
2411         int flags = filterOnlyVisibleRecents ? RunningTasks.FLAG_FILTER_ONLY_VISIBLE_RECENTS : 0;
2412         flags |= (keepIntentExtra ? RunningTasks.FLAG_KEEP_INTENT_EXTRA : 0);
2413         final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
2414         flags |= (crossUser ? RunningTasks.FLAG_CROSS_USERS : 0);
2415         final int[] profileIds = getUserManager().getProfileIds(
2416                 UserHandle.getUserId(callingUid), true);
2417         ArraySet<Integer> callingProfileIds = new ArraySet<>();
2418         for (int i = 0; i < profileIds.length; i++) {
2419             callingProfileIds.add(profileIds[i]);
2420         }
2421         ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2422 
2423         synchronized (mGlobalLock) {
2424             if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2425 
2426             final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
2427             flags |= (allowed ? RunningTasks.FLAG_ALLOWED : 0);
2428             mRootWindowContainer.getRunningTasks(
2429                     maxNum, list, flags, callingUid, callingProfileIds, displayId);
2430         }
2431 
2432         return list;
2433     }
2434 
2435     @Override
moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop)2436     public void moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop) {
2437         enforceTaskPermission("moveTaskToRootTask()");
2438         synchronized (mGlobalLock) {
2439             final long ident = Binder.clearCallingIdentity();
2440             try {
2441                 final Task task = mRootWindowContainer.anyTaskForId(taskId);
2442                 if (task == null) {
2443                     Slog.w(TAG, "moveTaskToRootTask: No task for id=" + taskId);
2444                     return;
2445                 }
2446 
2447                 ProtoLog.d(WM_DEBUG_TASKS, "moveTaskToRootTask: moving task=%d to "
2448                         + "rootTaskId=%d toTop=%b", taskId, rootTaskId, toTop);
2449 
2450                 final Task rootTask = mRootWindowContainer.getRootTask(rootTaskId);
2451                 if (rootTask == null) {
2452                     throw new IllegalStateException(
2453                             "moveTaskToRootTask: No rootTask for rootTaskId=" + rootTaskId);
2454                 }
2455                 if (!rootTask.isActivityTypeStandardOrUndefined()) {
2456                     throw new IllegalArgumentException("moveTaskToRootTask: Attempt to move task "
2457                             + taskId + " to rootTask " + rootTaskId);
2458                 }
2459                 task.reparent(rootTask, toTop, REPARENT_KEEP_ROOT_TASK_AT_FRONT, ANIMATE,
2460                         !DEFER_RESUME, "moveTaskToRootTask");
2461             } finally {
2462                 Binder.restoreCallingIdentity(ident);
2463             }
2464         }
2465     }
2466 
2467     /**
2468      * Removes root tasks in the input windowing modes from the system if they are of activity type
2469      * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2470      */
2471     @Override
removeRootTasksInWindowingModes(int[] windowingModes)2472     public void removeRootTasksInWindowingModes(int[] windowingModes) {
2473         enforceTaskPermission("removeRootTasksInWindowingModes()");
2474 
2475         synchronized (mGlobalLock) {
2476             final long ident = Binder.clearCallingIdentity();
2477             try {
2478                 mRootWindowContainer.removeRootTasksInWindowingModes(windowingModes);
2479             } finally {
2480                 Binder.restoreCallingIdentity(ident);
2481             }
2482         }
2483     }
2484 
2485     @Override
removeRootTasksWithActivityTypes(int[] activityTypes)2486     public void removeRootTasksWithActivityTypes(int[] activityTypes) {
2487         enforceTaskPermission("removeRootTasksWithActivityTypes()");
2488 
2489         synchronized (mGlobalLock) {
2490             final long ident = Binder.clearCallingIdentity();
2491             try {
2492                 mRootWindowContainer.removeRootTasksWithActivityTypes(activityTypes);
2493             } finally {
2494                 Binder.restoreCallingIdentity(ident);
2495             }
2496         }
2497     }
2498 
2499     @Override
getRecentTasks(int maxNum, int flags, int userId)2500     public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2501             int userId) {
2502         final int callingUid = Binder.getCallingUid();
2503         userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2504         final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
2505                 callingUid);
2506         if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_AND_UNLOCKED)) {
2507             Slog.i(TAG, "User " + userId + " is locked. Cannot load recents");
2508             return ParceledListSlice.emptyList();
2509         }
2510         mRecentTasks.loadRecentTasksIfNeeded(userId);
2511         synchronized (mGlobalLock) {
2512             return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
2513         }
2514     }
2515 
2516     @Override
getAllRootTaskInfos()2517     public List<RootTaskInfo> getAllRootTaskInfos() {
2518         enforceTaskPermission("getAllRootTaskInfos()");
2519         final long ident = Binder.clearCallingIdentity();
2520         try {
2521             synchronized (mGlobalLock) {
2522                 return mRootWindowContainer.getAllRootTaskInfos(INVALID_DISPLAY);
2523             }
2524         } finally {
2525             Binder.restoreCallingIdentity(ident);
2526         }
2527     }
2528 
2529     @Override
getRootTaskInfo(int windowingMode, int activityType)2530     public RootTaskInfo getRootTaskInfo(int windowingMode, int activityType) {
2531         enforceTaskPermission("getRootTaskInfo()");
2532         final long ident = Binder.clearCallingIdentity();
2533         try {
2534             synchronized (mGlobalLock) {
2535                 return mRootWindowContainer.getRootTaskInfo(windowingMode, activityType);
2536             }
2537         } finally {
2538             Binder.restoreCallingIdentity(ident);
2539         }
2540     }
2541 
2542     @Override
getAllRootTaskInfosOnDisplay(int displayId)2543     public List<RootTaskInfo> getAllRootTaskInfosOnDisplay(int displayId) {
2544         enforceTaskPermission("getAllRootTaskInfosOnDisplay()");
2545         final long ident = Binder.clearCallingIdentity();
2546         try {
2547             synchronized (mGlobalLock) {
2548                 return mRootWindowContainer.getAllRootTaskInfos(displayId);
2549             }
2550         } finally {
2551             Binder.restoreCallingIdentity(ident);
2552         }
2553     }
2554 
2555     @Override
getRootTaskInfoOnDisplay(int windowingMode, int activityType, int displayId)2556     public RootTaskInfo getRootTaskInfoOnDisplay(int windowingMode, int activityType,
2557             int displayId) {
2558         enforceTaskPermission("getRootTaskInfoOnDisplay()");
2559         final long ident = Binder.clearCallingIdentity();
2560         try {
2561             synchronized (mGlobalLock) {
2562                 return mRootWindowContainer.getRootTaskInfo(windowingMode, activityType, displayId);
2563             }
2564         } finally {
2565             Binder.restoreCallingIdentity(ident);
2566         }
2567     }
2568 
2569     @Override
cancelRecentsAnimation(boolean restoreHomeRootTaskPosition)2570     public void cancelRecentsAnimation(boolean restoreHomeRootTaskPosition) {
2571         enforceTaskPermission("cancelRecentsAnimation()");
2572         final long callingUid = Binder.getCallingUid();
2573         final long origId = Binder.clearCallingIdentity();
2574         try {
2575             synchronized (mGlobalLock) {
2576                 // Cancel the recents animation synchronously (do not hold the WM lock)
2577                 mWindowManager.cancelRecentsAnimation(restoreHomeRootTaskPosition
2578                         ? REORDER_MOVE_TO_ORIGINAL_POSITION
2579                         : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2580             }
2581         } finally {
2582             Binder.restoreCallingIdentity(origId);
2583         }
2584     }
2585 
2586     @Override
startSystemLockTaskMode(int taskId)2587     public void startSystemLockTaskMode(int taskId) {
2588         enforceTaskPermission("startSystemLockTaskMode");
2589         // This makes inner call to look as if it was initiated by system.
2590         final long ident = Binder.clearCallingIdentity();
2591         try {
2592             synchronized (mGlobalLock) {
2593                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2594                         MATCH_ATTACHED_TASK_ONLY);
2595                 if (task == null) {
2596                     return;
2597                 }
2598 
2599                 // When starting lock task mode the root task must be in front and focused
2600                 task.getRootTask().moveToFront("startSystemLockTaskMode");
2601                 startLockTaskMode(task, true /* isSystemCaller */);
2602             }
2603         } finally {
2604             Binder.restoreCallingIdentity(ident);
2605         }
2606     }
2607 
2608     /**
2609      * This API should be called by SystemUI only when user perform certain action to dismiss
2610      * lock task mode. We should only dismiss pinned lock task mode in this case.
2611      */
2612     @Override
stopSystemLockTaskMode()2613     public void stopSystemLockTaskMode() throws RemoteException {
2614         enforceTaskPermission("stopSystemLockTaskMode");
2615         stopLockTaskModeInternal(null, true /* isSystemCaller */);
2616     }
2617 
startLockTaskMode(@ullable Task task, boolean isSystemCaller)2618     void startLockTaskMode(@Nullable Task task, boolean isSystemCaller) {
2619         ProtoLog.w(WM_DEBUG_LOCKTASK, "startLockTaskMode: %s", task);
2620         if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2621             return;
2622         }
2623 
2624         final Task rootTask = mRootWindowContainer.getTopDisplayFocusedRootTask();
2625         if (rootTask == null || task != rootTask.getTopMostTask()) {
2626             throw new IllegalArgumentException("Invalid task, not in foreground");
2627         }
2628 
2629         // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2630         // system or a specific app.
2631         // * System-initiated requests will only start the pinned mode (screen pinning)
2632         // * App-initiated requests
2633         //   - will put the device in fully locked mode (LockTask), if the app is allowlisted
2634         //   - will start the pinned mode, otherwise
2635         final int callingUid = Binder.getCallingUid();
2636         final long ident = Binder.clearCallingIdentity();
2637         try {
2638             getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
2639         } finally {
2640             Binder.restoreCallingIdentity(ident);
2641         }
2642     }
2643 
stopLockTaskModeInternal(@ullable IBinder token, boolean isSystemCaller)2644     void stopLockTaskModeInternal(@Nullable IBinder token, boolean isSystemCaller) {
2645         final int callingUid = Binder.getCallingUid();
2646         final long ident = Binder.clearCallingIdentity();
2647         try {
2648             synchronized (mGlobalLock) {
2649                 Task task = null;
2650                 if (token != null) {
2651                     final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2652                     if (r == null) {
2653                         return;
2654                     }
2655                     task = r.getTask();
2656                 }
2657                 // If {@code isSystemCaller} is {@code true}, it means the user intends to stop
2658                 // pinned mode through UI; otherwise, it's called by an app and we need to stop
2659                 // locked or pinned mode, subject to checks.
2660                 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
2661             }
2662             // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2663             // task and jumping straight into a call in the case of emergency call back.
2664             TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2665             if (tm != null) {
2666                 tm.showInCallScreen(false);
2667             }
2668         } finally {
2669             Binder.restoreCallingIdentity(ident);
2670         }
2671     }
2672 
2673     @Override
updateLockTaskPackages(int userId, String[] packages)2674     public void updateLockTaskPackages(int userId, String[] packages) {
2675         final int callingUid = Binder.getCallingUid();
2676         if (callingUid != 0 && callingUid != SYSTEM_UID) {
2677             mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2678                     "updateLockTaskPackages()");
2679         }
2680         final long origId = Binder.clearCallingIdentity();
2681         try {
2682             synchronized (mGlobalLock) {
2683                 ProtoLog.w(WM_DEBUG_LOCKTASK, "Allowlisting %d:%s", userId,
2684                         Arrays.toString(packages));
2685                 getLockTaskController().updateLockTaskPackages(userId, packages);
2686             }
2687         } finally {
2688             Binder.restoreCallingIdentity(origId);
2689         }
2690     }
2691 
2692     @Override
isInLockTaskMode()2693     public boolean isInLockTaskMode() {
2694         return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2695     }
2696 
2697     @Override
getLockTaskModeState()2698     public int getLockTaskModeState() {
2699         return getLockTaskController().getLockTaskModeState();
2700     }
2701 
2702     @Override
getAppTasks(String callingPackage)2703     public List<IBinder> getAppTasks(String callingPackage) {
2704         assertPackageMatchesCallingUid(callingPackage);
2705         return getAppTasks(callingPackage, Binder.getCallingUid());
2706     }
2707 
getAppTasks(String pkgName, int uid)2708     private List<IBinder> getAppTasks(String pkgName, int uid) {
2709         final long ident = Binder.clearCallingIdentity();
2710         try {
2711             synchronized (mGlobalLock) {
2712                 return mRecentTasks.getAppTasksList(uid, pkgName);
2713             }
2714         } finally {
2715             Binder.restoreCallingIdentity(ident);
2716         }
2717     }
2718 
2719     @Override
finishVoiceTask(IVoiceInteractionSession session)2720     public void finishVoiceTask(IVoiceInteractionSession session) {
2721         synchronized (mGlobalLock) {
2722             final long origId = Binder.clearCallingIdentity();
2723             try {
2724                 // TODO: VI Consider treating local voice interactions and voice tasks
2725                 // differently here
2726                 mRootWindowContainer.finishVoiceTask(session);
2727             } finally {
2728                 Binder.restoreCallingIdentity(origId);
2729             }
2730         }
2731 
2732     }
2733 
2734     @Override
reportAssistContextExtras(IBinder assistToken, Bundle extras, AssistStructure structure, AssistContent content, Uri referrer)2735     public void reportAssistContextExtras(IBinder assistToken, Bundle extras,
2736             AssistStructure structure, AssistContent content, Uri referrer) {
2737         final PendingAssistExtras pae = (PendingAssistExtras) assistToken;
2738         synchronized (pae) {
2739             pae.result = extras;
2740             pae.structure = structure;
2741             pae.content = content;
2742             if (referrer != null) {
2743                 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2744             }
2745             if (!pae.activity.isAttached()) {
2746                 // Skip directly because the caller activity may have been destroyed. If a caller
2747                 // is waiting for the assist data, it will be notified by timeout
2748                 // (see PendingAssistExtras#run()) and then pendingAssistExtrasTimedOut will clean
2749                 // up the request.
2750                 return;
2751             }
2752             if (structure != null) {
2753                 // Pre-fill the task/activity component for all assist data receivers
2754                 structure.setTaskId(pae.activity.getTask().mTaskId);
2755                 structure.setActivityComponent(pae.activity.mActivityComponent);
2756                 structure.setHomeActivity(pae.isHome);
2757             }
2758             pae.haveResult = true;
2759             pae.notifyAll();
2760             if (pae.intent == null && pae.receiver == null) {
2761                 // Caller is just waiting for the result.
2762                 return;
2763             }
2764         }
2765         // We are now ready to launch the assist activity.
2766         IAssistDataReceiver sendReceiver = null;
2767         Bundle sendBundle = null;
2768         synchronized (mGlobalLock) {
2769             buildAssistBundleLocked(pae, extras);
2770             boolean exists = mPendingAssistExtras.remove(pae);
2771             mUiHandler.removeCallbacks(pae);
2772             if (!exists) {
2773                 // Timed out.
2774                 return;
2775             }
2776 
2777             if ((sendReceiver = pae.receiver) != null) {
2778                 // Caller wants result sent back to them.
2779                 sendBundle = new Bundle();
2780                 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
2781                         pae.activity.getTask().mTaskId);
2782                 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
2783                         pae.activity.assistToken);
2784                 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2785                 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2786                 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2787                 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2788             }
2789         }
2790         if (sendReceiver != null) {
2791             try {
2792                 sendReceiver.onHandleAssistData(sendBundle);
2793             } catch (RemoteException e) {
2794             }
2795             return;
2796         }
2797 
2798         final long ident = Binder.clearCallingIdentity();
2799         try {
2800             pae.intent.replaceExtras(pae.extras);
2801             pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2802                     | Intent.FLAG_ACTIVITY_SINGLE_TOP
2803                     | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2804             mInternal.closeSystemDialogs("assist");
2805 
2806             try {
2807                 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2808             } catch (ActivityNotFoundException e) {
2809                 Slog.w(TAG, "No activity to handle assist action.", e);
2810             }
2811         } finally {
2812             Binder.restoreCallingIdentity(ident);
2813         }
2814     }
2815 
2816     @Override
addAppTask(IBinder activityToken, Intent intent, ActivityManager.TaskDescription description, Bitmap thumbnail)2817     public int addAppTask(IBinder activityToken, Intent intent,
2818             ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2819         final int callingUid = Binder.getCallingUid();
2820         final long callingIdent = Binder.clearCallingIdentity();
2821 
2822         try {
2823             synchronized (mGlobalLock) {
2824                 ActivityRecord r = ActivityRecord.isInRootTaskLocked(activityToken);
2825                 if (r == null) {
2826                     throw new IllegalArgumentException("Activity does not exist; token="
2827                             + activityToken);
2828                 }
2829                 ComponentName comp = intent.getComponent();
2830                 if (comp == null) {
2831                     throw new IllegalArgumentException("Intent " + intent
2832                             + " must specify explicit component");
2833                 }
2834                 if (thumbnail.getWidth() != mThumbnailWidth
2835                         || thumbnail.getHeight() != mThumbnailHeight) {
2836                     throw new IllegalArgumentException("Bad thumbnail size: got "
2837                             + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
2838                             + mThumbnailWidth + "x" + mThumbnailHeight);
2839                 }
2840                 if (intent.getSelector() != null) {
2841                     intent.setSelector(null);
2842                 }
2843                 if (intent.getSourceBounds() != null) {
2844                     intent.setSourceBounds(null);
2845                 }
2846                 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2847                     if ((intent.getFlags() & Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2848                         // The caller has added this as an auto-remove task...  that makes no
2849                         // sense, so turn off auto-remove.
2850                         intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2851                     }
2852                 }
2853                 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2854                         STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2855                 if (ainfo == null || ainfo.applicationInfo.uid != callingUid) {
2856                     Slog.e(TAG, "Can't add task for another application: target uid="
2857                             + (ainfo == null ? Process.INVALID_UID : ainfo.applicationInfo.uid)
2858                             + ", calling uid=" + callingUid);
2859                     return INVALID_TASK_ID;
2860                 }
2861 
2862                 final Task rootTask = r.getRootTask();
2863                 final Task task = new Task.Builder(this)
2864                         .setWindowingMode(rootTask.getWindowingMode())
2865                         .setActivityType(rootTask.getActivityType())
2866                         .setActivityInfo(ainfo)
2867                         .setIntent(intent)
2868                         .setTaskId(rootTask.getDisplayArea().getNextRootTaskId())
2869                         .build();
2870 
2871                 if (!mRecentTasks.addToBottom(task)) {
2872                     // The app has too many tasks already and we can't add any more
2873                     rootTask.removeChild(task, "addAppTask");
2874                     return INVALID_TASK_ID;
2875                 }
2876                 task.getTaskDescription().copyFrom(description);
2877 
2878                 // TODO: Send the thumbnail to WM to store it.
2879 
2880                 return task.mTaskId;
2881             }
2882         } finally {
2883             Binder.restoreCallingIdentity(callingIdent);
2884         }
2885     }
2886 
2887     @Override
getAppTaskThumbnailSize()2888     public Point getAppTaskThumbnailSize() {
2889         synchronized (mGlobalLock) {
2890             return new Point(mThumbnailWidth, mThumbnailHeight);
2891         }
2892     }
2893 
2894     @Override
setTaskResizeable(int taskId, int resizeableMode)2895     public void setTaskResizeable(int taskId, int resizeableMode) {
2896         synchronized (mGlobalLock) {
2897             final Task task = mRootWindowContainer.anyTaskForId(
2898                     taskId, MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
2899             if (task == null) {
2900                 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2901                 return;
2902             }
2903             task.setResizeMode(resizeableMode);
2904         }
2905     }
2906 
2907     @Override
resizeTask(int taskId, Rect bounds, int resizeMode)2908     public void resizeTask(int taskId, Rect bounds, int resizeMode) {
2909         enforceTaskPermission("resizeTask()");
2910         final long ident = Binder.clearCallingIdentity();
2911         try {
2912             synchronized (mGlobalLock) {
2913                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2914                         MATCH_ATTACHED_TASK_ONLY);
2915                 if (task == null) {
2916                     Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2917                     return;
2918                 }
2919                 if (!task.getWindowConfiguration().canResizeTask()) {
2920                     Slog.w(TAG, "resizeTask not allowed on task=" + task);
2921                     return;
2922                 }
2923 
2924                 // Reparent the task to the right root task if necessary
2925                 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2926 
2927                 if (!getTransitionController().isShellTransitionsEnabled()) {
2928                     // After reparenting (which only resizes the task to the root task bounds),
2929                     // resize the task to the actual bounds provided
2930                     task.resize(bounds, resizeMode, preserveWindow);
2931                     return;
2932                 }
2933 
2934                 final Transition transition = new Transition(TRANSIT_CHANGE, 0 /* flags */,
2935                         getTransitionController(), mWindowManager.mSyncEngine);
2936                 getTransitionController().startCollectOrQueue(transition,
2937                         (deferred) -> {
2938                             if (deferred && !task.getWindowConfiguration().canResizeTask()) {
2939                                 Slog.w(TAG, "resizeTask not allowed on task=" + task);
2940                                 transition.abort();
2941                                 return;
2942                             }
2943                             getTransitionController().requestStartTransition(transition, task,
2944                                     null /* remoteTransition */, null /* displayChange */);
2945                             getTransitionController().collect(task);
2946                             task.resize(bounds, resizeMode, preserveWindow);
2947                             transition.setReady(task, true);
2948                         });
2949             }
2950         } finally {
2951             Binder.restoreCallingIdentity(ident);
2952         }
2953     }
2954 
2955     @Override
releaseSomeActivities(IApplicationThread appInt)2956     public void releaseSomeActivities(IApplicationThread appInt) {
2957         synchronized (mGlobalLock) {
2958             final long origId = Binder.clearCallingIdentity();
2959             try {
2960                 final WindowProcessController app = getProcessController(appInt);
2961                 app.releaseSomeActivities("low-mem");
2962             } finally {
2963                 Binder.restoreCallingIdentity(origId);
2964             }
2965         }
2966     }
2967 
2968     @Override
setLockScreenShown(boolean keyguardShowing, boolean aodShowing)2969     public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
2970         if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
2971                 != PackageManager.PERMISSION_GRANTED) {
2972             throw new SecurityException("Requires permission "
2973                     + android.Manifest.permission.DEVICE_POWER);
2974         }
2975 
2976         synchronized (mGlobalLock) {
2977             final long ident = Binder.clearCallingIdentity();
2978             if (mKeyguardShown != keyguardShowing) {
2979                 mKeyguardShown = keyguardShowing;
2980                 final Message msg = PooledLambda.obtainMessage(
2981                         ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
2982                         keyguardShowing);
2983                 mH.sendMessage(msg);
2984             }
2985             // Always reset the state regardless of keyguard-showing change, because that means the
2986             // unlock is either completed or canceled.
2987             if ((mDemoteTopAppReasons & DEMOTE_TOP_REASON_DURING_UNLOCKING) != 0) {
2988                 mDemoteTopAppReasons &= ~DEMOTE_TOP_REASON_DURING_UNLOCKING;
2989                 // The scheduling group of top process was demoted by unlocking, so recompute
2990                 // to restore its real top priority if possible.
2991                 if (mTopApp != null) {
2992                     mTopApp.scheduleUpdateOomAdj();
2993                 }
2994             }
2995             try {
2996                 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "setLockScreenShown");
2997                 mRootWindowContainer.forAllDisplays(displayContent -> {
2998                     mKeyguardController.setKeyguardShown(displayContent.getDisplayId(),
2999                             keyguardShowing, aodShowing);
3000                 });
3001                 maybeHideLockedProfileActivityLocked();
3002             } finally {
3003                 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
3004                 Binder.restoreCallingIdentity(ident);
3005             }
3006         }
3007 
3008         mH.post(() -> {
3009             for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3010                 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3011             }
3012         });
3013     }
3014 
3015     /**
3016      * Hides locked profile activity by going to home screen to avoid showing the user two lock
3017      * screens in a row.
3018      */
3019     @GuardedBy("mGlobalLock")
maybeHideLockedProfileActivityLocked()3020     private void maybeHideLockedProfileActivityLocked() {
3021         if (!mKeyguardController.isKeyguardLocked(DEFAULT_DISPLAY)
3022                 || mLastResumedActivity == null) {
3023             return;
3024         }
3025         var userInfo = getUserManager().getUserInfo(mLastResumedActivity.mUserId);
3026         if (userInfo == null || !userInfo.isManagedProfile()) {
3027             return;
3028         }
3029         if (mAmInternal.shouldConfirmCredentials(mLastResumedActivity.mUserId)) {
3030             mInternal.startHomeActivity(
3031                     mAmInternal.getCurrentUserId(), "maybeHideLockedProfileActivityLocked");
3032         }
3033     }
3034 
3035     // The caller MUST NOT hold the global lock.
onScreenAwakeChanged(boolean isAwake)3036     public void onScreenAwakeChanged(boolean isAwake) {
3037         mH.post(() -> {
3038             for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3039                 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3040             }
3041         });
3042 
3043         if (isAwake) {
3044             return;
3045         }
3046         // If the device is going to sleep, keep a higher priority temporarily for potential
3047         // animation of system UI. Even if AOD is not enabled, it should be no harm.
3048         final WindowProcessController proc;
3049         synchronized (mGlobalLockWithoutBoost) {
3050             mDemoteTopAppReasons &= ~DEMOTE_TOP_REASON_DURING_UNLOCKING;
3051             final WindowState notificationShade = mRootWindowContainer.getDefaultDisplay()
3052                     .getDisplayPolicy().getNotificationShade();
3053             proc = notificationShade != null ? notificationShade.getProcess() : null;
3054         }
3055         setProcessAnimatingWhileDozing(proc);
3056     }
3057 
3058     // The caller MUST NOT hold the global lock because it calls AM method directly.
setProcessAnimatingWhileDozing(WindowProcessController proc)3059     void setProcessAnimatingWhileDozing(WindowProcessController proc) {
3060         if (proc == null) return;
3061         // Set to activity manager directly to make sure the state can be seen by the subsequent
3062         // update of scheduling group.
3063         proc.setRunningAnimationUnsafe();
3064         mH.sendMessage(mH.obtainMessage(H.ADD_WAKEFULNESS_ANIMATING_REASON, proc));
3065         mH.removeMessages(H.REMOVE_WAKEFULNESS_ANIMATING_REASON, proc);
3066         mH.sendMessageDelayed(mH.obtainMessage(H.REMOVE_WAKEFULNESS_ANIMATING_REASON, proc),
3067                 DOZE_ANIMATING_STATE_RETAIN_TIME_MS);
3068         Trace.instant(TRACE_TAG_WINDOW_MANAGER, "requestWakefulnessAnimating");
3069     }
3070 
3071     @Override
getTaskDescriptionIcon(String filePath, int userId)3072     public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
3073         final int callingUid = Binder.getCallingUid();
3074         // Verify that the caller can make the request for the given userId
3075         userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
3076                 "getTaskDescriptionIcon");
3077         synchronized (mGlobalLock) {
3078             // Verify that the caller can make the request for given icon file path
3079             final ActivityRecord matchingActivity = mRootWindowContainer.getActivity(
3080                     r -> {
3081                         if (r.taskDescription == null
3082                                 || r.taskDescription.getIconFilename() == null) {
3083                             return false;
3084                         }
3085                         return r.taskDescription.getIconFilename().equals(filePath);
3086                     });
3087             if (matchingActivity == null || (matchingActivity.getUid() != callingUid)) {
3088                 // Caller UID doesn't match the requested Activity's UID, check if caller is
3089                 // privileged
3090                 try {
3091                     enforceActivityTaskPermission("getTaskDescriptionIcon");
3092                 } catch (SecurityException e) {
3093                     Slog.w(TAG, "getTaskDescriptionIcon(): request (callingUid=" + callingUid
3094                             + ", filePath=" + filePath + ", user=" + userId + ") doesn't match any "
3095                             + "activity");
3096                     throw e;
3097                 }
3098             }
3099         }
3100 
3101         final File passedIconFile = new File(filePath);
3102         final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3103                 passedIconFile.getName());
3104         if (!legitIconFile.getPath().equals(filePath)
3105                 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3106             throw new IllegalArgumentException("Bad file path: " + filePath
3107                     + " passed for userId " + userId);
3108         }
3109         return mRecentTasks.getTaskDescriptionIcon(filePath);
3110     }
3111 
3112     @Override
moveRootTaskToDisplay(int taskId, int displayId)3113     public void moveRootTaskToDisplay(int taskId, int displayId) {
3114         mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveRootTaskToDisplay()");
3115 
3116         synchronized (mGlobalLock) {
3117             final long ident = Binder.clearCallingIdentity();
3118             try {
3119                 ProtoLog.d(WM_DEBUG_TASKS, "moveRootTaskToDisplay: moving taskId=%d to "
3120                         + "displayId=%d", taskId, displayId);
3121                 mRootWindowContainer.moveRootTaskToDisplay(taskId, displayId, ON_TOP);
3122             } finally {
3123                 Binder.restoreCallingIdentity(ident);
3124             }
3125         }
3126     }
3127 
3128     /** Sets the task stack listener that gets callbacks when a task stack changes. */
3129     @Override
registerTaskStackListener(ITaskStackListener listener)3130     public void registerTaskStackListener(ITaskStackListener listener) {
3131         enforceTaskPermission("registerTaskStackListener()");
3132         mTaskChangeNotificationController.registerTaskStackListener(listener);
3133     }
3134 
3135     /** Unregister a task stack listener so that it stops receiving callbacks. */
3136     @Override
unregisterTaskStackListener(ITaskStackListener listener)3137     public void unregisterTaskStackListener(ITaskStackListener listener) {
3138         enforceTaskPermission("unregisterTaskStackListener()");
3139         mTaskChangeNotificationController.unregisterTaskStackListener(listener);
3140     }
3141 
3142     @Override
requestAssistContextExtras(int requestType, IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken, boolean checkActivityIsTop, boolean newSessionId)3143     public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3144             Bundle receiverExtras, IBinder activityToken, boolean checkActivityIsTop,
3145             boolean newSessionId) {
3146         return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3147                 activityToken, checkActivityIsTop, newSessionId, UserHandle.getCallingUserId(),
3148                 null, PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3149     }
3150 
3151     @Override
requestAssistDataForTask(IAssistDataReceiver receiver, int taskId, String callingPackageName, @Nullable String callingAttributionTag)3152     public boolean requestAssistDataForTask(IAssistDataReceiver receiver, int taskId,
3153             String callingPackageName, @Nullable String callingAttributionTag) {
3154         mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
3155                 "requestAssistDataForTask()");
3156         final long callingId = Binder.clearCallingIdentity();
3157         LocalService.ActivityTokens tokens = null;
3158         try {
3159             tokens = mInternal.getAttachedNonFinishingActivityForTask(taskId, null);
3160         } finally {
3161             Binder.restoreCallingIdentity(callingId);
3162         }
3163         if (tokens == null) {
3164             Log.e(TAG, "Could not find activity for task " + taskId);
3165             return false;
3166         }
3167 
3168         final AssistDataReceiverProxy proxy =
3169                 new AssistDataReceiverProxy(receiver, callingPackageName);
3170         Object lock = new Object();
3171         AssistDataRequester requester = new AssistDataRequester(mContext, mWindowManager,
3172                 getAppOpsManager(), proxy, lock, AppOpsManager.OP_ASSIST_STRUCTURE,
3173                 AppOpsManager.OP_NONE);
3174 
3175         List<IBinder> topActivityToken = new ArrayList<>();
3176         topActivityToken.add(tokens.getActivityToken());
3177         requester.requestAssistData(topActivityToken, true /* fetchData */,
3178                 false /* fetchScreenshot */, false /* fetchStructure */, true /* allowFetchData */,
3179                 false /* allowFetchScreenshot*/, true /* ignoreFocusCheck */,
3180                 Binder.getCallingUid(), callingPackageName, callingAttributionTag);
3181 
3182         return true;
3183     }
3184 
3185     @Override
requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken, int flags)3186     public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3187             IBinder activityToken, int flags) {
3188         return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3189                 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3190                 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3191     }
3192 
3193     @Override
getAssistContextExtras(int requestType)3194     public Bundle getAssistContextExtras(int requestType) {
3195         PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3196                 null, null, true /* checkActivityIsTop */, true /* newSessionId */,
3197                 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3198         if (pae == null) {
3199             return null;
3200         }
3201         synchronized (pae) {
3202             while (!pae.haveResult) {
3203                 try {
3204                     pae.wait();
3205                 } catch (InterruptedException e) {
3206                 }
3207             }
3208         }
3209         synchronized (mGlobalLock) {
3210             buildAssistBundleLocked(pae, pae.result);
3211             mPendingAssistExtras.remove(pae);
3212             mUiHandler.removeCallbacks(pae);
3213         }
3214         return pae.extras;
3215     }
3216 
3217     /**
3218      * Binder IPC calls go through the public entry point.
3219      * This can be called with or without the global lock held.
3220      */
checkCallingPermission(String permission)3221     private static int checkCallingPermission(String permission) {
3222         return checkPermission(
3223                 permission, Binder.getCallingPid(), Binder.getCallingUid());
3224     }
3225 
3226     /**
3227      * Returns true if the app can close system dialogs. Otherwise it either throws a {@link
3228      * SecurityException} or returns false with a logcat message depending on whether the app
3229      * targets SDK level {@link android.os.Build.VERSION_CODES#S} or not.
3230      */
checkCanCloseSystemDialogs(int pid, int uid, @Nullable String packageName)3231     boolean checkCanCloseSystemDialogs(int pid, int uid, @Nullable String packageName) {
3232         final WindowProcessController process;
3233         synchronized (mGlobalLock) {
3234             process = mProcessMap.getProcess(pid);
3235         }
3236         if (packageName == null && process != null) {
3237             // WindowProcessController.mInfo is final, so after the synchronized memory barrier
3238             // above, process.mInfo can't change. As for reading mInfo.packageName,
3239             // WindowProcessController doesn't own the ApplicationInfo object referenced by mInfo.
3240             // ProcessRecord for example also holds a reference to that object, so protecting access
3241             // to packageName with the WM lock would not be enough as we'd also need to synchronize
3242             // on the AM lock if we are worried about races, but we can't synchronize on AM lock
3243             // here. Hence, since this is only used for logging, we don't synchronize here.
3244             packageName = process.mInfo.packageName;
3245         }
3246         String caller = "(pid=" + pid + ", uid=" + uid + ")";
3247         if (packageName != null) {
3248             caller = packageName + " " + caller;
3249         }
3250         if (!canCloseSystemDialogs(pid, uid)) {
3251             // The app can't close system dialogs, throw only if it targets S+
3252             if (CompatChanges.isChangeEnabled(LOCK_DOWN_CLOSE_SYSTEM_DIALOGS, uid)) {
3253                 throw new SecurityException(
3254                         "Permission Denial: " + Intent.ACTION_CLOSE_SYSTEM_DIALOGS
3255                                 + " broadcast from " + caller + " requires "
3256                                 + Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS + ".");
3257             } else if (CompatChanges.isChangeEnabled(DROP_CLOSE_SYSTEM_DIALOGS, uid)) {
3258                 Slog.e(TAG,
3259                         "Permission Denial: " + Intent.ACTION_CLOSE_SYSTEM_DIALOGS
3260                                 + " broadcast from " + caller + " requires "
3261                                 + Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS
3262                                 + ", dropping broadcast.");
3263                 return false;
3264             } else {
3265                 Slog.w(TAG, Intent.ACTION_CLOSE_SYSTEM_DIALOGS
3266                         + " broadcast from " + caller + " will require "
3267                         + Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS
3268                         + " in future builds.");
3269                 return true;
3270             }
3271         }
3272         return true;
3273     }
3274 
canCloseSystemDialogs(int pid, int uid)3275     private boolean canCloseSystemDialogs(int pid, int uid) {
3276         if (checkPermission(Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS, pid, uid)
3277                 == PERMISSION_GRANTED) {
3278             return true;
3279         }
3280         synchronized (mGlobalLock) {
3281             // Check all the processes from the given uid, especially since for PendingIntents sent
3282             // the pid equals -1
3283             ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
3284             if (processes != null) {
3285                 for (int i = 0, n = processes.size(); i < n; i++) {
3286                     WindowProcessController process = processes.valueAt(i);
3287                     // Check if the instrumentation of the process has the permission. This covers
3288                     // the usual test started from the shell (which has the permission) case. This
3289                     // is needed for apps targeting SDK level < S but we are also allowing for
3290                     // targetSdk S+ as a convenience to avoid breaking a bunch of existing tests and
3291                     // asking them to adopt shell permissions to do this.
3292                     int sourceUid = process.getInstrumentationSourceUid();
3293                     if (process.isInstrumenting() && sourceUid != -1 && checkPermission(
3294                             Manifest.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS, -1, sourceUid)
3295                             == PERMISSION_GRANTED) {
3296                         return true;
3297                     }
3298                     // This is the notification trampoline use-case for example, where apps use
3299                     // Intent.ACSD to close the shade prior to starting an activity.
3300                     if (process.canCloseSystemDialogsByToken()) {
3301                         return true;
3302                     }
3303                 }
3304             }
3305             if (!CompatChanges.isChangeEnabled(LOCK_DOWN_CLOSE_SYSTEM_DIALOGS, uid)) {
3306                 // This covers the case where the app is displaying some UI on top of the
3307                 // notification shade and wants to start an activity. The app then sends the intent
3308                 // in order to move the notification shade out of the way and show the activity to
3309                 // the user. This is fine since the caller already has privilege to show a visible
3310                 // window on top of the notification shade, so it can already prevent the user from
3311                 // accessing the shade if it wants to. We only allow for targetSdk < S, for S+ we
3312                 // automatically collapse the shade on startActivity() for these apps.
3313                 // It's ok that the owner of the shade is not allowed *per this rule* because it has
3314                 // BROADCAST_CLOSE_SYSTEM_DIALOGS (SystemUI), so it would fall into that rule.
3315                 if (mRootWindowContainer.hasVisibleWindowAboveButDoesNotOwnNotificationShade(uid)) {
3316                     return true;
3317                 }
3318                 // Accessibility services are allowed to send the intent unless they are targeting
3319                 // S+, in which case they should use {@link AccessibilityService
3320                 // #GLOBAL_ACTION_DISMISS_NOTIFICATION_SHADE} to dismiss the notification shade.
3321                 if (ArrayUtils.contains(mAccessibilityServiceUids, uid)) {
3322                     return true;
3323                 }
3324             }
3325         }
3326         return false;
3327     }
3328 
3329     /**
3330      * An instance method that's easier for mocking in tests.
3331      */
enforceActivityTaskPermission(String func)3332     void enforceActivityTaskPermission(String func) {
3333         enforceTaskPermission(func);
3334     }
3335 
enforceTaskPermission(String func)3336     static void enforceTaskPermission(String func) {
3337         if (checkCallingPermission(MANAGE_ACTIVITY_TASKS) == PackageManager.PERMISSION_GRANTED) {
3338             return;
3339         }
3340 
3341         if (checkCallingPermission(MANAGE_ACTIVITY_STACKS) == PackageManager.PERMISSION_GRANTED) {
3342             Slog.w(TAG, "MANAGE_ACTIVITY_STACKS is deprecated, "
3343                     + "please use alternative permission: MANAGE_ACTIVITY_TASKS");
3344             return;
3345         }
3346 
3347         String msg = "Permission Denial: " + func + " from pid=" + Binder.getCallingPid() + ", uid="
3348                 + Binder.getCallingUid() + " requires android.permission.MANAGE_ACTIVITY_TASKS";
3349         Slog.w(TAG, msg);
3350         throw new SecurityException(msg);
3351     }
3352 
checkPermission(String permission, int pid, int uid)3353     static int checkPermission(String permission, int pid, int uid) {
3354         if (permission == null) {
3355             return PackageManager.PERMISSION_DENIED;
3356         }
3357         return checkComponentPermission(permission, pid, uid, -1, true);
3358     }
3359 
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)3360     public static int checkComponentPermission(String permission, int pid, int uid,
3361             int owningUid, boolean exported) {
3362         return ActivityManagerService.checkComponentPermission(
3363                 permission, pid, uid, owningUid, exported);
3364     }
3365 
isCallerRecents(int callingUid)3366     boolean isCallerRecents(int callingUid) {
3367         return mRecentTasks.isCallerRecents(callingUid);
3368     }
3369 
isGetTasksAllowed(String caller, int callingPid, int callingUid)3370     boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3371         if (isCallerRecents(callingUid)) {
3372             // Always allow the recents component to get tasks
3373             return true;
3374         }
3375 
3376         boolean allowed = checkPermission(android.Manifest.permission.REAL_GET_TASKS,
3377                 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3378         if (!allowed) {
3379             if (checkPermission(android.Manifest.permission.GET_TASKS,
3380                     callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3381                 // Temporary compatibility: some existing apps on the system image may
3382                 // still be requesting the old permission and not switched to the new
3383                 // one; if so, we'll still allow them full access.  This means we need
3384                 // to see if they are holding the old permission and are a system app.
3385                 try {
3386                     if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3387                         allowed = true;
3388                         ProtoLog.w(WM_DEBUG_TASKS,
3389                                 "%s: caller %d is using old GET_TASKS but privileged; allowing",
3390                                 caller, callingUid);
3391                     }
3392                 } catch (RemoteException e) {
3393                 }
3394             }
3395             ProtoLog.w(WM_DEBUG_TASKS,
3396                     "%s: caller %d does not hold REAL_GET_TASKS; limiting output", caller,
3397                     callingUid);
3398         }
3399         return allowed;
3400     }
3401 
isCrossUserAllowed(int pid, int uid)3402     boolean isCrossUserAllowed(int pid, int uid) {
3403         return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3404                 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3405     }
3406 
enqueueAssistContext(int requestType, Intent intent, String hint, IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken, boolean checkActivityIsTop, boolean newSessionId, int userHandle, Bundle args, long timeout, int flags)3407     private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3408             IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3409             boolean checkActivityIsTop, boolean newSessionId, int userHandle, Bundle args,
3410             long timeout, int flags) {
3411         mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
3412                 "enqueueAssistContext()");
3413 
3414         synchronized (mGlobalLock) {
3415             final Task rootTask = getTopDisplayFocusedRootTask();
3416             ActivityRecord activity =
3417                     rootTask != null ? rootTask.getTopNonFinishingActivity() : null;
3418             if (activity == null) {
3419                 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3420                 return null;
3421             }
3422             if (!activity.attachedToProcess()) {
3423                 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3424                 return null;
3425             }
3426             if (checkActivityIsTop) {
3427                 if (activityToken != null) {
3428                     ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3429                     if (activity != caller) {
3430                         Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3431                                 + " is not current top " + activity);
3432                         return null;
3433                     }
3434                 }
3435             } else {
3436                 activity = ActivityRecord.forTokenLocked(activityToken);
3437                 if (activity == null) {
3438                     Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3439                             + " couldn't be found");
3440                     return null;
3441                 }
3442                 if (!activity.attachedToProcess()) {
3443                     Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3444                     return null;
3445                 }
3446             }
3447 
3448             PendingAssistExtras pae;
3449             Bundle extras = new Bundle();
3450             if (args != null) {
3451                 extras.putAll(args);
3452             }
3453             extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
3454             extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
3455 
3456             pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3457                     userHandle);
3458             pae.isHome = activity.isActivityTypeHome();
3459 
3460             // Increment the sessionId if necessary
3461             if (newSessionId) {
3462                 mViSessionId++;
3463             }
3464             try {
3465                 activity.app.getThread().requestAssistContextExtras(activity.token, pae,
3466                         requestType, mViSessionId, flags);
3467                 mPendingAssistExtras.add(pae);
3468                 mUiHandler.postDelayed(pae, timeout);
3469             } catch (RemoteException e) {
3470                 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3471                 return null;
3472             }
3473             return pae;
3474         }
3475     }
3476 
buildAssistBundleLocked(PendingAssistExtras pae, Bundle result)3477     private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3478         if (result != null) {
3479             pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3480         }
3481         if (pae.hint != null) {
3482             pae.extras.putBoolean(pae.hint, true);
3483         }
3484     }
3485 
pendingAssistExtrasTimedOut(PendingAssistExtras pae)3486     private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3487         IAssistDataReceiver receiver;
3488         synchronized (mGlobalLock) {
3489             mPendingAssistExtras.remove(pae);
3490             receiver = pae.receiver;
3491         }
3492         if (receiver != null) {
3493             // Caller wants result sent back to them.
3494             Bundle sendBundle = new Bundle();
3495             // At least return the receiver extras
3496             sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3497             try {
3498                 pae.receiver.onHandleAssistData(sendBundle);
3499             } catch (RemoteException e) {
3500             }
3501         }
3502     }
3503 
3504     public class PendingAssistExtras extends Binder implements Runnable {
3505         public final ActivityRecord activity;
3506         public boolean isHome;
3507         public final Bundle extras;
3508         public final Intent intent;
3509         public final String hint;
3510         public final IAssistDataReceiver receiver;
3511         public final int userHandle;
3512         public boolean haveResult = false;
3513         public Bundle result = null;
3514         public AssistStructure structure = null;
3515         public AssistContent content = null;
3516         public Bundle receiverExtras;
3517 
PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent, String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras, int _userHandle)3518         public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3519                 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3520                 int _userHandle) {
3521             activity = _activity;
3522             extras = _extras;
3523             intent = _intent;
3524             hint = _hint;
3525             receiver = _receiver;
3526             receiverExtras = _receiverExtras;
3527             userHandle = _userHandle;
3528         }
3529 
3530         @Override
run()3531         public void run() {
3532             Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3533             synchronized (this) {
3534                 haveResult = true;
3535                 notifyAll();
3536             }
3537             pendingAssistExtrasTimedOut(this);
3538         }
3539     }
3540 
3541     @Override
isAssistDataAllowed()3542     public boolean isAssistDataAllowed() {
3543         int userId;
3544         boolean hasRestrictedWindow;
3545         synchronized (mGlobalLock) {
3546             final Task focusedRootTask = getTopDisplayFocusedRootTask();
3547             if (focusedRootTask == null || focusedRootTask.isActivityTypeAssistant()) {
3548                 return false;
3549             }
3550 
3551             final ActivityRecord activity = focusedRootTask.getTopNonFinishingActivity();
3552             if (activity == null) {
3553                 return false;
3554             }
3555             userId = activity.mUserId;
3556             DisplayContent displayContent = activity.getDisplayContent();
3557             if (displayContent == null) {
3558                 return false;
3559             }
3560             final long callingIdentity = Binder.clearCallingIdentity();
3561             try {
3562                 hasRestrictedWindow = displayContent.forAllWindows(
3563                         windowState -> windowState.isOnScreen() && (
3564                                 UserManager.isUserTypePrivateProfile(
3565                                         getUserManager().getProfileType(windowState.mShowUserId))
3566                                         || hasUserRestriction(
3567                                         UserManager.DISALLOW_ASSIST_CONTENT,
3568                                         windowState.mShowUserId)), true /* traverseTopToBottom */);
3569             } finally {
3570                 Binder.restoreCallingIdentity(callingIdentity);
3571             }
3572         }
3573         return DevicePolicyCache.getInstance().isScreenCaptureAllowed(userId)
3574                 && !hasRestrictedWindow;
3575     }
3576 
onLocalVoiceInteractionStartedLocked(IBinder activity, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor)3577     private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3578             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3579         ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3580         if (activityToCallback == null) return;
3581         activityToCallback.setVoiceSessionLocked(voiceSession);
3582 
3583         // Inform the activity
3584         try {
3585             activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3586                     voiceInteractor);
3587             final long token = Binder.clearCallingIdentity();
3588             try {
3589                 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
3590             } finally {
3591                 Binder.restoreCallingIdentity(token);
3592             }
3593             // TODO: VI Should we cache the activity so that it's easier to find later
3594             // rather than scan through all the root tasks and activities?
3595         } catch (RemoteException re) {
3596             activityToCallback.clearVoiceSessionLocked();
3597             // TODO: VI Should this terminate the voice session?
3598         }
3599     }
3600 
startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid)3601     private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3602         Slog.d(TAG, "<<<  startRunningVoiceLocked()");
3603         mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3604         if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3605             boolean wasRunningVoice = mRunningVoice != null;
3606             mRunningVoice = session;
3607             if (!wasRunningVoice) {
3608                 mVoiceWakeLock.acquire();
3609                 updateSleepIfNeededLocked();
3610             }
3611         }
3612     }
3613 
finishRunningVoiceLocked()3614     void finishRunningVoiceLocked() {
3615         if (mRunningVoice != null) {
3616             mRunningVoice = null;
3617             mVoiceWakeLock.release();
3618             updateSleepIfNeededLocked();
3619         }
3620     }
3621 
3622     @Override
setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake)3623     public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3624         synchronized (mGlobalLock) {
3625             if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3626                 if (keepAwake) {
3627                     mVoiceWakeLock.acquire();
3628                 } else {
3629                     mVoiceWakeLock.release();
3630                 }
3631             }
3632         }
3633     }
3634 
3635     @Override
keyguardGoingAway(int flags)3636     public void keyguardGoingAway(int flags) {
3637         mAmInternal.enforceCallingPermission(CONTROL_KEYGUARD, "unlock keyguard");
3638         enforceNotIsolatedCaller("keyguardGoingAway");
3639         final long token = Binder.clearCallingIdentity();
3640         try {
3641             synchronized (mGlobalLock) {
3642                 // Keyguard asked us to clear the home task snapshot before going away, so do that.
3643                 if ((flags & KEYGUARD_GOING_AWAY_FLAG_TO_LAUNCHER_CLEAR_SNAPSHOT) != 0) {
3644                     mActivityClientController.invalidateHomeTaskSnapshot(null /* token */);
3645                 } else if (mKeyguardShown) {
3646                     // Only set if it is not unlocking to launcher which may also animate.
3647                     mDemoteTopAppReasons |= DEMOTE_TOP_REASON_DURING_UNLOCKING;
3648                 }
3649 
3650                 mRootWindowContainer.forAllDisplays(displayContent -> {
3651                     mKeyguardController.keyguardGoingAway(displayContent.getDisplayId(), flags);
3652                 });
3653             }
3654             WallpaperManagerInternal wallpaperManagerInternal = getWallpaperManagerInternal();
3655             if (wallpaperManagerInternal != null) {
3656                 wallpaperManagerInternal.onKeyguardGoingAway();
3657             }
3658         } finally {
3659             Binder.restoreCallingIdentity(token);
3660         }
3661     }
3662 
3663     @Override
suppressResizeConfigChanges(boolean suppress)3664     public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
3665         mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_TASKS,
3666                 "suppressResizeConfigChanges()");
3667         synchronized (mGlobalLock) {
3668             mSuppressResizeConfigChanges = suppress;
3669         }
3670     }
3671 
3672     /**
3673      * A splash screen view has copied, pass it to an activity.
3674      *
3675      * @param taskId Id of task to handle the material to reconstruct the view.
3676      * @param parcelable Used to reconstruct the view, null means the surface is un-copyable.
3677      * @hide
3678      */
3679     @Override
onSplashScreenViewCopyFinished(int taskId, @Nullable SplashScreenViewParcelable parcelable)3680     public void onSplashScreenViewCopyFinished(int taskId,
3681             @Nullable SplashScreenViewParcelable parcelable)
3682                 throws RemoteException {
3683         mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_TASKS,
3684                 "copySplashScreenViewFinish()");
3685         synchronized (mGlobalLock) {
3686             final Task task = mRootWindowContainer.anyTaskForId(taskId,
3687                     MATCH_ATTACHED_TASK_ONLY);
3688             if (task != null) {
3689                 final ActivityRecord r = task.getTopWaitSplashScreenActivity();
3690                 if (r != null) {
3691                     r.onCopySplashScreenFinish(parcelable);
3692                 }
3693             }
3694         }
3695     }
3696 
3697     /**
3698      * Prepare to enter PiP mode after {@link TransitionController#requestStartDisplayTransition}.
3699      *
3700      * @param r activity auto entering pip
3701      * @return true if the activity is about to auto-enter pip or is already in pip mode.
3702      */
prepareAutoEnterPictureAndPictureMode(ActivityRecord r)3703     boolean prepareAutoEnterPictureAndPictureMode(ActivityRecord r) {
3704         // If the activity is already in picture in picture mode, then just return early
3705         if (r.inPinnedWindowingMode()) {
3706             return true;
3707         }
3708 
3709         if (r.canAutoEnterPip() && getTransitionController().getCollectingTransition() != null) {
3710             // This will be used later to construct TransitionRequestInfo for Shell to resolve.
3711             // It will also be passed into a direct moveActivityToPinnedRootTask() call via
3712             // startTransition()
3713             getTransitionController().getCollectingTransition().setPipActivity(r);
3714             return true;
3715         }
3716         return false;
3717     }
3718 
enterPictureInPictureMode(@onNull ActivityRecord r, @NonNull PictureInPictureParams params, boolean fromClient)3719     boolean enterPictureInPictureMode(@NonNull ActivityRecord r,
3720             @NonNull PictureInPictureParams params, boolean fromClient) {
3721         return enterPictureInPictureMode(r, params, fromClient, false /* isAutoEnter */);
3722     }
3723 
3724     /**
3725      * Puts the given activity in picture in picture mode if possible.
3726      *
3727      * @param fromClient true if this comes from a client call (eg. Activity.enterPip).
3728      * @param isAutoEnter true if this comes from an automatic pip-enter.
3729      * @return true if the activity is now in picture-in-picture mode, or false if it could not
3730      * enter picture-in-picture mode.
3731      */
enterPictureInPictureMode(@onNull ActivityRecord r, @NonNull PictureInPictureParams params, boolean fromClient, boolean isAutoEnter)3732     boolean enterPictureInPictureMode(@NonNull ActivityRecord r,
3733             @NonNull PictureInPictureParams params, boolean fromClient, boolean isAutoEnter) {
3734         // If the activity is already in picture in picture mode, then just return early
3735         if (r.inPinnedWindowingMode()) {
3736             return true;
3737         }
3738 
3739         // Activity supports picture-in-picture, now check that we can enter PiP at this
3740         // point, if it is
3741         if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3742                 false /* beforeStopping */)) {
3743             return false;
3744         }
3745 
3746         // If the app is using auto-enter, and it explicitly requests entering PiP while pausing,
3747         // return false immediately since auto-enter should take in place instead.
3748         if (fromClient && r.isState(PAUSING) && params.isAutoEnterEnabled()) {
3749             Slog.w(TAG, "Skip client enterPictureInPictureMode request while pausing,"
3750                     + " auto-enter-pip is enabled");
3751             return false;
3752         }
3753 
3754         if (isPip2ExperimentEnabled()) {
3755             // If PiP2 flag is on and request to enter PiP comes in,
3756             // we request a direct transition TRANSIT_PIP from Shell to get the right entry bounds.
3757             // So PiP activity isn't moved to a pinned task until after
3758             // Shell calls back into Core with the entry bounds to be applied with startWCT.
3759             final Transition enterPipTransition = new Transition(TRANSIT_PIP,
3760                     0 /* flags */, getTransitionController(), mWindowManager.mSyncEngine);
3761             enterPipTransition.setPipActivity(r);
3762             r.mAutoEnteringPip = isAutoEnter;
3763             getTransitionController().startCollectOrQueue(enterPipTransition, (deferred) -> {
3764                 getTransitionController().requestStartTransition(enterPipTransition,
3765                         r.getTask(), null /* remoteTransition */, null /* displayChange */);
3766             });
3767             return true;
3768         }
3769 
3770         // If the app is using legacy-entry (not auto-enter), then we will get a client-request
3771         // that was actually a server-request (via pause(userLeaving=true)). This happens when
3772         // the app is PAUSING, so detect that case here.
3773         boolean originallyFromClient = fromClient
3774                 && (!r.isState(PAUSING) || params.isAutoEnterEnabled());
3775 
3776         // Create a transition only for this pip entry if it is coming from the app without the
3777         // system requesting that the app enter-pip. If the system requested it, that means it
3778         // should be part of that transition if possible.
3779         final Transition transition =
3780                 (getTransitionController().isShellTransitionsEnabled() && originallyFromClient)
3781                 ? new Transition(TRANSIT_PIP, 0 /* flags */,
3782                         getTransitionController(), mWindowManager.mSyncEngine)
3783                 : null;
3784 
3785         if (r.getTaskFragment() != null && r.getTaskFragment().isEmbeddedWithBoundsOverride()
3786                 && transition != null) {
3787             transition.addFlag(FLAG_IN_TASK_WITH_EMBEDDED_ACTIVITY);
3788         }
3789 
3790         final Runnable enterPipRunnable = () -> {
3791             synchronized (mGlobalLock) {
3792                 if (r.getParent() == null) {
3793                     Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
3794                     if (transition != null) {
3795                         transition.abort();
3796                     }
3797                     return;
3798                 }
3799                 EventLogTags.writeWmEnterPip(r.mUserId, System.identityHashCode(r),
3800                         r.shortComponentName, Boolean.toString(isAutoEnter));
3801                 r.setPictureInPictureParams(params);
3802                 r.mAutoEnteringPip = isAutoEnter;
3803                 mRootWindowContainer.moveActivityToPinnedRootTask(r,
3804                         null /* launchIntoPipHostActivity */, "enterPictureInPictureMode",
3805                         transition);
3806                 // Continue the pausing process after entering pip.
3807                 if (r.isState(PAUSING) && r.mPauseSchedulePendingForPip) {
3808                     r.getTask().schedulePauseActivity(r, false /* userLeaving */,
3809                             false /* pauseImmediately */, true /* autoEnteringPip */,
3810                             "auto-pip");
3811                 }
3812                 r.mAutoEnteringPip = false;
3813             }
3814         };
3815 
3816         if (r.isKeyguardLocked()) {
3817             // If the keyguard is showing or occluded, then try and dismiss it before
3818             // entering picture-in-picture (this will prompt the user to authenticate if the
3819             // device is currently locked).
3820             mActivityClientController.dismissKeyguard(r.token, new KeyguardDismissCallback() {
3821                 @Override
3822                 public void onDismissSucceeded() {
3823                     if (transition == null) {
3824                         mH.post(enterPipRunnable);
3825                         return;
3826                     }
3827                     getTransitionController().startCollectOrQueue(transition, (deferred) -> {
3828                         if (deferred) {
3829                             enterPipRunnable.run();
3830                         } else {
3831                             mH.post(enterPipRunnable);
3832                         }
3833                     });
3834                 }
3835             }, null /* message */);
3836         } else {
3837             // Enter picture in picture immediately otherwise
3838             if (transition != null) {
3839                 getTransitionController().startCollectOrQueue(transition,
3840                         (deferred) -> enterPipRunnable.run());
3841             } else {
3842                 enterPipRunnable.run();
3843             }
3844         }
3845         return true;
3846     }
3847 
3848     @Override
getWindowOrganizerController()3849     public IWindowOrganizerController getWindowOrganizerController() {
3850         return mWindowOrganizerController;
3851     }
3852 
3853     /**
3854      * Check that we have the features required for VR-related API calls, and throw an exception if
3855      * not.
3856      */
enforceSystemHasVrFeature()3857     public void enforceSystemHasVrFeature() {
3858         if (!mContext.getPackageManager().hasSystemFeature(
3859                 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3860             throw new UnsupportedOperationException("VR mode not supported on this device!");
3861         }
3862     }
3863 
3864     @Override
supportsLocalVoiceInteraction()3865     public boolean supportsLocalVoiceInteraction() {
3866         return LocalServices.getService(VoiceInteractionManagerInternal.class)
3867                 .supportsLocalVoiceInteraction();
3868     }
3869 
3870     @Override
updateConfiguration(Configuration values)3871     public boolean updateConfiguration(Configuration values) {
3872         mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
3873 
3874         synchronized (mGlobalLock) {
3875             if (mWindowManager == null) {
3876                 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
3877                 return false;
3878             }
3879 
3880             if (values == null) {
3881                 // sentinel: fetch the current configuration from the window manager
3882                 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
3883             }
3884 
3885             mH.sendMessage(PooledLambda.obtainMessage(
3886                     ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
3887                     DEFAULT_DISPLAY));
3888 
3889             final long origId = Binder.clearCallingIdentity();
3890             try {
3891                 if (values != null) {
3892                     Settings.System.clearConfiguration(values);
3893                 }
3894                 updateConfigurationLocked(values, null, false, false /* persistent */,
3895                         UserHandle.USER_NULL, false /* deferResume */);
3896                 return mTmpUpdateConfigurationResult.changes != 0;
3897             } finally {
3898                 Binder.restoreCallingIdentity(origId);
3899             }
3900         }
3901     }
3902 
3903     @Override
cancelTaskWindowTransition(int taskId)3904     public void cancelTaskWindowTransition(int taskId) {
3905         enforceTaskPermission("cancelTaskWindowTransition()");
3906         final long ident = Binder.clearCallingIdentity();
3907         try {
3908             synchronized (mGlobalLock) {
3909                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
3910                         MATCH_ATTACHED_TASK_ONLY);
3911                 if (task == null) {
3912                     Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
3913                     return;
3914                 }
3915                 task.cancelTaskWindowTransition();
3916             }
3917         } finally {
3918             Binder.restoreCallingIdentity(ident);
3919         }
3920     }
3921 
3922     @Override
getTaskSnapshot(int taskId, boolean isLowResolution)3923     public TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
3924         mAmInternal.enforceCallingPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
3925         final long ident = Binder.clearCallingIdentity();
3926         try {
3927             final Task task;
3928             synchronized (mGlobalLock) {
3929                 task = mRootWindowContainer.anyTaskForId(taskId,
3930                         MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
3931                 if (task == null) {
3932                     Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
3933                     return null;
3934                 }
3935             }
3936             // Don't call this while holding the lock as this operation might hit the disk.
3937             return mWindowManager.mTaskSnapshotController.getSnapshot(taskId,
3938                     task.mUserId, true /* restoreFromDisk */, isLowResolution);
3939         } finally {
3940             Binder.restoreCallingIdentity(ident);
3941         }
3942     }
3943 
3944     @Override
takeTaskSnapshot(int taskId, boolean updateCache)3945     public TaskSnapshot takeTaskSnapshot(int taskId, boolean updateCache) {
3946         mAmInternal.enforceCallingPermission(READ_FRAME_BUFFER, "takeTaskSnapshot()");
3947         final long ident = Binder.clearCallingIdentity();
3948         try {
3949             synchronized (mGlobalLock) {
3950                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
3951                         MATCH_ATTACHED_TASK_OR_RECENT_TASKS);
3952                 if (task == null || !task.isVisible()) {
3953                     Slog.w(TAG, "takeTaskSnapshot: taskId=" + taskId + " not found or not visible");
3954                     return null;
3955                 }
3956                 // Note that if updateCache is true, ActivityRecord#shouldUseAppThemeSnapshot will
3957                 // be used to decide whether the task is allowed to be captured because that may
3958                 // be retrieved by recents. While if updateCache is false, the real snapshot will
3959                 // always be taken and the snapshot won't be put into SnapshotPersister.
3960                 if (updateCache) {
3961                     return mWindowManager.mTaskSnapshotController.recordSnapshot(task);
3962                 } else {
3963                     return mWindowManager.mTaskSnapshotController.snapshot(task);
3964                 }
3965             }
3966         } finally {
3967             Binder.restoreCallingIdentity(ident);
3968         }
3969     }
3970 
3971     /** Return the user id of the last resumed activity. */
3972     @Override
3973     public @UserIdInt
getLastResumedActivityUserId()3974     int getLastResumedActivityUserId() {
3975         mAmInternal.enforceCallingPermission(
3976                 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
3977         synchronized (mGlobalLock) {
3978             if (mLastResumedActivity == null) {
3979                 return getCurrentUserId();
3980             }
3981             return mLastResumedActivity.mUserId;
3982         }
3983     }
3984 
3985     @Override
updateLockTaskFeatures(int userId, int flags)3986     public void updateLockTaskFeatures(int userId, int flags) {
3987         final int callingUid = Binder.getCallingUid();
3988         if (callingUid != 0 && callingUid != SYSTEM_UID) {
3989             mAmInternal.enforceCallingPermission(
3990                     android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3991                     "updateLockTaskFeatures()");
3992         }
3993         synchronized (mGlobalLock) {
3994             ProtoLog.w(WM_DEBUG_LOCKTASK, "Allowing features %d:0x%s",
3995                     userId, Integer.toHexString(flags));
3996             getLockTaskController().updateLockTaskFeatures(userId, flags);
3997         }
3998     }
3999 
4000     @Override
registerRemoteAnimationForNextActivityStart(String packageName, RemoteAnimationAdapter adapter, IBinder launchCookie)4001     public void registerRemoteAnimationForNextActivityStart(String packageName,
4002             RemoteAnimationAdapter adapter, IBinder launchCookie) {
4003         mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4004                 "registerRemoteAnimationForNextActivityStart");
4005         adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
4006         synchronized (mGlobalLock) {
4007             final long origId = Binder.clearCallingIdentity();
4008             try {
4009                 getActivityStartController().registerRemoteAnimationForNextActivityStart(
4010                         packageName, adapter, launchCookie);
4011             } finally {
4012                 Binder.restoreCallingIdentity(origId);
4013             }
4014         }
4015     }
4016 
4017     @Override
registerRemoteAnimationsForDisplay(int displayId, RemoteAnimationDefinition definition)4018     public void registerRemoteAnimationsForDisplay(int displayId,
4019             RemoteAnimationDefinition definition) {
4020         mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4021                 "registerRemoteAnimations");
4022         definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
4023         synchronized (mGlobalLock) {
4024             final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
4025             if (display == null) {
4026                 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4027                 return;
4028             }
4029             final long origId = Binder.clearCallingIdentity();
4030             try {
4031                 display.registerRemoteAnimations(definition);
4032             } finally {
4033                 Binder.restoreCallingIdentity(origId);
4034             }
4035         }
4036     }
4037 
4038     /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4039     @Override
alwaysShowUnsupportedCompileSdkWarning(ComponentName activity)4040     public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4041         synchronized (mGlobalLock) {
4042             final long origId = Binder.clearCallingIdentity();
4043             try {
4044                 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
4045             } finally {
4046                 Binder.restoreCallingIdentity(origId);
4047             }
4048         }
4049     }
4050 
4051     @Override
setVrThread(int tid)4052     public void setVrThread(int tid) {
4053         enforceSystemHasVrFeature();
4054         synchronized (mGlobalLock) {
4055             final int pid = Binder.getCallingPid();
4056             final WindowProcessController wpc = mProcessMap.getProcess(pid);
4057             mVrController.setVrThreadLocked(tid, pid, wpc);
4058         }
4059     }
4060 
4061     @Override
setPersistentVrThread(int tid)4062     public void setPersistentVrThread(int tid) {
4063         if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
4064                 != PERMISSION_GRANTED) {
4065             final String msg = "Permission Denial: setPersistentVrThread() from pid="
4066                     + Binder.getCallingPid()
4067                     + ", uid=" + Binder.getCallingUid()
4068                     + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4069             Slog.w(TAG, msg);
4070             throw new SecurityException(msg);
4071         }
4072         enforceSystemHasVrFeature();
4073         synchronized (mGlobalLock) {
4074             final int pid = Binder.getCallingPid();
4075             final WindowProcessController proc = mProcessMap.getProcess(pid);
4076             mVrController.setPersistentVrThreadLocked(tid, pid, proc);
4077         }
4078     }
4079 
4080     @Override
stopAppSwitches()4081     public void stopAppSwitches() {
4082         mAmInternal.enforceCallingPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4083         synchronized (mGlobalLock) {
4084             mAppSwitchesState = APP_SWITCH_DISALLOW;
4085             mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
4086             mH.removeMessages(H.RESUME_FG_APP_SWITCH_MSG);
4087             mH.sendEmptyMessageDelayed(H.RESUME_FG_APP_SWITCH_MSG, RESUME_FG_APP_SWITCH_MS);
4088         }
4089     }
4090 
4091     @Override
resumeAppSwitches()4092     public void resumeAppSwitches() {
4093         mAmInternal.enforceCallingPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4094         synchronized (mGlobalLock) {
4095             mAppSwitchesState = APP_SWITCH_ALLOW;
4096             mH.removeMessages(H.RESUME_FG_APP_SWITCH_MSG);
4097         }
4098     }
4099 
getLastStopAppSwitchesTime()4100     long getLastStopAppSwitchesTime() {
4101         return mLastStopAppSwitchesTime;
4102     }
4103 
4104     /** @return whether the system should disable UI modes incompatible with VR mode. */
shouldDisableNonVrUiLocked()4105     boolean shouldDisableNonVrUiLocked() {
4106         return mVrController.shouldDisableNonVrUiLocked();
4107     }
4108 
applyUpdateVrModeLocked(ActivityRecord r)4109     void applyUpdateVrModeLocked(ActivityRecord r) {
4110         // VR apps are expected to run in a main display. If an app is turning on VR for
4111         // itself, but isn't on the main display, then move it there before enabling VR Mode.
4112         if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4113             Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4114                     + " to main display for VR");
4115             mRootWindowContainer.moveRootTaskToDisplay(
4116                     r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
4117         }
4118         mH.post(() -> {
4119             if (!mVrController.onVrModeChanged(r)) {
4120                 return;
4121             }
4122             synchronized (mGlobalLock) {
4123                 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4124                 mWindowManager.disableNonVrUi(disableNonVrUi);
4125                 if (disableNonVrUi) {
4126                     // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4127                     // then remove the root pinned task.
4128                     mRootWindowContainer.removeRootTasksInWindowingModes(WINDOWING_MODE_PINNED);
4129                 }
4130             }
4131         });
4132     }
4133 
4134     @Override
getPackageScreenCompatMode(String packageName)4135     public int getPackageScreenCompatMode(String packageName) {
4136         enforceNotIsolatedCaller("getPackageScreenCompatMode");
4137         synchronized (mGlobalLock) {
4138             return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4139         }
4140     }
4141 
4142     @Override
setPackageScreenCompatMode(String packageName, int mode)4143     public void setPackageScreenCompatMode(String packageName, int mode) {
4144         mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4145                 "setPackageScreenCompatMode");
4146         synchronized (mGlobalLock) {
4147             mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4148         }
4149     }
4150 
4151     @Override
getPackageAskScreenCompat(String packageName)4152     public boolean getPackageAskScreenCompat(String packageName) {
4153         enforceNotIsolatedCaller("getPackageAskScreenCompat");
4154         synchronized (mGlobalLock) {
4155             return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4156         }
4157     }
4158 
4159     @Override
setPackageAskScreenCompat(String packageName, boolean ask)4160     public void setPackageAskScreenCompat(String packageName, boolean ask) {
4161         mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4162                 "setPackageAskScreenCompat");
4163         synchronized (mGlobalLock) {
4164             mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4165         }
4166     }
4167 
relaunchReasonToString(int relaunchReason)4168     public static String relaunchReasonToString(int relaunchReason) {
4169         switch (relaunchReason) {
4170             case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4171                 return "window_resize";
4172             case RELAUNCH_REASON_FREE_RESIZE:
4173                 return "free_resize";
4174             default:
4175                 return null;
4176         }
4177     }
4178 
getTopDisplayFocusedRootTask()4179     Task getTopDisplayFocusedRootTask() {
4180         return mRootWindowContainer.getTopDisplayFocusedRootTask();
4181     }
4182 
4183     /** Pokes the task persister. */
notifyTaskPersisterLocked(Task task, boolean flush)4184     void notifyTaskPersisterLocked(Task task, boolean flush) {
4185         mRecentTasks.notifyTaskPersisterLocked(task, flush);
4186     }
4187 
4188     /**
4189      * Clears launch params for the given package.
4190      *
4191      * @param packageNames the names of the packages of which the launch params are to be cleared
4192      */
4193     @Override
clearLaunchParamsForPackages(List<String> packageNames)4194     public void clearLaunchParamsForPackages(List<String> packageNames) {
4195         enforceTaskPermission("clearLaunchParamsForPackages");
4196         synchronized (mGlobalLock) {
4197             for (int i = 0; i < packageNames.size(); ++i) {
4198                 mTaskSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4199             }
4200         }
4201     }
4202 
4203     @Override
onPictureInPictureUiStateChanged(PictureInPictureUiState pipState)4204     public void onPictureInPictureUiStateChanged(PictureInPictureUiState pipState) {
4205         enforceTaskPermission("onPictureInPictureUiStateChanged");
4206         synchronized (mGlobalLock) {
4207             // The PictureInPictureUiState is sent to current pip task if there is any
4208             // -or- the top standard task (state like entering PiP does not require a pinned task).
4209             final Task task;
4210             if (mRootWindowContainer.getDefaultTaskDisplayArea().hasPinnedTask()) {
4211                 task = mRootWindowContainer.getDefaultTaskDisplayArea().getRootPinnedTask();
4212             } else {
4213                 task = mRootWindowContainer.getDefaultTaskDisplayArea().getRootTask(
4214                         t -> t.isActivityTypeStandard());
4215             }
4216             if (task != null && task.getTopMostActivity() != null
4217                     && !task.getTopMostActivity().isState(FINISHING, DESTROYING, DESTROYED)) {
4218                 mWindowManager.mAtmService.mActivityClientController
4219                         .onPictureInPictureUiStateChanged(task.getTopMostActivity(), pipState);
4220             }
4221         }
4222     }
4223 
4224     @Override
detachNavigationBarFromApp(@onNull IBinder transition)4225     public void detachNavigationBarFromApp(@NonNull IBinder transition) {
4226         mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4227                 "detachNavigationBarFromApp");
4228         final long token = Binder.clearCallingIdentity();
4229         try {
4230             synchronized (mGlobalLock) {
4231                 getTransitionController().legacyDetachNavigationBarFromApp(transition);
4232             }
4233         } finally {
4234             Binder.restoreCallingIdentity(token);
4235         }
4236     }
4237 
dumpLastANRLocked(PrintWriter pw)4238     void dumpLastANRLocked(PrintWriter pw) {
4239         pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4240         if (mLastANRState == null) {
4241             pw.println("  <no ANR has occurred since boot>");
4242         } else {
4243             pw.println(mLastANRState);
4244         }
4245     }
4246 
dumpLastANRTracesLocked(PrintWriter pw)4247     void dumpLastANRTracesLocked(PrintWriter pw) {
4248         pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4249 
4250         final File[] files = new File(ANR_TRACE_DIR).listFiles();
4251         if (ArrayUtils.isEmpty(files)) {
4252             pw.println("  <no ANR has occurred since boot>");
4253             return;
4254         }
4255         // Find the latest file.
4256         File latest = null;
4257         for (File f : files) {
4258             if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4259                 latest = f;
4260             }
4261         }
4262         pw.print("File: ");
4263         pw.print(latest.getName());
4264         pw.println();
4265         try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4266             String line;
4267             while ((line = in.readLine()) != null) {
4268                 pw.println(line);
4269             }
4270         } catch (IOException e) {
4271             pw.print("Unable to read: ");
4272             pw.print(e);
4273             pw.println();
4274         }
4275     }
4276 
dumpTopResumedActivityLocked(PrintWriter pw)4277     void dumpTopResumedActivityLocked(PrintWriter pw) {
4278         pw.println("ACTIVITY MANAGER TOP-RESUMED (dumpsys activity top-resumed)");
4279         ActivityRecord topRecord = mRootWindowContainer.getTopResumedActivity();
4280         if (topRecord != null) {
4281             topRecord.dump(pw, "", true);
4282         }
4283     }
4284 
dumpVisibleActivitiesLocked(PrintWriter pw, int displayIdFilter)4285     void dumpVisibleActivitiesLocked(PrintWriter pw, int displayIdFilter) {
4286         pw.println("ACTIVITY MANAGER VISIBLE ACTIVITIES (dumpsys activity visible)");
4287         ArrayList<ActivityRecord> activities =
4288                 mRootWindowContainer.getDumpActivities("all", /* dumpVisibleRootTasksOnly */ true,
4289                         /* dumpFocusedRootTaskOnly */ false, UserHandle.USER_ALL);
4290         boolean needSeparator = false;
4291         boolean printedAnything = false;
4292         for (int i = activities.size() - 1; i >= 0; i--) {
4293             ActivityRecord activity = activities.get(i);
4294             if (!activity.isVisible() || (displayIdFilter != INVALID_DISPLAY
4295                     && activity.getDisplayId() != displayIdFilter)) {
4296                 continue;
4297             }
4298             if (needSeparator) {
4299                 pw.println();
4300             }
4301             printedAnything = true;
4302             activity.dump(pw, "", true);
4303             needSeparator = true;
4304         }
4305         if (!printedAnything) {
4306             pw.println("(nothing)");
4307         }
4308     }
4309 
dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter)4310     void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4311             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage,
4312             int displayIdFilter) {
4313         dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage, displayIdFilter,
4314                 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4315     }
4316 
dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter, String header)4317     void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4318             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter,
4319             String header) {
4320         pw.println(header);
4321 
4322         boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
4323                 dumpPackage, displayIdFilter);
4324         boolean needSep = printedAnything;
4325 
4326         boolean printed = ActivityTaskSupervisor.printThisActivity(pw,
4327                 mRootWindowContainer.getTopResumedActivity(), dumpPackage, displayIdFilter, needSep,
4328                 "  ResumedActivity: ", /* header= */ null);
4329         if (printed) {
4330             printedAnything = true;
4331             needSep = false;
4332         }
4333 
4334         if (dumpPackage == null) {
4335             if (needSep) {
4336                 pw.println();
4337             }
4338             printedAnything = true;
4339             mTaskSupervisor.dump(pw, "  ");
4340             mTaskOrganizerController.dump(pw, "  ");
4341             mVisibleActivityProcessTracker.dump(pw, "  ");
4342             mActiveUids.dump(pw, "  ");
4343             if (mDemoteTopAppReasons != 0) {
4344                 pw.println("  mDemoteTopAppReasons=" + mDemoteTopAppReasons);
4345             }
4346             if (!mStartingProcessActivities.isEmpty()) {
4347                 pw.println("  mStartingProcessActivities=" + mStartingProcessActivities);
4348             }
4349         }
4350 
4351         if (!printedAnything) {
4352             pw.println("  (nothing)");
4353         }
4354     }
4355 
dumpActivityContainersLocked(PrintWriter pw)4356     void dumpActivityContainersLocked(PrintWriter pw) {
4357         pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
4358         mRootWindowContainer.dumpChildrenNames(pw, "");
4359         pw.println(" ");
4360     }
4361 
dumpActivityStarterLocked(PrintWriter pw, String dumpPackage)4362     void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4363         pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4364         getActivityStartController().dump(pw, "", dumpPackage);
4365     }
4366 
4367     /** Dumps installed packages having app-specific config. */
dumpInstalledPackagesConfig(PrintWriter pw)4368     void dumpInstalledPackagesConfig(PrintWriter pw) {
4369         mPackageConfigPersister.dump(pw, getCurrentUserId());
4370     }
4371 
4372     /**
4373      * There are three things that cmd can be:
4374      * - a flattened component name that matches an existing activity
4375      * - the cmd arg isn't the flattened component name of an existing activity:
4376      * dump all activity whose component contains the cmd as a substring
4377      * - A hex number of the ActivityRecord object instance.
4378      * <p>
4379      * The caller should not hold lock when calling this method because it will wait for the
4380      * activities to complete the dump.
4381      *
4382      * @param dumpVisibleRootTasksOnly dump activity with {@param name} only if in a visible root
4383      *                                 task
4384      * @param dumpFocusedRootTaskOnly  dump activity with {@param name} only if in the focused
4385      *                                 root task
4386      */
dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly, boolean dumpFocusedRootTaskOnly, int displayIdFilter, @UserIdInt int userId, long timeout)4387     protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4388             int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly,
4389             boolean dumpFocusedRootTaskOnly, int displayIdFilter, @UserIdInt int userId,
4390             long timeout) {
4391         ArrayList<ActivityRecord> activities;
4392 
4393         synchronized (mGlobalLock) {
4394             activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleRootTasksOnly,
4395                     dumpFocusedRootTaskOnly, userId);
4396         }
4397 
4398         if (activities.size() <= 0) {
4399             return false;
4400         }
4401 
4402         String[] newArgs = new String[args.length - opti];
4403         System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4404 
4405         Task lastTask = null;
4406         boolean needSep = false;
4407         boolean printedAnything = false;
4408         for (int i = activities.size() - 1; i >= 0; i--) {
4409             ActivityRecord r = activities.get(i);
4410             if (needSep) {
4411                 pw.println();
4412             }
4413             needSep = true;
4414             synchronized (mGlobalLock) {
4415                 Task task = r.getTask();
4416                 int displayId = task.getDisplayId();
4417                 if (displayIdFilter != INVALID_DISPLAY && displayId != displayIdFilter) {
4418                     continue;
4419                 }
4420                 if (lastTask != task) {
4421                     printedAnything = true;
4422                     lastTask = task;
4423                     pw.print("TASK ");
4424                     pw.print(lastTask.affinity);
4425                     pw.print(" id=");
4426                     pw.print(lastTask.mTaskId);
4427                     pw.print(" userId=");
4428                     pw.print(lastTask.mUserId);
4429                     printDisplayInfoAndNewLine(pw, r);
4430                     if (dumpAll) {
4431                         lastTask.dump(pw, "  ");
4432                     }
4433                 }
4434             }
4435             dumpActivity("  ", fd, pw, activities.get(i), newArgs, dumpAll, timeout);
4436         }
4437         if (!printedAnything) {
4438             // Typically happpens when no task matches displayIdFilter
4439             pw.println("(nothing)");
4440         }
4441         return true;
4442     }
4443 
4444     /**
4445      * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4446      * there is a thread associated with the activity.
4447      */
dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw, ActivityRecord r, String[] args, boolean dumpAll, long timeout)4448     private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4449             ActivityRecord r, String[] args, boolean dumpAll, long timeout) {
4450         String innerPrefix = prefix + "  ";
4451         IApplicationThread appThread = null;
4452         synchronized (mGlobalLock) {
4453             pw.print(prefix);
4454             pw.print("ACTIVITY ");
4455             pw.print(r.shortComponentName);
4456             pw.print(" ");
4457             pw.print(Integer.toHexString(System.identityHashCode(r)));
4458             pw.print(" pid=");
4459             if (r.hasProcess()) {
4460                 pw.print(r.app.getPid());
4461                 appThread = r.app.getThread();
4462             } else {
4463                 pw.print("(not running)");
4464             }
4465             pw.print(" userId=");
4466             pw.print(r.mUserId);
4467             pw.print(" uid=");
4468             pw.print(r.getUid());
4469             printDisplayInfoAndNewLine(pw, r);
4470             if (dumpAll) {
4471                 r.dump(pw, innerPrefix, /* dumpAll= */ true);
4472             }
4473         }
4474         if (appThread != null) {
4475             // flush anything that is already in the PrintWriter since the thread is going
4476             // to write to the file descriptor directly
4477             pw.flush();
4478             try (TransferPipe tp = new TransferPipe()) {
4479                 appThread.dumpActivity(tp.getWriteFd(), r.token, innerPrefix, args);
4480                 tp.go(fd, timeout);
4481             } catch (IOException e) {
4482                 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4483             } catch (RemoteException e) {
4484                 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4485             }
4486         }
4487     }
4488 
printDisplayInfoAndNewLine(PrintWriter pw, ActivityRecord r)4489     private void printDisplayInfoAndNewLine(PrintWriter pw, ActivityRecord r) {
4490         pw.print(" displayId=");
4491         DisplayContent displayContent = r.getDisplayContent();
4492         if (displayContent == null) {
4493             pw.println("N/A");
4494             return;
4495         }
4496         Display display = displayContent.getDisplay();
4497         pw.print(display.getDisplayId());
4498         pw.print("(type=");
4499         pw.print(Display.typeToString(display.getType()));
4500         pw.println(")");
4501     }
4502 
writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness, boolean testPssMode)4503     private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4504             boolean testPssMode) {
4505         final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4506         proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4507                 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
4508         final int tokenSize = mRootWindowContainer.mSleepTokens.size();
4509         for (int i = 0; i < tokenSize; i++) {
4510             final RootWindowContainer.SleepToken st =
4511                     mRootWindowContainer.mSleepTokens.valueAt(i);
4512             proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4513                     st.toString());
4514         }
4515         proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4516         proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4517                 mShuttingDown);
4518         proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4519                 testPssMode);
4520         proto.end(sleepToken);
4521     }
4522 
getCurrentUserId()4523     int getCurrentUserId() {
4524         return mAmInternal.getCurrentUserId();
4525     }
4526 
enforceNotIsolatedCaller(String caller)4527     static void enforceNotIsolatedCaller(String caller) {
4528         if (UserHandle.isIsolated(Binder.getCallingUid())) {
4529             throw new SecurityException("Isolated process not allowed to call " + caller);
4530         }
4531     }
4532 
getConfiguration()4533     public Configuration getConfiguration() {
4534         Configuration ci;
4535         synchronized (mGlobalLock) {
4536             ci = new Configuration(getGlobalConfigurationForCallingPid());
4537             ci.userSetLocale = false;
4538         }
4539         return ci;
4540     }
4541 
4542     /**
4543      * Current global configuration information. Contains general settings for the entire system,
4544      * also corresponds to the merged configuration of the default display.
4545      */
getGlobalConfiguration()4546     Configuration getGlobalConfiguration() {
4547         // Return default configuration before mRootWindowContainer initialized, which happens
4548         // while initializing process record for system, see {@link
4549         // ActivityManagerService#setSystemProcess}.
4550         return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
4551                 : new Configuration();
4552     }
4553 
updateConfigurationLocked(Configuration values, ActivityRecord starting, boolean initLocale)4554     boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4555             boolean initLocale) {
4556         return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4557     }
4558 
updateConfigurationLocked(Configuration values, ActivityRecord starting, boolean initLocale, boolean deferResume)4559     boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4560             boolean initLocale, boolean deferResume) {
4561         // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4562         return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4563                 UserHandle.USER_NULL, deferResume);
4564     }
4565 
updatePersistentConfiguration(Configuration values, @UserIdInt int userId)4566     public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
4567         final long origId = Binder.clearCallingIdentity();
4568         try {
4569             synchronized (mGlobalLock) {
4570                 // Window configuration is unrelated to persistent configuration (e.g. font scale,
4571                 // locale). Unset it to avoid affecting the current display configuration.
4572                 values.windowConfiguration.setToDefaults();
4573                 updateConfigurationLocked(values, null, false, true, userId,
4574                         false /* deferResume */);
4575             }
4576         } finally {
4577             Binder.restoreCallingIdentity(origId);
4578         }
4579     }
4580 
4581     /**
4582      * Do either or both things: (1) change the current configuration, and (2)
4583      * make sure the given activity is running with the (now) current
4584      * configuration.  Returns true if the activity has been left running, or
4585      * false if <var>starting</var> is being destroyed to match the new
4586      * configuration.
4587      *
4588      * @param userId is only used when persistent parameter is set to true to persist configuration
4589      *               for that particular user
4590      */
updateConfigurationLocked(Configuration values, ActivityRecord starting, boolean initLocale, boolean persistent, int userId, boolean deferResume)4591     boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4592             boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4593         int changes = 0;
4594         boolean kept = true;
4595 
4596         deferWindowLayout();
4597         try {
4598             if (values != null) {
4599                 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId);
4600                 mTmpUpdateConfigurationResult.changes = changes;
4601                 mTmpUpdateConfigurationResult.mIsUpdating = true;
4602             }
4603 
4604             if (!deferResume) {
4605                 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4606             }
4607         } finally {
4608             mTmpUpdateConfigurationResult.mIsUpdating = false;
4609             continueWindowLayout();
4610         }
4611         mTmpUpdateConfigurationResult.activityRelaunched = !kept;
4612         return kept;
4613     }
4614 
4615     /** Update default (global) configuration and notify listeners about changes. */
updateGlobalConfigurationLocked(@onNull Configuration values, boolean initLocale, boolean persistent, int userId)4616     int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4617             boolean persistent, int userId) {
4618 
4619         mTempConfig.setTo(getGlobalConfiguration());
4620         final int changes = mTempConfig.updateFrom(values);
4621         if (changes == 0) {
4622             return 0;
4623         }
4624 
4625         Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "updateGlobalConfiguration");
4626         ProtoLog.i(WM_DEBUG_CONFIGURATION, "Updating global configuration "
4627                 + "to: %s", values);
4628         writeConfigurationChanged(changes);
4629         FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
4630                 values.colorMode,
4631                 values.densityDpi,
4632                 values.fontScale,
4633                 values.hardKeyboardHidden,
4634                 values.keyboard,
4635                 values.keyboardHidden,
4636                 values.mcc,
4637                 values.mnc,
4638                 values.navigation,
4639                 values.navigationHidden,
4640                 values.orientation,
4641                 values.screenHeightDp,
4642                 values.screenLayout,
4643                 values.screenWidthDp,
4644                 values.smallestScreenWidthDp,
4645                 values.touchscreen,
4646                 values.uiMode);
4647 
4648         // Note: certain tests currently run as platform_app which is not allowed
4649         // to set debug system properties. To ensure that system properties are set
4650         // only when allowed, we check the current UID.
4651         if (Process.myUid() == Process.SYSTEM_UID) {
4652             if (values.mcc != 0) {
4653                 SystemProperties.set("debug.tracing.mcc", Integer.toString(values.mcc));
4654             }
4655             if (values.mnc != 0) {
4656                 SystemProperties.set("debug.tracing.mnc", Integer.toString(values.mnc));
4657             }
4658         }
4659 
4660         if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4661             final LocaleList locales = values.getLocales();
4662             int bestLocaleIndex = 0;
4663             if (locales.size() > 1) {
4664                 if (mSupportedSystemLocales == null) {
4665                     mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4666                 }
4667                 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4668             }
4669             SystemProperties.set("persist.sys.locale",
4670                     locales.get(bestLocaleIndex).toLanguageTag());
4671             LocaleList.setDefault(locales, bestLocaleIndex);
4672         }
4673 
4674         mTempConfig.seq = increaseConfigurationSeqLocked();
4675 
4676         Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4677         // TODO(multi-display): Update UsageEvents#Event to include displayId.
4678         mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
4679 
4680         // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
4681         updateShouldShowDialogsLocked(mTempConfig);
4682 
4683         AttributeCache ac = AttributeCache.instance();
4684         if (ac != null) {
4685             ac.updateConfiguration(mTempConfig);
4686         }
4687 
4688         // Make sure all resources in our process are updated right now, so that anyone who is going
4689         // to retrieve resource values after we return will be sure to get the new ones. This is
4690         // especially important during boot, where the first config change needs to guarantee all
4691         // resources have that config before following boot code is executed.
4692         mSystemThread.applyConfigurationToResources(mTempConfig);
4693 
4694         if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
4695             final Message msg = PooledLambda.obtainMessage(
4696                     ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4697                     this, userId, new Configuration(mTempConfig));
4698             mH.sendMessage(msg);
4699         }
4700 
4701         SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
4702         for (int i = pidMap.size() - 1; i >= 0; i--) {
4703             final int pid = pidMap.keyAt(i);
4704             final WindowProcessController app = pidMap.get(pid);
4705             ProtoLog.v(WM_DEBUG_CONFIGURATION, "Update process config of %s to new "
4706                     + "config %s", app.mName, mTempConfig);
4707             app.onConfigurationChanged(mTempConfig);
4708         }
4709 
4710         final Message msg = PooledLambda.obtainMessage(
4711                 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4712                 mAmInternal, changes, initLocale);
4713         mH.sendMessage(msg);
4714 
4715         Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "RootConfigChange");
4716         // Update stored global config and notify everyone about the change.
4717         mRootWindowContainer.onConfigurationChanged(mTempConfig);
4718         Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
4719 
4720         Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
4721         return changes;
4722     }
4723 
increaseAssetConfigurationSeq()4724     private int increaseAssetConfigurationSeq() {
4725         mGlobalAssetsSeq = Math.max(++mGlobalAssetsSeq, 1);
4726         return mGlobalAssetsSeq;
4727     }
4728 
4729     /**
4730      * Updates the {@link ApplicationInfo}s of the package activities th that are attached in the
4731      * WM hierarchy.
4732      */
updateActivityApplicationInfo(int userId, ArrayMap<String, ApplicationInfo> applicationInfoByPackage)4733     public void updateActivityApplicationInfo(int userId,
4734             ArrayMap<String, ApplicationInfo> applicationInfoByPackage) {
4735         synchronized (mGlobalLock) {
4736             if (mRootWindowContainer != null) {
4737                 mRootWindowContainer.updateActivityApplicationInfo(userId,
4738                         applicationInfoByPackage);
4739             }
4740         }
4741     }
4742 
4743     /**
4744      * Update the asset configuration and increase the assets sequence number.
4745      * @param processes the processes that needs to update the asset configuration
4746      */
updateAssetConfiguration(List<WindowProcessController> processes, boolean updateFrameworkRes)4747     public void updateAssetConfiguration(List<WindowProcessController> processes,
4748             boolean updateFrameworkRes) {
4749         synchronized (mGlobalLock) {
4750             final int assetSeq = increaseAssetConfigurationSeq();
4751 
4752             if (updateFrameworkRes) {
4753                 Configuration newConfig = new Configuration();
4754                 newConfig.assetsSeq = assetSeq;
4755                 updateConfiguration(newConfig);
4756             }
4757 
4758             // Always update the override of every process so the asset sequence of the process is
4759             // always greater than or equal to the global configuration.
4760             for (int i = processes.size() - 1; i >= 0; i--) {
4761                 final WindowProcessController wpc = processes.get(i);
4762                 wpc.updateAssetConfiguration(assetSeq);
4763             }
4764         }
4765     }
4766 
startPowerMode(@owerModeReason int reason)4767     void startPowerMode(@PowerModeReason int reason) {
4768         final int prevReasons = mPowerModeReasons;
4769         mPowerModeReasons |= reason;
4770         if ((reason & POWER_MODE_REASON_UNKNOWN_VISIBILITY) != 0) {
4771             if (mRetainPowerModeAndTopProcessState) {
4772                 mH.removeMessages(H.END_POWER_MODE_UNKNOWN_VISIBILITY_MSG);
4773             }
4774             mRetainPowerModeAndTopProcessState = true;
4775             mH.sendEmptyMessageDelayed(H.END_POWER_MODE_UNKNOWN_VISIBILITY_MSG,
4776                     POWER_MODE_UNKNOWN_VISIBILITY_TIMEOUT_MS);
4777             Slog.d(TAG, "Temporarily retain top process state for launching app");
4778         }
4779         if (mPowerManagerInternal == null) {
4780             return;
4781         }
4782 
4783         // START_ACTIVITY can be used with UNKNOWN_VISIBILITY. CHANGE_DISPLAY should be used alone.
4784         if ((reason & POWER_MODE_REASON_START_ACTIVITY) != 0
4785                 && (prevReasons & POWER_MODE_REASON_START_ACTIVITY) == 0) {
4786             Trace.instant(Trace.TRACE_TAG_WINDOW_MANAGER, "StartModeLaunch");
4787             mPowerManagerInternal.setPowerMode(PowerManagerInternal.MODE_LAUNCH, true);
4788         } else if (reason == POWER_MODE_REASON_CHANGE_DISPLAY
4789                 && (prevReasons & POWER_MODE_REASON_CHANGE_DISPLAY) == 0) {
4790             Trace.instant(Trace.TRACE_TAG_WINDOW_MANAGER, "StartModeDisplayChange");
4791             mPowerManagerInternal.setPowerMode(PowerManagerInternal.MODE_DISPLAY_CHANGE, true);
4792         }
4793     }
4794 
endPowerMode(@owerModeReason int reason)4795     void endPowerMode(@PowerModeReason int reason) {
4796         if (mPowerModeReasons == 0) return;
4797         final int prevReasons = mPowerModeReasons;
4798         mPowerModeReasons &= ~reason;
4799 
4800         if ((mPowerModeReasons & POWER_MODE_REASON_UNKNOWN_VISIBILITY) != 0) {
4801             boolean allResolved = true;
4802             for (int i = mRootWindowContainer.getChildCount() - 1; i >= 0; i--) {
4803                 allResolved &= mRootWindowContainer.getChildAt(i).mUnknownAppVisibilityController
4804                         .allResolved();
4805             }
4806             if (allResolved) {
4807                 mPowerModeReasons &= ~POWER_MODE_REASON_UNKNOWN_VISIBILITY;
4808                 mRetainPowerModeAndTopProcessState = false;
4809                 mH.removeMessages(H.END_POWER_MODE_UNKNOWN_VISIBILITY_MSG);
4810             }
4811         }
4812         if (mPowerManagerInternal == null) {
4813             return;
4814         }
4815 
4816         // If the launching apps have unknown visibility, only end launch power mode until the
4817         // states are resolved.
4818         final int endLaunchModeReasons = POWER_MODE_REASON_START_ACTIVITY
4819                 | POWER_MODE_REASON_UNKNOWN_VISIBILITY;
4820         if ((prevReasons & endLaunchModeReasons) != 0
4821                 && (mPowerModeReasons & endLaunchModeReasons) == 0) {
4822             Trace.instant(Trace.TRACE_TAG_WINDOW_MANAGER, "EndModeLaunch");
4823             mPowerManagerInternal.setPowerMode(PowerManagerInternal.MODE_LAUNCH, false);
4824         }
4825         if ((prevReasons & POWER_MODE_REASON_CHANGE_DISPLAY) != 0
4826                 && (mPowerModeReasons & POWER_MODE_REASON_CHANGE_DISPLAY) == 0) {
4827             Trace.instant(Trace.TRACE_TAG_WINDOW_MANAGER, "EndModeDisplayChange");
4828             mPowerManagerInternal.setPowerMode(PowerManagerInternal.MODE_DISPLAY_CHANGE, false);
4829         }
4830     }
4831 
4832     /** @see WindowSurfacePlacer#deferLayout */
deferWindowLayout()4833     void deferWindowLayout() {
4834         if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
4835             // Reset the reasons at the first entrance because we only care about the changes in the
4836             // deferred scope.
4837             mLayoutReasons = 0;
4838         }
4839 
4840         mWindowManager.mWindowPlacerLocked.deferLayout();
4841     }
4842 
4843     /** @see WindowSurfacePlacer#continueLayout */
continueWindowLayout()4844     void continueWindowLayout() {
4845         mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
4846         if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
4847             Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
4848         }
4849 
4850         // ClientTransactions is queued during #deferWindowLayout() for performance.
4851         // Notify to continue.
4852         mLifecycleManager.onLayoutContinued();
4853     }
4854 
4855     /**
4856      * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
4857      * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
4858      * defer count is gone.
4859      */
addWindowLayoutReasons(@ayoutReason int reasons)4860     void addWindowLayoutReasons(@LayoutReason int reasons) {
4861         mLayoutReasons |= reasons;
4862     }
4863 
updateEventDispatchingLocked(boolean booted)4864     private void updateEventDispatchingLocked(boolean booted) {
4865         mWindowManager.setEventDispatching(booted && !mShuttingDown);
4866     }
4867 
sendPutConfigurationForUserMsg(int userId, Configuration config)4868     private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
4869         final ContentResolver resolver = mContext.getContentResolver();
4870         Settings.System.putConfigurationForUser(resolver, config, userId);
4871     }
4872 
isActivityStartsLoggingEnabled()4873     boolean isActivityStartsLoggingEnabled() {
4874         return mAmInternal.isActivityStartsLoggingEnabled();
4875     }
4876 
isBackgroundActivityStartsEnabled()4877     boolean isBackgroundActivityStartsEnabled() {
4878         return mAmInternal.isBackgroundActivityStartsEnabled();
4879     }
4880 
getInputDispatchingTimeoutMillisLocked(ActivityRecord r)4881     static long getInputDispatchingTimeoutMillisLocked(ActivityRecord r) {
4882         if (r == null || !r.hasProcess()) {
4883             return DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
4884         }
4885         return getInputDispatchingTimeoutMillisLocked(r.app);
4886     }
4887 
getInputDispatchingTimeoutMillisLocked(WindowProcessController r)4888     private static long getInputDispatchingTimeoutMillisLocked(WindowProcessController r) {
4889         if (r == null) {
4890             return DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
4891         }
4892         return r.getInputDispatchingTimeoutMillis();
4893     }
4894 
4895     /**
4896      * Decide based on the configuration whether we should show the ANR,
4897      * crash, etc dialogs.  The idea is that if there is no affordance to
4898      * press the on-screen buttons, or the user experience would be more
4899      * greatly impacted than the crash itself, we shouldn't show the dialog.
4900      *
4901      * A thought: SystemUI might also want to get told about this, the Power
4902      * dialog / global actions also might want different behaviors.
4903      */
updateShouldShowDialogsLocked(Configuration config)4904     private void updateShouldShowDialogsLocked(Configuration config) {
4905         final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
4906                 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
4907                 && config.navigation == Configuration.NAVIGATION_NONAV);
4908         final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
4909                 HIDE_ERROR_DIALOGS, 0) != 0;
4910         mShowDialogs = inputMethodExists
4911                 && ActivityTaskManager.currentUiModeSupportsErrorDialogs(config)
4912                 && !hideDialogsSet;
4913     }
4914 
updateFontScaleIfNeeded(@serIdInt int userId)4915     private void updateFontScaleIfNeeded(@UserIdInt int userId) {
4916         if (userId != getCurrentUserId()) {
4917             return;
4918         }
4919 
4920         final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
4921                 FONT_SCALE, 1.0f, userId);
4922 
4923         synchronized (mGlobalLock) {
4924             if (getGlobalConfiguration().fontScale == scaleFactor) {
4925                 return;
4926             }
4927 
4928             final Configuration configuration
4929                     = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4930             configuration.fontScale = scaleFactor;
4931             updatePersistentConfiguration(configuration, userId);
4932         }
4933     }
4934 
updateFontWeightAdjustmentIfNeeded(@serIdInt int userId)4935     private void updateFontWeightAdjustmentIfNeeded(@UserIdInt int userId) {
4936         if (userId != getCurrentUserId()) {
4937             return;
4938         }
4939 
4940         final int fontWeightAdjustment =
4941                 Settings.Secure.getIntForUser(
4942                         mContext.getContentResolver(),
4943                         Settings.Secure.FONT_WEIGHT_ADJUSTMENT,
4944                         Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED,
4945                         userId);
4946 
4947         synchronized (mGlobalLock) {
4948             if (getGlobalConfiguration().fontWeightAdjustment == fontWeightAdjustment) {
4949                 return;
4950             }
4951 
4952             final Configuration configuration =
4953                     mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4954             configuration.fontWeightAdjustment = fontWeightAdjustment;
4955             updatePersistentConfiguration(configuration, userId);
4956         }
4957     }
4958 
4959     // Actually is sleeping or shutting down or whatever else in the future
4960     // is an inactive state.
isSleepingOrShuttingDownLocked()4961     boolean isSleepingOrShuttingDownLocked() {
4962         return isSleepingLocked() || mShuttingDown;
4963     }
4964 
isSleepingLocked()4965     boolean isSleepingLocked() {
4966         return mSleeping;
4967     }
4968 
4969     /** Update AMS states when an activity is resumed. */
setLastResumedActivityUncheckLocked(ActivityRecord r, String reason)4970     void setLastResumedActivityUncheckLocked(ActivityRecord r, String reason) {
4971         final Task task = r.getTask();
4972         if (task.isActivityTypeStandard()) {
4973             if (mCurAppTimeTracker != r.appTimeTracker) {
4974                 // We are switching app tracking.  Complete the current one.
4975                 if (mCurAppTimeTracker != null) {
4976                     mCurAppTimeTracker.stop();
4977                     mH.obtainMessage(
4978                             REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
4979                     mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
4980                     mCurAppTimeTracker = null;
4981                 }
4982                 if (r.appTimeTracker != null) {
4983                     mCurAppTimeTracker = r.appTimeTracker;
4984                     startTimeTrackingFocusedActivityLocked();
4985                 }
4986             } else {
4987                 startTimeTrackingFocusedActivityLocked();
4988             }
4989         } else {
4990             r.appTimeTracker = null;
4991         }
4992         // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
4993         // TODO: Probably not, because we don't want to resume voice on switching
4994         // back to this activity
4995         if (task.voiceInteractor != null) {
4996             startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
4997         } else {
4998             finishRunningVoiceLocked();
4999 
5000             if (mLastResumedActivity != null) {
5001                 final IVoiceInteractionSession session;
5002 
5003                 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
5004                 if (lastResumedActivityTask != null
5005                         && lastResumedActivityTask.voiceSession != null) {
5006                     session = lastResumedActivityTask.voiceSession;
5007                 } else {
5008                     session = mLastResumedActivity.voiceSession;
5009                 }
5010 
5011                 if (session != null) {
5012                     // We had been in a voice interaction session, but now focused has
5013                     // move to something different.  Just finish the session, we can't
5014                     // return to it and retain the proper state and synchronization with
5015                     // the voice interaction service.
5016                     finishVoiceTask(session);
5017                 }
5018             }
5019         }
5020 
5021         if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5022             mAmInternal.sendForegroundProfileChanged(r.mUserId);
5023         }
5024         final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5025 
5026         updateResumedAppTrace(r);
5027         mLastResumedActivity = r;
5028 
5029         // Don't take focus when transient launching. We don't want the app to know anything
5030         // until we've committed to the gesture. The focus will be transferred at the end of
5031         // the transition (if the transient launch is committed) or early if explicitly requested
5032         // via `setFocused*`.
5033         boolean focusedAppChanged = false;
5034         if (!getTransitionController().isTransientCollect(r)) {
5035             focusedAppChanged = r.mDisplayContent.setFocusedApp(r);
5036             if (focusedAppChanged) {
5037                 mWindowManager.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL,
5038                         true /*updateInputWindows*/);
5039             }
5040         }
5041         if (task != prevTask) {
5042             mTaskSupervisor.mRecentTasks.add(task);
5043         }
5044 
5045         if (focusedAppChanged) {
5046             applyUpdateLockStateLocked(r);
5047         }
5048         if (mVrController.mVrService != null) {
5049             applyUpdateVrModeLocked(r);
5050         }
5051 
5052         EventLogTags.writeWmSetResumedActivity(r.mUserId, r.shortComponentName, reason);
5053     }
5054 
5055     final class SleepTokenAcquirerImpl implements ActivityTaskManagerInternal.SleepTokenAcquirer {
5056         private final String mTag;
5057         private final SparseArray<RootWindowContainer.SleepToken> mSleepTokens =
5058                 new SparseArray<>();
5059 
SleepTokenAcquirerImpl(@onNull String tag)5060         SleepTokenAcquirerImpl(@NonNull String tag) {
5061             mTag = tag;
5062         }
5063 
5064         @Override
acquire(int displayId)5065         public void acquire(int displayId) {
5066             acquire(displayId, false /* isSwappingDisplay */);
5067         }
5068 
5069         @Override
acquire(int displayId, boolean isSwappingDisplay)5070         public void acquire(int displayId, boolean isSwappingDisplay) {
5071             synchronized (mGlobalLock) {
5072                 if (!mSleepTokens.contains(displayId)) {
5073                     mSleepTokens.append(displayId,
5074                             mRootWindowContainer.createSleepToken(mTag, displayId,
5075                                     isSwappingDisplay));
5076                     updateSleepIfNeededLocked();
5077                 }
5078             }
5079         }
5080 
5081         @Override
release(int displayId)5082         public void release(int displayId) {
5083             synchronized (mGlobalLock) {
5084                 final RootWindowContainer.SleepToken token = mSleepTokens.get(displayId);
5085                 if (token != null) {
5086                     mRootWindowContainer.removeSleepToken(token);
5087                     mSleepTokens.remove(displayId);
5088                 }
5089             }
5090         }
5091     }
5092 
updateSleepIfNeededLocked()5093     void updateSleepIfNeededLocked() {
5094         final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
5095         final boolean wasSleeping = mSleeping;
5096         boolean updateOomAdj = false;
5097 
5098         if (!shouldSleep) {
5099             // If wasSleeping is true, we need to wake up activity manager state from when
5100             // we started sleeping. In either case, we need to apply the sleep tokens, which
5101             // will wake up root tasks or put them to sleep as appropriate.
5102             if (wasSleeping) {
5103                 mSleeping = false;
5104                 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5105                         FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
5106                 startTimeTrackingFocusedActivityLocked();
5107                 if (mTopApp != null) {
5108                     mTopApp.addToPendingTop();
5109                 }
5110                 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5111                 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
5112                 mTaskSupervisor.comeOutOfSleepIfNeededLocked();
5113             }
5114             mRootWindowContainer.applySleepTokens(true /* applyToRootTasks */);
5115             if (wasSleeping) {
5116                 updateOomAdj = true;
5117             }
5118         } else if (!mSleeping && shouldSleep) {
5119             mSleeping = true;
5120             FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5121                     FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
5122             if (mCurAppTimeTracker != null) {
5123                 mCurAppTimeTracker.stop();
5124             }
5125             mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5126             Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
5127             mTaskSupervisor.goingToSleepLocked();
5128             updateResumedAppTrace(null /* resumed */);
5129             updateOomAdj = true;
5130         }
5131         if (updateOomAdj) {
5132             updateOomAdj();
5133         }
5134     }
5135 
updateOomAdj()5136     void updateOomAdj() {
5137         mH.removeCallbacks(mUpdateOomAdjRunnable);
5138         mH.post(mUpdateOomAdjRunnable);
5139     }
5140 
updateCpuStats()5141     void updateCpuStats() {
5142         mH.post(mAmInternal::updateCpuStats);
5143     }
5144 
updateBatteryStats(ActivityRecord component, boolean resumed)5145     void updateBatteryStats(ActivityRecord component, boolean resumed) {
5146         final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
5147                 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5148                 resumed);
5149         mH.sendMessage(m);
5150     }
5151 
updateTopApp(ActivityRecord topResumedActivity)5152     void updateTopApp(ActivityRecord topResumedActivity) {
5153         final ActivityRecord top = topResumedActivity != null ? topResumedActivity
5154                 // If there is no resumed activity, it will choose the pausing or focused activity.
5155                 : mRootWindowContainer.getTopResumedActivity();
5156         mTopApp = top != null ? top.app : null;
5157         if (mTopApp == mPreviousProcess) mPreviousProcess = null;
5158     }
5159 
5160     /**
5161      * The process state of previous activity is more important than the regular background to keep
5162      * around in case the user wants to return to it.
5163      */
updatePreviousProcess(ActivityRecord stoppedActivity)5164     void updatePreviousProcess(ActivityRecord stoppedActivity) {
5165         if (stoppedActivity.app != null && mTopApp != null
5166                 // Don't replace the previous process if the stopped one is the top, e.g. sleeping.
5167                 && stoppedActivity.app != mTopApp
5168                 // The stopped activity must have been visible later than the previous.
5169                 && stoppedActivity.lastVisibleTime > mPreviousProcessVisibleTime
5170                 // Home has its own retained state, so don't let it occupy the previous.
5171                 && stoppedActivity.app != mHomeProcess) {
5172             mPreviousProcess = stoppedActivity.app;
5173             mPreviousProcessVisibleTime = stoppedActivity.lastVisibleTime;
5174         }
5175     }
5176 
updateActivityUsageStats(ActivityRecord activity, int event)5177     void updateActivityUsageStats(ActivityRecord activity, int event) {
5178         ComponentName taskRoot = null;
5179         int taskId = INVALID_TASK_ID;
5180         final Task task = activity.getTask();
5181         if (task != null) {
5182             final ActivityRecord rootActivity = task.getRootActivity();
5183             if (rootActivity != null) {
5184                 taskRoot = rootActivity.mActivityComponent;
5185             }
5186             taskId = task.mTaskId;
5187         }
5188         final Message m = PooledLambda.obtainMessage(
5189                 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
5190                 activity.mActivityComponent, activity.mUserId, event, activity.token, taskRoot,
5191                 new ActivityId(taskId, activity.shareableActivityToken));
5192         mH.sendMessage(m);
5193     }
5194 
startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop, String hostingType)5195     void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5196             String hostingType) {
5197         if (!mStartingProcessActivities.contains(activity)) {
5198             mStartingProcessActivities.add(activity);
5199         } else if (mProcessNames.get(
5200                 activity.processName, activity.info.applicationInfo.uid) != null) {
5201             // The process is already starting. Wait for it to attach.
5202             return;
5203         }
5204         try {
5205             if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5206                 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
5207                         + activity.processName);
5208             }
5209             // Post message to start process to avoid possible deadlock of calling into AMS with the
5210             // ATMS lock held.
5211             final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5212                     mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5213                     isTop, hostingType, activity.intent.getComponent());
5214             mH.sendMessage(m);
5215         } finally {
5216             Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
5217         }
5218     }
5219 
setBooting(boolean booting)5220     void setBooting(boolean booting) {
5221         mAmInternal.setBooting(booting);
5222     }
5223 
isBooting()5224     boolean isBooting() {
5225         return mAmInternal.isBooting();
5226     }
5227 
setBooted(boolean booted)5228     void setBooted(boolean booted) {
5229         mAmInternal.setBooted(booted);
5230     }
5231 
isBooted()5232     boolean isBooted() {
5233         return mAmInternal.isBooted();
5234     }
5235 
postFinishBooting(boolean finishBooting, boolean enableScreen)5236     void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5237         mH.post(() -> {
5238             if (finishBooting) {
5239                 mAmInternal.finishBooting();
5240             }
5241             if (enableScreen) {
5242                 mInternal.enableScreenAfterBoot(isBooted());
5243             }
5244         });
5245     }
5246 
setHeavyWeightProcess(ActivityRecord root)5247     void setHeavyWeightProcess(ActivityRecord root) {
5248         mHeavyWeightProcess = root.app;
5249         final Message m = PooledLambda.obtainMessage(
5250                 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5251                 root.app, root.intent, root.mUserId);
5252         mH.sendMessage(m);
5253     }
5254 
clearHeavyWeightProcessIfEquals(WindowProcessController proc)5255     void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5256         if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5257             return;
5258         }
5259 
5260         mHeavyWeightProcess = null;
5261         final Message m = PooledLambda.obtainMessage(
5262                 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5263                 proc.mUserId);
5264         mH.sendMessage(m);
5265     }
5266 
cancelHeavyWeightProcessNotification(int userId)5267     private void cancelHeavyWeightProcessNotification(int userId) {
5268         final INotificationManager inm = NotificationManager.getService();
5269         if (inm == null) {
5270             return;
5271         }
5272         try {
5273             inm.cancelNotificationWithTag("android", "android", null,
5274                     SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5275         } catch (RuntimeException e) {
5276             Slog.w(TAG, "Error canceling notification for service", e);
5277         } catch (RemoteException e) {
5278         }
5279 
5280     }
5281 
postHeavyWeightProcessNotification( WindowProcessController proc, Intent intent, int userId)5282     private void postHeavyWeightProcessNotification(
5283             WindowProcessController proc, Intent intent, int userId) {
5284         if (proc == null) {
5285             return;
5286         }
5287 
5288         final INotificationManager inm = NotificationManager.getService();
5289         if (inm == null) {
5290             return;
5291         }
5292 
5293         try {
5294             Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5295             String text = mContext.getString(R.string.heavy_weight_notification,
5296                     context.getApplicationInfo().loadLabel(context.getPackageManager()));
5297             Notification notification =
5298                     new Notification.Builder(context,
5299                             SystemNotificationChannels.HEAVY_WEIGHT_APP)
5300                             .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5301                             .setWhen(0)
5302                             .setOngoing(true)
5303                             .setTicker(text)
5304                             .setColor(mContext.getColor(
5305                                     com.android.internal.R.color.system_notification_accent_color))
5306                             .setContentTitle(text)
5307                             .setContentText(
5308                                     mContext.getText(R.string.heavy_weight_notification_detail))
5309                             .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5310                                     intent, PendingIntent.FLAG_CANCEL_CURRENT
5311                                             | PendingIntent.FLAG_IMMUTABLE, null,
5312                                     new UserHandle(userId)))
5313                             .build();
5314             try {
5315                 inm.enqueueNotificationWithTag("android", "android", null,
5316                         SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5317             } catch (RuntimeException e) {
5318                 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5319             } catch (RemoteException e) {
5320             }
5321         } catch (PackageManager.NameNotFoundException e) {
5322             Slog.w(TAG, "Unable to create context for heavy notification", e);
5323         }
5324 
5325     }
5326 
getIntentSenderLocked(int type, String packageName, String featureId, int callingUid, int userId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions)5327     IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5328             int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5329             Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
5330 
5331         ActivityRecord activity = null;
5332         if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5333             activity = ActivityRecord.isInRootTaskLocked(token);
5334             if (activity == null) {
5335                 Slog.w(TAG, "Failed createPendingResult: activity " + token
5336                         + " not in any root task");
5337                 return null;
5338             }
5339             if (activity.finishing) {
5340                 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5341                 return null;
5342             }
5343         }
5344 
5345         final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5346                 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5347                 resolvedTypes, flags, bOptions);
5348         final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5349         if (noCreate) {
5350             return rec;
5351         }
5352         if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5353             if (activity.pendingResults == null) {
5354                 activity.pendingResults = new HashSet<>();
5355             }
5356             activity.pendingResults.add(rec.ref);
5357         }
5358         return rec;
5359     }
5360 
5361     // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
startTimeTrackingFocusedActivityLocked()5362     private void startTimeTrackingFocusedActivityLocked() {
5363         final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
5364         if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5365             mCurAppTimeTracker.start(resumedActivity.packageName);
5366         }
5367     }
5368 
updateResumedAppTrace(@ullable ActivityRecord resumed)5369     private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5370         if (Trace.isTagEnabled(Trace.TRACE_TAG_WINDOW_MANAGER)) {
5371             if (mTracedResumedActivity != null) {
5372                 Trace.asyncTraceForTrackEnd(TRACE_TAG_WINDOW_MANAGER,
5373                         "Focused app", System.identityHashCode(mTracedResumedActivity));
5374             }
5375             if (resumed != null) {
5376                 Trace.asyncTraceForTrackBegin(TRACE_TAG_WINDOW_MANAGER,
5377                         "Focused app", resumed.mActivityComponent.flattenToShortString(),
5378                         System.identityHashCode(resumed));
5379             }
5380         }
5381         mTracedResumedActivity = resumed;
5382     }
5383 
5384     /** Applies latest configuration and/or visibility updates if needed. */
ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes)5385     boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5386         if (starting == null && mTaskSupervisor.isRootVisibilityUpdateDeferred()) {
5387             return true;
5388         }
5389         boolean kept = true;
5390         final Task mainRootTask = mRootWindowContainer.getTopDisplayFocusedRootTask();
5391         // mainRootTask is null during startup.
5392         if (mainRootTask != null) {
5393             if (changes != 0 && starting == null) {
5394                 // If the configuration changed, and the caller is not already
5395                 // in the process of starting an activity, then find the top
5396                 // activity to check if its configuration needs to change.
5397                 starting = mainRootTask.topRunningActivity();
5398             }
5399 
5400             if (starting != null) {
5401                 kept = starting.ensureActivityConfiguration();
5402                 // And we need to make sure at this point that all other activities
5403                 // are made visible with the correct configuration.
5404                 mRootWindowContainer.ensureActivitiesVisible(starting);
5405             }
5406         }
5407 
5408         return kept;
5409     }
5410 
scheduleAppGcsLocked()5411     void scheduleAppGcsLocked() {
5412         mH.post(() -> mAmInternal.scheduleAppGcs());
5413     }
5414 
compatibilityInfoForPackageLocked(ApplicationInfo ai)5415     CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5416         return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5417     }
5418 
5419     /**
5420      * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5421      * PackageManager could be unavailable at construction time and therefore needs to be accessed
5422      * on demand.
5423      */
getPackageManager()5424     IPackageManager getPackageManager() {
5425         return AppGlobals.getPackageManager();
5426     }
5427 
getPackageManagerInternalLocked()5428     PackageManagerInternal getPackageManagerInternalLocked() {
5429         if (mPmInternal == null) {
5430             mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5431         }
5432         return mPmInternal;
5433     }
5434 
getSysUiServiceComponentLocked()5435     ComponentName getSysUiServiceComponentLocked() {
5436         if (mSysUiServiceComponent == null) {
5437             final PackageManagerInternal pm = getPackageManagerInternalLocked();
5438             mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5439         }
5440         return mSysUiServiceComponent;
5441     }
5442 
getPermissionPolicyInternal()5443     PermissionPolicyInternal getPermissionPolicyInternal() {
5444         if (mPermissionPolicyInternal == null) {
5445             mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5446         }
5447         return mPermissionPolicyInternal;
5448     }
5449 
getStatusBarManagerInternal()5450     StatusBarManagerInternal getStatusBarManagerInternal() {
5451         if (mStatusBarManagerInternal == null) {
5452             mStatusBarManagerInternal = LocalServices.getService(StatusBarManagerInternal.class);
5453         }
5454         return mStatusBarManagerInternal;
5455     }
5456 
getWallpaperManagerInternal()5457     WallpaperManagerInternal getWallpaperManagerInternal() {
5458         if (mWallpaperManagerInternal == null) {
5459             mWallpaperManagerInternal = LocalServices.getService(WallpaperManagerInternal.class);
5460         }
5461         return mWallpaperManagerInternal;
5462     }
5463 
getAppWarningsLocked()5464     AppWarnings getAppWarningsLocked() {
5465         return mAppWarnings;
5466     }
5467 
getHomeIntent()5468     Intent getHomeIntent() {
5469         Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5470         intent.setComponent(mTopComponent);
5471         intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5472         if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5473             intent.addCategory(Intent.CATEGORY_HOME);
5474         }
5475         return intent;
5476     }
5477 
5478     /**
5479      * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5480      * activities.
5481      *
5482      * @param preferredPackage Specify a preferred package name, otherwise use the package name
5483      *                         defined in config_secondaryHomePackage.
5484      * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5485      */
getSecondaryHomeIntent(String preferredPackage)5486     Intent getSecondaryHomeIntent(String preferredPackage) {
5487         final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5488         final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5489                 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5490         if (preferredPackage == null || useSystemProvidedLauncher) {
5491             // Using the package name stored in config if no preferred package name or forced.
5492             final String secondaryHomePackage = mContext.getResources().getString(
5493                     com.android.internal.R.string.config_secondaryHomePackage);
5494             intent.setPackage(secondaryHomePackage);
5495         } else {
5496             intent.setPackage(preferredPackage);
5497         }
5498         intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5499         if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5500             intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5501         }
5502         return intent;
5503     }
5504 
getAppInfoForUser(ApplicationInfo info, int userId)5505     ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5506         if (info == null) return null;
5507         ApplicationInfo newInfo = new ApplicationInfo(info);
5508         newInfo.initForUser(userId);
5509         return newInfo;
5510     }
5511 
getProcessController(String processName, int uid)5512     WindowProcessController getProcessController(String processName, int uid) {
5513         if (uid == SYSTEM_UID) {
5514             // The system gets to run in any process. If there are multiple processes with the same
5515             // uid, just pick the first (this should never happen).
5516             final SparseArray<WindowProcessController> procs =
5517                     mProcessNames.getMap().get(processName);
5518             if (procs == null) return null;
5519             final int procCount = procs.size();
5520             for (int i = 0; i < procCount; i++) {
5521                 final int procUid = procs.keyAt(i);
5522                 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5523                     // Don't use an app process or different user process for system component.
5524                     continue;
5525                 }
5526                 return procs.valueAt(i);
5527             }
5528         }
5529 
5530         return mProcessNames.get(processName, uid);
5531     }
5532 
getProcessController(IApplicationThread thread)5533     WindowProcessController getProcessController(IApplicationThread thread) {
5534         if (thread == null) {
5535             return null;
5536         }
5537 
5538         final IBinder threadBinder = thread.asBinder();
5539         final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5540         for (int i = pmap.size() - 1; i >= 0; i--) {
5541             final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5542             for (int j = procs.size() - 1; j >= 0; j--) {
5543                 final WindowProcessController proc = procs.valueAt(j);
5544                 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5545                     return proc;
5546                 }
5547             }
5548         }
5549 
5550         return null;
5551     }
5552 
5553     /**
5554      * Returns the {@link WindowProcessController} for the app process for the given uid and pid.
5555      *
5556      * If no such {@link WindowProcessController} is found, it does not belong to an app, or the
5557      * pid does not match the uid {@code null} is returned.
5558      */
getProcessController(int pid, int uid)5559     WindowProcessController getProcessController(int pid, int uid) {
5560         final WindowProcessController proc = mProcessMap.getProcess(pid);
5561         if (proc == null) return null;
5562         if (UserHandle.isApp(uid) && proc.mUid == uid) {
5563             return proc;
5564         }
5565         return null;
5566     }
5567 
5568     /**
5569      * Returns the package name if (and only if) the package name can be uniquely determined.
5570      * Otherwise returns {@code null}.
5571      *
5572      * The provided pid must match the provided uid, otherwise this also returns null.
5573      */
getPackageNameIfUnique(int uid, int pid)5574     @Nullable String getPackageNameIfUnique(int uid, int pid) {
5575         final WindowProcessController proc = mProcessMap.getProcess(pid);
5576         if (proc == null || proc.mUid != uid) {
5577             Slog.w(TAG, "callingPackage for (uid=" + uid + ", pid=" + pid + ") has no WPC");
5578             return null;
5579         }
5580         List<String> realCallingPackages = proc.getPackageList();
5581         if (realCallingPackages.size() != 1) {
5582             Slog.w(TAG, "callingPackage for (uid=" + uid + ", pid=" + pid + ") is ambiguous: "
5583                     + realCallingPackages);
5584             return null;
5585         }
5586         return realCallingPackages.get(0);
5587     }
5588 
5589     /** A uid is considered to be foreground if it has a visible non-toast window. */
5590     @HotPath(caller = HotPath.START_SERVICE)
hasActiveVisibleWindow(int uid)5591     boolean hasActiveVisibleWindow(int uid) {
5592         if (mVisibleActivityProcessTracker.hasVisibleActivity(uid)) {
5593             return true;
5594         }
5595         return mActiveUids.hasNonAppVisibleWindow(uid);
5596     }
5597 
isDeviceOwner(int uid)5598     boolean isDeviceOwner(int uid) {
5599         return uid >= 0 && mDeviceOwnerUid == uid;
5600     }
5601 
setDeviceOwnerUid(int uid)5602     void setDeviceOwnerUid(int uid) {
5603         mDeviceOwnerUid = uid;
5604     }
5605 
isAffiliatedProfileOwner(int uid)5606     boolean isAffiliatedProfileOwner(int uid) {
5607         return uid >= 0 && mProfileOwnerUids.contains(uid)
5608             && DeviceStateCache.getInstance().hasAffiliationWithDevice(UserHandle.getUserId(uid));
5609     }
5610 
setProfileOwnerUids(Set<Integer> uids)5611     void setProfileOwnerUids(Set<Integer> uids) {
5612         mProfileOwnerUids = uids;
5613     }
5614 
5615     /**
5616      * Saves the current activity manager state and includes the saved state in the next dump of
5617      * activity manager.
5618      */
saveANRState(ActivityRecord activity, String reason)5619     void saveANRState(ActivityRecord activity, String reason) {
5620         final StringWriter sw = new StringWriter();
5621         final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
5622         pw.println("  ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
5623         if (reason != null) {
5624             pw.println("  Reason: " + reason);
5625         }
5626         pw.println();
5627         if (activity != null) {
5628             final Task rootTask = activity.getRootTask();
5629             if (rootTask != null) {
5630                 rootTask.forAllTaskFragments(
5631                         tf -> tf.dumpInner("  ", pw, true /* dumpAll */, null /* dumpPackage */));
5632                 pw.println();
5633             }
5634             mActivityStartController.dump(pw, "  ", activity.packageName);
5635             if (mActivityStartController.getLastStartActivity() != activity) {
5636                 activity.dump(pw, "  ", true /* dumpAll */);
5637             }
5638         }
5639         ActivityTaskSupervisor.printThisActivity(pw, mRootWindowContainer.getTopResumedActivity(),
5640                 null /* dumpPackage */, INVALID_DISPLAY, true /* needSep */,
5641                 "  ResumedActivity: ", /* header= */ null /* header */);
5642         mLockTaskController.dump(pw, "  ");
5643         mKeyguardController.dump(pw, "  ");
5644         pw.println("-------------------------------------------------------------------"
5645                 + "------------");
5646         pw.close();
5647 
5648         mLastANRState = sw.toString();
5649     }
5650 
logAppTooSlow(WindowProcessController app, long startTime, String msg)5651     void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5652         if (true || Build.IS_USER) {
5653             return;
5654         }
5655 
5656         StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5657         StrictMode.allowThreadDiskWrites();
5658         try {
5659             File tracesDir = new File("/data/anr");
5660             File tracesFile = null;
5661             try {
5662                 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5663 
5664                 StringBuilder sb = new StringBuilder();
5665                 String timeString =
5666                         TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5667                 sb.append(timeString);
5668                 sb.append(": ");
5669                 TimeUtils.formatDuration(SystemClock.uptimeMillis() - startTime, sb);
5670                 sb.append(" since ");
5671                 sb.append(msg);
5672                 FileOutputStream fos = new FileOutputStream(tracesFile);
5673                 fos.write(sb.toString().getBytes());
5674                 if (app == null) {
5675                     fos.write("\n*** No application process!".getBytes());
5676                 }
5677                 fos.close();
5678                 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5679             } catch (IOException e) {
5680                 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5681                 return;
5682             }
5683 
5684             if (app != null && app.getPid() > 0) {
5685                 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5686                 firstPids.add(app.getPid());
5687                 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null, null, null);
5688             }
5689 
5690             File lastTracesFile = null;
5691             File curTracesFile = null;
5692             for (int i = 9; i >= 0; i--) {
5693                 String name = String.format(Locale.US, "slow%02d.txt", i);
5694                 curTracesFile = new File(tracesDir, name);
5695                 if (curTracesFile.exists()) {
5696                     if (lastTracesFile != null) {
5697                         curTracesFile.renameTo(lastTracesFile);
5698                     } else {
5699                         curTracesFile.delete();
5700                     }
5701                 }
5702                 lastTracesFile = curTracesFile;
5703             }
5704             tracesFile.renameTo(curTracesFile);
5705         } finally {
5706             StrictMode.setThreadPolicy(oldPolicy);
5707         }
5708     }
5709 
isAssociatedCompanionApp(int userId, int uid)5710     boolean isAssociatedCompanionApp(int userId, int uid) {
5711         final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5712         if (allUids == null) {
5713             return false;
5714         }
5715         return allUids.contains(uid);
5716     }
5717 
5718     @Override
onTransact(int code, Parcel data, Parcel reply, int flags)5719     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
5720             throws RemoteException {
5721         try {
5722             return super.onTransact(code, data, reply, flags);
5723         } catch (RuntimeException e) {
5724             throw logAndRethrowRuntimeExceptionOnTransact(TAG, e);
5725         }
5726     }
5727 
5728     /** Provides the full stack traces of non-security exception that occurs in onTransact. */
logAndRethrowRuntimeExceptionOnTransact(String name, RuntimeException e)5729     static RuntimeException logAndRethrowRuntimeExceptionOnTransact(String name,
5730             RuntimeException e) {
5731         if (!(e instanceof SecurityException)) {
5732             Slog.w(TAG, name + " onTransact aborts"
5733                     + " UID:" + Binder.getCallingUid()
5734                     + " PID:" + Binder.getCallingPid(), e);
5735         }
5736         throw e;
5737     }
5738 
5739     @Override
setRunningRemoteTransitionDelegate(IApplicationThread delegate)5740     public void setRunningRemoteTransitionDelegate(IApplicationThread delegate) {
5741         final TransitionController controller = getTransitionController();
5742         // A quick path without entering WM lock.
5743         if (delegate != null && controller.mRemotePlayer.reportRunning(delegate)) {
5744             // The delegate was known as running remote transition.
5745             return;
5746         }
5747         mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
5748                 "setRunningRemoteTransition");
5749         final int callingPid = Binder.getCallingPid();
5750         final int callingUid = Binder.getCallingUid();
5751         synchronized (mGlobalLock) {
5752             // Also only allow a process which is already runningRemoteAnimation to mark another
5753             // process.
5754             final WindowProcessController callingProc = getProcessController(callingPid,
5755                     callingUid);
5756             if (callingProc == null || !callingProc.isRunningRemoteTransition()) {
5757                 final String msg = "Can't call setRunningRemoteTransition from a process (pid="
5758                         + callingPid + " uid=" + callingUid + ") which isn't itself running a "
5759                         + "remote transition.";
5760                 Slog.e(TAG, msg);
5761                 throw new SecurityException(msg);
5762             }
5763             final WindowProcessController wpc = getProcessController(delegate);
5764             if (wpc == null) {
5765                 Slog.w(TAG, "setRunningRemoteTransition: no process for " + delegate);
5766                 return;
5767             }
5768             controller.mRemotePlayer.update(wpc, true /* running */, false /* predict */);
5769         }
5770     }
5771 
5772     @Override
registerScreenCaptureObserver(IBinder activityToken, IScreenCaptureObserver observer)5773     public void registerScreenCaptureObserver(IBinder activityToken,
5774             IScreenCaptureObserver observer) {
5775         mAmInternal.enforceCallingPermission(DETECT_SCREEN_CAPTURE,
5776                 "registerScreenCaptureObserver");
5777         synchronized (mGlobalLock) {
5778             ActivityRecord activityRecord = ActivityRecord.forTokenLocked(activityToken);
5779             if (activityRecord != null) {
5780                 activityRecord.registerCaptureObserver(observer);
5781             }
5782         }
5783     }
5784 
5785     @Override
unregisterScreenCaptureObserver(IBinder activityToken, IScreenCaptureObserver observer)5786     public void unregisterScreenCaptureObserver(IBinder activityToken,
5787             IScreenCaptureObserver observer) {
5788         mAmInternal.enforceCallingPermission(DETECT_SCREEN_CAPTURE,
5789                 "unregisterScreenCaptureObserver");
5790         synchronized (mGlobalLock) {
5791             ActivityRecord activityRecord = ActivityRecord.forTokenLocked(activityToken);
5792             if (activityRecord != null) {
5793                 activityRecord.unregisterCaptureObserver(observer);
5794             }
5795         }
5796     }
5797 
registerCompatScaleProvider(@ompatScaleProvider.CompatScaleModeOrderId int id, @NonNull CompatScaleProvider provider)5798     void registerCompatScaleProvider(@CompatScaleProvider.CompatScaleModeOrderId int id,
5799             @NonNull CompatScaleProvider provider) {
5800         mCompatModePackages.registerCompatScaleProvider(id, provider);
5801     }
5802 
unregisterCompatScaleProvider(@ompatScaleProvider.CompatScaleModeOrderId int id)5803     void unregisterCompatScaleProvider(@CompatScaleProvider.CompatScaleModeOrderId int id) {
5804         mCompatModePackages.unregisterCompatScaleProvider(id);
5805     }
5806 
5807     /**
5808      * Returns {@code true} if the process represented by the pid passed as argument is
5809      * instrumented and the instrumentation source was granted with the permission also
5810      * passed as argument.
5811      */
instrumentationSourceHasPermission(int pid, String permission)5812     boolean instrumentationSourceHasPermission(int pid, String permission) {
5813         final WindowProcessController process;
5814         synchronized (mGlobalLock) {
5815             process = mProcessMap.getProcess(pid);
5816         }
5817         if (process == null || !process.isInstrumenting()) {
5818             return false;
5819         }
5820         final int sourceUid = process.getInstrumentationSourceUid();
5821         return checkPermission(permission, -1, sourceUid) == PackageManager.PERMISSION_GRANTED;
5822     }
5823 
5824     /**
5825      * Wrap the {@link ActivityOptions} in {@link SafeActivityOptions} and attach caller options
5826      * that allow using the callers permissions to start background activities.
5827      */
createSafeActivityOptionsWithBalAllowed( @ullable ActivityOptions options)5828     private SafeActivityOptions createSafeActivityOptionsWithBalAllowed(
5829             @Nullable ActivityOptions options) {
5830         if (options == null) {
5831             options = ActivityOptions.makeBasic().setPendingIntentBackgroundActivityStartMode(
5832                 ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
5833         } else if (options.getPendingIntentBackgroundActivityStartMode()
5834                 == ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED) {
5835             options.setPendingIntentBackgroundActivityStartMode(
5836                     ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
5837         }
5838         return new SafeActivityOptions(options);
5839     }
5840 
5841     /**
5842      * Wrap the options {@link Bundle} in {@link SafeActivityOptions} and attach caller options
5843      * that allow using the callers permissions to start background activities.
5844      */
createSafeActivityOptionsWithBalAllowed(@ullable Bundle bOptions)5845     private SafeActivityOptions createSafeActivityOptionsWithBalAllowed(@Nullable Bundle bOptions) {
5846         return createSafeActivityOptionsWithBalAllowed(ActivityOptions.fromBundle(bOptions));
5847     }
5848 
5849     final class H extends Handler {
5850         static final int REPORT_TIME_TRACKER_MSG = 1;
5851         static final int END_POWER_MODE_UNKNOWN_VISIBILITY_MSG = 3;
5852         static final int RESUME_FG_APP_SWITCH_MSG = 4;
5853         static final int ADD_WAKEFULNESS_ANIMATING_REASON = 5;
5854         static final int REMOVE_WAKEFULNESS_ANIMATING_REASON = 6;
5855 
5856         static final int FIRST_ACTIVITY_TASK_MSG = 100;
5857         static final int FIRST_SUPERVISOR_TASK_MSG = 200;
5858 
H(Looper looper)5859         H(Looper looper) {
5860             super(looper);
5861         }
5862 
5863         @Override
handleMessage(Message msg)5864         public void handleMessage(Message msg) {
5865             switch (msg.what) {
5866                 case REPORT_TIME_TRACKER_MSG: {
5867                     AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5868                     tracker.deliverResult(mContext);
5869                 }
5870                 break;
5871                 case ADD_WAKEFULNESS_ANIMATING_REASON: {
5872                     final WindowProcessController proc = (WindowProcessController) msg.obj;
5873                     synchronized (mGlobalLock) {
5874                         proc.addAnimatingReason(
5875                                 WindowProcessController.ANIMATING_REASON_WAKEFULNESS_CHANGE);
5876                     }
5877                 }
5878                 break;
5879                 case REMOVE_WAKEFULNESS_ANIMATING_REASON: {
5880                     final WindowProcessController proc = (WindowProcessController) msg.obj;
5881                     synchronized (mGlobalLock) {
5882                         proc.removeAnimatingReason(
5883                                 WindowProcessController.ANIMATING_REASON_WAKEFULNESS_CHANGE);
5884                     }
5885                     Trace.instant(TRACE_TAG_WINDOW_MANAGER, "finishWakefulnessAnimating");
5886                 }
5887                 break;
5888                 case END_POWER_MODE_UNKNOWN_VISIBILITY_MSG: {
5889                     synchronized (mGlobalLock) {
5890                         mRetainPowerModeAndTopProcessState = false;
5891                         endPowerMode(POWER_MODE_REASON_UNKNOWN_VISIBILITY);
5892                         if (mTopApp != null
5893                                 && mTopProcessState == ActivityManager.PROCESS_STATE_TOP_SLEEPING) {
5894                             // Restore the scheduling group for sleeping.
5895                             mTopApp.updateProcessInfo(false /* updateServiceConnection */,
5896                                     false /* activityChange */, true /* updateOomAdj */,
5897                                     false /* addPendingTopUid */);
5898                         }
5899                     }
5900                 }
5901                 break;
5902                 case RESUME_FG_APP_SWITCH_MSG: {
5903                     synchronized (mGlobalLock) {
5904                         if (mAppSwitchesState == APP_SWITCH_DISALLOW) {
5905                             mAppSwitchesState = APP_SWITCH_FG_ONLY;
5906                         }
5907                     }
5908                 }
5909                 break;
5910             }
5911         }
5912     }
5913 
5914     final class UiHandler extends Handler {
5915         static final int DISMISS_DIALOG_UI_MSG = 1;
5916 
UiHandler()5917         public UiHandler() {
5918             super(UiThread.get().getLooper(), null, true);
5919         }
5920 
5921         @Override
handleMessage(Message msg)5922         public void handleMessage(Message msg) {
5923             switch (msg.what) {
5924                 case DISMISS_DIALOG_UI_MSG: {
5925                     final Dialog d = (Dialog) msg.obj;
5926                     d.dismiss();
5927                     break;
5928                 }
5929             }
5930         }
5931     }
5932 
5933     final class LocalService extends ActivityTaskManagerInternal {
5934         @Override
createSleepTokenAcquirer(@onNull String tag)5935         public SleepTokenAcquirer createSleepTokenAcquirer(@NonNull String tag) {
5936             Objects.requireNonNull(tag);
5937             return new SleepTokenAcquirerImpl(tag);
5938         }
5939 
5940         @Override
getHomeActivityForUser(int userId)5941         public ComponentName getHomeActivityForUser(int userId) {
5942             synchronized (mGlobalLock) {
5943                 final ActivityRecord homeActivity =
5944                         mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
5945                 return homeActivity == null ? null : homeActivity.mActivityComponent;
5946             }
5947         }
5948 
5949         @Override
onLocalVoiceInteractionStarted(IBinder activity, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor)5950         public void onLocalVoiceInteractionStarted(IBinder activity,
5951                 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5952             synchronized (mGlobalLock) {
5953                 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
5954             }
5955         }
5956 
5957         @Override
getTopVisibleActivities()5958         public List<ActivityAssistInfo> getTopVisibleActivities() {
5959             synchronized (mGlobalLock) {
5960                 return mRootWindowContainer.getTopVisibleActivities();
5961             }
5962         }
5963 
5964         @Override
hasResumedActivity(int uid)5965         public boolean hasResumedActivity(int uid) {
5966             return mVisibleActivityProcessTracker.hasResumedActivity(uid);
5967         }
5968 
5969         @Override
setBackgroundActivityStartCallback( @ullable BackgroundActivityStartCallback backgroundActivityStartCallback)5970         public void setBackgroundActivityStartCallback(
5971                 @Nullable BackgroundActivityStartCallback backgroundActivityStartCallback) {
5972             mBackgroundActivityStartCallback = backgroundActivityStartCallback;
5973         }
5974 
5975         @Override
setAccessibilityServiceUids(IntArray uids)5976         public void setAccessibilityServiceUids(IntArray uids) {
5977             synchronized (mGlobalLock) {
5978                 mAccessibilityServiceUids = uids.toArray();
5979             }
5980         }
5981 
5982         @Override
startActivitiesAsPackage(String packageName, @Nullable String featureId, int userId, Intent[] intents, Bundle bOptions)5983         public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
5984                 int userId, Intent[] intents, Bundle bOptions) {
5985             Objects.requireNonNull(intents, "intents");
5986             final String[] resolvedTypes = new String[intents.length];
5987 
5988             // UID of the package on user userId.
5989             // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5990             // packageUid may not be initialized.
5991             int packageUid = 0;
5992             final long ident = Binder.clearCallingIdentity();
5993 
5994             try {
5995                 for (int i = 0; i < intents.length; i++) {
5996                     resolvedTypes[i] =
5997                             intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5998                 }
5999 
6000                 packageUid = AppGlobals.getPackageManager().getPackageUid(
6001                         packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6002             } catch (RemoteException e) {
6003                 // Shouldn't happen.
6004             } finally {
6005                 Binder.restoreCallingIdentity(ident);
6006             }
6007 
6008             return getActivityStartController().startActivitiesInPackage(
6009                     packageUid, packageName, featureId,
6010                     intents, resolvedTypes, null /* resultTo */,
6011                     SafeActivityOptions.fromBundle(bOptions), userId,
6012                     false /* validateIncomingUser */, null /* originatingPendingIntent */,
6013                     BackgroundStartPrivileges.NONE);
6014         }
6015 
6016         @Override
startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid, String callingPackage, @Nullable String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId, boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, BackgroundStartPrivileges forcedBalByPiSender)6017         public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6018                 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6019                 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6020                 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
6021                 BackgroundStartPrivileges forcedBalByPiSender) {
6022             assertPackageMatchesCallingUid(callingPackage);
6023             return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6024                     realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6025                     resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
6026                     forcedBalByPiSender);
6027         }
6028 
6029         @Override
startActivityInPackage(int uid, int realCallingPid, int realCallingUid, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason, boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, BackgroundStartPrivileges forcedBalByPiSender)6030         public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6031                 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6032                 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6033                 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6034                 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
6035                 BackgroundStartPrivileges forcedBalByPiSender) {
6036             assertPackageMatchesCallingUid(callingPackage);
6037             return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6038                     realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6039                     resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6040                     reason, validateIncomingUser, originatingPendingIntent,
6041                     forcedBalByPiSender);
6042         }
6043 
6044         @Override
startActivityAsUser(IApplicationThread caller, String callerPackage, @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo, int startFlags, Bundle options, int userId)6045         public int startActivityAsUser(IApplicationThread caller, String callerPackage,
6046                 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6047                 int startFlags, Bundle options, int userId) {
6048             return ActivityTaskManagerService.this.startActivityAsUser(
6049                     caller, callerPackage, callerFeatureId, intent,
6050                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6051                     resultTo, null, 0, startFlags, null, options, userId,
6052                     false /*validateIncomingUser*/);
6053         }
6054 
6055         @Override
startActivityWithScreenshot(@onNull Intent intent, @NonNull String callingPackage, int callingUid, int callingPid, @Nullable IBinder resultTo, @Nullable Bundle options, int userId)6056         public int startActivityWithScreenshot(@NonNull Intent intent,
6057                 @NonNull String callingPackage, int callingUid, int callingPid,
6058                 @Nullable IBinder resultTo, @Nullable Bundle options, int userId) {
6059             userId = getActivityStartController().checkTargetUser(userId,
6060                     false /* validateIncomingUser */, Binder.getCallingPid(),
6061                     Binder.getCallingUid(), "startActivityWithScreenshot");
6062 
6063             return getActivityStartController()
6064                     .obtainStarter(intent, "startActivityWithScreenshot")
6065                     .setCallingUid(callingUid)
6066                     .setCallingPid(callingPid)
6067                     .setCallingPackage(callingPackage)
6068                     .setResultTo(resultTo)
6069                     .setActivityOptions(createSafeActivityOptionsWithBalAllowed(options))
6070                     .setRealCallingUid(Binder.getCallingUid())
6071                     .setUserId(userId)
6072                     .setBackgroundStartPrivileges(BackgroundStartPrivileges.ALLOW_BAL)
6073                     .setFreezeScreen(true)
6074                     .execute();
6075         }
6076 
6077         /**
6078          * Called after virtual display Id is updated by
6079          * {@link com.android.server.vr.Vr2dDisplay} with a specific
6080          * {@param vrVr2dDisplayId}.
6081          */
6082         @Override
setVr2dDisplayId(int vr2dDisplayId)6083         public void setVr2dDisplayId(int vr2dDisplayId) {
6084             ProtoLog.d(WM_DEBUG_TASKS, "setVr2dDisplayId called for: %d", vr2dDisplayId);
6085             synchronized (mGlobalLock) {
6086                 mVr2dDisplayId = vr2dDisplayId;
6087             }
6088         }
6089 
6090         @Override
getDisplayId(IBinder token)6091         public int getDisplayId(IBinder token) {
6092             synchronized (mGlobalLock) {
6093                 ActivityRecord r = ActivityRecord.forTokenLocked(token);
6094                 if (r == null) {
6095                     throw new IllegalArgumentException(
6096                             "getDisplayId: No activity record matching token=" + token);
6097                 }
6098                 return r.getDisplayId();
6099             }
6100         }
6101 
6102         @Override
registerScreenObserver(ScreenObserver observer)6103         public void registerScreenObserver(ScreenObserver observer) {
6104             mScreenObservers.add(observer);
6105         }
6106 
6107         @Override
unregisterScreenObserver(ScreenObserver observer)6108         public void unregisterScreenObserver(ScreenObserver observer) {
6109             mScreenObservers.remove(observer);
6110         }
6111 
6112         @Override
isCallerRecents(int callingUid)6113         public boolean isCallerRecents(int callingUid) {
6114             return ActivityTaskManagerService.this.isCallerRecents(callingUid);
6115         }
6116 
6117         @Override
isRecentsComponentHomeActivity(int userId)6118         public boolean isRecentsComponentHomeActivity(int userId) {
6119             return getRecentTasks().isRecentsComponentHomeActivity(userId);
6120         }
6121 
6122         @Override
checkCanCloseSystemDialogs(int pid, int uid, @Nullable String packageName)6123         public boolean checkCanCloseSystemDialogs(int pid, int uid, @Nullable String packageName) {
6124             return ActivityTaskManagerService.this.checkCanCloseSystemDialogs(pid, uid,
6125                     packageName);
6126         }
6127 
6128         @Override
canCloseSystemDialogs(int pid, int uid)6129         public boolean canCloseSystemDialogs(int pid, int uid) {
6130             return ActivityTaskManagerService.this.canCloseSystemDialogs(pid, uid);
6131         }
6132 
6133         @Override
notifyActiveVoiceInteractionServiceChanged(ComponentName component)6134         public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6135             synchronized (mGlobalLock) {
6136                 mActiveVoiceInteractionServiceComponent = component;
6137             }
6138         }
6139 
6140         @Override
notifyActiveDreamChanged(@ullable ComponentName dreamComponent)6141         public void notifyActiveDreamChanged(@Nullable ComponentName dreamComponent) {
6142             synchronized (mGlobalLock) {
6143                 mActiveDreamComponent = dreamComponent;
6144             }
6145         }
6146 
6147         @Override
startDreamActivity(@onNull Intent intent, int callingUid, int callingPid)6148         public IAppTask startDreamActivity(@NonNull Intent intent, int callingUid, int callingPid) {
6149             return startDreamActivityInternal(intent, callingUid, callingPid);
6150         }
6151 
6152         @Override
setAllowAppSwitches(@onNull String type, int uid, int userId)6153         public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6154             if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6155                 return;
6156             }
6157             synchronized (mGlobalLock) {
6158                 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6159                 if (types == null) {
6160                     if (uid < 0) {
6161                         return;
6162                     }
6163                     types = new ArrayMap<>();
6164                     mAllowAppSwitchUids.put(userId, types);
6165                 }
6166                 if (uid < 0) {
6167                     types.remove(type);
6168                 } else {
6169                     types.put(type, uid);
6170                 }
6171             }
6172         }
6173 
6174         @Override
onUserStopped(int userId)6175         public void onUserStopped(int userId) {
6176             synchronized (mGlobalLock) {
6177                 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6178                 mAllowAppSwitchUids.remove(userId);
6179             }
6180         }
6181 
6182         @Override
isGetTasksAllowed(String caller, int callingPid, int callingUid)6183         public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6184             return ActivityTaskManagerService.this.isGetTasksAllowed(
6185                     caller, callingPid, callingUid);
6186         }
6187 
6188         @HotPath(caller = HotPath.PROCESS_CHANGE)
6189         @Override
onProcessAdded(WindowProcessController proc)6190         public void onProcessAdded(WindowProcessController proc) {
6191             synchronized (mGlobalLockWithoutBoost) {
6192                 mProcessNames.put(proc.mName, proc.mUid, proc);
6193             }
6194         }
6195 
6196         @HotPath(caller = HotPath.PROCESS_CHANGE)
6197         @Override
onProcessRemoved(String name, int uid)6198         public void onProcessRemoved(String name, int uid) {
6199             synchronized (mGlobalLockWithoutBoost) {
6200                 final WindowProcessController proc = mProcessNames.remove(name, uid);
6201                 if (proc != null && !mStartingProcessActivities.isEmpty()) {
6202                     for (int i = mStartingProcessActivities.size() - 1; i >= 0; i--) {
6203                         final ActivityRecord r = mStartingProcessActivities.get(i);
6204                         if (uid == r.info.applicationInfo.uid && name.equals(r.processName)) {
6205                             Slog.w(TAG, proc + " is removed with pending start " + r);
6206                             mStartingProcessActivities.remove(i);
6207                             // If visible, finish it to avoid getting stuck on screen.
6208                             if (r.isVisibleRequested()) {
6209                                 r.finishIfPossible("starting-proc-removed", false /* oomAdj */);
6210                             }
6211                         }
6212                     }
6213                 }
6214             }
6215         }
6216 
6217         @HotPath(caller = HotPath.PROCESS_CHANGE)
6218         @Override
onCleanUpApplicationRecord(WindowProcessController proc)6219         public void onCleanUpApplicationRecord(WindowProcessController proc) {
6220             synchronized (mGlobalLockWithoutBoost) {
6221                 if (proc == mHomeProcess) {
6222                     mHomeProcess = null;
6223                 }
6224                 if (proc == mPreviousProcess) {
6225                     mPreviousProcess = null;
6226                 }
6227             }
6228         }
6229 
6230         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
6231         @Override
getTopProcessState()6232         public int getTopProcessState() {
6233             if (mRetainPowerModeAndTopProcessState) {
6234                 // There is a launching app while device may be sleeping, force the top state so
6235                 // the launching process can have top-app scheduling group.
6236                 return ActivityManager.PROCESS_STATE_TOP;
6237             }
6238             return mTopProcessState;
6239         }
6240 
6241         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
6242         @Override
useTopSchedGroupForTopProcess()6243         public boolean useTopSchedGroupForTopProcess() {
6244             // If it is non-zero, there may be a more important UI/animation than the top app.
6245             return mDemoteTopAppReasons == 0;
6246         }
6247 
6248         @HotPath(caller = HotPath.PROCESS_CHANGE)
6249         @Override
clearHeavyWeightProcessIfEquals(WindowProcessController proc)6250         public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6251             synchronized (mGlobalLockWithoutBoost) {
6252                 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6253             }
6254         }
6255 
6256         @Override
finishHeavyWeightApp()6257         public void finishHeavyWeightApp() {
6258             synchronized (mGlobalLock) {
6259                 if (mHeavyWeightProcess != null) {
6260                     mHeavyWeightProcess.finishActivities();
6261                 }
6262                 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6263                         mHeavyWeightProcess);
6264             }
6265         }
6266 
6267         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
6268         @Override
isSleeping()6269         public boolean isSleeping() {
6270             return mSleeping;
6271         }
6272 
6273         @Override
isShuttingDown()6274         public boolean isShuttingDown() {
6275             return mShuttingDown;
6276         }
6277 
6278         @Override
shuttingDown(boolean booted, int timeout)6279         public boolean shuttingDown(boolean booted, int timeout) {
6280             mShuttingDown = true;
6281             synchronized (mGlobalLock) {
6282                 mRootWindowContainer.prepareForShutdown();
6283                 updateEventDispatchingLocked(booted);
6284                 notifyTaskPersisterLocked(null, true);
6285                 return mTaskSupervisor.shutdownLocked(timeout);
6286             }
6287         }
6288 
6289         @Override
enableScreenAfterBoot(boolean booted)6290         public void enableScreenAfterBoot(boolean booted) {
6291             writeBootProgressEnableScreen(SystemClock.uptimeMillis());
6292             mWindowManager.enableScreenAfterBoot();
6293             synchronized (mGlobalLock) {
6294                 updateEventDispatchingLocked(booted);
6295             }
6296         }
6297 
6298         @Override
showStrictModeViolationDialog()6299         public boolean showStrictModeViolationDialog() {
6300             synchronized (mGlobalLock) {
6301                 return mShowDialogs && !mSleeping && !mShuttingDown;
6302             }
6303         }
6304 
6305         @Override
showSystemReadyErrorDialogsIfNeeded()6306         public void showSystemReadyErrorDialogsIfNeeded() {
6307             if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6308                 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "showSystemReadyErrorDialogs");
6309             }
6310             // Pull the check for build consistency outside the lock, to avoid holding the lock for
6311             // too long, given that `Build.isBuildConsistent()` takes relatively long.
6312             boolean isBuildConsistent = Build.isBuildConsistent();
6313             synchronized (mGlobalLock) {
6314                 try {
6315                     if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6316                         Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6317                                 + " data partition or your device will be unstable.");
6318                         mUiHandler.post(() -> {
6319                             if (mShowDialogs) {
6320                                 AlertDialog d = new BaseErrorDialog(mUiContext);
6321                                 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6322                                 d.setCancelable(false);
6323                                 d.setTitle(mUiContext.getText(R.string.android_system_label));
6324                                 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6325                                 d.setButton(DialogInterface.BUTTON_POSITIVE,
6326                                         mUiContext.getText(R.string.ok),
6327                                         mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6328                                 d.show();
6329                             }
6330                         });
6331                     }
6332                 } catch (RemoteException e) {
6333                 }
6334 
6335                 if (!isBuildConsistent) {
6336                     Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6337                     mUiHandler.post(() -> {
6338                         if (mShowDialogs) {
6339                             AlertDialog d = new BaseErrorDialog(mUiContext);
6340                             d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6341                             d.setCancelable(false);
6342                             d.setTitle(mUiContext.getText(R.string.android_system_label));
6343                             d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6344                             d.setButton(DialogInterface.BUTTON_POSITIVE,
6345                                     mUiContext.getText(R.string.ok),
6346                                     mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6347                             d.show();
6348                         }
6349                     });
6350                 }
6351             }
6352             Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6353         }
6354 
6355         @Override
onProcessMapped(int pid, WindowProcessController proc)6356         public void onProcessMapped(int pid, WindowProcessController proc) {
6357             synchronized (mGlobalLock) {
6358                 mProcessMap.put(pid, proc);
6359             }
6360         }
6361 
6362         @Override
onProcessUnMapped(int pid)6363         public void onProcessUnMapped(int pid) {
6364             synchronized (mGlobalLock) {
6365                 mProcessMap.remove(pid);
6366             }
6367         }
6368 
6369         @Override
onPackageDataCleared(String name, int userId)6370         public void onPackageDataCleared(String name, int userId) {
6371             synchronized (mGlobalLock) {
6372                 mCompatModePackages.handlePackageDataClearedLocked(name);
6373                 mAppWarnings.onPackageDataCleared(name, userId);
6374                 mPackageConfigPersister.onPackageDataCleared(name, userId);
6375             }
6376         }
6377 
6378         @Override
onPackageUninstalled(String name, int userId)6379         public void onPackageUninstalled(String name, int userId) {
6380             synchronized (mGlobalLock) {
6381                 mAppWarnings.onPackageUninstalled(name, userId);
6382                 mCompatModePackages.handlePackageUninstalledLocked(name);
6383                 mPackageConfigPersister.onPackageUninstall(name, userId);
6384             }
6385         }
6386 
6387         @Override
onPackageAdded(String name, boolean replacing)6388         public void onPackageAdded(String name, boolean replacing) {
6389             synchronized (mGlobalLock) {
6390                 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6391             }
6392         }
6393 
6394         @Override
onPackageReplaced(ApplicationInfo aInfo)6395         public void onPackageReplaced(ApplicationInfo aInfo) {
6396             synchronized (mGlobalLock) {
6397                 // In case if setWindowManager hasn't been called yet when booting.
6398                 if (mRootWindowContainer == null) return;
6399                 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
6400             }
6401         }
6402 
6403         @Override
compatibilityInfoForPackage(ApplicationInfo ai)6404         public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6405             synchronized (mGlobalLock) {
6406                 return compatibilityInfoForPackageLocked(ai);
6407             }
6408         }
6409 
6410         @Override
sendActivityResult(int callingUid, IBinder activityToken, String resultWho, int requestCode, int resultCode, Intent data)6411         public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6412                 int requestCode, int resultCode, Intent data) {
6413             final ActivityRecord r;
6414             synchronized (mGlobalLock) {
6415                 r = ActivityRecord.isInRootTaskLocked(activityToken);
6416                 if (r == null || r.getRootTask() == null) {
6417                     return;
6418                 }
6419             }
6420 
6421             // Carefully collect grants without holding lock
6422             final NeededUriGrants dataGrants = collectGrants(data, r);
6423 
6424             synchronized (mGlobalLock) {
6425                 r.sendResult(callingUid, resultWho, requestCode, resultCode, data, new Binder(),
6426                         dataGrants);
6427             }
6428         }
6429 
6430         @Override
clearPendingResultForActivity(IBinder activityToken, WeakReference<PendingIntentRecord> pir)6431         public void clearPendingResultForActivity(IBinder activityToken,
6432                 WeakReference<PendingIntentRecord> pir) {
6433             synchronized (mGlobalLock) {
6434                 final ActivityRecord r = ActivityRecord.isInRootTaskLocked(activityToken);
6435                 if (r != null && r.pendingResults != null) {
6436                     r.pendingResults.remove(pir);
6437                 }
6438             }
6439         }
6440 
6441         @Override
getActivityName(IBinder activityToken)6442         public ComponentName getActivityName(IBinder activityToken) {
6443             synchronized (mGlobalLock) {
6444                 final ActivityRecord r = ActivityRecord.isInRootTaskLocked(activityToken);
6445                 return r != null ? r.intent.getComponent() : null;
6446             }
6447         }
6448 
6449         @Override
getAttachedNonFinishingActivityForTask(int taskId, IBinder token)6450         public ActivityTokens getAttachedNonFinishingActivityForTask(int taskId,
6451                 IBinder token) {
6452             synchronized (mGlobalLock) {
6453                 final Task task = mRootWindowContainer.anyTaskForId(taskId,
6454                         MATCH_ATTACHED_TASK_ONLY);
6455                 if (task == null) {
6456                     Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6457                             + " Requested task not found");
6458                     return null;
6459                 }
6460                 final List<ActivityRecord> list = new ArrayList<>();
6461                 task.forAllActivities(r -> {
6462                     if (!r.finishing) {
6463                         list.add(r);
6464                     }
6465                 });
6466                 if (list.size() <= 0) {
6467                     return null;
6468                 }
6469                 // pass null, get top Activity
6470                 if (token == null && list.get(0).attachedToProcess()) {
6471                     ActivityRecord topRecord = list.get(0);
6472                     return new ActivityTokens(topRecord.token, topRecord.assistToken,
6473                             topRecord.app.getThread(), topRecord.shareableActivityToken,
6474                             topRecord.getUid());
6475                 }
6476                 // find the expected Activity
6477                 for (int i = 0; i < list.size(); i++) {
6478                     ActivityRecord record = list.get(i);
6479                     if (record.shareableActivityToken == token && record.attachedToProcess()) {
6480                         return new ActivityTokens(record.token, record.assistToken,
6481                                 record.app.getThread(), record.shareableActivityToken,
6482                                 record.getUid());
6483                     }
6484                 }
6485                 return null;
6486             }
6487         }
6488 
6489         @Override
getIntentSender(int type, String packageName, @Nullable String featureId, int callingUid, int userId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions)6490         public IIntentSender getIntentSender(int type, String packageName,
6491                 @Nullable String featureId, int callingUid, int userId, IBinder token,
6492                 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6493                 int flags, Bundle bOptions) {
6494             synchronized (mGlobalLock) {
6495                 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6496                         token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6497             }
6498         }
6499 
6500         @Override
getServiceConnectionsHolder(IBinder token)6501         public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6502             final ActivityRecord r = ActivityRecord.forToken(token);
6503             if (r == null || !r.inHistory) {
6504                 return null;
6505             }
6506             return r.getOrCreateServiceConnectionsHolder();
6507         }
6508 
6509         @Override
getHomeIntent()6510         public Intent getHomeIntent() {
6511             synchronized (mGlobalLock) {
6512                 return ActivityTaskManagerService.this.getHomeIntent();
6513             }
6514         }
6515 
6516         @Override
startHomeActivity(int userId, String reason)6517         public boolean startHomeActivity(int userId, String reason) {
6518             synchronized (mGlobalLock) {
6519                 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
6520             }
6521         }
6522 
6523         @Override
startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting, boolean fromHomeKey)6524         public boolean startHomeOnDisplay(int userId, String reason, int displayId,
6525                 boolean allowInstrumenting, boolean fromHomeKey) {
6526             synchronized (mGlobalLock) {
6527                 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
6528                         allowInstrumenting, fromHomeKey);
6529             }
6530         }
6531 
6532         @Override
startHomeOnAllDisplays(int userId, String reason)6533         public boolean startHomeOnAllDisplays(int userId, String reason) {
6534             synchronized (mGlobalLock) {
6535                 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
6536             }
6537         }
6538 
6539         @Override
updateTopComponentForFactoryTest()6540         public void updateTopComponentForFactoryTest() {
6541             synchronized (mGlobalLock) {
6542                 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6543                     return;
6544                 }
6545                 final ResolveInfo ri = mContext.getPackageManager()
6546                         .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6547                 final CharSequence errorMsg;
6548                 if (ri != null) {
6549                     final ActivityInfo ai = ri.activityInfo;
6550                     final ApplicationInfo app = ai.applicationInfo;
6551                     if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6552                         mTopAction = Intent.ACTION_FACTORY_TEST;
6553                         mTopData = null;
6554                         mTopComponent = new ComponentName(app.packageName, ai.name);
6555                         errorMsg = null;
6556                     } else {
6557                         errorMsg = mContext.getResources().getText(
6558                                 com.android.internal.R.string.factorytest_not_system);
6559                     }
6560                 } else {
6561                     errorMsg = mContext.getResources().getText(
6562                             com.android.internal.R.string.factorytest_no_action);
6563                 }
6564                 if (errorMsg == null) {
6565                     return;
6566                 }
6567 
6568                 mTopAction = null;
6569                 mTopData = null;
6570                 mTopComponent = null;
6571                 mUiHandler.post(() -> {
6572                     Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6573                     d.show();
6574                     mAmInternal.ensureBootCompleted();
6575                 });
6576             }
6577         }
6578 
6579         @HotPath(caller = HotPath.PROCESS_CHANGE)
6580         @Override
handleAppDied(WindowProcessController wpc, boolean restarting, Runnable finishInstrumentationCallback)6581         public void handleAppDied(WindowProcessController wpc, boolean restarting,
6582                 Runnable finishInstrumentationCallback) {
6583             synchronized (mGlobalLockWithoutBoost) {
6584                 mTaskSupervisor.beginDeferResume();
6585                 final boolean hasVisibleActivities;
6586                 try {
6587                     // Remove this application's activities from active lists.
6588                     hasVisibleActivities = wpc.handleAppDied();
6589                 } finally {
6590                     mTaskSupervisor.endDeferResume();
6591                 }
6592 
6593                 if (!restarting && hasVisibleActivities) {
6594                     deferWindowLayout();
6595                     try {
6596                         mRootWindowContainer.ensureVisibilityOnVisibleActivityDiedOrCrashed(
6597                                 "handleAppDied");
6598                     } finally {
6599                         continueWindowLayout();
6600                     }
6601                 }
6602             }
6603             if (wpc.isInstrumenting()) {
6604                 finishInstrumentationCallback.run();
6605             }
6606         }
6607 
6608         @Override
closeSystemDialogs(String reason)6609         public void closeSystemDialogs(String reason) {
6610             enforceNotIsolatedCaller("closeSystemDialogs");
6611             final int pid = Binder.getCallingPid();
6612             final int uid = Binder.getCallingUid();
6613             if (!checkCanCloseSystemDialogs(pid, uid, null)) {
6614                 return;
6615             }
6616 
6617             final long origId = Binder.clearCallingIdentity();
6618             try {
6619                 synchronized (mGlobalLock) {
6620                     // Only allow this from foreground processes, so that background
6621                     // applications can't abuse it to prevent system UI from being shown.
6622                     if (uid >= FIRST_APPLICATION_UID) {
6623                         final WindowProcessController proc = mProcessMap.getProcess(pid);
6624                         if (!proc.isPerceptible()) {
6625                             Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6626                                     + " from background process " + proc);
6627                             return;
6628                         }
6629                     }
6630                     mWindowManager.closeSystemDialogs(reason);
6631 
6632                     mRootWindowContainer.closeSystemDialogActivities(reason);
6633                 }
6634                 // Call into AM outside the synchronized block.
6635                 mAmInternal.broadcastCloseSystemDialogs(reason);
6636             } finally {
6637                 Binder.restoreCallingIdentity(origId);
6638             }
6639         }
6640 
6641         @Override
cleanupDisabledPackageComponents( String packageName, Set<String> disabledClasses, int userId, boolean booted)6642         public void cleanupDisabledPackageComponents(
6643                 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6644             synchronized (mGlobalLock) {
6645                 // In case if setWindowManager hasn't been called yet when booting.
6646                 if (mRootWindowContainer == null) return;
6647                 // Clean-up disabled activities.
6648                 if (mRootWindowContainer.finishDisabledPackageActivities(
6649                         packageName, disabledClasses, true /* doit */, false /* evenPersistent */,
6650                         userId, false /* onlyRemoveNoProcess */) && booted) {
6651                     mRootWindowContainer.resumeFocusedTasksTopActivities();
6652                     mTaskSupervisor.scheduleIdle();
6653                 }
6654 
6655                 // Clean-up disabled tasks
6656                 getRecentTasks().cleanupDisabledPackageTasksLocked(
6657                         packageName, disabledClasses, userId);
6658             }
6659         }
6660 
6661         @Override
onForceStopPackage(String packageName, boolean doit, boolean evenPersistent, int userId)6662         public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6663                 int userId) {
6664             synchronized (mGlobalLock) {
6665                 // In case if setWindowManager hasn't been called yet when booting.
6666                 if (mRootWindowContainer == null) return false;
6667                 return mRootWindowContainer.finishDisabledPackageActivities(packageName,
6668                         null /* filterByClasses */, doit, evenPersistent, userId,
6669                         // Only remove the activities without process because the activities with
6670                         // attached process will be removed when handling process died with
6671                         // WindowProcessController#isRemoved == true.
6672                         true /* onlyRemoveNoProcess */);
6673             }
6674         }
6675 
6676         @Override
resumeTopActivities(boolean scheduleIdle)6677         public void resumeTopActivities(boolean scheduleIdle) {
6678             synchronized (mGlobalLock) {
6679                 mRootWindowContainer.resumeFocusedTasksTopActivities();
6680                 if (scheduleIdle) {
6681                     mTaskSupervisor.scheduleIdle();
6682                 }
6683             }
6684         }
6685 
6686         @HotPath(caller = HotPath.PROCESS_CHANGE)
6687         @Override
preBindApplication(WindowProcessController wpc)6688         public void preBindApplication(WindowProcessController wpc) {
6689             synchronized (mGlobalLockWithoutBoost) {
6690                 mTaskSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6691             }
6692         }
6693 
6694         @HotPath(caller = HotPath.PROCESS_CHANGE)
6695         @Override
attachApplication(WindowProcessController wpc)6696         public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6697             synchronized (mGlobalLockWithoutBoost) {
6698                 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6699                     Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6700                 }
6701                 try {
6702                     return mRootWindowContainer.attachApplication(wpc);
6703                 } finally {
6704                     Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6705                 }
6706             }
6707         }
6708 
6709         @Override
notifyLockedProfile(@serIdInt int userId)6710         public void notifyLockedProfile(@UserIdInt int userId) {
6711             try {
6712                 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6713                     throw new SecurityException("Only privileged app can call notifyLockedProfile");
6714                 }
6715             } catch (RemoteException ex) {
6716                 throw new SecurityException("Fail to check is caller a privileged app", ex);
6717             }
6718 
6719             synchronized (mGlobalLock) {
6720                 final long ident = Binder.clearCallingIdentity();
6721                 try {
6722                     if (mAmInternal.shouldConfirmCredentials(userId)) {
6723                         maybeHideLockedProfileActivityLocked();
6724                         mRootWindowContainer.lockAllProfileTasks(userId);
6725                     }
6726                 } finally {
6727                     Binder.restoreCallingIdentity(ident);
6728                 }
6729             }
6730         }
6731 
6732         @Override
startConfirmDeviceCredentialIntent(Intent intent, Bundle options)6733         public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6734             enforceTaskPermission("startConfirmDeviceCredentialIntent");
6735 
6736             synchronized (mGlobalLock) {
6737                 final long ident = Binder.clearCallingIdentity();
6738                 try {
6739                     intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6740                     final ActivityOptions activityOptions = options != null
6741                             ? new ActivityOptions(options) : ActivityOptions.makeBasic();
6742                     mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6743                             UserHandle.CURRENT);
6744                 } finally {
6745                     Binder.restoreCallingIdentity(ident);
6746                 }
6747             }
6748         }
6749 
6750         @Override
writeActivitiesToProto(ProtoOutputStream proto)6751         public void writeActivitiesToProto(ProtoOutputStream proto) {
6752             synchronized (mGlobalLock) {
6753                 // The output proto of "activity --proto activities"
6754                 mRootWindowContainer.dumpDebug(
6755                         proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
6756             }
6757         }
6758 
6759         @Override
dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter)6760         public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6761                 boolean dumpAll, boolean dumpClient, String dumpPackage, int displayIdFilter) {
6762             synchronized (mGlobalLock) {
6763                 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6764                     dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
6765                             displayIdFilter);
6766                 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6767                     dumpLastANRLocked(pw);
6768                 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6769                     dumpLastANRTracesLocked(pw);
6770                 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6771                     dumpActivityStarterLocked(pw, dumpPackage);
6772                 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6773                     dumpActivityContainersLocked(pw);
6774                 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6775                     if (getRecentTasks() != null) {
6776                         getRecentTasks().dump(pw, dumpAll, dumpPackage);
6777                     }
6778                 } else if (DUMP_TOP_RESUMED_ACTIVITY.equals(cmd)) {
6779                     dumpTopResumedActivityLocked(pw);
6780                 } else if (DUMP_VISIBLE_ACTIVITIES.equals(cmd)) {
6781                     dumpVisibleActivitiesLocked(pw, displayIdFilter);
6782                 }
6783             }
6784         }
6785 
6786         @Override
dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode, int wakefulness)6787         public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6788                 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6789                 int wakefulness) {
6790             synchronized (mGlobalLock) {
6791                 if (mHomeProcess != null && (dumpPackage == null
6792                         || mHomeProcess.containsPackage(dumpPackage))) {
6793                     if (needSep) {
6794                         pw.println();
6795                         needSep = false;
6796                     }
6797                     pw.println("  mHomeProcess: " + mHomeProcess);
6798                 }
6799                 if (mPreviousProcess != null && (dumpPackage == null
6800                         || mPreviousProcess.containsPackage(dumpPackage))) {
6801                     if (needSep) {
6802                         pw.println();
6803                         needSep = false;
6804                     }
6805                     pw.println("  mPreviousProcess: " + mPreviousProcess);
6806                 }
6807                 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6808                         || mPreviousProcess.containsPackage(dumpPackage))) {
6809                     StringBuilder sb = new StringBuilder(128);
6810                     sb.append("  mPreviousProcessVisibleTime: ");
6811                     TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6812                     pw.println(sb);
6813                 }
6814                 if (mHeavyWeightProcess != null && (dumpPackage == null
6815                         || mHeavyWeightProcess.containsPackage(dumpPackage))) {
6816                     if (needSep) {
6817                         pw.println();
6818                         needSep = false;
6819                     }
6820                     pw.println("  mHeavyWeightProcess: " + mHeavyWeightProcess);
6821                 }
6822                 if (dumpPackage == null) {
6823                     pw.println("  mGlobalConfiguration: " + getGlobalConfiguration());
6824                     mRootWindowContainer.dumpDisplayConfigs(pw, "  ");
6825                 }
6826                 if (dumpAll) {
6827                     final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
6828                     if (dumpPackage == null && topFocusedRootTask != null) {
6829                         pw.println("  mConfigWillChange: " + topFocusedRootTask.mConfigWillChange);
6830                     }
6831                     if (mCompatModePackages.getPackages().size() > 0) {
6832                         boolean printed = false;
6833                         for (Map.Entry<String, Integer> entry
6834                                 : mCompatModePackages.getPackages().entrySet()) {
6835                             String pkg = entry.getKey();
6836                             int mode = entry.getValue();
6837                             if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6838                                 continue;
6839                             }
6840                             if (!printed) {
6841                                 pw.println("  mScreenCompatPackages:");
6842                                 printed = true;
6843                             }
6844                             pw.println("    " + pkg + ": " + mode);
6845                         }
6846                     }
6847                 }
6848 
6849                 if (dumpPackage == null) {
6850                     pw.println("  mWakefulness="
6851                             + PowerManagerInternal.wakefulnessToString(wakefulness));
6852                     pw.println("  mSleepTokens=" + mRootWindowContainer.mSleepTokens);
6853                     if (mRunningVoice != null) {
6854                         pw.println("  mRunningVoice=" + mRunningVoice);
6855                         pw.println("  mVoiceWakeLock" + mVoiceWakeLock);
6856                     }
6857                     pw.println("  mSleeping=" + mSleeping);
6858                     pw.println("  mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6859                     pw.println("  mVrController=" + mVrController);
6860                 }
6861                 if (mCurAppTimeTracker != null) {
6862                     mCurAppTimeTracker.dumpWithHeader(pw, "  ", true);
6863                 }
6864                 if (mAllowAppSwitchUids.size() > 0) {
6865                     boolean printed = false;
6866                     for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6867                         ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6868                         for (int j = 0; j < types.size(); j++) {
6869                             if (dumpPackage == null ||
6870                                     UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6871                                 if (needSep) {
6872                                     pw.println();
6873                                     needSep = false;
6874                                 }
6875                                 if (!printed) {
6876                                     pw.println("  mAllowAppSwitchUids:");
6877                                     printed = true;
6878                                 }
6879                                 pw.print("    User ");
6880                                 pw.print(mAllowAppSwitchUids.keyAt(i));
6881                                 pw.print(": Type ");
6882                                 pw.print(types.keyAt(j));
6883                                 pw.print(" = ");
6884                                 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6885                                 pw.println();
6886                             }
6887                         }
6888                     }
6889                 }
6890                 if (dumpPackage == null) {
6891                     if (mController != null) {
6892                         pw.println("  mController=" + mController
6893                                 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6894                     }
6895                     pw.println("  mGoingToSleepWakeLock=" + mTaskSupervisor.mGoingToSleepWakeLock);
6896                     pw.println("  mLaunchingActivityWakeLock="
6897                             + mTaskSupervisor.mLaunchingActivityWakeLock);
6898                 }
6899 
6900                 return needSep;
6901             }
6902         }
6903 
6904         @Override
writeProcessesToProto(ProtoOutputStream proto, String dumpPackage, int wakeFullness, boolean testPssMode)6905         public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6906                 int wakeFullness, boolean testPssMode) {
6907             synchronized (mGlobalLock) {
6908                 if (dumpPackage == null) {
6909                     getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
6910                     final Task topFocusedRootTask = getTopDisplayFocusedRootTask();
6911                     if (topFocusedRootTask != null) {
6912                         proto.write(CONFIG_WILL_CHANGE, topFocusedRootTask.mConfigWillChange);
6913                     }
6914                     writeSleepStateToProto(proto, wakeFullness, testPssMode);
6915                     if (mRunningVoice != null) {
6916                         final long vrToken = proto.start(
6917                                 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6918                         proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6919                                 mRunningVoice.toString());
6920                         mVoiceWakeLock.dumpDebug(
6921                                 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6922                         proto.end(vrToken);
6923                     }
6924                     mVrController.dumpDebug(proto,
6925                             ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
6926                     if (mController != null) {
6927                         final long token = proto.start(CONTROLLER);
6928                         proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
6929                                 mController.toString());
6930                         proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6931                         proto.end(token);
6932                     }
6933                     mTaskSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
6934                     mTaskSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
6935                             LAUNCHING_ACTIVITY);
6936                 }
6937 
6938                 if (mHomeProcess != null && (dumpPackage == null
6939                         || mHomeProcess.containsPackage(dumpPackage))) {
6940                     mHomeProcess.dumpDebug(proto, HOME_PROC);
6941                 }
6942 
6943                 if (mPreviousProcess != null && (dumpPackage == null
6944                         || mPreviousProcess.containsPackage(dumpPackage))) {
6945                     mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
6946                     proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6947                 }
6948 
6949                 if (mHeavyWeightProcess != null && (dumpPackage == null
6950                         || mHeavyWeightProcess.containsPackage(dumpPackage))) {
6951                     mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
6952                 }
6953 
6954                 for (Map.Entry<String, Integer> entry
6955                         : mCompatModePackages.getPackages().entrySet()) {
6956                     String pkg = entry.getKey();
6957                     int mode = entry.getValue();
6958                     if (dumpPackage == null || dumpPackage.equals(pkg)) {
6959                         long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6960                         proto.write(PACKAGE, pkg);
6961                         proto.write(MODE, mode);
6962                         proto.end(compatToken);
6963                     }
6964                 }
6965 
6966                 if (mCurAppTimeTracker != null) {
6967                     mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
6968                 }
6969 
6970             }
6971         }
6972 
6973         @Override
dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly, boolean dumpFocusedRootTaskOnly, int displayIdFilter, @UserIdInt int userId)6974         public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6975                 String[] args, int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly,
6976                 boolean dumpFocusedRootTaskOnly, int displayIdFilter,
6977                 @UserIdInt int userId) {
6978             return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
6979                     dumpVisibleRootTasksOnly, dumpFocusedRootTaskOnly, displayIdFilter, userId,
6980                     /* timeout= */ 5000);
6981         }
6982 
6983         @Override
dumpForOom(PrintWriter pw)6984         public void dumpForOom(PrintWriter pw) {
6985             synchronized (mGlobalLock) {
6986                 pw.println("  mHomeProcess: " + mHomeProcess);
6987                 pw.println("  mPreviousProcess: " + mPreviousProcess);
6988                 if (mHeavyWeightProcess != null) {
6989                     pw.println("  mHeavyWeightProcess: " + mHeavyWeightProcess);
6990                 }
6991             }
6992         }
6993 
6994         @Override
canGcNow()6995         public boolean canGcNow() {
6996             synchronized (mGlobalLock) {
6997                 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
6998             }
6999         }
7000 
7001         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
7002         @Override
getTopApp()7003         public WindowProcessController getTopApp() {
7004             return mTopApp;
7005         }
7006 
7007         @Override
scheduleDestroyAllActivities(String reason)7008         public void scheduleDestroyAllActivities(String reason) {
7009             synchronized (mGlobalLock) {
7010                 mRootWindowContainer.scheduleDestroyAllActivities(reason);
7011             }
7012         }
7013 
7014         @Override
removeUser(int userId)7015         public void removeUser(int userId) {
7016             synchronized (mGlobalLock) {
7017                 mRootWindowContainer.removeUser(userId);
7018                 mPackageConfigPersister.removeUser(userId);
7019             }
7020         }
7021 
7022         @Override
switchUser(int userId, UserState userState)7023         public boolean switchUser(int userId, UserState userState) {
7024             synchronized (mGlobalLock) {
7025                 return mRootWindowContainer.switchUser(userId, userState);
7026             }
7027         }
7028 
7029         @Override
onHandleAppCrash(@onNull WindowProcessController wpc)7030         public void onHandleAppCrash(@NonNull WindowProcessController wpc) {
7031             synchronized (mGlobalLock) {
7032                 wpc.handleAppCrash();
7033             }
7034         }
7035 
7036         @Override
finishTopCrashedActivities(WindowProcessController crashedApp, String reason)7037         public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7038             synchronized (mGlobalLock) {
7039                 deferWindowLayout();
7040                 try {
7041                     final Task finishedTask = mRootWindowContainer.finishTopCrashedActivities(
7042                             crashedApp, reason);
7043                     if (finishedTask != null) {
7044                         mRootWindowContainer.ensureVisibilityOnVisibleActivityDiedOrCrashed(reason);
7045                         return finishedTask.mTaskId;
7046                     }
7047                     return INVALID_TASK_ID;
7048                 } finally {
7049                     continueWindowLayout();
7050                 }
7051             }
7052         }
7053 
7054         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
7055         @Override
onUidActive(int uid, int procState)7056         public void onUidActive(int uid, int procState) {
7057             mActiveUids.onUidActive(uid, procState);
7058         }
7059 
7060         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
7061         @Override
onUidInactive(int uid)7062         public void onUidInactive(int uid) {
7063             mActiveUids.onUidInactive(uid);
7064         }
7065 
7066         @HotPath(caller = HotPath.OOM_ADJUSTMENT)
7067         @Override
onUidProcStateChanged(int uid, int procState)7068         public void onUidProcStateChanged(int uid, int procState) {
7069             mActiveUids.onUidProcStateChanged(uid, procState);
7070         }
7071 
7072         @Override
handleAppCrashInActivityController(String processName, int pid, String shortMsg, String longMsg, long timeMillis, String stackTrace, Runnable killCrashingAppCallback)7073         public boolean handleAppCrashInActivityController(String processName, int pid,
7074                 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7075                 Runnable killCrashingAppCallback) {
7076             Runnable targetRunnable = null;
7077             synchronized (mGlobalLock) {
7078                 if (mController == null) {
7079                     return false;
7080                 }
7081 
7082                 try {
7083                     if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7084                             stackTrace)) {
7085                         targetRunnable = killCrashingAppCallback;
7086                     }
7087                 } catch (RemoteException e) {
7088                     mController = null;
7089                     Watchdog.getInstance().setActivityController(null);
7090                 }
7091             }
7092             if (targetRunnable != null) {
7093                 targetRunnable.run();
7094                 return true;
7095             }
7096             return false;
7097         }
7098 
7099         @Override
removeRecentTasksByPackageName(String packageName, int userId)7100         public void removeRecentTasksByPackageName(String packageName, int userId) {
7101             synchronized (mGlobalLock) {
7102                 mRecentTasks.removeTasksByPackageName(packageName, userId);
7103             }
7104         }
7105 
7106         @Override
cleanupRecentTasksForUser(int userId)7107         public void cleanupRecentTasksForUser(int userId) {
7108             synchronized (mGlobalLock) {
7109                 mRecentTasks.cleanupLocked(userId);
7110             }
7111         }
7112 
7113         @Override
loadRecentTasksForUser(int userId)7114         public void loadRecentTasksForUser(int userId) {
7115             // This runs on android.fg thread when the user is unlocking.
7116             mRecentTasks.loadRecentTasksIfNeeded(userId);
7117             mPackageConfigPersister.loadUserPackages(userId);
7118         }
7119 
7120         @Override
onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId)7121         public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7122             synchronized (mGlobalLock) {
7123                 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7124             }
7125         }
7126 
7127         @Override
flushRecentTasks()7128         public void flushRecentTasks() {
7129             mRecentTasks.flush();
7130         }
7131 
7132         @Override
clearLockedTasks(String reason)7133         public void clearLockedTasks(String reason) {
7134             synchronized (mGlobalLock) {
7135                 getLockTaskController().clearLockedTasks(reason);
7136             }
7137         }
7138 
7139         @Override
updateUserConfiguration()7140         public void updateUserConfiguration() {
7141             synchronized (mGlobalLock) {
7142                 final Configuration configuration = new Configuration(getGlobalConfiguration());
7143                 final int currentUserId = mAmInternal.getCurrentUserId();
7144                 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7145                         configuration, currentUserId, Settings.System.canWrite(mContext));
7146                 updateConfigurationLocked(configuration, null /* starting */,
7147                         false /* initLocale */, false /* persistent */, currentUserId,
7148                         false /* deferResume */);
7149             }
7150         }
7151 
7152         @Override
canShowErrorDialogs()7153         public boolean canShowErrorDialogs() {
7154             synchronized (mGlobalLock) {
7155                 return mShowDialogs && !mSleeping && !mShuttingDown
7156                         && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7157                         && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7158                         mAmInternal.getCurrentUserId())
7159                         && !(UserManager.isDeviceInDemoMode(mContext)
7160                         && mAmInternal.getCurrentUser().isDemo());
7161             }
7162         }
7163 
7164         @Override
setProfileApp(String profileApp)7165         public void setProfileApp(String profileApp) {
7166             synchronized (mGlobalLock) {
7167                 mProfileApp = profileApp;
7168             }
7169         }
7170 
7171         @Override
setProfileProc(WindowProcessController wpc)7172         public void setProfileProc(WindowProcessController wpc) {
7173             synchronized (mGlobalLock) {
7174                 mProfileProc = wpc;
7175             }
7176         }
7177 
7178         @Override
setProfilerInfo(ProfilerInfo profilerInfo)7179         public void setProfilerInfo(ProfilerInfo profilerInfo) {
7180             synchronized (mGlobalLock) {
7181                 mProfilerInfo = profilerInfo;
7182             }
7183         }
7184 
7185         @Override
getLaunchObserverRegistry()7186         public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7187             synchronized (mGlobalLock) {
7188                 return mTaskSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7189             }
7190         }
7191 
7192         @Nullable
7193         @Override
getUriPermissionOwnerForActivity(@onNull IBinder activityToken)7194         public IBinder getUriPermissionOwnerForActivity(@NonNull IBinder activityToken) {
7195             ActivityTaskManagerService.enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
7196             synchronized (mGlobalLock) {
7197                 ActivityRecord r = ActivityRecord.isInRootTaskLocked(activityToken);
7198                 return (r == null) ? null : r.getUriPermissionsLocked().getExternalToken();
7199             }
7200         }
7201 
7202         @Override
getTaskSnapshotBlocking( int taskId, boolean isLowResolution)7203         public TaskSnapshot getTaskSnapshotBlocking(
7204                 int taskId, boolean isLowResolution) {
7205             return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution);
7206         }
7207 
7208         @Override
isUidForeground(int uid)7209         public boolean isUidForeground(int uid) {
7210             return ActivityTaskManagerService.this.hasActiveVisibleWindow(uid);
7211         }
7212 
7213         @Override
setDeviceOwnerUid(int uid)7214         public void setDeviceOwnerUid(int uid) {
7215             synchronized (mGlobalLock) {
7216                 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
7217             }
7218         }
7219 
7220         @Override
setProfileOwnerUids(Set<Integer> uids)7221         public void setProfileOwnerUids(Set<Integer> uids) {
7222             synchronized (mGlobalLock) {
7223                 ActivityTaskManagerService.this.setProfileOwnerUids(uids);
7224             }
7225         }
7226 
7227         @Override
setCompanionAppUids(int userId, Set<Integer> companionAppUids)7228         public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) {
7229             synchronized (mGlobalLock) {
7230                 mCompanionAppUidsMap.put(userId, companionAppUids);
7231             }
7232         }
7233 
7234 
7235         @Override
isBaseOfLockedTask(String packageName)7236         public boolean isBaseOfLockedTask(String packageName) {
7237             synchronized (mGlobalLock) {
7238                 return getLockTaskController().isBaseOfLockedTask(packageName);
7239             }
7240         }
7241 
7242         @Override
createPackageConfigurationUpdater()7243         public PackageConfigurationUpdater createPackageConfigurationUpdater() {
7244             return new PackageConfigurationUpdaterImpl(Binder.getCallingPid(),
7245                     ActivityTaskManagerService.this);
7246         }
7247 
7248         @Override
createPackageConfigurationUpdater( String packageName , int userId)7249         public PackageConfigurationUpdater createPackageConfigurationUpdater(
7250                 String packageName , int userId) {
7251             return new PackageConfigurationUpdaterImpl(packageName, userId,
7252                     ActivityTaskManagerService.this);
7253         }
7254 
7255         @Override
7256         @Nullable
getApplicationConfig(String packageName, int userId)7257         public ActivityTaskManagerInternal.PackageConfig getApplicationConfig(String packageName,
7258                 int userId) {
7259             return mPackageConfigPersister.findPackageConfiguration(packageName, userId);
7260         }
7261 
7262         @Override
hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage)7263         public boolean hasSystemAlertWindowPermission(int callingUid, int callingPid,
7264                 String callingPackage) {
7265             return ActivityTaskManagerService.this.hasSystemAlertWindowPermission(callingUid,
7266                     callingPid, callingPackage);
7267         }
7268 
7269         @Override
registerActivityStartInterceptor( @ctivityInterceptorCallback.OrderedId int id, ActivityInterceptorCallback callback)7270         public void registerActivityStartInterceptor(
7271                 @ActivityInterceptorCallback.OrderedId int id,
7272                 ActivityInterceptorCallback callback) {
7273             synchronized (mGlobalLock) {
7274                 if (mActivityInterceptorCallbacks.contains(id)) {
7275                     throw new IllegalArgumentException("Duplicate id provided: " + id);
7276                 }
7277                 if (callback == null) {
7278                     throw new IllegalArgumentException("The passed ActivityInterceptorCallback "
7279                             + "can not be null");
7280                 }
7281                 if (!ActivityInterceptorCallback.isValidOrderId(id)) {
7282                     throw new IllegalArgumentException(
7283                             "Provided id " + id + " is not in range of valid ids for system "
7284                                     + "services [" + SYSTEM_FIRST_ORDERED_ID + ","
7285                                     + SYSTEM_LAST_ORDERED_ID + "] nor in range of valid ids for "
7286                                     + "mainline module services [" + MAINLINE_FIRST_ORDERED_ID + ","
7287                                     + MAINLINE_LAST_ORDERED_ID + "]");
7288                 }
7289                 mActivityInterceptorCallbacks.put(id, callback);
7290             }
7291         }
7292 
7293         @Override
unregisterActivityStartInterceptor( @ctivityInterceptorCallback.OrderedId int id)7294         public void unregisterActivityStartInterceptor(
7295                 @ActivityInterceptorCallback.OrderedId int id) {
7296             synchronized (mGlobalLock) {
7297                 if (!mActivityInterceptorCallbacks.contains(id)) {
7298                     throw new IllegalArgumentException(
7299                             "ActivityInterceptorCallback with id (" + id + ") is not registered");
7300                 }
7301                 mActivityInterceptorCallbacks.remove(id);
7302             }
7303         }
7304 
7305         @Override
getMostRecentTaskFromBackground()7306         public ActivityManager.RecentTaskInfo getMostRecentTaskFromBackground() {
7307             List<ActivityManager.RunningTaskInfo> runningTaskInfoList = getTasks(1);
7308             ActivityManager.RunningTaskInfo runningTaskInfo;
7309             if (runningTaskInfoList.size() > 0) {
7310                 runningTaskInfo = runningTaskInfoList.get(0);
7311             } else {
7312                 Slog.i(TAG, "No running task found!");
7313                 return null;
7314             }
7315             // Get 2 most recent tasks.
7316             List<ActivityManager.RecentTaskInfo> recentTaskInfoList =
7317                     getRecentTasks(
7318                                     2,
7319                                     ActivityManager.RECENT_IGNORE_UNAVAILABLE,
7320                                     mContext.getUserId())
7321                             .getList();
7322             ActivityManager.RecentTaskInfo targetTask = null;
7323             for (ActivityManager.RecentTaskInfo info : recentTaskInfoList) {
7324                 // Find a recent task that is not the current running task on screen.
7325                 if (info.id != runningTaskInfo.id) {
7326                     targetTask = info;
7327                     break;
7328                 }
7329             }
7330             return targetTask;
7331         }
7332 
7333         @Override
getAppTasks(String pkgName, int uid)7334         public List<ActivityManager.AppTask> getAppTasks(String pkgName, int uid) {
7335             ArrayList<ActivityManager.AppTask> tasks = new ArrayList<>();
7336             List<IBinder> appTasks = ActivityTaskManagerService.this.getAppTasks(pkgName, uid);
7337             int numAppTasks = appTasks.size();
7338             for (int i = 0; i < numAppTasks; i++) {
7339                 tasks.add(new ActivityManager.AppTask(IAppTask.Stub.asInterface(appTasks.get(i))));
7340             }
7341             return tasks;
7342         }
7343 
7344         @Override
getTaskToShowPermissionDialogOn(String pkgName, int uid)7345         public int getTaskToShowPermissionDialogOn(String pkgName, int uid) {
7346             synchronized (ActivityTaskManagerService.this.mGlobalLock) {
7347                 return ActivityTaskManagerService.this.mRootWindowContainer
7348                         .getTaskToShowPermissionDialogOn(pkgName, uid);
7349             }
7350         }
7351 
7352         @Override
restartTaskActivityProcessIfVisible(int taskId, String packageName)7353         public void restartTaskActivityProcessIfVisible(int taskId, String packageName) {
7354             synchronized (ActivityTaskManagerService.this.mGlobalLock) {
7355                 final Task task =
7356                         ActivityTaskManagerService.this.mRootWindowContainer
7357                                 .anyTaskForId(taskId, MATCH_ATTACHED_TASK_ONLY);
7358                 if (task == null) {
7359                     Slog.w(TAG, "Failed to restart Activity. No task found for id: " + taskId);
7360                     return;
7361                 }
7362 
7363                 final ActivityRecord activity = task.getActivity(activityRecord -> {
7364                     return packageName.equals(activityRecord.packageName)
7365                             && !activityRecord.finishing;
7366                 });
7367 
7368                 if (activity == null) {
7369                     Slog.w(TAG, "Failed to restart Activity. No Activity found for package name: "
7370                             + packageName + " in task: " + taskId);
7371                     return;
7372                 }
7373 
7374                 activity.restartProcessIfVisible();
7375             }
7376         }
7377 
7378         /** Sets the task stack listener that gets callbacks when a task stack changes. */
7379         @Override
registerTaskStackListener(ITaskStackListener listener)7380         public void registerTaskStackListener(ITaskStackListener listener) {
7381             ActivityTaskManagerService.this.registerTaskStackListener(listener);
7382         }
7383 
7384         /** Unregister a task stack listener so that it stops receiving callbacks. */
7385         @Override
unregisterTaskStackListener(ITaskStackListener listener)7386         public void unregisterTaskStackListener(ITaskStackListener listener) {
7387             ActivityTaskManagerService.this.unregisterTaskStackListener(listener);
7388         }
7389 
7390         @Override
registerCompatScaleProvider(@ompatScaleProvider.CompatScaleModeOrderId int id, @NonNull CompatScaleProvider provider)7391         public void registerCompatScaleProvider(@CompatScaleProvider.CompatScaleModeOrderId int id,
7392                 @NonNull CompatScaleProvider provider) {
7393             ActivityTaskManagerService.this.registerCompatScaleProvider(id, provider);
7394         }
7395 
7396         @Override
unregisterCompatScaleProvider( @ompatScaleProvider.CompatScaleModeOrderId int id)7397         public void unregisterCompatScaleProvider(
7398                 @CompatScaleProvider.CompatScaleModeOrderId int id) {
7399             ActivityTaskManagerService.this.unregisterCompatScaleProvider(id);
7400         }
7401 
7402         @Override
isAssistDataAllowed()7403         public boolean isAssistDataAllowed() {
7404             return ActivityTaskManagerService.this.isAssistDataAllowed();
7405         }
7406     }
7407 
7408     /** Cache the return value for {@link #isPip2ExperimentEnabled()} */
7409     private static Boolean sIsPip2ExperimentEnabled = null;
7410 
7411     /**
7412      * @return {@code true} if PiP2 implementation should be used. Besides the trunk stable flag,
7413      * system property can be used to override this read only flag during development.
7414      * It's currently limited to phone form factor, i.e., not enabled on ARC / TV.
7415      */
isPip2ExperimentEnabled()7416     static boolean isPip2ExperimentEnabled() {
7417         if (sIsPip2ExperimentEnabled == null) {
7418             final FeatureInfo arcFeature = SystemConfig.getInstance().getAvailableFeatures().get(
7419                     "org.chromium.arc");
7420             final FeatureInfo tvFeature = SystemConfig.getInstance().getAvailableFeatures().get(
7421                     FEATURE_LEANBACK);
7422             final boolean isArc = arcFeature != null && arcFeature.version >= 0;
7423             final boolean isTv = tvFeature != null && tvFeature.version >= 0;
7424             sIsPip2ExperimentEnabled = SystemProperties.getBoolean(
7425                     "persist.wm_shell.pip2", false)
7426                     || (Flags.enablePip2Implementation() && !isArc && !isTv);
7427         }
7428         return sIsPip2ExperimentEnabled;
7429     }
7430 }
7431