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