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