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