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 50 import com.android.internal.os.TimeoutRecord; 51 52 import java.lang.annotation.Retention; 53 import java.lang.annotation.RetentionPolicy; 54 import java.util.ArrayList; 55 import java.util.List; 56 import java.util.Map; 57 import java.util.Set; 58 import java.util.function.BiFunction; 59 60 /** 61 * Activity manager local system service interface. 62 * 63 * @hide Only for use within the system server. 64 */ 65 public abstract class ActivityManagerInternal { 66 67 public enum ServiceNotificationPolicy { 68 /** 69 * The Notification is not associated with any foreground service. 70 */ 71 NOT_FOREGROUND_SERVICE, 72 /** 73 * The Notification is associated with a foreground service, but the 74 * notification system should handle it just like non-FGS notifications. 75 */ 76 SHOW_IMMEDIATELY, 77 /** 78 * The Notification is associated with a foreground service, and the 79 * notification system should ignore it unless it has already been shown (in 80 * which case it should be used to update the currently displayed UI). 81 */ 82 UPDATE_ONLY 83 } 84 85 // Access modes for handleIncomingUser. 86 /** 87 * Allows access to a caller with {@link android.Manifest.permission#INTERACT_ACROSS_USERS}. 88 */ 89 public static final int ALLOW_NON_FULL = 0; 90 /** 91 * Allows access to a caller with {@link android.Manifest.permission#INTERACT_ACROSS_USERS} 92 * if in the same profile group. 93 * Otherwise, {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} is required. 94 */ 95 public static final int ALLOW_NON_FULL_IN_PROFILE = 1; 96 /** 97 * Allows access to a caller only if it has the full 98 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}. 99 */ 100 public static final int ALLOW_FULL_ONLY = 2; 101 /** 102 * Allows access to a caller with {@link android.Manifest.permission#INTERACT_ACROSS_PROFILES} 103 * if in the same profile group. 104 * Otherwise, {@link android.Manifest.permission#INTERACT_ACROSS_USERS} is required and suffices 105 * as in {@link #ALLOW_NON_FULL}. 106 */ 107 public static final int ALLOW_PROFILES_OR_NON_FULL = 3; 108 109 /** 110 * Returns profile information in free form string in two separate strings. 111 * See AppProfiler for the output format. 112 * The output can only be used for human consumption. The format may change 113 * in the future. 114 * Do not call it frequently. 115 * @param time uptime for the cpu state 116 * @param lines lines of the cpu state should be returned 117 * @return a pair of Strings. The first is the current cpu load, the second is the cpu state. 118 */ getAppProfileStatsForDebugging(long time, int lines)119 public abstract Pair<String, String> getAppProfileStatsForDebugging(long time, int lines); 120 121 /** 122 * Verify that calling app has access to the given provider. 123 */ checkContentProviderAccess(String authority, @UserIdInt int userId)124 public abstract String checkContentProviderAccess(String authority, @UserIdInt int userId); 125 126 /** 127 * Verify that calling UID has access to the given provider. 128 */ checkContentProviderUriPermission(Uri uri, @UserIdInt int userId, int callingUid, int modeFlags)129 public abstract int checkContentProviderUriPermission(Uri uri, @UserIdInt int userId, 130 int callingUid, int modeFlags); 131 132 // Called by the power manager. onWakefulnessChanged(int wakefulness)133 public abstract void onWakefulnessChanged(int wakefulness); 134 135 /** 136 * @return {@code true} if process start is successful, {@code false} otherwise. 137 */ startIsolatedProcess(String entryPoint, String[] mainArgs, String processName, String abiOverride, int uid, Runnable crashHandler)138 public abstract boolean startIsolatedProcess(String entryPoint, String[] mainArgs, 139 String processName, String abiOverride, int uid, Runnable crashHandler); 140 141 /** 142 * Called when a user has been deleted. This can happen during normal device usage 143 * or just at startup, when partially removed users are purged. Any state persisted by the 144 * ActivityManager should be purged now. 145 * 146 * @param userId The user being cleaned up. 147 */ onUserRemoved(@serIdInt int userId)148 public abstract void onUserRemoved(@UserIdInt int userId); 149 150 /** 151 * Start user, if it is not already running, but don't bring it to foreground. 152 * @param userId ID of the user to start 153 * @return true if the user has been successfully started 154 */ startUserInBackground(int userId)155 public abstract boolean startUserInBackground(int userId); 156 157 /** 158 * Kill foreground apps from the specified user. 159 */ killForegroundAppsForUser(@serIdInt int userId)160 public abstract void killForegroundAppsForUser(@UserIdInt int userId); 161 162 /** 163 * Sets how long a {@link PendingIntent} can be temporarily allowlisted to bypass restrictions 164 * such as Power Save mode. 165 * @param target 166 * @param allowlistToken 167 * @param duration temp allowlist duration in milliseconds. 168 * @param type temp allowlist type defined at {@link TempAllowListType} 169 * @param reasonCode one of {@link ReasonCode} 170 * @param reason A human-readable reason for logging purposes. 171 */ setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, long duration, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason)172 public abstract void setPendingIntentAllowlistDuration(IIntentSender target, 173 IBinder allowlistToken, long duration, @TempAllowListType int type, 174 @ReasonCode int reasonCode, @Nullable String reason); 175 176 /** 177 * Returns the flags set for a {@link PendingIntent}. 178 */ getPendingIntentFlags(IIntentSender target)179 public abstract int getPendingIntentFlags(IIntentSender target); 180 181 /** 182 * Allows a {@link PendingIntent} to start activities from background. 183 */ setPendingIntentAllowBgActivityStarts( IIntentSender target, IBinder allowlistToken, int flags)184 public abstract void setPendingIntentAllowBgActivityStarts( 185 IIntentSender target, IBinder allowlistToken, int flags); 186 187 /** 188 * Voids {@link PendingIntent}'s privilege to start activities from background. 189 */ clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken)190 public abstract void clearPendingIntentAllowBgActivityStarts(IIntentSender target, 191 IBinder allowlistToken); 192 193 /** 194 * Allow DeviceIdleController to tell us about what apps are allowlisted. 195 */ setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids)196 public abstract void setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids); 197 198 /** 199 * Update information about which app IDs are on the temp allowlist. 200 * @param appids the updated list of appIds in temp allowlist. 201 * If null, it is to update only changingUid. 202 * @param changingUid uid to add or remove to temp allowlist. 203 * @param adding true to add to temp allowlist, false to remove from temp allowlist. 204 * @param durationMs when adding is true, the duration to be in temp allowlist. 205 * @param type temp allowlist type defined at {@link TempAllowListType}. 206 * @param reasonCode one of {@link ReasonCode} 207 * @param reason A human-readable reason for logging purposes. 208 * @param callingUid the callingUid that setup this temp allowlist, only valid when param adding 209 * is true. 210 */ updateDeviceIdleTempAllowlist(@ullable int[] appids, int changingUid, boolean adding, long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason, int callingUid)211 public abstract void updateDeviceIdleTempAllowlist(@Nullable int[] appids, int changingUid, 212 boolean adding, long durationMs, @TempAllowListType int type, 213 @ReasonCode int reasonCode, 214 @Nullable String reason, int callingUid); 215 216 /** 217 * Get the procstate for the UID. The return value will be between 218 * {@link ActivityManager#MIN_PROCESS_STATE} and {@link ActivityManager#MAX_PROCESS_STATE}. 219 * Note if the UID doesn't exist, it'll return {@link ActivityManager#PROCESS_STATE_NONEXISTENT} 220 * (-1). 221 */ getUidProcessState(int uid)222 public abstract int getUidProcessState(int uid); 223 224 /** 225 * Get a map of pid and package name that process of that pid Android/data and Android/obb 226 * directory is not mounted to lowerfs. 227 */ getProcessesWithPendingBindMounts(int userId)228 public abstract Map<Integer, String> getProcessesWithPendingBindMounts(int userId); 229 230 /** 231 * @return {@code true} if system is ready, {@code false} otherwise. 232 */ isSystemReady()233 public abstract boolean isSystemReady(); 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 /** 481 * Oom Adj Reason: Follow up update for time sensitive state evaluations. 482 */ 483 public static final int OOM_ADJ_REASON_FOLLOW_UP = 23; 484 485 @IntDef(prefix = {"OOM_ADJ_REASON_"}, value = { 486 OOM_ADJ_REASON_NONE, 487 OOM_ADJ_REASON_ACTIVITY, 488 OOM_ADJ_REASON_FINISH_RECEIVER, 489 OOM_ADJ_REASON_START_RECEIVER, 490 OOM_ADJ_REASON_BIND_SERVICE, 491 OOM_ADJ_REASON_UNBIND_SERVICE, 492 OOM_ADJ_REASON_START_SERVICE, 493 OOM_ADJ_REASON_GET_PROVIDER, 494 OOM_ADJ_REASON_REMOVE_PROVIDER, 495 OOM_ADJ_REASON_UI_VISIBILITY, 496 OOM_ADJ_REASON_ALLOWLIST, 497 OOM_ADJ_REASON_PROCESS_BEGIN, 498 OOM_ADJ_REASON_PROCESS_END, 499 OOM_ADJ_REASON_SHORT_FGS_TIMEOUT, 500 OOM_ADJ_REASON_SYSTEM_INIT, 501 OOM_ADJ_REASON_BACKUP, 502 OOM_ADJ_REASON_SHELL, 503 OOM_ADJ_REASON_REMOVE_TASK, 504 OOM_ADJ_REASON_UID_IDLE, 505 OOM_ADJ_REASON_STOP_SERVICE, 506 OOM_ADJ_REASON_EXECUTING_SERVICE, 507 OOM_ADJ_REASON_RESTRICTION_CHANGE, 508 OOM_ADJ_REASON_COMPONENT_DISABLED, 509 OOM_ADJ_REASON_FOLLOW_UP, 510 }) 511 @Retention(RetentionPolicy.SOURCE) 512 public @interface OomAdjReason {} 513 514 /** 515 * Request to update oom adj. 516 */ updateOomAdj(@omAdjReason int oomAdjReason)517 public abstract void updateOomAdj(@OomAdjReason int oomAdjReason); updateCpuStats()518 public abstract void updateCpuStats(); 519 520 /** 521 * Update battery stats on activity usage. 522 * @param activity 523 * @param uid 524 * @param userId 525 * @param started 526 */ updateBatteryStats( ComponentName activity, int uid, @UserIdInt int userId, boolean resumed)527 public abstract void updateBatteryStats( 528 ComponentName activity, int uid, @UserIdInt int userId, boolean resumed); 529 530 /** 531 * Update UsageStats of the activity. 532 * @param activity 533 * @param userId 534 * @param event 535 * @param appToken ActivityRecord's appToken. 536 * @param taskRoot Task's root 537 */ updateActivityUsageStats( ComponentName activity, @UserIdInt int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)538 public abstract void updateActivityUsageStats( 539 ComponentName activity, @UserIdInt int userId, int event, IBinder appToken, 540 ComponentName taskRoot, ActivityId activityId); updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)541 public abstract void updateForegroundTimeIfOnBattery( 542 String packageName, int uid, long cpuTimeDiff); sendForegroundProfileChanged(@serIdInt int userId)543 public abstract void sendForegroundProfileChanged(@UserIdInt int userId); 544 545 /** 546 * Returns whether the given user requires credential entry at this time. This is used to 547 * intercept activity launches for apps corresponding to locked profiles due to separate 548 * challenge being triggered or when the profile user is yet to be unlocked. 549 */ shouldConfirmCredentials(@serIdInt int userId)550 public abstract boolean shouldConfirmCredentials(@UserIdInt int userId); 551 552 /** 553 * Used in conjunction with {@link #noteAlarmStart(PendingIntent, WorkSource, int, String)} to 554 * note an alarm duration for battery attribution 555 */ noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)556 public abstract void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, 557 String tag); 558 559 /** 560 * Used in conjunction with {@link #noteAlarmFinish(PendingIntent, WorkSource, int, String)} to 561 * note an alarm duration for battery attribution 562 */ noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)563 public abstract void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, 564 String tag); 565 566 /** 567 * Used to note a wakeup alarm for battery attribution. 568 */ noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)569 public abstract void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, 570 String sourcePkg, String tag); 571 572 /** 573 * Returns whether this app is disallowed to run in the background. 574 * 575 * @see ActivityManager#APP_START_MODE_DISABLED 576 */ isAppStartModeDisabled(int uid, String packageName)577 public abstract boolean isAppStartModeDisabled(int uid, String packageName); 578 579 /** 580 * Returns the ids of the current user and all of its profiles (if any), regardless of the 581 * running state of the profiles. 582 */ getCurrentProfileIds()583 public abstract int[] getCurrentProfileIds(); getCurrentUser()584 public abstract UserInfo getCurrentUser(); ensureNotSpecialUser(@serIdInt int userId)585 public abstract void ensureNotSpecialUser(@UserIdInt int userId); isCurrentProfile(@serIdInt int userId)586 public abstract boolean isCurrentProfile(@UserIdInt int userId); hasStartedUserState(@serIdInt int userId)587 public abstract boolean hasStartedUserState(@UserIdInt int userId); finishUserSwitch(Object uss)588 public abstract void finishUserSwitch(Object uss); 589 590 /** Schedule the execution of all pending app GCs. */ scheduleAppGcs()591 public abstract void scheduleAppGcs(); 592 593 /** Gets the task id for a given activity. */ getTaskIdForActivity(@onNull IBinder token, boolean onlyRoot)594 public abstract int getTaskIdForActivity(@NonNull IBinder token, boolean onlyRoot); 595 596 /** Gets the basic info for a given activity. */ getActivityPresentationInfo(@onNull IBinder token)597 public abstract ActivityPresentationInfo getActivityPresentationInfo(@NonNull IBinder token); 598 setBooting(boolean booting)599 public abstract void setBooting(boolean booting); isBooting()600 public abstract boolean isBooting(); setBooted(boolean booted)601 public abstract void setBooted(boolean booted); isBooted()602 public abstract boolean isBooted(); finishBooting()603 public abstract void finishBooting(); 604 605 /** 606 * Temp allowlist a UID for PendingIntent. 607 * @param callerPid the PID that sent the PendingIntent. 608 * @param callerUid the UID that sent the PendingIntent. 609 * @param targetUid the UID that is been temp allowlisted. 610 * @param duration temp allowlist duration in milliseconds. 611 * @param type temp allowlist type defined at {@link TempAllowListType} 612 * @param reasonCode one of {@link ReasonCode} 613 * @param reason 614 */ tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)615 public abstract void tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, 616 long duration, int type, @ReasonCode int reasonCode, String reason); 617 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)618 public abstract int broadcastIntentInPackage(String packageName, @Nullable String featureId, 619 int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 620 IApplicationThread resultToThread, IIntentReceiver resultTo, int resultCode, 621 String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, 622 boolean serialized, boolean sticky, @UserIdInt int userId, 623 BackgroundStartPrivileges backgroundStartPrivileges, 624 @Nullable int[] broadcastAllowList); 625 startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, @UserIdInt int userId, BackgroundStartPrivileges backgroundStartPrivileges)626 public abstract ComponentName startServiceInPackage(int uid, Intent service, 627 String resolvedType, boolean fgRequired, String callingPackage, 628 @Nullable String callingFeatureId, @UserIdInt int userId, 629 BackgroundStartPrivileges backgroundStartPrivileges) 630 throws TransactionTooLargeException; 631 disconnectActivityFromServices(Object connectionHolder)632 public abstract void disconnectActivityFromServices(Object connectionHolder); cleanUpServices(@serIdInt int userId, ComponentName component, Intent baseIntent)633 public abstract void cleanUpServices(@UserIdInt int userId, ComponentName component, 634 Intent baseIntent); getActivityInfoForUser(ActivityInfo aInfo, @UserIdInt int userId)635 public abstract ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, @UserIdInt int userId); ensureBootCompleted()636 public abstract void ensureBootCompleted(); updateOomLevelsForDisplay(int displayId)637 public abstract void updateOomLevelsForDisplay(int displayId); isActivityStartsLoggingEnabled()638 public abstract boolean isActivityStartsLoggingEnabled(); 639 /** Returns true if the background activity starts is enabled. */ isBackgroundActivityStartsEnabled()640 public abstract boolean isBackgroundActivityStartsEnabled(); 641 /** 642 * Returns The current {@link BackgroundStartPrivileges} of the UID. 643 */ 644 @NonNull getBackgroundStartPrivileges(int uid)645 public abstract BackgroundStartPrivileges getBackgroundStartPrivileges(int uid); reportCurKeyguardUsageEvent(boolean keyguardShowing)646 public abstract void reportCurKeyguardUsageEvent(boolean keyguardShowing); 647 648 /** 649 * Returns whether the app is in a state where it is allowed to schedule a 650 * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}. 651 */ canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)652 public abstract boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName); 653 654 /** @see com.android.server.am.ActivityManagerService#monitor */ monitor()655 public abstract void monitor(); 656 657 /** Input dispatch timeout to a window, start the ANR process. Return the timeout extension, 658 * in milliseconds, or 0 to abort dispatch. */ inputDispatchingTimedOut(int pid, boolean aboveSystem, TimeoutRecord timeoutRecord)659 public abstract long inputDispatchingTimedOut(int pid, boolean aboveSystem, 660 TimeoutRecord timeoutRecord); 661 inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, TimeoutRecord timeoutRecord)662 public abstract boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName, 663 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, 664 boolean aboveSystem, TimeoutRecord timeoutRecord); 665 666 /** 667 * App started responding to input events. This signal can be used to abort the ANR process and 668 * hide the ANR dialog. 669 */ inputDispatchingResumed(int pid)670 public abstract void inputDispatchingResumed(int pid); 671 672 /** 673 * User tapped "wait" in the ANR dialog - reschedule the dialog to be shown again at a later 674 * time. 675 * @param data AppNotRespondingDialog.Data object 676 */ rescheduleAnrDialog(Object data)677 public abstract void rescheduleAnrDialog(Object data); 678 679 /** 680 * Sends {@link android.content.Intent#ACTION_CONFIGURATION_CHANGED} with all the appropriate 681 * flags. 682 */ broadcastGlobalConfigurationChanged(int changes, boolean initLocale)683 public abstract void broadcastGlobalConfigurationChanged(int changes, boolean initLocale); 684 685 /** 686 * Sends {@link android.content.Intent#ACTION_CLOSE_SYSTEM_DIALOGS} with all the appropriate 687 * flags. 688 */ broadcastCloseSystemDialogs(String reason)689 public abstract void broadcastCloseSystemDialogs(String reason); 690 691 /** 692 * Trigger an ANR for the specified process. 693 */ appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)694 public abstract void appNotResponding(@NonNull String processName, int uid, 695 @NonNull TimeoutRecord timeoutRecord); 696 697 /** 698 * Kills all background processes, except those matching any of the specified properties. 699 * 700 * @param minTargetSdk the target SDK version at or above which to preserve processes, 701 * or {@code -1} to ignore the target SDK 702 * @param maxProcState the process state at or below which to preserve processes, 703 * or {@code -1} to ignore the process state 704 */ killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)705 public abstract void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState); 706 707 /** Starts a given process. */ startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)708 public abstract void startProcess(String processName, ApplicationInfo info, 709 boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName); 710 711 /** Starts up the starting activity process for debugging if needed. 712 * This function needs to be called synchronously from WindowManager context so the caller 713 * passes a lock {@code wmLock} and waits to be notified. 714 * 715 * @param wmLock calls {@code notify} on the object to wake up the caller. 716 */ setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)717 public abstract void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, 718 ProfilerInfo profilerInfo, Object wmLock); 719 720 /** Returns mount mode for process running with given pid */ getStorageMountMode(int pid, int uid)721 public abstract int getStorageMountMode(int pid, int uid); 722 723 /** Returns true if the given uid is the app in the foreground. */ isAppForeground(int uid)724 public abstract boolean isAppForeground(int uid); 725 726 /** Returns true if the given process name and uid is currently marked 'bad' */ isAppBad(String processName, int uid)727 public abstract boolean isAppBad(String processName, int uid); 728 729 /** Remove pending backup for the given userId. */ clearPendingBackup(@serIdInt int userId)730 public abstract void clearPendingBackup(@UserIdInt int userId); 731 732 /** 733 * When power button is very long pressed, call this interface to do some pre-shutdown work 734 * like persisting database etc. 735 */ prepareForPossibleShutdown()736 public abstract void prepareForPossibleShutdown(); 737 738 /** 739 * Returns {@code true} if {@code uid} is running a foreground service of a specific 740 * {@code foregroundServiceType}. 741 */ hasRunningForegroundService(int uid, int foregroundServiceType)742 public abstract boolean hasRunningForegroundService(int uid, int foregroundServiceType); 743 744 /** 745 * Returns {@code true} if the given notification channel currently has a 746 * notification associated with a foreground service. This is an AMS check 747 * because that is the source of truth for the FGS state. 748 */ hasForegroundServiceNotification(String pkg, @UserIdInt int userId, String channelId)749 public abstract boolean hasForegroundServiceNotification(String pkg, @UserIdInt int userId, 750 String channelId); 751 752 /** 753 * Tell the service lifecycle logic that the given Notification content is now 754 * canonical for any foreground-service visibility policy purposes. 755 * 756 * Returns a description of any FGs-related policy around the given Notification: 757 * not associated with an FGS; ensure display; or only update if already displayed. 758 */ applyForegroundServiceNotification( Notification notification, String tag, int id, String pkg, @UserIdInt int userId)759 public abstract ServiceNotificationPolicy applyForegroundServiceNotification( 760 Notification notification, String tag, int id, String pkg, @UserIdInt int userId); 761 762 /** 763 * Callback from the notification subsystem that the given FGS notification has 764 * been evaluated, and either shown or explicitly overlooked. This can happen 765 * after either Service.startForeground() or NotificationManager.notify(). 766 */ onForegroundServiceNotificationUpdate(boolean shown, Notification notification, int id, String pkg, @UserIdInt int userId)767 public abstract void onForegroundServiceNotificationUpdate(boolean shown, 768 Notification notification, int id, String pkg, @UserIdInt int userId); 769 770 /** 771 * Fully stop the given app's processes without restoring service starts or 772 * bindings, but without the other durable effects of the full-scale 773 * "force stop" intervention. 774 */ stopAppForUser(String pkg, @UserIdInt int userId)775 public abstract void stopAppForUser(String pkg, @UserIdInt int userId); 776 777 /** 778 * Registers the specified {@code processObserver} to be notified of future changes to 779 * process state. 780 */ registerProcessObserver(IProcessObserver processObserver)781 public abstract void registerProcessObserver(IProcessObserver processObserver); 782 783 /** 784 * Unregisters the specified {@code processObserver}. 785 */ unregisterProcessObserver(IProcessObserver processObserver)786 public abstract void unregisterProcessObserver(IProcessObserver processObserver); 787 788 /** 789 * Gets the uid of the instrumentation source if there is an unfinished instrumentation that 790 * targets the given uid. 791 * 792 * @param uid The uid to be checked for 793 * 794 * @return the uid of the instrumentation source, if there is an instrumentation whose target 795 * application uid matches the given uid, and {@link android.os.Process#INVALID_UID} otherwise. 796 */ getInstrumentationSourceUid(int uid)797 public abstract int getInstrumentationSourceUid(int uid); 798 799 /** Is this a device owner app? */ isDeviceOwner(int uid)800 public abstract boolean isDeviceOwner(int uid); 801 802 /** 803 * Called by DevicePolicyManagerService to set the uid of the device owner. 804 */ setDeviceOwnerUid(int uid)805 public abstract void setDeviceOwnerUid(int uid); 806 807 /** Is this a profile owner app? */ isProfileOwner(int uid)808 public abstract boolean isProfileOwner(int uid); 809 810 /** 811 * Called by DevicePolicyManagerService to set the uid of the profile owner. 812 * @param profileOwnerUids The profile owner UIDs. The ownership of the array is 813 * passed to callee. 814 */ setProfileOwnerUid(ArraySet<Integer> profileOwnerUids)815 public abstract void setProfileOwnerUid(ArraySet<Integer> profileOwnerUids); 816 817 /** 818 * Set all associated companion app that belongs to a userId. 819 * @param userId 820 * @param companionAppUids ActivityManager will take ownership of this Set, the caller 821 * shouldn't touch this Set after calling this interface. 822 */ setCompanionAppUids(int userId, Set<Integer> companionAppUids)823 public abstract void setCompanionAppUids(int userId, Set<Integer> companionAppUids); 824 825 /** 826 * is the uid an associated companion app of a userId? 827 * @param userId 828 * @param uid 829 * @return 830 */ isAssociatedCompanionApp(int userId, int uid)831 public abstract boolean isAssociatedCompanionApp(int userId, int uid); 832 833 /** 834 * Sends a broadcast, assuming the caller to be the system and allowing the inclusion of an 835 * approved allowlist of app Ids >= {@link android.os.Process#FIRST_APPLICATION_UID} that the 836 * broadcast my be sent to; any app Ids < {@link android.os.Process#FIRST_APPLICATION_UID} are 837 * automatically allowlisted. 838 * 839 * @param filterExtrasForReceiver A function to filter intent extras for the given receiver by 840 * using the rules of package visibility. Returns extras with legitimate package info that the 841 * receiver is able to access, or {@code null} if none of the packages is visible to the 842 * receiver. 843 * @param serialized Specifies whether or not the broadcast should be delivered to the 844 * receivers in a serial order. 845 * 846 * @see com.android.server.am.ActivityManagerService#broadcastIntentWithFeature( 847 * IApplicationThread, String, Intent, String, IIntentReceiver, int, String, Bundle, 848 * String[], int, Bundle, boolean, boolean, int) 849 */ broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)850 public abstract int broadcastIntent(Intent intent, 851 IIntentReceiver resultTo, 852 String[] requiredPermissions, boolean serialized, 853 int userId, int[] appIdAllowList, 854 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, 855 @Nullable Bundle bOptions); 856 857 /** 858 * Variant of 859 * {@link #broadcastIntent(Intent, IIntentReceiver, String[], boolean, int, int[], BiFunction, Bundle)} 860 * that allows sender to receive a finish callback once the broadcast delivery is completed, 861 * but provides no ordering guarantee for how the broadcast is delivered to receivers. 862 */ broadcastIntentWithCallback(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)863 public abstract int broadcastIntentWithCallback(Intent intent, 864 IIntentReceiver resultTo, 865 String[] requiredPermissions, 866 int userId, int[] appIdAllowList, 867 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, 868 @Nullable Bundle bOptions); 869 870 /** 871 * Add uid to the ActivityManagerService PendingStartActivityUids list. 872 * @param uid uid 873 * @param pid pid of the ProcessRecord that is pending top. 874 */ addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread)875 public abstract void addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread); 876 877 /** 878 * Delete uid from the ActivityManagerService PendingStartActivityUids list. 879 * @param uid uid 880 * @param nowElapsed starting time of updateOomAdj 881 */ deletePendingTopUid(int uid, long nowElapsed)882 public abstract void deletePendingTopUid(int uid, long nowElapsed); 883 884 /** 885 * Is the uid in ActivityManagerService PendingStartActivityUids list? 886 * @param uid 887 * @return true if exists, false otherwise. 888 */ isPendingTopUid(int uid)889 public abstract boolean isPendingTopUid(int uid); 890 891 /** 892 * @return the intent for the given intent sender. 893 */ 894 @Nullable getIntentForIntentSender(IIntentSender sender)895 public abstract Intent getIntentForIntentSender(IIntentSender sender); 896 897 /** 898 * Effectively PendingIntent.getActivityForUser(), but the PendingIntent is 899 * owned by the given uid rather than by the caller (i.e. the system). 900 */ getPendingIntentActivityAsApp( int requestCode, @NonNull Intent intent, int flags, Bundle options, String ownerPkgName, int ownerUid)901 public abstract PendingIntent getPendingIntentActivityAsApp( 902 int requestCode, @NonNull Intent intent, int flags, Bundle options, 903 String ownerPkgName, int ownerUid); 904 905 /** 906 * Effectively PendingIntent.getActivityForUser(), but the PendingIntent is 907 * owned by the given uid rather than by the caller (i.e. the system). 908 */ getPendingIntentActivityAsApp( int requestCode, @NonNull Intent[] intents, int flags, Bundle options, String ownerPkgName, int ownerUid)909 public abstract PendingIntent getPendingIntentActivityAsApp( 910 int requestCode, @NonNull Intent[] intents, int flags, Bundle options, 911 String ownerPkgName, int ownerUid); 912 913 /** 914 * @return mBootTimeTempAllowlistDuration of ActivityManagerConstants. 915 */ getBootTimeTempAllowListDuration()916 public abstract long getBootTimeTempAllowListDuration(); 917 918 /** Register an {@link AnrController} to control the ANR dialog behavior */ registerAnrController(AnrController controller)919 public abstract void registerAnrController(AnrController controller); 920 921 /** Unregister an {@link AnrController} */ unregisterAnrController(AnrController controller)922 public abstract void unregisterAnrController(AnrController controller); 923 924 /** 925 * Is the FGS started from an uid temporarily allowed to have while-in-use permission? 926 */ isTempAllowlistedForFgsWhileInUse(int uid)927 public abstract boolean isTempAllowlistedForFgsWhileInUse(int uid); 928 929 /** 930 * Return the temp allowlist type when server push messaging is over the quota. 931 */ getPushMessagingOverQuotaBehavior()932 public abstract @TempAllowListType int getPushMessagingOverQuotaBehavior(); 933 934 /** 935 * Return the startForeground() grace period after calling startForegroundService(). 936 */ getServiceStartForegroundTimeout()937 public abstract int getServiceStartForegroundTimeout(); 938 939 /** 940 * Returns the capability of the given uid 941 */ getUidCapability(int uid)942 public abstract @ProcessCapability int getUidCapability(int uid); 943 944 /** 945 * @return The PID list of the isolated process with packages matching the given uid. 946 */ 947 @Nullable getIsolatedProcesses(int uid)948 public abstract List<Integer> getIsolatedProcesses(int uid); 949 950 /** @see ActivityManagerService#sendIntentSender */ sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)951 public abstract int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, 952 Intent intent, String resolvedType, 953 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options); 954 955 /** 956 * Sets the provider to communicate between voice interaction manager service and 957 * ActivityManagerService. 958 */ setVoiceInteractionManagerProvider( @ullable VoiceInteractionManagerProvider provider)959 public abstract void setVoiceInteractionManagerProvider( 960 @Nullable VoiceInteractionManagerProvider provider); 961 962 /** 963 * Sets whether the current foreground user (and its profiles) should be stopped after switched 964 * out. 965 */ setStopUserOnSwitch(@topUserOnSwitch int value)966 public abstract void setStopUserOnSwitch(@StopUserOnSwitch int value); 967 968 /** 969 * Provides the interface to communicate between voice interaction manager service and 970 * ActivityManagerService. 971 */ 972 public interface VoiceInteractionManagerProvider { 973 /** 974 * Notifies the service when an activity is destroyed. 975 */ notifyActivityDestroyed(IBinder activityToken)976 void notifyActivityDestroyed(IBinder activityToken); 977 } 978 979 /** 980 * Get the restriction level of the given UID, if it hosts multiple packages, 981 * return least restricted level. 982 */ getRestrictionLevel(int uid)983 public abstract @RestrictionLevel int getRestrictionLevel(int uid); 984 985 /** 986 * Get the restriction level of the given package for given user id. 987 */ getRestrictionLevel(String pkg, @UserIdInt int userId)988 public abstract @RestrictionLevel int getRestrictionLevel(String pkg, @UserIdInt int userId); 989 990 /** 991 * Get whether or not apps would be put into restricted standby bucket automatically 992 * when it's background-restricted. 993 */ isBgAutoRestrictedBucketFeatureFlagEnabled()994 public abstract boolean isBgAutoRestrictedBucketFeatureFlagEnabled(); 995 996 /** 997 * A listener interface, which will be notified on background restriction changes. 998 */ 999 public interface AppBackgroundRestrictionListener { 1000 /** 1001 * Called when the background restriction level of given uid/package is changed. 1002 */ onRestrictionLevelChanged(int uid, String packageName, @RestrictionLevel int newLevel)1003 default void onRestrictionLevelChanged(int uid, String packageName, 1004 @RestrictionLevel int newLevel) { 1005 } 1006 1007 /** 1008 * Called when toggling the feature flag of moving to restricted standby bucket 1009 * automatically on background-restricted. 1010 */ onAutoRestrictedBucketFeatureFlagChanged(boolean autoRestrictedBucket)1011 default void onAutoRestrictedBucketFeatureFlagChanged(boolean autoRestrictedBucket) { 1012 } 1013 } 1014 1015 /** 1016 * Register the background restriction listener callback. 1017 */ addAppBackgroundRestrictionListener( @onNull AppBackgroundRestrictionListener listener)1018 public abstract void addAppBackgroundRestrictionListener( 1019 @NonNull AppBackgroundRestrictionListener listener); 1020 1021 /** 1022 * A listener interface, which will be notified on foreground service state changes. 1023 */ 1024 public interface ForegroundServiceStateListener { 1025 /** 1026 * Call when the given process's foreground service state changes. 1027 * 1028 * @param packageName The package name of the process. 1029 * @param uid The UID of the process. 1030 * @param pid The pid of the process. 1031 * @param started {@code true} if the process transits from non-FGS state to FGS state. 1032 */ onForegroundServiceStateChanged(String packageName, int uid, int pid, boolean started)1033 void onForegroundServiceStateChanged(String packageName, int uid, int pid, boolean started); 1034 1035 /** 1036 * Call when the notification of the foreground service is updated. 1037 * 1038 * @param packageName The package name of the process. 1039 * @param uid The UID of the process. 1040 * @param foregroundId The current foreground service notification ID. 1041 * @param canceling The given notification is being canceled. 1042 */ onForegroundServiceNotificationUpdated(String packageName, int uid, int foregroundId, boolean canceling)1043 void onForegroundServiceNotificationUpdated(String packageName, int uid, int foregroundId, 1044 boolean canceling); 1045 } 1046 1047 /** 1048 * Register the foreground service state change listener callback. 1049 */ addForegroundServiceStateListener( @onNull ForegroundServiceStateListener listener)1050 public abstract void addForegroundServiceStateListener( 1051 @NonNull ForegroundServiceStateListener listener); 1052 1053 /** 1054 * A listener interface, which will be notified on the package sends a broadcast. 1055 */ 1056 public interface BroadcastEventListener { 1057 /** 1058 * Called when the given package/uid is sending a broadcast. 1059 */ onSendingBroadcast(String packageName, int uid)1060 void onSendingBroadcast(String packageName, int uid); 1061 } 1062 1063 /** 1064 * Register the broadcast event listener callback. 1065 */ addBroadcastEventListener(@onNull BroadcastEventListener listener)1066 public abstract void addBroadcastEventListener(@NonNull BroadcastEventListener listener); 1067 1068 /** 1069 * A listener interface, which will be notified on the package binding to a service. 1070 */ 1071 public interface BindServiceEventListener { 1072 /** 1073 * Called when the given package/uid is binding to a service 1074 */ onBindingService(String packageName, int uid)1075 void onBindingService(String packageName, int uid); 1076 } 1077 1078 /** 1079 * Register the bind service event listener callback. 1080 */ addBindServiceEventListener(@onNull BindServiceEventListener listener)1081 public abstract void addBindServiceEventListener(@NonNull BindServiceEventListener listener); 1082 1083 /** 1084 * Restart android. 1085 */ restart()1086 public abstract void restart(); 1087 1088 /** 1089 * Returns some summary statistics of the current PendingIntent queue - sizes and counts. 1090 */ getPendingIntentStats()1091 public abstract List<PendingIntentStats> getPendingIntentStats(); 1092 1093 /** 1094 * Register the UidObserver for NetworkPolicyManager service. 1095 * 1096 * This is equivalent to calling 1097 * {@link IActivityManager#registerUidObserver(IUidObserver, int, int, String)} but having a 1098 * separate method for NetworkPolicyManager service so that it's UidObserver can be called 1099 * separately outside the usual UidObserver flow. 1100 */ registerNetworkPolicyUidObserver(@onNull IUidObserver observer, int which, int cutpoint, @NonNull String callingPackage)1101 public abstract void registerNetworkPolicyUidObserver(@NonNull IUidObserver observer, 1102 int which, int cutpoint, @NonNull String callingPackage); 1103 1104 /** 1105 * Return all client package names of a service. 1106 */ getClientPackages(String servicePackageName)1107 public abstract ArraySet<String> getClientPackages(String servicePackageName); 1108 1109 /** 1110 * Trigger an unsafe intent usage strict mode violation. 1111 */ triggerUnsafeIntentStrictMode(int callingPid, int type, Intent intent)1112 public abstract void triggerUnsafeIntentStrictMode(int callingPid, int type, Intent intent); 1113 1114 /** 1115 * Start a foreground service delegate. 1116 * @param options foreground service delegate options. 1117 * @param connection a service connection served as callback to caller. 1118 * @return true if delegate is started successfully, false otherwise. 1119 * @hide 1120 */ startForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options, @Nullable ServiceConnection connection)1121 public abstract boolean startForegroundServiceDelegate( 1122 @NonNull ForegroundServiceDelegationOptions options, 1123 @Nullable ServiceConnection connection); 1124 1125 /** 1126 * Stop a foreground service delegate. 1127 * @param options the foreground service delegate options. 1128 * @hide 1129 */ stopForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options)1130 public abstract void stopForegroundServiceDelegate( 1131 @NonNull ForegroundServiceDelegationOptions options); 1132 1133 /** 1134 * Stop a foreground service delegate by service connection. 1135 * @param connection service connection used to start delegate previously. 1136 * @hide 1137 */ stopForegroundServiceDelegate(@onNull ServiceConnection connection)1138 public abstract void stopForegroundServiceDelegate(@NonNull ServiceConnection connection); 1139 1140 /** 1141 * Same as {@link android.app.IActivityManager#startProfile(int userId)}, but it would succeed 1142 * even if the profile is disabled - it should only be called by 1143 * {@link com.android.server.devicepolicy.DevicePolicyManagerService} when starting a profile 1144 * while it's being created. 1145 */ startProfileEvenWhenDisabled(@serIdInt int userId)1146 public abstract boolean startProfileEvenWhenDisabled(@UserIdInt int userId); 1147 1148 /** 1149 * Internal method for logging foreground service API journey start. 1150 * Used with FGS metrics logging 1151 * 1152 * @hide 1153 */ logFgsApiBegin(int apiType, int uid, int pid)1154 public abstract void logFgsApiBegin(int apiType, int uid, int pid); 1155 1156 /** 1157 * Internal method for logging foreground service API journey end. 1158 * Used with FGS metrics logging 1159 * 1160 * @hide 1161 */ logFgsApiEnd(int apiType, int uid, int pid)1162 public abstract void logFgsApiEnd(int apiType, int uid, int pid); 1163 1164 /** 1165 * Checks whether an app will be able to start a foreground service or not. 1166 * 1167 * @param pid The process id belonging to the app to be checked. 1168 * @param uid The UID of the app to be checked. 1169 * @param packageName The package name of the app to be checked. 1170 * @return whether the app will be able to start a foreground service or not. 1171 */ canStartForegroundService( int pid, int uid, @NonNull String packageName)1172 public abstract boolean canStartForegroundService( 1173 int pid, int uid, @NonNull String packageName); 1174 1175 /** 1176 * Returns {@code true} if a foreground service started by an uid is allowed to have 1177 * while-in-use permissions. 1178 * 1179 * @param pid The process id belonging to the app to be checked. 1180 * @param uid The UID of the app to be checked. 1181 * @param packageName The package name of the app to be checked. 1182 * @return whether the foreground service is allowed to have while-in-use permissions. 1183 * @hide 1184 */ canAllowWhileInUsePermissionInFgs( int pid, int uid, @NonNull String packageName)1185 public abstract boolean canAllowWhileInUsePermissionInFgs( 1186 int pid, int uid, @NonNull String packageName); 1187 1188 /** 1189 * Temporarily allow foreground service started by an uid to have while-in-use permission 1190 * for durationMs. 1191 * 1192 * @param uid The UID of the app that starts the foreground service. 1193 * @param durationMs elapsedRealTime duration in milliseconds. 1194 * @hide 1195 */ tempAllowWhileInUsePermissionInFgs(int uid, long durationMs)1196 public abstract void tempAllowWhileInUsePermissionInFgs(int uid, long durationMs); 1197 1198 /** 1199 * The list of the events about the {@link android.media.projection.IMediaProjection} itself. 1200 * 1201 * @hide 1202 */ 1203 @Retention(RetentionPolicy.SOURCE) 1204 @IntDef({ 1205 MEDIA_PROJECTION_TOKEN_EVENT_CREATED, 1206 MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED, 1207 }) 1208 public @interface MediaProjectionTokenEvent{}; 1209 1210 /** 1211 * An instance of {@link android.media.projection.IMediaProjection} has been created 1212 * by the system. 1213 * 1214 * @hide 1215 */ 1216 public static final @MediaProjectionTokenEvent int MEDIA_PROJECTION_TOKEN_EVENT_CREATED = 0; 1217 1218 /** 1219 * An instance of {@link android.media.projection.IMediaProjection} has been destroyed 1220 * by the system. 1221 * 1222 * @hide 1223 */ 1224 public static final @MediaProjectionTokenEvent int MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED = 1; 1225 1226 /** 1227 * Called after the system created/destroyed a media projection for an app, if the user 1228 * has granted the permission to start a media projection from this app. 1229 * 1230 * <p>This API is specifically for the use case of enforcing the FGS type 1231 * {@code android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION}, 1232 * where the app who is starting this type of FGS must have been granted with the permission 1233 * to start the projection via the {@link android.media.projection.MediaProjection} APIs. 1234 * 1235 * @param uid The uid of the app which the system created/destroyed a media projection for. 1236 * @param projectionToken The {@link android.media.projection.IMediaProjection} token that 1237 * the system created/destroyed. 1238 * @param event The actual event happening to the given {@code projectionToken}. 1239 */ notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, @MediaProjectionTokenEvent int event)1240 public abstract void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, 1241 @MediaProjectionTokenEvent int event); 1242 1243 /** 1244 * @return The stats event for the cached apps high watermark since last pull. 1245 */ 1246 @NonNull 1247 // TODO: restore to android.util.StatsEvent once Ravenwood includes Mainline stubs getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull)1248 public abstract Object getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull); 1249 1250 /** 1251 * Internal method for clearing app data, with the extra param that is used to indicate restore. 1252 * Used by Backup service during restore operation. 1253 * 1254 * @hide 1255 */ clearApplicationUserData(String packageName, boolean keepState, boolean isRestore, IPackageDataObserver observer, int userId)1256 public abstract boolean clearApplicationUserData(String packageName, boolean keepState, 1257 boolean isRestore, IPackageDataObserver observer, int userId); 1258 1259 1260 /** 1261 * Method that checks if system is Headless (don't delay launch) case in which it 1262 * should also check if ThemeOverlayController is ready (don't delay) or not (delay). 1263 * 1264 * @param userId 1265 * @return Boolean indicating if Home launch should wait for ThemeOverlayController signal 1266 * @hide 1267 */ shouldDelayHomeLaunch(int userId)1268 public abstract boolean shouldDelayHomeLaunch(int userId); 1269 1270 /** 1271 * Add a startup timestamp to the most recent start of the specified process. 1272 * 1273 * @param key The {@link ApplicationStartInfo} start timestamp key of the timestamp to add. 1274 * @param timestampNs The clock monotonic timestamp to add in nanoseconds. 1275 * @param uid The UID of the process to add this timestamp to. 1276 * @param pid The process id of the process to add this timestamp to. 1277 * @param userId The userId in the multi-user environment. 1278 */ addStartInfoTimestamp(int key, long timestampNs, int uid, int pid, int userId)1279 public abstract void addStartInfoTimestamp(int key, long timestampNs, int uid, int pid, 1280 int userId); 1281 1282 /** 1283 * It is similar {@link IActivityManager#killApplication(String, int, int, String, int)} but 1284 * it immediately stop the package. 1285 * 1286 * <p>Note: Do not call this method from inside PMS's lock, otherwise it'll run into 1287 * watchdog reset. 1288 * @hide 1289 */ killApplicationSync(String pkgName, int appId, int userId, String reason, int exitInfoReason)1290 public abstract void killApplicationSync(String pkgName, int appId, int userId, 1291 String reason, int exitInfoReason); 1292 } 1293