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