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