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