1 /* 2 * Copyright (C) 2014 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 android.app; 18 19 import static android.app.ActivityManager.StopUserOnSwitch; 20 21 import android.annotation.IntDef; 22 import android.annotation.NonNull; 23 import android.annotation.Nullable; 24 import android.annotation.PermissionMethod; 25 import android.annotation.PermissionName; 26 import android.annotation.SpecialUsers.CanBeALL; 27 import android.annotation.UserIdInt; 28 import android.app.ActivityManager.ProcessCapability; 29 import android.app.ActivityManager.RestrictionLevel; 30 import android.app.assist.ActivityId; 31 import android.content.ComponentName; 32 import android.content.IIntentReceiver; 33 import android.content.IIntentSender; 34 import android.content.Intent; 35 import android.content.ServiceConnection; 36 import android.content.pm.ActivityInfo; 37 import android.content.pm.ActivityPresentationInfo; 38 import android.content.pm.ApplicationInfo; 39 import android.content.pm.IPackageDataObserver; 40 import android.content.pm.UserInfo; 41 import android.net.Uri; 42 import android.os.Bundle; 43 import android.os.IBinder; 44 import android.os.PowerExemptionManager.ReasonCode; 45 import android.os.PowerExemptionManager.TempAllowListType; 46 import android.os.TransactionTooLargeException; 47 import android.os.WorkSource; 48 import android.os.instrumentation.IOffsetCallback; 49 import android.os.instrumentation.MethodDescriptor; 50 import android.util.ArraySet; 51 import android.util.Pair; 52 53 import com.android.internal.os.TimeoutRecord; 54 55 import java.lang.annotation.Retention; 56 import java.lang.annotation.RetentionPolicy; 57 import java.util.ArrayList; 58 import java.util.List; 59 import java.util.Map; 60 import java.util.Set; 61 import java.util.concurrent.Executor; 62 import java.util.function.BiFunction; 63 64 /** 65 * Activity manager local system service interface. 66 * 67 * @hide Only for use within the system server. 68 */ 69 public abstract class ActivityManagerInternal { 70 71 public enum ServiceNotificationPolicy { 72 /** 73 * The Notification is not associated with any foreground service. 74 */ 75 NOT_FOREGROUND_SERVICE, 76 /** 77 * The Notification is associated with a foreground service, but the 78 * notification system should handle it just like non-FGS notifications. 79 */ 80 SHOW_IMMEDIATELY, 81 /** 82 * The Notification is associated with a foreground service, and the 83 * notification system should ignore it unless it has already been shown (in 84 * which case it should be used to update the currently displayed UI). 85 */ 86 UPDATE_ONLY 87 } 88 89 // Access modes for handleIncomingUser. 90 /** 91 * Allows access to a caller with {@link android.Manifest.permission#INTERACT_ACROSS_USERS}. 92 */ 93 public static final int ALLOW_NON_FULL = 0; 94 /** 95 * Allows access to a caller with {@link android.Manifest.permission#INTERACT_ACROSS_USERS} 96 * if in the same profile group. 97 * Otherwise, {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} is required. 98 */ 99 public static final int ALLOW_NON_FULL_IN_PROFILE = 1; 100 /** 101 * Allows access to a caller only if it has the full 102 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}. 103 */ 104 public static final int ALLOW_FULL_ONLY = 2; 105 /** 106 * Allows access to a caller with {@link android.Manifest.permission#INTERACT_ACROSS_PROFILES} 107 * if in the same profile group. 108 * Otherwise, {@link android.Manifest.permission#INTERACT_ACROSS_USERS} is required and suffices 109 * as in {@link #ALLOW_NON_FULL}. 110 */ 111 public static final int ALLOW_PROFILES_OR_NON_FULL = 3; 112 113 /** 114 * Returns profile information in free form string in two separate strings. 115 * See AppProfiler for the output format. 116 * The output can only be used for human consumption. The format may change 117 * in the future. 118 * Do not call it frequently. 119 * @param time uptime for the cpu state 120 * @param lines lines of the cpu state should be returned 121 * @return a pair of Strings. The first is the current cpu load, the second is the cpu state. 122 */ getAppProfileStatsForDebugging(long time, int lines)123 public abstract Pair<String, String> getAppProfileStatsForDebugging(long time, int lines); 124 125 /** 126 * Verify that calling app has access to the given provider. 127 */ checkContentProviderAccess(String authority, @UserIdInt int userId)128 public abstract String checkContentProviderAccess(String authority, @UserIdInt int userId); 129 130 /** 131 * Verify that calling UID has access to the given provider. 132 */ checkContentProviderUriPermission(Uri uri, @UserIdInt int userId, int callingUid, int modeFlags)133 public abstract int checkContentProviderUriPermission(Uri uri, @UserIdInt int userId, 134 int callingUid, int modeFlags); 135 136 // Called by the power manager. onWakefulnessChanged(int wakefulness)137 public abstract void onWakefulnessChanged(int wakefulness); 138 139 /** 140 * @return {@code true} if process start is successful, {@code false} otherwise. 141 */ startIsolatedProcess(String entryPoint, String[] mainArgs, String processName, String abiOverride, int uid, Runnable crashHandler)142 public abstract boolean startIsolatedProcess(String entryPoint, String[] mainArgs, 143 String processName, String abiOverride, int uid, Runnable crashHandler); 144 145 /** 146 * Called when a user is being deleted. This can happen during normal device usage 147 * or just at startup, when partially removed users are purged. Any state persisted by the 148 * ActivityManager should be purged now. 149 * 150 * @param userId The user being cleaned up. 151 */ onUserRemoving(@serIdInt int userId)152 public abstract void onUserRemoving(@UserIdInt int userId); 153 154 /** 155 * Called when a user has been deleted. This can happen during normal device usage 156 * or just at startup, when partially removed users are purged. Any state persisted by the 157 * ActivityManager should be purged now. 158 * 159 * @param userId The user being cleaned up. 160 */ onUserRemoved(@serIdInt int userId)161 public abstract void onUserRemoved(@UserIdInt int userId); 162 163 /** 164 * Start user, if it is not already running, but don't bring it to foreground. 165 * @param userId ID of the user to start 166 * @return true if the user has been successfully started 167 */ startUserInBackground(int userId)168 public abstract boolean startUserInBackground(int userId); 169 170 /** 171 * Kill foreground apps from the specified user. 172 */ killForegroundAppsForUser(@serIdInt int userId)173 public abstract void killForegroundAppsForUser(@UserIdInt int userId); 174 175 /** 176 * Sets how long a {@link PendingIntent} can be temporarily allowlisted to bypass restrictions 177 * such as Power Save mode. 178 * @param target 179 * @param allowlistToken 180 * @param duration temp allowlist duration in milliseconds. 181 * @param type temp allowlist type defined at {@link TempAllowListType} 182 * @param reasonCode one of {@link ReasonCode} 183 * @param reason A human-readable reason for logging purposes. 184 */ setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, long duration, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason)185 public abstract void setPendingIntentAllowlistDuration(IIntentSender target, 186 IBinder allowlistToken, long duration, @TempAllowListType int type, 187 @ReasonCode int reasonCode, @Nullable String reason); 188 189 /** 190 * Returns the flags set for a {@link PendingIntent}. 191 */ getPendingIntentFlags(IIntentSender target)192 public abstract int getPendingIntentFlags(IIntentSender target); 193 194 /** 195 * Allows a {@link PendingIntent} to start activities from background. 196 */ setPendingIntentAllowBgActivityStarts( IIntentSender target, IBinder allowlistToken, int flags)197 public abstract void setPendingIntentAllowBgActivityStarts( 198 IIntentSender target, IBinder allowlistToken, int flags); 199 200 /** 201 * Voids {@link PendingIntent}'s privilege to start activities from background. 202 */ clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken)203 public abstract void clearPendingIntentAllowBgActivityStarts(IIntentSender target, 204 IBinder allowlistToken); 205 206 /** 207 * Allow DeviceIdleController to tell us about what apps are allowlisted. 208 */ setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids)209 public abstract void setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids); 210 211 /** 212 * Update information about which app IDs are on the temp allowlist. 213 * @param appids the updated list of appIds in temp allowlist. 214 * If null, it is to update only changingUid. 215 * @param changingUid uid to add or remove to temp allowlist. 216 * @param adding true to add to temp allowlist, false to remove from temp allowlist. 217 * @param durationMs when adding is true, the duration to be in temp allowlist. 218 * @param type temp allowlist type defined at {@link TempAllowListType}. 219 * @param reasonCode one of {@link ReasonCode} 220 * @param reason A human-readable reason for logging purposes. 221 * @param callingUid the callingUid that setup this temp allowlist, only valid when param adding 222 * is true. 223 */ updateDeviceIdleTempAllowlist(@ullable int[] appids, int changingUid, boolean adding, long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason, int callingUid)224 public abstract void updateDeviceIdleTempAllowlist(@Nullable int[] appids, int changingUid, 225 boolean adding, long durationMs, @TempAllowListType int type, 226 @ReasonCode int reasonCode, 227 @Nullable String reason, int callingUid); 228 229 /** 230 * Get the procstate for the UID. The return value will be between 231 * {@link ActivityManager#MIN_PROCESS_STATE} and {@link ActivityManager#MAX_PROCESS_STATE}. 232 * Note if the UID doesn't exist, it'll return {@link ActivityManager#PROCESS_STATE_NONEXISTENT} 233 * (-1). 234 */ getUidProcessState(int uid)235 public abstract int getUidProcessState(int uid); 236 237 /** 238 * Get a map of pid and package name that process of that pid Android/data and Android/obb 239 * directory is not mounted to lowerfs. 240 */ getProcessesWithPendingBindMounts(int userId)241 public abstract Map<Integer, String> getProcessesWithPendingBindMounts(int userId); 242 243 /** 244 * @return {@code true} if system is ready, {@code false} otherwise. 245 */ isSystemReady()246 public abstract boolean isSystemReady(); 247 248 /** 249 * Enforce capability restrictions on use of the given BroadcastOptions 250 */ enforceBroadcastOptionsPermissions(@ullable Bundle options, int callingUid)251 public abstract void enforceBroadcastOptionsPermissions(@Nullable Bundle options, 252 int callingUid); 253 254 /** 255 * Returns package name given pid. 256 * 257 * @param pid The pid we are searching package name for. 258 */ 259 @Nullable getPackageNameByPid(int pid)260 public abstract String getPackageNameByPid(int pid); 261 262 /** 263 * Sets if the given pid has an overlay UI or not. 264 * 265 * @param pid The pid we are setting overlay UI for. 266 * @param hasOverlayUi True if the process has overlay UI. 267 * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY 268 */ setHasOverlayUi(int pid, boolean hasOverlayUi)269 public abstract void setHasOverlayUi(int pid, boolean hasOverlayUi); 270 271 /** 272 * Called after the network policy rules are updated by 273 * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid} and 274 * {@param procStateSeq}. 275 */ notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)276 public abstract void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq); 277 278 /** 279 * Inform ActivityManagerService about the latest {@code blockedReasons} for an uid, which 280 * can be used to understand whether the {@code uid} is allowed to access network or not. 281 */ onUidBlockedReasonsChanged(int uid, int blockedReasons)282 public abstract void onUidBlockedReasonsChanged(int uid, int blockedReasons); 283 284 /** 285 * @return true if runtime was restarted, false if it's normal boot 286 */ isRuntimeRestarted()287 public abstract boolean isRuntimeRestarted(); 288 289 /** 290 * Returns if more users can be started without stopping currently running users. 291 */ canStartMoreUsers()292 public abstract boolean canStartMoreUsers(); 293 294 /** 295 * Sets the user switcher message for switching from a user. 296 */ setSwitchingFromUserMessage(@serIdInt int user, @Nullable String message)297 public abstract void setSwitchingFromUserMessage(@UserIdInt int user, @Nullable String message); 298 299 /** 300 * Sets the user switcher message for switching to a user. 301 */ setSwitchingToUserMessage(@serIdInt int user, @Nullable String message)302 public abstract void setSwitchingToUserMessage(@UserIdInt int user, @Nullable String message); 303 304 /** 305 * Returns maximum number of users that can run simultaneously. 306 */ getMaxRunningUsers()307 public abstract int getMaxRunningUsers(); 308 309 /** 310 * Whether an UID is active or idle. 311 */ isUidActive(int uid)312 public abstract boolean isUidActive(int uid); 313 314 /** 315 * Returns a list of running processes along with corresponding uids, pids and their oom score. 316 * 317 * Only processes managed by ActivityManagerService are included. 318 */ getMemoryStateForProcesses()319 public abstract List<ProcessMemoryState> getMemoryStateForProcesses(); 320 321 /** 322 * Checks to see if the calling pid is allowed to handle the user. Returns adjusted user id as 323 * needed. 324 */ handleIncomingUser(int callingPid, int callingUid, @UserIdInt int userId, boolean allowAll, int allowMode, String name, String callerPackage)325 public abstract int handleIncomingUser(int callingPid, int callingUid, @UserIdInt int userId, 326 boolean allowAll, int allowMode, String name, String callerPackage); 327 328 /** Checks if the calling binder pid/uid has the given permission. */ 329 @PermissionMethod enforceCallingPermission(@ermissionName String permission, String func)330 public abstract void enforceCallingPermission(@PermissionName String permission, String func); 331 332 /** 333 * Returns the current and target user ids as a {@link Pair}. Target user id will be 334 * {@link android.os.UserHandle#USER_NULL} if there is not an ongoing user switch. 335 */ getCurrentAndTargetUserIds()336 public abstract Pair<Integer, Integer> getCurrentAndTargetUserIds(); 337 338 /** Returns the current user id. */ getCurrentUserId()339 public abstract int getCurrentUserId(); 340 341 /** Returns the currently started user ids. */ getStartedUserIds()342 public abstract int[] getStartedUserIds(); 343 344 /** Returns true if the user is running. */ isUserRunning(@serIdInt int userId, int flags)345 public abstract boolean isUserRunning(@UserIdInt int userId, int flags); 346 347 /** Trims memory usage in the system by removing/stopping unused application processes. */ trimApplications()348 public abstract void trimApplications(); 349 350 /** Kill the processes in the list due to their tasks been removed. */ killProcessesForRemovedTask(ArrayList<Object> procsToKill)351 public abstract void killProcessesForRemovedTask(ArrayList<Object> procsToKill); 352 353 /** Kill the process immediately. */ killProcess(String processName, int uid, String reason)354 public abstract void killProcess(String processName, int uid, String reason); 355 356 /** 357 * Returns {@code true} if {@code uid} is running an activity from {@code packageName}. 358 */ hasRunningActivity(int uid, @Nullable String packageName)359 public abstract boolean hasRunningActivity(int uid, @Nullable String packageName); 360 361 /** 362 * Oom Adj Reason: none - internal use only, do not use it. 363 * @hide 364 */ 365 public static final int OOM_ADJ_REASON_NONE = 0; 366 367 /** 368 * Oom Adj Reason: activity changes. 369 * @hide 370 */ 371 public static final int OOM_ADJ_REASON_ACTIVITY = 1; 372 373 /** 374 * Oom Adj Reason: finishing a broadcast receiver. 375 * @hide 376 */ 377 public static final int OOM_ADJ_REASON_FINISH_RECEIVER = 2; 378 379 /** 380 * Oom Adj Reason: starting a broadcast receiver. 381 * @hide 382 */ 383 public static final int OOM_ADJ_REASON_START_RECEIVER = 3; 384 385 /** 386 * Oom Adj Reason: binding to a service. 387 * @hide 388 */ 389 public static final int OOM_ADJ_REASON_BIND_SERVICE = 4; 390 391 /** 392 * Oom Adj Reason: unbinding from a service. 393 * @hide 394 */ 395 public static final int OOM_ADJ_REASON_UNBIND_SERVICE = 5; 396 397 /** 398 * Oom Adj Reason: starting a service. 399 * @hide 400 */ 401 public static final int OOM_ADJ_REASON_START_SERVICE = 6; 402 403 /** 404 * Oom Adj Reason: connecting to a content provider. 405 * @hide 406 */ 407 public static final int OOM_ADJ_REASON_GET_PROVIDER = 7; 408 409 /** 410 * Oom Adj Reason: disconnecting from a content provider. 411 * @hide 412 */ 413 public static final int OOM_ADJ_REASON_REMOVE_PROVIDER = 8; 414 415 /** 416 * Oom Adj Reason: UI visibility changes. 417 * @hide 418 */ 419 public static final int OOM_ADJ_REASON_UI_VISIBILITY = 9; 420 421 /** 422 * Oom Adj Reason: device power allowlist changes. 423 * @hide 424 */ 425 public static final int OOM_ADJ_REASON_ALLOWLIST = 10; 426 427 /** 428 * Oom Adj Reason: starting a process. 429 * @hide 430 */ 431 public static final int OOM_ADJ_REASON_PROCESS_BEGIN = 11; 432 433 /** 434 * Oom Adj Reason: ending a process. 435 * @hide 436 */ 437 public static final int OOM_ADJ_REASON_PROCESS_END = 12; 438 439 /** 440 * Oom Adj Reason: short FGS timeout. 441 * @hide 442 */ 443 public static final int OOM_ADJ_REASON_SHORT_FGS_TIMEOUT = 13; 444 445 /** 446 * Oom Adj Reason: system initialization. 447 * @hide 448 */ 449 public static final int OOM_ADJ_REASON_SYSTEM_INIT = 14; 450 451 /** 452 * Oom Adj Reason: backup/restore. 453 * @hide 454 */ 455 public static final int OOM_ADJ_REASON_BACKUP = 15; 456 457 /** 458 * Oom Adj Reason: instrumented by the SHELL. 459 * @hide 460 */ 461 public static final int OOM_ADJ_REASON_SHELL = 16; 462 463 /** 464 * Oom Adj Reason: task stack is being removed. 465 */ 466 public static final int OOM_ADJ_REASON_REMOVE_TASK = 17; 467 468 /** 469 * Oom Adj Reason: uid idle. 470 */ 471 public static final int OOM_ADJ_REASON_UID_IDLE = 18; 472 473 /** 474 * Oom Adj Reason: stop service. 475 */ 476 public static final int OOM_ADJ_REASON_STOP_SERVICE = 19; 477 478 /** 479 * Oom Adj Reason: executing service. 480 */ 481 public static final int OOM_ADJ_REASON_EXECUTING_SERVICE = 20; 482 483 /** 484 * Oom Adj Reason: background restriction changes. 485 */ 486 public static final int OOM_ADJ_REASON_RESTRICTION_CHANGE = 21; 487 488 /** 489 * Oom Adj Reason: A package or its component is disabled. 490 */ 491 public static final int OOM_ADJ_REASON_COMPONENT_DISABLED = 22; 492 493 /** 494 * Oom Adj Reason: Follow up update for time sensitive state evaluations. 495 */ 496 public static final int OOM_ADJ_REASON_FOLLOW_UP = 23; 497 498 /** 499 * Oom Adj Reason: Update after oom adjuster configuration has changed. 500 */ 501 public static final int OOM_ADJ_REASON_RECONFIGURATION = 24; 502 503 @IntDef(prefix = {"OOM_ADJ_REASON_"}, value = { 504 OOM_ADJ_REASON_NONE, 505 OOM_ADJ_REASON_ACTIVITY, 506 OOM_ADJ_REASON_FINISH_RECEIVER, 507 OOM_ADJ_REASON_START_RECEIVER, 508 OOM_ADJ_REASON_BIND_SERVICE, 509 OOM_ADJ_REASON_UNBIND_SERVICE, 510 OOM_ADJ_REASON_START_SERVICE, 511 OOM_ADJ_REASON_GET_PROVIDER, 512 OOM_ADJ_REASON_REMOVE_PROVIDER, 513 OOM_ADJ_REASON_UI_VISIBILITY, 514 OOM_ADJ_REASON_ALLOWLIST, 515 OOM_ADJ_REASON_PROCESS_BEGIN, 516 OOM_ADJ_REASON_PROCESS_END, 517 OOM_ADJ_REASON_SHORT_FGS_TIMEOUT, 518 OOM_ADJ_REASON_SYSTEM_INIT, 519 OOM_ADJ_REASON_BACKUP, 520 OOM_ADJ_REASON_SHELL, 521 OOM_ADJ_REASON_REMOVE_TASK, 522 OOM_ADJ_REASON_UID_IDLE, 523 OOM_ADJ_REASON_STOP_SERVICE, 524 OOM_ADJ_REASON_EXECUTING_SERVICE, 525 OOM_ADJ_REASON_RESTRICTION_CHANGE, 526 OOM_ADJ_REASON_COMPONENT_DISABLED, 527 OOM_ADJ_REASON_FOLLOW_UP, 528 OOM_ADJ_REASON_RECONFIGURATION, 529 }) 530 @Retention(RetentionPolicy.SOURCE) 531 public @interface OomAdjReason {} 532 533 /** 534 * Request to update oom adj. 535 */ updateOomAdj(@omAdjReason int oomAdjReason)536 public abstract void updateOomAdj(@OomAdjReason int oomAdjReason); updateCpuStats()537 public abstract void updateCpuStats(); 538 539 /** 540 * Update battery stats on activity usage. 541 * @param activity 542 * @param uid 543 * @param userId 544 * @param started 545 */ updateBatteryStats( ComponentName activity, int uid, @UserIdInt int userId, boolean resumed)546 public abstract void updateBatteryStats( 547 ComponentName activity, int uid, @UserIdInt int userId, boolean resumed); 548 549 /** 550 * Update UsageStats of the activity. 551 * @param activity 552 * @param userId 553 * @param event 554 * @param appToken ActivityRecord's appToken. 555 * @param taskRoot Task's root 556 */ updateActivityUsageStats( ComponentName activity, @UserIdInt int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)557 public abstract void updateActivityUsageStats( 558 ComponentName activity, @UserIdInt int userId, int event, IBinder appToken, 559 ComponentName taskRoot, ActivityId activityId); updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)560 public abstract void updateForegroundTimeIfOnBattery( 561 String packageName, int uid, long cpuTimeDiff); sendForegroundProfileChanged(@serIdInt int userId)562 public abstract void sendForegroundProfileChanged(@UserIdInt int userId); 563 564 /** 565 * Returns whether the given user requires credential entry at this time. This is used to 566 * intercept activity launches for apps corresponding to locked profiles due to separate 567 * challenge being triggered or when the profile user is yet to be unlocked. 568 */ shouldConfirmCredentials(@serIdInt int userId)569 public abstract boolean shouldConfirmCredentials(@UserIdInt int userId); 570 571 /** 572 * Used in conjunction with {@link #noteAlarmStart(PendingIntent, WorkSource, int, String)} to 573 * note an alarm duration for battery attribution 574 */ noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)575 public abstract void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, 576 String tag); 577 578 /** 579 * Used in conjunction with {@link #noteAlarmFinish(PendingIntent, WorkSource, int, String)} to 580 * note an alarm duration for battery attribution 581 */ noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)582 public abstract void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, 583 String tag); 584 585 /** 586 * Used to note a wakeup alarm for battery attribution. 587 */ noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)588 public abstract void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, 589 String sourcePkg, String tag); 590 591 /** 592 * Returns whether this app is disallowed to run in the background. 593 * 594 * @see ActivityManager#APP_START_MODE_DISABLED 595 */ isAppStartModeDisabled(int uid, String packageName)596 public abstract boolean isAppStartModeDisabled(int uid, String packageName); 597 598 /** 599 * Returns the ids of the current user and all of its profiles (if any), regardless of the 600 * running state of the profiles. 601 */ getCurrentProfileIds()602 public abstract int[] getCurrentProfileIds(); getCurrentUser()603 public abstract UserInfo getCurrentUser(); ensureNotSpecialUser(@serIdInt int userId)604 public abstract void ensureNotSpecialUser(@UserIdInt int userId); isCurrentProfile(@serIdInt int userId)605 public abstract boolean isCurrentProfile(@UserIdInt int userId); hasStartedUserState(@serIdInt int userId)606 public abstract boolean hasStartedUserState(@UserIdInt int userId); finishUserSwitch(Object uss)607 public abstract void finishUserSwitch(Object uss); 608 609 /** Schedule the execution of all pending app GCs. */ scheduleAppGcs()610 public abstract void scheduleAppGcs(); 611 612 /** Gets the task id for a given activity. */ getTaskIdForActivity(@onNull IBinder token, boolean onlyRoot)613 public abstract int getTaskIdForActivity(@NonNull IBinder token, boolean onlyRoot); 614 615 /** Gets the basic info for a given activity. */ getActivityPresentationInfo(@onNull IBinder token)616 public abstract ActivityPresentationInfo getActivityPresentationInfo(@NonNull IBinder token); 617 setBooting(boolean booting)618 public abstract void setBooting(boolean booting); isBooting()619 public abstract boolean isBooting(); setBooted(boolean booted)620 public abstract void setBooted(boolean booted); isBooted()621 public abstract boolean isBooted(); finishBooting()622 public abstract void finishBooting(); 623 624 /** 625 * Temp allowlist a UID for PendingIntent. 626 * @param callerPid the PID that sent the PendingIntent. 627 * @param callerUid the UID that sent the PendingIntent. 628 * @param targetUid the UID that is been temp allowlisted. 629 * @param duration temp allowlist duration in milliseconds. 630 * @param type temp allowlist type defined at {@link TempAllowListType} 631 * @param reasonCode one of {@link ReasonCode} 632 * @param reason 633 */ tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)634 public abstract void tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, 635 long duration, int type, @ReasonCode int reasonCode, String reason); 636 broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IApplicationThread resultToThread, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, @UserIdInt int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList)637 public abstract int broadcastIntentInPackage(String packageName, @Nullable String featureId, 638 int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 639 IApplicationThread resultToThread, IIntentReceiver resultTo, int resultCode, 640 String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, 641 boolean serialized, boolean sticky, @UserIdInt int userId, 642 BackgroundStartPrivileges backgroundStartPrivileges, 643 @Nullable int[] broadcastAllowList); 644 startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, @UserIdInt int userId, BackgroundStartPrivileges backgroundStartPrivileges)645 public abstract ComponentName startServiceInPackage(int uid, Intent service, 646 String resolvedType, boolean fgRequired, String callingPackage, 647 @Nullable String callingFeatureId, @UserIdInt int userId, 648 BackgroundStartPrivileges backgroundStartPrivileges) 649 throws TransactionTooLargeException; 650 disconnectActivityFromServices(Object connectionHolder)651 public abstract void disconnectActivityFromServices(Object connectionHolder); cleanUpServices(@serIdInt int userId, ComponentName component, Intent baseIntent)652 public abstract void cleanUpServices(@UserIdInt int userId, ComponentName component, 653 Intent baseIntent); getActivityInfoForUser(ActivityInfo aInfo, @UserIdInt int userId)654 public abstract ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, @UserIdInt int userId); ensureBootCompleted()655 public abstract void ensureBootCompleted(); updateOomLevelsForDisplay(int displayId)656 public abstract void updateOomLevelsForDisplay(int displayId); isActivityStartsLoggingEnabled()657 public abstract boolean isActivityStartsLoggingEnabled(); 658 /** Returns true if the background activity starts is enabled. */ isBackgroundActivityStartsEnabled()659 public abstract boolean isBackgroundActivityStartsEnabled(); 660 /** 661 * Returns The current {@link BackgroundStartPrivileges} of the UID. 662 */ 663 @NonNull getBackgroundStartPrivileges(int uid)664 public abstract BackgroundStartPrivileges getBackgroundStartPrivileges(int uid); reportCurKeyguardUsageEvent(boolean keyguardShowing)665 public abstract void reportCurKeyguardUsageEvent(boolean keyguardShowing); 666 667 /** 668 * Returns whether the app is in a state where it is allowed to schedule a 669 * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}. 670 */ canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)671 public abstract boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName); 672 673 /** @see com.android.server.am.ActivityManagerService#monitor */ monitor()674 public abstract void monitor(); 675 676 /** Input dispatch timeout to a window, start the ANR process. Return the timeout extension, 677 * in milliseconds, or 0 to abort dispatch. */ inputDispatchingTimedOut(int pid, boolean aboveSystem, TimeoutRecord timeoutRecord)678 public abstract long inputDispatchingTimedOut(int pid, boolean aboveSystem, 679 TimeoutRecord timeoutRecord); 680 inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, TimeoutRecord timeoutRecord)681 public abstract boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName, 682 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, 683 boolean aboveSystem, TimeoutRecord timeoutRecord); 684 685 /** 686 * App started responding to input events. This signal can be used to abort the ANR process and 687 * hide the ANR dialog. 688 */ inputDispatchingResumed(int pid)689 public abstract void inputDispatchingResumed(int pid); 690 691 /** 692 * User tapped "wait" in the ANR dialog - reschedule the dialog to be shown again at a later 693 * time. 694 * @param data AppNotRespondingDialog.Data object 695 */ rescheduleAnrDialog(Object data)696 public abstract void rescheduleAnrDialog(Object data); 697 698 /** 699 * Sends {@link android.content.Intent#ACTION_CONFIGURATION_CHANGED} with all the appropriate 700 * flags. 701 */ broadcastGlobalConfigurationChanged(int changes, boolean initLocale)702 public abstract void broadcastGlobalConfigurationChanged(int changes, boolean initLocale); 703 704 /** 705 * Sends {@link android.content.Intent#ACTION_CLOSE_SYSTEM_DIALOGS} with all the appropriate 706 * flags. 707 */ broadcastCloseSystemDialogs(String reason)708 public abstract void broadcastCloseSystemDialogs(String reason); 709 710 /** 711 * Trigger an ANR for the specified process. 712 */ appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)713 public abstract void appNotResponding(@NonNull String processName, int uid, 714 @NonNull TimeoutRecord timeoutRecord); 715 716 /** 717 * Kills all background processes, except those matching any of the specified properties. 718 * 719 * @param minTargetSdk the target SDK version at or above which to preserve processes, 720 * or {@code -1} to ignore the target SDK 721 * @param maxProcState the process state at or below which to preserve processes, 722 * or {@code -1} to ignore the process state 723 */ killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)724 public abstract void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState); 725 726 /** Starts a given process. */ startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)727 public abstract void startProcess(String processName, ApplicationInfo info, 728 boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName); 729 730 /** Starts up the starting activity process for debugging if needed. 731 * This function needs to be called synchronously from WindowManager context so the caller 732 * passes a lock {@code wmLock} and waits to be notified. 733 * 734 * @param wmLock calls {@code notify} on the object to wake up the caller. 735 */ setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)736 public abstract void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, 737 ProfilerInfo profilerInfo, Object wmLock); 738 739 /** Returns mount mode for process running with given pid */ getStorageMountMode(int pid, int uid)740 public abstract int getStorageMountMode(int pid, int uid); 741 742 /** Returns true if the given uid is the app in the foreground. */ isAppForeground(int uid)743 public abstract boolean isAppForeground(int uid); 744 745 /** Returns true if the given process name and uid is currently marked 'bad' */ isAppBad(String processName, int uid)746 public abstract boolean isAppBad(String processName, int uid); 747 748 /** Remove pending backup for the given userId. */ clearPendingBackup(@serIdInt int userId)749 public abstract void clearPendingBackup(@UserIdInt int userId); 750 751 /** 752 * When power button is very long pressed, call this interface to do some pre-shutdown work 753 * like persisting database etc. 754 */ prepareForPossibleShutdown()755 public abstract void prepareForPossibleShutdown(); 756 757 /** 758 * Returns {@code true} if {@code uid} is running a foreground service of a specific 759 * {@code foregroundServiceType}. 760 */ hasRunningForegroundService(int uid, int foregroundServiceType)761 public abstract boolean hasRunningForegroundService(int uid, int foregroundServiceType); 762 763 /** 764 * Returns {@code true} if the given notification channel currently has a 765 * notification associated with a foreground service. This is an AMS check 766 * because that is the source of truth for the FGS state. 767 */ hasForegroundServiceNotification(String pkg, @UserIdInt int userId, String channelId)768 public abstract boolean hasForegroundServiceNotification(String pkg, @UserIdInt int userId, 769 String channelId); 770 771 /** 772 * Tell the service lifecycle logic that the given Notification content is now 773 * canonical for any foreground-service visibility policy purposes. 774 * 775 * Returns a description of any FGs-related policy around the given Notification: 776 * not associated with an FGS; ensure display; or only update if already displayed. 777 */ applyForegroundServiceNotification( Notification notification, String tag, int id, String pkg, @UserIdInt int userId)778 public abstract ServiceNotificationPolicy applyForegroundServiceNotification( 779 Notification notification, String tag, int id, String pkg, @UserIdInt int userId); 780 781 /** 782 * Callback from the notification subsystem that the given FGS notification has 783 * been evaluated, and either shown or explicitly overlooked. This can happen 784 * after either Service.startForeground() or NotificationManager.notify(). 785 */ onForegroundServiceNotificationUpdate(boolean shown, Notification notification, int id, String pkg, @UserIdInt int userId)786 public abstract void onForegroundServiceNotificationUpdate(boolean shown, 787 Notification notification, int id, String pkg, @UserIdInt int userId); 788 789 /** 790 * Fully stop the given app's processes without restoring service starts or 791 * bindings, but without the other durable effects of the full-scale 792 * "force stop" intervention. 793 */ stopAppForUser(String pkg, @UserIdInt int userId)794 public abstract void stopAppForUser(String pkg, @UserIdInt int userId); 795 796 /** 797 * Registers the specified {@code processObserver} to be notified of future changes to 798 * process state. 799 */ registerProcessObserver(IProcessObserver processObserver)800 public abstract void registerProcessObserver(IProcessObserver processObserver); 801 802 /** 803 * Unregisters the specified {@code processObserver}. 804 */ unregisterProcessObserver(IProcessObserver processObserver)805 public abstract void unregisterProcessObserver(IProcessObserver processObserver); 806 807 /** 808 * Gets the uid of the instrumentation source if there is an unfinished instrumentation that 809 * targets the given uid. 810 * 811 * @param uid The uid to be checked for 812 * 813 * @return the uid of the instrumentation source, if there is an instrumentation whose target 814 * application uid matches the given uid, and {@link android.os.Process#INVALID_UID} otherwise. 815 */ getInstrumentationSourceUid(int uid)816 public abstract int getInstrumentationSourceUid(int uid); 817 818 /** Is this a device owner app? */ isDeviceOwner(int uid)819 public abstract boolean isDeviceOwner(int uid); 820 821 /** 822 * Called by DevicePolicyManagerService to set the uid of the device owner. 823 */ setDeviceOwnerUid(int uid)824 public abstract void setDeviceOwnerUid(int uid); 825 826 /** Is this a profile owner app? */ isProfileOwner(int uid)827 public abstract boolean isProfileOwner(int uid); 828 829 /** 830 * Called by DevicePolicyManagerService to set the uid of the profile owner. 831 * @param profileOwnerUids The profile owner UIDs. The ownership of the array is 832 * passed to callee. 833 */ setProfileOwnerUid(ArraySet<Integer> profileOwnerUids)834 public abstract void setProfileOwnerUid(ArraySet<Integer> profileOwnerUids); 835 836 /** 837 * Set all associated companion app that belongs to a userId. 838 * @param userId 839 * @param companionAppUids ActivityManager will take ownership of this Set, the caller 840 * shouldn't touch this Set after calling this interface. 841 */ setCompanionAppUids(int userId, Set<Integer> companionAppUids)842 public abstract void setCompanionAppUids(int userId, Set<Integer> companionAppUids); 843 844 /** 845 * is the uid an associated companion app of a userId? 846 * @param userId 847 * @param uid 848 * @return 849 */ isAssociatedCompanionApp(int userId, int uid)850 public abstract boolean isAssociatedCompanionApp(int userId, int uid); 851 852 /** 853 * Sends a broadcast, assuming the caller to be the system and allowing the inclusion of an 854 * approved allowlist of app Ids >= {@link android.os.Process#FIRST_APPLICATION_UID} that the 855 * broadcast my be sent to; any app Ids < {@link android.os.Process#FIRST_APPLICATION_UID} are 856 * automatically allowlisted. 857 * 858 * @param filterExtrasForReceiver A function to filter intent extras for the given receiver by 859 * using the rules of package visibility. Returns extras with legitimate package info that the 860 * receiver is able to access, or {@code null} if none of the packages is visible to the 861 * receiver. 862 * @param serialized Specifies whether or not the broadcast should be delivered to the 863 * receivers in a serial order. 864 * 865 * @see com.android.server.am.ActivityManagerService#broadcastIntentWithFeature( 866 * IApplicationThread, String, Intent, String, IIntentReceiver, int, String, Bundle, 867 * String[], int, Bundle, boolean, boolean, int) 868 */ broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)869 public abstract int broadcastIntent(Intent intent, 870 IIntentReceiver resultTo, 871 String[] requiredPermissions, boolean serialized, 872 int userId, int[] appIdAllowList, 873 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, 874 @Nullable Bundle bOptions); 875 876 /** 877 * Variant of 878 * {@link #broadcastIntent(Intent, IIntentReceiver, String[], boolean, int, int[], BiFunction, Bundle)} 879 * that allows sender to receive a finish callback once the broadcast delivery is completed, 880 * but provides no ordering guarantee for how the broadcast is delivered to receivers. 881 */ broadcastIntentWithCallback(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)882 public abstract int broadcastIntentWithCallback(Intent intent, 883 IIntentReceiver resultTo, 884 String[] requiredPermissions, 885 int userId, int[] appIdAllowList, 886 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, 887 @Nullable Bundle bOptions); 888 889 /** 890 * Add uid to the ActivityManagerService PendingStartActivityUids list. 891 * @param uid uid 892 * @param pid pid of the ProcessRecord that is pending top. 893 */ addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread)894 public abstract void addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread); 895 896 /** 897 * Delete uid from the ActivityManagerService PendingStartActivityUids list. 898 * @param uid uid 899 * @param nowElapsed starting time of updateOomAdj 900 */ deletePendingTopUid(int uid, long nowElapsed)901 public abstract void deletePendingTopUid(int uid, long nowElapsed); 902 903 /** 904 * Is the uid in ActivityManagerService PendingStartActivityUids list? 905 * @param uid 906 * @return true if exists, false otherwise. 907 */ isPendingTopUid(int uid)908 public abstract boolean isPendingTopUid(int uid); 909 910 /** 911 * @return the intent for the given intent sender. 912 */ 913 @Nullable getIntentForIntentSender(IIntentSender sender)914 public abstract Intent getIntentForIntentSender(IIntentSender sender); 915 916 /** 917 * Effectively PendingIntent.getActivityForUser(), but the PendingIntent is 918 * owned by the given uid rather than by the caller (i.e. the system). 919 */ getPendingIntentActivityAsApp( int requestCode, @NonNull Intent intent, int flags, Bundle options, String ownerPkgName, int ownerUid)920 public abstract PendingIntent getPendingIntentActivityAsApp( 921 int requestCode, @NonNull Intent intent, int flags, Bundle options, 922 String ownerPkgName, int ownerUid); 923 924 /** 925 * Effectively PendingIntent.getActivityForUser(), but the PendingIntent is 926 * owned by the given uid rather than by the caller (i.e. the system). 927 */ getPendingIntentActivityAsApp( int requestCode, @NonNull Intent[] intents, int flags, Bundle options, String ownerPkgName, int ownerUid)928 public abstract PendingIntent getPendingIntentActivityAsApp( 929 int requestCode, @NonNull Intent[] intents, int flags, Bundle options, 930 String ownerPkgName, int ownerUid); 931 932 /** 933 * @return mBootTimeTempAllowlistDuration of ActivityManagerConstants. 934 */ getBootTimeTempAllowListDuration()935 public abstract long getBootTimeTempAllowListDuration(); 936 937 /** Register an {@link AnrController} to control the ANR dialog behavior */ registerAnrController(AnrController controller)938 public abstract void registerAnrController(AnrController controller); 939 940 /** Unregister an {@link AnrController} */ unregisterAnrController(AnrController controller)941 public abstract void unregisterAnrController(AnrController controller); 942 943 /** 944 * Is the FGS started from an uid temporarily allowed to have while-in-use permission? 945 */ isTempAllowlistedForFgsWhileInUse(int uid)946 public abstract boolean isTempAllowlistedForFgsWhileInUse(int uid); 947 948 /** 949 * Return the temp allowlist type when server push messaging is over the quota. 950 */ getPushMessagingOverQuotaBehavior()951 public abstract @TempAllowListType int getPushMessagingOverQuotaBehavior(); 952 953 /** 954 * Return the startForeground() grace period after calling startForegroundService(). 955 */ getServiceStartForegroundTimeout()956 public abstract int getServiceStartForegroundTimeout(); 957 958 /** 959 * Returns the capability of the given uid 960 */ getUidCapability(int uid)961 public abstract @ProcessCapability int getUidCapability(int uid); 962 963 /** 964 * @return The PID list of the isolated process with packages matching the given uid. 965 */ 966 @Nullable getIsolatedProcesses(int uid)967 public abstract List<Integer> getIsolatedProcesses(int uid); 968 969 /** @see ActivityManagerService#sendIntentSender */ sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)970 public abstract int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, 971 Intent intent, String resolvedType, 972 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options); 973 974 /** 975 * Sets the provider to communicate between voice interaction manager service and 976 * ActivityManagerService. 977 */ setVoiceInteractionManagerProvider( @ullable VoiceInteractionManagerProvider provider)978 public abstract void setVoiceInteractionManagerProvider( 979 @Nullable VoiceInteractionManagerProvider provider); 980 981 /** 982 * Get whether or not the previous user's packages will be killed before the user is 983 * stopped during a user switch. 984 * 985 * <p> The primary use case of this method is for {@link com.android.server.SystemService} 986 * classes to call this API in their 987 * {@link com.android.server.SystemService#onUserSwitching} method implementation to prevent 988 * restarting any of the previous user's processes that will be killed during the user switch. 989 */ isEarlyPackageKillEnabledForUserSwitch(int fromUserId, int toUserId)990 public abstract boolean isEarlyPackageKillEnabledForUserSwitch(int fromUserId, int toUserId); 991 992 /** 993 * Sets whether the current foreground user (and its profiles) should be stopped after switched 994 * out. 995 */ setStopUserOnSwitch(@topUserOnSwitch int value)996 public abstract void setStopUserOnSwitch(@StopUserOnSwitch int value); 997 998 /** 999 * Provides the interface to communicate between voice interaction manager service and 1000 * ActivityManagerService. 1001 */ 1002 public interface VoiceInteractionManagerProvider { 1003 /** 1004 * Notifies the service when an activity is destroyed. 1005 */ notifyActivityDestroyed(IBinder activityToken)1006 void notifyActivityDestroyed(IBinder activityToken); 1007 } 1008 1009 /** 1010 * Get the restriction level of the given UID, if it hosts multiple packages, 1011 * return least restricted level. 1012 */ getRestrictionLevel(int uid)1013 public abstract @RestrictionLevel int getRestrictionLevel(int uid); 1014 1015 /** 1016 * Get the restriction level of the given package for given user id. 1017 */ getRestrictionLevel(String pkg, @UserIdInt int userId)1018 public abstract @RestrictionLevel int getRestrictionLevel(String pkg, @UserIdInt int userId); 1019 1020 /** 1021 * Get whether or not apps would be put into restricted standby bucket automatically 1022 * when it's background-restricted. 1023 */ isBgAutoRestrictedBucketFeatureFlagEnabled()1024 public abstract boolean isBgAutoRestrictedBucketFeatureFlagEnabled(); 1025 1026 /** 1027 * A listener interface, which will be notified on background restriction changes. 1028 */ 1029 public interface AppBackgroundRestrictionListener { 1030 /** 1031 * Called when the background restriction level of given uid/package is changed. 1032 */ onRestrictionLevelChanged(int uid, String packageName, @RestrictionLevel int newLevel)1033 default void onRestrictionLevelChanged(int uid, String packageName, 1034 @RestrictionLevel int newLevel) { 1035 } 1036 1037 /** 1038 * Called when toggling the feature flag of moving to restricted standby bucket 1039 * automatically on background-restricted. 1040 */ onAutoRestrictedBucketFeatureFlagChanged(boolean autoRestrictedBucket)1041 default void onAutoRestrictedBucketFeatureFlagChanged(boolean autoRestrictedBucket) { 1042 } 1043 } 1044 1045 /** 1046 * Register the background restriction listener callback. 1047 */ addAppBackgroundRestrictionListener( @onNull AppBackgroundRestrictionListener listener)1048 public abstract void addAppBackgroundRestrictionListener( 1049 @NonNull AppBackgroundRestrictionListener listener); 1050 1051 /** 1052 * A listener interface, which will be notified on foreground service state changes. 1053 */ 1054 public interface ForegroundServiceStateListener { 1055 /** 1056 * Call when the given process's foreground service state changes. 1057 * 1058 * @param packageName The package name of the process. 1059 * @param uid The UID of the process. 1060 * @param pid The pid of the process. 1061 * @param started {@code true} if the process transits from non-FGS state to FGS state. 1062 */ onForegroundServiceStateChanged(String packageName, int uid, int pid, boolean started)1063 void onForegroundServiceStateChanged(String packageName, int uid, int pid, boolean started); 1064 1065 /** 1066 * Call when the notification of the foreground service is updated. 1067 * 1068 * @param packageName The package name of the process. 1069 * @param uid The UID of the process. 1070 * @param foregroundId The current foreground service notification ID. 1071 * @param canceling The given notification is being canceled. 1072 */ onForegroundServiceNotificationUpdated(String packageName, int uid, int foregroundId, boolean canceling)1073 void onForegroundServiceNotificationUpdated(String packageName, int uid, int foregroundId, 1074 boolean canceling); 1075 } 1076 1077 /** 1078 * Register the foreground service state change listener callback. 1079 */ addForegroundServiceStateListener( @onNull ForegroundServiceStateListener listener)1080 public abstract void addForegroundServiceStateListener( 1081 @NonNull ForegroundServiceStateListener listener); 1082 1083 /** 1084 * A listener interface, which will be notified on the package sends a broadcast. 1085 */ 1086 public interface BroadcastEventListener { 1087 /** 1088 * Called when the given package/uid is sending a broadcast. 1089 */ onSendingBroadcast(String packageName, int uid)1090 void onSendingBroadcast(String packageName, int uid); 1091 } 1092 1093 /** 1094 * Register the broadcast event listener callback. 1095 */ addBroadcastEventListener(@onNull BroadcastEventListener listener)1096 public abstract void addBroadcastEventListener(@NonNull BroadcastEventListener listener); 1097 1098 /** 1099 * A listener interface, which will be notified on the package binding to a service. 1100 */ 1101 public interface BindServiceEventListener { 1102 /** 1103 * Called when the given package/uid is binding to a service 1104 */ onBindingService(String packageName, int uid)1105 void onBindingService(String packageName, int uid); 1106 } 1107 1108 /** 1109 * Register the bind service event listener callback. 1110 */ addBindServiceEventListener(@onNull BindServiceEventListener listener)1111 public abstract void addBindServiceEventListener(@NonNull BindServiceEventListener listener); 1112 1113 /** 1114 * Restart android. 1115 */ restart()1116 public abstract void restart(); 1117 1118 /** 1119 * Returns some summary statistics of the current PendingIntent queue - sizes and counts. 1120 */ getPendingIntentStats()1121 public abstract List<PendingIntentStats> getPendingIntentStats(); 1122 1123 /** 1124 * Register the UidObserver for NetworkPolicyManager service. 1125 * 1126 * This is equivalent to calling 1127 * {@link IActivityManager#registerUidObserver(IUidObserver, int, int, String)} but having a 1128 * separate method for NetworkPolicyManager service so that it's UidObserver can be called 1129 * separately outside the usual UidObserver flow. 1130 */ registerNetworkPolicyUidObserver(@onNull IUidObserver observer, int which, int cutpoint, @NonNull String callingPackage)1131 public abstract void registerNetworkPolicyUidObserver(@NonNull IUidObserver observer, 1132 int which, int cutpoint, @NonNull String callingPackage); 1133 1134 /** 1135 * Return all client package names of a service. 1136 */ getClientPackages(String servicePackageName)1137 public abstract ArraySet<String> getClientPackages(String servicePackageName); 1138 1139 /** 1140 * Trigger an unsafe intent usage strict mode violation. 1141 */ triggerUnsafeIntentStrictMode(int callingPid, int type, Intent intent)1142 public abstract void triggerUnsafeIntentStrictMode(int callingPid, int type, Intent intent); 1143 1144 /** 1145 * Start a foreground service delegate. 1146 * @param options foreground service delegate options. 1147 * @param connection a service connection served as callback to caller. 1148 * @return true if delegate is started successfully, false otherwise. 1149 * @hide 1150 */ startForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options, @Nullable ServiceConnection connection)1151 public abstract boolean startForegroundServiceDelegate( 1152 @NonNull ForegroundServiceDelegationOptions options, 1153 @Nullable ServiceConnection connection); 1154 1155 /** 1156 * Stop a foreground service delegate. 1157 * @param options the foreground service delegate options. 1158 * @hide 1159 */ stopForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options)1160 public abstract void stopForegroundServiceDelegate( 1161 @NonNull ForegroundServiceDelegationOptions options); 1162 1163 /** 1164 * Stop a foreground service delegate by service connection. 1165 * @param connection service connection used to start delegate previously. 1166 * @hide 1167 */ stopForegroundServiceDelegate(@onNull ServiceConnection connection)1168 public abstract void stopForegroundServiceDelegate(@NonNull ServiceConnection connection); 1169 1170 /** 1171 * Notifies that a media foreground service associated with a media session has 1172 * transitioned to a "user-disengaged" state. 1173 * Upon receiving this notification, service may be removed from the foreground state. It 1174 * should only be called by {@link com.android.server.media.MediaSessionService} 1175 * 1176 * @param packageName The package name of the app running the media foreground service. 1177 * @param userId The user ID associated with the foreground service. 1178 * @param notificationId The ID of the media notification associated with the foreground 1179 * service. 1180 */ notifyInactiveMediaForegroundService(@onNull String packageName, @UserIdInt int userId, int notificationId)1181 public abstract void notifyInactiveMediaForegroundService(@NonNull String packageName, 1182 @UserIdInt int userId, int notificationId); 1183 1184 /** 1185 * Notifies that a media service associated with a media session has transitioned to a 1186 * "user-engaged" state. Upon receiving this notification, service will transition to the 1187 * foreground state. It should only be called by 1188 * {@link com.android.server.media.MediaSessionService} 1189 * 1190 * @param packageName The package name of the app running the media service. 1191 * @param userId The user ID associated with the service. 1192 * @param notificationId The ID of the media notification associated with the service. 1193 */ notifyActiveMediaForegroundService(@onNull String packageName, @UserIdInt int userId, int notificationId)1194 public abstract void notifyActiveMediaForegroundService(@NonNull String packageName, 1195 @UserIdInt int userId, int notificationId); 1196 1197 /** 1198 * Same as {@link android.app.IActivityManager#startProfile(int userId)}, but it would succeed 1199 * even if the profile is disabled - it should only be called by 1200 * {@link com.android.server.devicepolicy.DevicePolicyManagerService} when starting a profile 1201 * while it's being created. 1202 */ startProfileEvenWhenDisabled(@serIdInt int userId)1203 public abstract boolean startProfileEvenWhenDisabled(@UserIdInt int userId); 1204 1205 /** 1206 * Internal method for logging foreground service API journey start. 1207 * Used with FGS metrics logging 1208 * 1209 * @hide 1210 */ logFgsApiBegin(int apiType, int uid, int pid)1211 public abstract void logFgsApiBegin(int apiType, int uid, int pid); 1212 1213 /** 1214 * Internal method for logging foreground service API journey end. 1215 * Used with FGS metrics logging 1216 * 1217 * @hide 1218 */ logFgsApiEnd(int apiType, int uid, int pid)1219 public abstract void logFgsApiEnd(int apiType, int uid, int pid); 1220 1221 /** 1222 * Checks whether an app will be able to start a foreground service or not. 1223 * 1224 * @param pid The process id belonging to the app to be checked. 1225 * @param uid The UID of the app to be checked. 1226 * @param packageName The package name of the app to be checked. 1227 * @return whether the app will be able to start a foreground service or not. 1228 */ canStartForegroundService( int pid, int uid, @NonNull String packageName)1229 public abstract boolean canStartForegroundService( 1230 int pid, int uid, @NonNull String packageName); 1231 1232 /** 1233 * Returns {@code true} if a foreground service started by an uid is allowed to have 1234 * while-in-use permissions. 1235 * 1236 * @param pid The process id belonging to the app to be checked. 1237 * @param uid The UID of the app to be checked. 1238 * @param packageName The package name of the app to be checked. 1239 * @return whether the foreground service is allowed to have while-in-use permissions. 1240 * @hide 1241 */ canAllowWhileInUsePermissionInFgs( int pid, int uid, @NonNull String packageName)1242 public abstract boolean canAllowWhileInUsePermissionInFgs( 1243 int pid, int uid, @NonNull String packageName); 1244 1245 /** 1246 * Temporarily allow foreground service started by an uid to have while-in-use permission 1247 * for durationMs. 1248 * 1249 * @param uid The UID of the app that starts the foreground service. 1250 * @param durationMs elapsedRealTime duration in milliseconds. 1251 * @hide 1252 */ tempAllowWhileInUsePermissionInFgs(int uid, long durationMs)1253 public abstract void tempAllowWhileInUsePermissionInFgs(int uid, long durationMs); 1254 1255 /** 1256 * The list of the events about the {@link android.media.projection.IMediaProjection} itself. 1257 * 1258 * @hide 1259 */ 1260 @Retention(RetentionPolicy.SOURCE) 1261 @IntDef({ 1262 MEDIA_PROJECTION_TOKEN_EVENT_CREATED, 1263 MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED, 1264 }) 1265 public @interface MediaProjectionTokenEvent{}; 1266 1267 /** 1268 * An instance of {@link android.media.projection.IMediaProjection} has been created 1269 * by the system. 1270 * 1271 * @hide 1272 */ 1273 public static final @MediaProjectionTokenEvent int MEDIA_PROJECTION_TOKEN_EVENT_CREATED = 0; 1274 1275 /** 1276 * An instance of {@link android.media.projection.IMediaProjection} has been destroyed 1277 * by the system. 1278 * 1279 * @hide 1280 */ 1281 public static final @MediaProjectionTokenEvent int MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED = 1; 1282 1283 /** 1284 * Called after the system created/destroyed a media projection for an app, if the user 1285 * has granted the permission to start a media projection from this app. 1286 * 1287 * <p>This API is specifically for the use case of enforcing the FGS type 1288 * {@code android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION}, 1289 * where the app who is starting this type of FGS must have been granted with the permission 1290 * to start the projection via the {@link android.media.projection.MediaProjection} APIs. 1291 * 1292 * @param uid The uid of the app which the system created/destroyed a media projection for. 1293 * @param projectionToken The {@link android.media.projection.IMediaProjection} token that 1294 * the system created/destroyed. 1295 * @param event The actual event happening to the given {@code projectionToken}. 1296 */ notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, @MediaProjectionTokenEvent int event)1297 public abstract void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, 1298 @MediaProjectionTokenEvent int event); 1299 1300 /** 1301 * @return The stats event for the cached apps high watermark since last pull. 1302 */ 1303 @NonNull 1304 // TODO: restore to android.util.StatsEvent once Ravenwood includes Mainline stubs getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull)1305 public abstract Object getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull); 1306 1307 /** 1308 * Internal method for clearing app data, with the extra param that is used to indicate restore. 1309 * Used by Backup service during restore operation. 1310 * 1311 * @hide 1312 */ clearApplicationUserData(String packageName, boolean keepState, boolean isRestore, IPackageDataObserver observer, int userId)1313 public abstract boolean clearApplicationUserData(String packageName, boolean keepState, 1314 boolean isRestore, IPackageDataObserver observer, int userId); 1315 1316 1317 /** 1318 * Method that checks if system is Headless (don't delay launch) case in which it 1319 * should also check if ThemeOverlayController is ready (don't delay) or not (delay). 1320 * 1321 * @param userId 1322 * @return Boolean indicating if Home launch should wait for ThemeOverlayController signal 1323 * @hide 1324 */ shouldDelayHomeLaunch(int userId)1325 public abstract boolean shouldDelayHomeLaunch(int userId); 1326 1327 /** 1328 * Used to track when a process is frozen or unfrozen. 1329 */ 1330 public interface FrozenProcessListener { 1331 /** 1332 * Called when a process is frozen. 1333 */ onProcessFrozen(int pid)1334 void onProcessFrozen(int pid); 1335 1336 /** 1337 * Called when a process is unfrozen. 1338 */ onProcessUnfrozen(int pid)1339 void onProcessUnfrozen(int pid); 1340 } 1341 1342 /** 1343 * Register the frozen process event listener callback. The same listener may be reused for 1344 * multiple pids. Listeners are dropped when the process dies. 1345 */ addFrozenProcessListener(int pid, @NonNull Executor executor, @NonNull FrozenProcessListener listener)1346 public abstract void addFrozenProcessListener(int pid, @NonNull Executor executor, 1347 @NonNull FrozenProcessListener listener); 1348 1349 /** 1350 * Add a startup timestamp to the most recent start of the specified process. 1351 * 1352 * @param key The {@link ApplicationStartInfo} start timestamp key of the timestamp to add. 1353 * @param timestampNs The clock monotonic timestamp to add in nanoseconds. 1354 * @param uid The UID of the process to add this timestamp to. 1355 * @param pid The process id of the process to add this timestamp to. 1356 * @param userId The userId in the multi-user environment. 1357 */ addStartInfoTimestamp(int key, long timestampNs, int uid, int pid, int userId)1358 public abstract void addStartInfoTimestamp(int key, long timestampNs, int uid, int pid, 1359 int userId); 1360 1361 /** 1362 * It is similar {@link IActivityManager#killApplication(String, int, int, String, int)} but 1363 * it immediately stop the package. 1364 * 1365 * <p>Note: Do not call this method from inside PMS's lock, otherwise it'll run into 1366 * watchdog reset. 1367 * @hide 1368 */ killApplicationSync(String pkgName, int appId, @CanBeALL @UserIdInt int userId, String reason, int exitInfoReason)1369 public abstract void killApplicationSync(String pkgName, int appId, 1370 @CanBeALL @UserIdInt int userId, String reason, int exitInfoReason); 1371 1372 /** 1373 * Queries the offset data for a given method on a process. 1374 * @hide 1375 */ getExecutableMethodFileOffsets(@onNull String processName, int pid, int uid, @NonNull MethodDescriptor methodDescriptor, @NonNull IOffsetCallback callback)1376 public abstract void getExecutableMethodFileOffsets(@NonNull String processName, 1377 int pid, int uid, @NonNull MethodDescriptor methodDescriptor, 1378 @NonNull IOffsetCallback callback); 1379 1380 /** 1381 * Add a creator token for all embedded intents (stored as extra) of the given intent. 1382 * 1383 * @param intent The given intent 1384 * @param creatorPackage the package name of the creator app. 1385 * @hide 1386 */ addCreatorToken(Intent intent, String creatorPackage)1387 public abstract void addCreatorToken(Intent intent, String creatorPackage); 1388 } 1389