1 /* 2 * Copyright (C) 2012 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.os; 18 19 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_BADGED_LABEL; 20 import static android.app.admin.DevicePolicyResources.UNDEFINED; 21 22 import android.Manifest; 23 import android.accounts.AccountManager; 24 import android.annotation.ColorInt; 25 import android.annotation.DrawableRes; 26 import android.annotation.IntDef; 27 import android.annotation.NonNull; 28 import android.annotation.Nullable; 29 import android.annotation.RequiresPermission; 30 import android.annotation.StringDef; 31 import android.annotation.SuppressAutoDoc; 32 import android.annotation.SuppressLint; 33 import android.annotation.SystemApi; 34 import android.annotation.SystemService; 35 import android.annotation.TestApi; 36 import android.annotation.UserHandleAware; 37 import android.annotation.UserIdInt; 38 import android.annotation.WorkerThread; 39 import android.app.Activity; 40 import android.app.ActivityManager; 41 import android.app.PropertyInvalidatedCache; 42 import android.app.admin.DevicePolicyManager; 43 import android.app.compat.CompatChanges; 44 import android.compat.annotation.ChangeId; 45 import android.compat.annotation.EnabledSince; 46 import android.compat.annotation.UnsupportedAppUsage; 47 import android.content.ComponentName; 48 import android.content.Context; 49 import android.content.Intent; 50 import android.content.IntentFilter; 51 import android.content.IntentSender; 52 import android.content.pm.UserInfo; 53 import android.content.pm.UserInfo.UserInfoFlag; 54 import android.content.res.Resources; 55 import android.graphics.Bitmap; 56 import android.graphics.BitmapFactory; 57 import android.graphics.Rect; 58 import android.graphics.drawable.Drawable; 59 import android.location.LocationManager; 60 import android.provider.Settings; 61 import android.util.AndroidException; 62 import android.util.ArraySet; 63 import android.util.Log; 64 import android.view.WindowManager.LayoutParams; 65 66 import com.android.internal.R; 67 import com.android.internal.os.RoSystemProperties; 68 import com.android.internal.util.FrameworkStatsLog; 69 70 import java.io.IOException; 71 import java.lang.annotation.Retention; 72 import java.lang.annotation.RetentionPolicy; 73 import java.util.ArrayList; 74 import java.util.List; 75 import java.util.Objects; 76 import java.util.Set; 77 78 /** 79 * Manages users and user details on a multi-user system. There are two major categories of 80 * users: fully customizable users with their own login, and profiles that share a workspace 81 * with a related user. 82 * <p> 83 * Users are different from accounts, which are managed by 84 * {@link AccountManager}. Each user can have their own set of accounts. 85 * <p> 86 * See {@link DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE} for more on managed profiles. 87 */ 88 @SystemService(Context.USER_SERVICE) 89 public class UserManager { 90 91 private static final String TAG = "UserManager"; 92 @UnsupportedAppUsage 93 private final IUserManager mService; 94 /** Holding the Application context (not constructor param context). */ 95 private final Context mContext; 96 97 /** The userId of the constructor param context. To be used instead of mContext.getUserId(). */ 98 private final @UserIdInt int mUserId; 99 100 /** The userType of UserHandle.myUserId(); empty string if not a profile; null until cached. */ 101 private String mProfileTypeOfProcessUser = null; 102 103 /** 104 * User type representing a {@link UserHandle#USER_SYSTEM system} user that is a human user. 105 * This type of user cannot be created; it can only pre-exist on first boot. 106 * @hide 107 */ 108 @SystemApi 109 public static final String USER_TYPE_FULL_SYSTEM = "android.os.usertype.full.SYSTEM"; 110 111 /** 112 * User type representing a regular non-profile non-{@link UserHandle#USER_SYSTEM system} human 113 * user. 114 * This is sometimes called an ordinary 'secondary user'. 115 * @hide 116 */ 117 @SystemApi 118 public static final String USER_TYPE_FULL_SECONDARY = "android.os.usertype.full.SECONDARY"; 119 120 /** 121 * User type representing a guest user that may be transient. 122 * @hide 123 */ 124 @SystemApi 125 public static final String USER_TYPE_FULL_GUEST = "android.os.usertype.full.GUEST"; 126 127 /** 128 * User type representing a user for demo purposes only, which can be removed at any time. 129 * @hide 130 */ 131 public static final String USER_TYPE_FULL_DEMO = "android.os.usertype.full.DEMO"; 132 133 /** 134 * User type representing a "restricted profile" user, which is a full user that is subject to 135 * certain restrictions from a parent user. Note, however, that it is NOT technically a profile. 136 * @hide 137 */ 138 public static final String USER_TYPE_FULL_RESTRICTED = "android.os.usertype.full.RESTRICTED"; 139 140 /** 141 * User type representing a managed profile, which is a profile that is to be managed by a 142 * device policy controller (DPC). 143 * The intended purpose is for work profiles, which are managed by a corporate entity. 144 * @hide 145 */ 146 @SystemApi 147 public static final String USER_TYPE_PROFILE_MANAGED = "android.os.usertype.profile.MANAGED"; 148 149 /** 150 * User type representing a clone profile. Clone profile is a user profile type used to run 151 * second instance of an otherwise single user App (eg, messengers). Only the primary user 152 * is allowed to have a clone profile. 153 * 154 * @hide 155 */ 156 @SystemApi 157 public static final String USER_TYPE_PROFILE_CLONE = "android.os.usertype.profile.CLONE"; 158 159 /** 160 * User type representing a generic profile for testing purposes. Only on debuggable builds. 161 * @hide 162 */ 163 public static final String USER_TYPE_PROFILE_TEST = "android.os.usertype.profile.TEST"; 164 165 /** 166 * User type representing a {@link UserHandle#USER_SYSTEM system} user that is <b>not</b> a 167 * human user. 168 * This type of user cannot be created; it can only pre-exist on first boot. 169 * @hide 170 */ 171 @SystemApi 172 public static final String USER_TYPE_SYSTEM_HEADLESS = "android.os.usertype.system.HEADLESS"; 173 174 /** 175 * Flag passed to {@link #requestQuietModeEnabled} to request disabling quiet mode only if 176 * there is no need to confirm the user credentials. If credentials are required to disable 177 * quiet mode, {@link #requestQuietModeEnabled} will do nothing and return {@code false}. 178 */ 179 public static final int QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED = 0x1; 180 181 /** 182 * Flag passed to {@link #requestQuietModeEnabled} to request disabling quiet mode without 183 * asking for credentials. This is used when managed profile password is forgotten. It starts 184 * the user in locked state so that a direct boot aware DPC could reset the password. 185 * Should not be used together with 186 * {@link #QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED} or an exception will be thrown. 187 * @hide 188 */ 189 public static final int QUIET_MODE_DISABLE_DONT_ASK_CREDENTIAL = 0x2; 190 191 /** 192 * List of flags available for the {@link #requestQuietModeEnabled} method. 193 * @hide 194 */ 195 @Retention(RetentionPolicy.SOURCE) 196 @IntDef(flag = true, prefix = { "QUIET_MODE_" }, value = { 197 QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED, 198 QUIET_MODE_DISABLE_DONT_ASK_CREDENTIAL}) 199 public @interface QuietModeFlag {} 200 201 /** 202 * @hide 203 * No user restriction. 204 */ 205 @SystemApi 206 public static final int RESTRICTION_NOT_SET = 0x0; 207 208 /** 209 * @hide 210 * User restriction set by system/user. 211 */ 212 @SystemApi 213 public static final int RESTRICTION_SOURCE_SYSTEM = 0x1; 214 215 /** 216 * @hide 217 * User restriction set by a device owner. 218 */ 219 @SystemApi 220 public static final int RESTRICTION_SOURCE_DEVICE_OWNER = 0x2; 221 222 /** 223 * @hide 224 * User restriction set by a profile owner. 225 */ 226 @SystemApi 227 public static final int RESTRICTION_SOURCE_PROFILE_OWNER = 0x4; 228 229 /** @hide */ 230 @Retention(RetentionPolicy.SOURCE) 231 @IntDef(flag = true, prefix = { "RESTRICTION_" }, value = { 232 RESTRICTION_NOT_SET, 233 RESTRICTION_SOURCE_SYSTEM, 234 RESTRICTION_SOURCE_DEVICE_OWNER, 235 RESTRICTION_SOURCE_PROFILE_OWNER 236 }) 237 @SystemApi 238 public @interface UserRestrictionSource {} 239 240 /** 241 * Specifies if a user is disallowed from adding and removing accounts, unless they are 242 * {@link android.accounts.AccountManager#addAccountExplicitly programmatically} added by 243 * Authenticator. 244 * The default value is <code>false</code>. 245 * 246 * <p>From {@link android.os.Build.VERSION_CODES#N} a profile or device owner app can still 247 * use {@link android.accounts.AccountManager} APIs to add or remove accounts when account 248 * management is disallowed. 249 * 250 * <p>Key for user restrictions. 251 * <p>Type: Boolean 252 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 253 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 254 * @see #getUserRestrictions() 255 */ 256 public static final String DISALLOW_MODIFY_ACCOUNTS = "no_modify_accounts"; 257 258 /** 259 * Specifies if a user is disallowed from changing Wi-Fi access points via Settings. This 260 * restriction does not affect Wi-Fi tethering settings. 261 * 262 * <p>A device owner and a profile owner can set this restriction, although the restriction has 263 * no effect in a managed profile. When it is set by a device owner, a profile owner on the 264 * primary user or by a profile owner of an organization-owned managed profile on the parent 265 * profile, it disallows the primary user from changing Wi-Fi access points. 266 * 267 * <p>The default value is <code>false</code>. 268 * 269 * <p>Key for user restrictions. 270 * <p>Type: Boolean 271 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 272 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 273 * @see #getUserRestrictions() 274 */ 275 public static final String DISALLOW_CONFIG_WIFI = "no_config_wifi"; 276 277 /** 278 * Specifies if a user is disallowed from enabling/disabling Wi-Fi. 279 * 280 * <p>This restriction can only be set by a device owner, 281 * a profile owner of an organization-owned managed profile on the parent profile. 282 * When it is set by any of these owners, it applies globally - i.e., it disables airplane mode 283 * from changing Wi-Fi state. 284 * 285 * <p>The default value is <code>false</code>. 286 * 287 * <p>Key for user restrictions. 288 * <p>Type: Boolean 289 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 290 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 291 * @see #getUserRestrictions() 292 */ 293 public static final String DISALLOW_CHANGE_WIFI_STATE = "no_change_wifi_state"; 294 295 /** 296 * Specifies if a user is disallowed from using Wi-Fi tethering. 297 * 298 * <p>This restriction does not limit the user's ability to modify or connect to regular 299 * Wi-Fi networks, which is separately controlled by {@link #DISALLOW_CONFIG_WIFI}. 300 * 301 * <p>This restriction can only be set by a device owner, 302 * a profile owner of an organization-owned managed profile on the parent profile. 303 * When it is set by any of these owners, it prevents all users from using 304 * Wi-Fi tethering. Other forms of tethering are not affected. 305 * 306 * This user restriction disables only Wi-Fi tethering. 307 * Use {@link #DISALLOW_CONFIG_TETHERING} to limit all forms of tethering. 308 * When {@link #DISALLOW_CONFIG_TETHERING} is set, this user restriction becomes obsolete. 309 * 310 * <p>The default value is <code>false</code>. 311 * 312 * <p>Key for user restrictions. 313 * <p>Type: Boolean 314 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 315 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 316 * @see #getUserRestrictions() 317 */ 318 public static final String DISALLOW_WIFI_TETHERING = "no_wifi_tethering"; 319 320 /** 321 * Specifies if users are disallowed from sharing Wi-Fi for admin configured networks. 322 * 323 * <p>Device owner and profile owner can set this restriction. 324 * When it is set by any of these owners, it prevents all users from 325 * sharing Wi-Fi for networks configured by these owners. 326 * Other networks not configured by these owners are not affected. 327 * 328 * <p>The default value is <code>false</code>. 329 * 330 * <p>Key for user restrictions. 331 * <p>Type: Boolean 332 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 333 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 334 * @see #getUserRestrictions() 335 */ 336 public static final String DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI = 337 "no_sharing_admin_configured_wifi"; 338 339 /** 340 * Specifies if a user is disallowed from using Wi-Fi Direct. 341 * 342 * <p>This restriction can only be set by a device owner, 343 * a profile owner of an organization-owned managed profile on the parent profile. 344 * When it is set by any of these owners, it prevents all users from using 345 * Wi-Fi Direct. 346 * 347 * <p>The default value is <code>false</code>. 348 * 349 * <p>Key for user restrictions. 350 * <p>Type: Boolean 351 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 352 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 353 * @see #getUserRestrictions() 354 */ 355 public static final String DISALLOW_WIFI_DIRECT = "no_wifi_direct"; 356 357 /** 358 * Specifies if a user is disallowed from adding a new Wi-Fi configuration. 359 * 360 * <p>This restriction can only be set by a device owner, 361 * a profile owner of an organization-owned managed profile on the parent profile. 362 * When it is set by any of these owners, it prevents all users from adding 363 * a new Wi-Fi configuration. This does not limit the owner and carrier's ability 364 * to add a new configuration. 365 * 366 * <p>The default value is <code>false</code>. 367 * 368 * <p>Key for user restrictions. 369 * <p>Type: Boolean 370 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 371 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 372 * @see #getUserRestrictions() 373 */ 374 public static final String DISALLOW_ADD_WIFI_CONFIG = "no_add_wifi_config"; 375 376 /** 377 * Specifies if a user is disallowed from changing the device 378 * language. The default value is <code>false</code>. 379 * 380 * <p>Key for user restrictions. 381 * <p>Type: Boolean 382 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 383 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 384 * @see #getUserRestrictions() 385 */ 386 public static final String DISALLOW_CONFIG_LOCALE = "no_config_locale"; 387 388 /** 389 * Specifies if a user is disallowed from installing applications. This user restriction also 390 * prevents device owners and profile owners installing apps. The default value is 391 * {@code false}. 392 * 393 * <p>Key for user restrictions. 394 * <p>Type: Boolean 395 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 396 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 397 * @see #getUserRestrictions() 398 */ 399 public static final String DISALLOW_INSTALL_APPS = "no_install_apps"; 400 401 /** 402 * Specifies if a user is disallowed from uninstalling applications. 403 * The default value is <code>false</code>. 404 * 405 * <p>Key for user restrictions. 406 * <p>Type: Boolean 407 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 408 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 409 * @see #getUserRestrictions() 410 */ 411 public static final String DISALLOW_UNINSTALL_APPS = "no_uninstall_apps"; 412 413 /** 414 * Specifies if a user is disallowed from turning on location sharing. 415 * 416 * <p>In a managed profile, location sharing by default reflects the primary user's setting, but 417 * can be overridden and forced off by setting this restriction to true in the managed profile. 418 * 419 * <p>A device owner and a profile owner can set this restriction. When it is set by a device 420 * owner, a profile owner on the primary user or by a profile owner of an organization-owned 421 * managed profile on the parent profile, it prevents the primary user from turning on 422 * location sharing. 423 * 424 * <p>The default value is <code>false</code>. 425 * 426 * <p>Key for user restrictions. 427 * <p>Type: Boolean 428 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 429 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 430 * @see #getUserRestrictions() 431 */ 432 public static final String DISALLOW_SHARE_LOCATION = "no_share_location"; 433 434 /** 435 * Specifies if airplane mode is disallowed on the device. 436 * 437 * <p>This restriction can only be set by a device owner, a profile owner on the primary 438 * user or a profile owner of an organization-owned managed profile on the parent profile. 439 * When it is set by any of these owners, it applies globally - i.e., it disables airplane mode 440 * on the entire device. 441 * 442 * <p>The default value is <code>false</code>. 443 * 444 * <p>Key for user restrictions. 445 * <p>Type: Boolean 446 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 447 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 448 * @see #getUserRestrictions() 449 */ 450 public static final String DISALLOW_AIRPLANE_MODE = "no_airplane_mode"; 451 452 /** 453 * Specifies if a user is disallowed from configuring brightness. When device owner sets it, 454 * it'll only be applied on the target(system) user. 455 * 456 * <p>The default value is <code>false</code>. 457 * 458 * <p>This user restriction has no effect on managed profiles. 459 * <p>Key for user restrictions. 460 * <p>Type: Boolean 461 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 462 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 463 * @see #getUserRestrictions() 464 */ 465 public static final String DISALLOW_CONFIG_BRIGHTNESS = "no_config_brightness"; 466 467 /** 468 * Specifies if ambient display is disallowed for the user. 469 * 470 * <p>The default value is <code>false</code>. 471 * 472 * <p>This user restriction has no effect on managed profiles. 473 * <p>Key for user restrictions. 474 * <p>Type: Boolean 475 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 476 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 477 * @see #getUserRestrictions() 478 */ 479 public static final String DISALLOW_AMBIENT_DISPLAY = "no_ambient_display"; 480 481 /** 482 * Specifies if a user is disallowed from changing screen off timeout. 483 * 484 * <p>The default value is <code>false</code>. 485 * 486 * <p>This user restriction has no effect on managed profiles. 487 * <p>Key for user restrictions. 488 * <p>Type: Boolean 489 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 490 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 491 * @see #getUserRestrictions() 492 */ 493 public static final String DISALLOW_CONFIG_SCREEN_TIMEOUT = "no_config_screen_timeout"; 494 495 /** 496 * Specifies if a user is disallowed from enabling the 497 * "Unknown Sources" setting, that allows installation of apps from unknown sources. 498 * Unknown sources exclude adb and special apps such as trusted app stores. 499 * The default value is <code>false</code>. 500 * 501 * <p>Key for user restrictions. 502 * <p>Type: Boolean 503 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 504 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 505 * @see #getUserRestrictions() 506 */ 507 public static final String DISALLOW_INSTALL_UNKNOWN_SOURCES = "no_install_unknown_sources"; 508 509 /** 510 * This restriction is a device-wide version of {@link #DISALLOW_INSTALL_UNKNOWN_SOURCES}. 511 * 512 * Specifies if all users on the device are disallowed from enabling the 513 * "Unknown Sources" setting, that allows installation of apps from unknown sources. 514 * 515 * This restriction can be enabled by the profile owner, in which case all accounts and 516 * profiles will be affected. 517 * 518 * The default value is <code>false</code>. 519 * 520 * <p>Key for user restrictions. 521 * <p>Type: Boolean 522 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 523 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 524 * @see #getUserRestrictions() 525 */ 526 public static final String DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY = 527 "no_install_unknown_sources_globally"; 528 529 /** 530 * Specifies if a user is disallowed from configuring bluetooth via Settings. This does 531 * <em>not</em> restrict the user from turning bluetooth on or off. 532 * 533 * <p>This restriction doesn't prevent the user from using bluetooth. For disallowing usage of 534 * bluetooth completely on the device, use {@link #DISALLOW_BLUETOOTH}. 535 * 536 * <p>A device owner and a profile owner can set this restriction, although the restriction has 537 * no effect in a managed profile. When it is set by a device owner, a profile owner on the 538 * primary user or by a profile owner of an organization-owned managed profile on the parent 539 * profile, it disallows the primary user from configuring bluetooth. 540 * 541 * <p>The default value is <code>false</code>. 542 * 543 * <p>Key for user restrictions. 544 * <p>Type: Boolean 545 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 546 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 547 * @see #getUserRestrictions() 548 */ 549 public static final String DISALLOW_CONFIG_BLUETOOTH = "no_config_bluetooth"; 550 551 /** 552 * Specifies if bluetooth is disallowed on the device. If bluetooth is disallowed on the device, 553 * bluetooth cannot be turned on or configured via Settings. 554 * 555 * <p>This restriction can only be set by a device owner, a profile owner on the primary 556 * user or a profile owner of an organization-owned managed profile on the parent profile. 557 * When it is set by a device owner, it applies globally - i.e., it disables bluetooth on 558 * the entire device and all users will be affected. When it is set by a profile owner on the 559 * primary user or by a profile owner of an organization-owned managed profile on the parent 560 * profile, it disables the primary user from using bluetooth and configuring bluetooth 561 * in Settings. 562 * 563 * <p>The default value is <code>false</code>. 564 * 565 * <p>Key for user restrictions. 566 * <p>Type: Boolean 567 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 568 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 569 * @see #getUserRestrictions() 570 */ 571 public static final String DISALLOW_BLUETOOTH = "no_bluetooth"; 572 573 /** 574 * Specifies if outgoing bluetooth sharing is disallowed. 575 * 576 * <p>A device owner and a profile owner can set this restriction. When it is set by a device 577 * owner, it applies globally. When it is set by a profile owner on the primary user or by a 578 * profile owner of an organization-owned managed profile on the parent profile, it disables 579 * the primary user from any outgoing bluetooth sharing. 580 * 581 * <p>Default is <code>true</code> for managed profiles and false otherwise. 582 * 583 * <p>When a device upgrades to {@link android.os.Build.VERSION_CODES#O}, the system sets it 584 * for all existing managed profiles. 585 * 586 * <p>Key for user restrictions. 587 * <p>Type: Boolean 588 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 589 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 590 * @see #getUserRestrictions() 591 */ 592 public static final String DISALLOW_BLUETOOTH_SHARING = "no_bluetooth_sharing"; 593 594 /** 595 * Specifies if a user is disallowed from transferring files over USB. 596 * 597 * <p>This restriction can only be set by a <a href="https://developers.google.com/android/work/terminology#device_owner_do"> 598 * device owner</a> or a <a href="https://developers.google.com/android/work/terminology#profile_owner_po"> 599 * profile owner</a> on the primary user's profile or a profile owner of an organization-owned 600 * <a href="https://developers.google.com/android/work/terminology#managed_profile"> 601 * managed profile</a> on the parent profile. 602 * When it is set by a device owner, it applies globally. When it is set by a profile owner 603 * on the primary user or by a profile owner of an organization-owned managed profile on 604 * the parent profile, it disables the primary user from transferring files over USB. No other 605 * user on the device is able to use file transfer over USB because the UI for file transfer 606 * is always associated with the primary user. 607 * 608 * <p>The default value is <code>false</code>. 609 * 610 * <p>Key for user restrictions. 611 * <p>Type: Boolean 612 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 613 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 614 * @see #getUserRestrictions() 615 */ 616 public static final String DISALLOW_USB_FILE_TRANSFER = "no_usb_file_transfer"; 617 618 /** 619 * Specifies if a user is disallowed from configuring user 620 * credentials. The default value is <code>false</code>. 621 * 622 * <p>Key for user restrictions. 623 * <p>Type: Boolean 624 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 625 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 626 * @see #getUserRestrictions() 627 */ 628 public static final String DISALLOW_CONFIG_CREDENTIALS = "no_config_credentials"; 629 630 /** 631 * When set on the admin user this specifies if the user can remove users. 632 * When set on a non-admin secondary user, this specifies if the user can remove itself. 633 * This restriction has no effect on managed profiles. 634 * The default value is <code>false</code>. 635 * 636 * <p>Key for user restrictions. 637 * <p>Type: Boolean 638 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 639 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 640 * @see #getUserRestrictions() 641 */ 642 public static final String DISALLOW_REMOVE_USER = "no_remove_user"; 643 644 /** 645 * Specifies if managed profiles of this user can be removed, other than by its profile owner. 646 * The default value is <code>false</code>. 647 * <p> 648 * This restriction has no effect on managed profiles. 649 * 650 * <p>Key for user restrictions. 651 * <p>Type: Boolean 652 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 653 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 654 * @see #getUserRestrictions() 655 * @deprecated As the ability to have a managed profile on a fully-managed device has been 656 * removed from the platform, this restriction will be silently ignored when applied by the 657 * device owner. 658 * When the device is provisioned with a managed profile on an organization-owned device, 659 * the managed profile could not be removed anyway. 660 */ 661 @Deprecated 662 public static final String DISALLOW_REMOVE_MANAGED_PROFILE = "no_remove_managed_profile"; 663 664 /** 665 * Specifies if a user is disallowed from enabling or accessing debugging features. 666 * 667 * <p>A device owner and a profile owner can set this restriction. When it is set by a device 668 * owner, a profile owner on the primary user or by a profile owner of an organization-owned 669 * managed profile on the parent profile, it disables debugging features altogether, including 670 * USB debugging. When set on a managed profile or a secondary user, it blocks debugging for 671 * that user only, including starting activities, making service calls, accessing content 672 * providers, sending broadcasts, installing/uninstalling packages, clearing user data, etc. 673 * 674 * <p>The default value is <code>false</code>. 675 * 676 * <p>Key for user restrictions. 677 * <p>Type: Boolean 678 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 679 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 680 * @see #getUserRestrictions() 681 */ 682 public static final String DISALLOW_DEBUGGING_FEATURES = "no_debugging_features"; 683 684 /** 685 * Specifies if a user is disallowed from configuring a VPN. The default value is 686 * <code>false</code>. This restriction has an effect when set by device owners and, in Android 687 * 6.0 ({@linkplain android.os.Build.VERSION_CODES#M API level 23}) or higher, profile owners. 688 * <p>This restriction also prevents VPNs from starting. However, in Android 7.0 689 * ({@linkplain android.os.Build.VERSION_CODES#N API level 24}) or higher, the system does 690 * start always-on VPNs created by the device or profile owner. 691 * <p>From Android 12 ({@linkplain android.os.Build.VERSION_CODES#S API level 31}) enforcing 692 * this restriction clears currently active VPN if it was configured by the user. 693 * 694 * <p>Key for user restrictions. 695 * <p>Type: Boolean 696 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 697 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 698 * @see #getUserRestrictions() 699 */ 700 public static final String DISALLOW_CONFIG_VPN = "no_config_vpn"; 701 702 /** 703 * Specifies if a user is disallowed from enabling or disabling location providers. As a 704 * result, user is disallowed from turning on or off location via Settings. 705 * 706 * <p>A device owner and a profile owner can set this restriction. When it is set by a device 707 * owner, a profile owner on the primary user or by a profile owner of an organization-owned 708 * managed profile on the parent profile, it disallows the primary user from turning location 709 * on or off. 710 * 711 * <p>The default value is <code>false</code>. 712 * 713 * <p>This user restriction is different from {@link #DISALLOW_SHARE_LOCATION}, 714 * as a device owner or a profile owner can still enable or disable location mode via 715 * {@link DevicePolicyManager#setLocationEnabled} when this restriction is on. 716 * 717 * <p>Key for user restrictions. 718 * <p>Type: Boolean 719 * @see LocationManager#isLocationEnabled() 720 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 721 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 722 * @see #getUserRestrictions() 723 */ 724 public static final String DISALLOW_CONFIG_LOCATION = "no_config_location"; 725 726 /** 727 * Specifies configuring date, time and timezone is disallowed via Settings. 728 * 729 * <p>A device owner and a profile owner can set this restriction, although the restriction has 730 * no effect in a managed profile. When it is set by a device owner or by a profile owner of an 731 * organization-owned managed profile on the parent profile, it applies globally - i.e., 732 * it disables date, time and timezone setting on the entire device and all users are affected. 733 * When it is set by a profile owner on the primary user, it disables the primary user 734 * from configuring date, time and timezone and disables all configuring of date, time and 735 * timezone in Settings. 736 * 737 * <p>The default value is <code>false</code>. 738 * 739 * <p>Key for user restrictions. 740 * <p>Type: Boolean 741 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 742 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 743 * @see #getUserRestrictions() 744 */ 745 public static final String DISALLOW_CONFIG_DATE_TIME = "no_config_date_time"; 746 747 /** 748 * Specifies if a user is disallowed from using and configuring Tethering and portable hotspots 749 * via Settings. 750 * 751 * <p>This restriction can only be set by a device owner, a profile owner on the primary 752 * user or a profile owner of an organization-owned managed profile on the parent profile. 753 * When it is set by a device owner, it applies globally. When it is set by a profile owner 754 * on the primary user or by a profile owner of an organization-owned managed profile on 755 * the parent profile, it disables the primary user from using Tethering and hotspots and 756 * disables all configuring of Tethering and hotspots in Settings. 757 * 758 * <p>The default value is <code>false</code>. 759 * 760 * <p>In Android 9.0 or higher, if tethering is enabled when this restriction is set, 761 * tethering will be automatically turned off. 762 * 763 * <p>Key for user restrictions. 764 * <p>Type: Boolean 765 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 766 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 767 * @see #getUserRestrictions() 768 */ 769 public static final String DISALLOW_CONFIG_TETHERING = "no_config_tethering"; 770 771 /** 772 * Specifies if a user is disallowed from resetting network settings 773 * from Settings. This can only be set by device owners and profile owners on the primary user. 774 * The default value is <code>false</code>. 775 * <p>This restriction has no effect on secondary users and managed profiles since only the 776 * primary user can reset the network settings of the device. 777 * 778 * <p>Key for user restrictions. 779 * <p>Type: Boolean 780 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 781 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 782 * @see #getUserRestrictions() 783 */ 784 public static final String DISALLOW_NETWORK_RESET = "no_network_reset"; 785 786 /** 787 * Specifies if a user is disallowed from factory resetting from Settings. 788 * This can only be set by device owners and profile owners on an admin user. 789 * The default value is <code>false</code>. 790 * <p>This restriction has no effect on non-admin users since they cannot factory reset the 791 * device. 792 * 793 * <p>Key for user restrictions. 794 * <p>Type: Boolean 795 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 796 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 797 * @see #getUserRestrictions() 798 */ 799 public static final String DISALLOW_FACTORY_RESET = "no_factory_reset"; 800 801 /** 802 * Specifies if a user is disallowed from adding new users. This can only be set by device 803 * owners or profile owners on the primary user. The default value is <code>false</code>. 804 * <p>This restriction has no effect on secondary users and managed profiles since only the 805 * primary user can add other users. 806 * <p> When the device is an organization-owned device provisioned with a managed profile, 807 * this restriction will be set as a base restriction which cannot be removed by any admin. 808 * 809 * <p>Key for user restrictions. 810 * <p>Type: Boolean 811 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 812 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 813 * @see #getUserRestrictions() 814 */ 815 public static final String DISALLOW_ADD_USER = "no_add_user"; 816 817 /** 818 * Specifies if a user is disallowed from adding managed profiles. 819 * <p>The default value for an unmanaged user is <code>false</code>. 820 * For users with a device owner set, the default is <code>true</code>. 821 * <p>This restriction has no effect on managed profiles. 822 * 823 * <p>Key for user restrictions. 824 * <p>Type: Boolean 825 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 826 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 827 * @see #getUserRestrictions() 828 * @deprecated As the ability to have a managed profile on a fully-managed device has been 829 * removed from the platform, this restriction will be silently ignored when applied by the 830 * device owner. 831 */ 832 @Deprecated 833 public static final String DISALLOW_ADD_MANAGED_PROFILE = "no_add_managed_profile"; 834 835 /** 836 * Specifies if a user is disallowed from creating clone profile. 837 * <p>The default value for an unmanaged user is <code>false</code>. 838 * For users with a device owner set, the default is <code>true</code>. 839 * 840 * <p>Key for user restrictions. 841 * <p>Type: Boolean 842 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 843 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 844 * @see #getUserRestrictions() 845 * @hide 846 */ 847 public static final String DISALLOW_ADD_CLONE_PROFILE = "no_add_clone_profile"; 848 849 /** 850 * Specifies if a user is disallowed from disabling application verification. The default 851 * value is <code>false</code>. 852 * 853 * <p>In Android 8.0 ({@linkplain android.os.Build.VERSION_CODES#O API level 26}) and higher, 854 * this is a global user restriction. If a device owner or profile owner sets this restriction, 855 * the system enforces app verification across all users on the device. Running in earlier 856 * Android versions, this restriction affects only the profile that sets it. 857 * 858 * <p>Key for user restrictions. 859 * <p>Type: Boolean 860 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 861 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 862 * @see #getUserRestrictions() 863 */ 864 public static final String ENSURE_VERIFY_APPS = "ensure_verify_apps"; 865 866 /** 867 * Specifies if a user is disallowed from configuring cell broadcasts. 868 * 869 * <p>This restriction can only be set by a device owner, a profile owner on the primary 870 * user or a profile owner of an organization-owned managed profile on the parent profile. 871 * When it is set by a device owner, it applies globally. When it is set by a profile owner 872 * on the primary user or by a profile owner of an organization-owned managed profile on 873 * the parent profile, it disables the primary user from configuring cell broadcasts. 874 * 875 * <p>The default value is <code>false</code>. 876 * 877 * <p>This restriction has no effect on secondary users and managed profiles since only the 878 * primary user can configure cell broadcasts. 879 * 880 * <p>Key for user restrictions. 881 * <p>Type: Boolean 882 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 883 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 884 * @see #getUserRestrictions() 885 */ 886 public static final String DISALLOW_CONFIG_CELL_BROADCASTS = "no_config_cell_broadcasts"; 887 888 /** 889 * Specifies if a user is disallowed from configuring mobile networks. 890 * 891 * <p>This restriction can only be set by a device owner, a profile owner on the primary 892 * user or a profile owner of an organization-owned managed profile on the parent profile. 893 * When it is set by a device owner, it applies globally. When it is set by a profile owner 894 * on the primary user or by a profile owner of an organization-owned managed profile on 895 * the parent profile, it disables the primary user from configuring mobile networks. 896 * 897 * <p>The default value is <code>false</code>. 898 * 899 * <p>This restriction has no effect on secondary users and managed profiles since only the 900 * primary user can configure mobile networks. 901 * 902 * <p>Key for user restrictions. 903 * <p>Type: Boolean 904 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 905 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 906 * @see #getUserRestrictions() 907 */ 908 public static final String DISALLOW_CONFIG_MOBILE_NETWORKS = "no_config_mobile_networks"; 909 910 /** 911 * Specifies if a user is disallowed from modifying 912 * applications in Settings or launchers. The following actions will not be allowed when this 913 * restriction is enabled: 914 * <li>uninstalling apps</li> 915 * <li>disabling apps</li> 916 * <li>clearing app caches</li> 917 * <li>clearing app data</li> 918 * <li>force stopping apps</li> 919 * <li>clearing app defaults</li> 920 * <p> 921 * The default value is <code>false</code>. 922 * 923 * <p><strong>Note:</strong> The user will still be able to perform those actions via other 924 * means (such as adb). Third party apps will also be able to uninstall apps via the 925 * {@link android.content.pm.PackageInstaller}. {@link #DISALLOW_UNINSTALL_APPS} or 926 * {@link DevicePolicyManager#setUninstallBlocked(ComponentName, String, boolean)} should be 927 * used to prevent the user from uninstalling apps completely, and 928 * {@link DevicePolicyManager#addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)} 929 * to add a default intent handler for a given intent filter. 930 * 931 * <p>Key for user restrictions. 932 * <p>Type: Boolean 933 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 934 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 935 * @see #getUserRestrictions() 936 */ 937 public static final String DISALLOW_APPS_CONTROL = "no_control_apps"; 938 939 /** 940 * Specifies if a user is disallowed from mounting physical external media. 941 * 942 * <p>This restriction can only be set by a device owner, a profile owner on the primary 943 * user or a profile owner of an organization-owned managed profile on the parent profile. 944 * When it is set by a device owner, it applies globally. When it is set by a profile owner 945 * on the primary user or by a profile owner of an organization-owned managed profile on 946 * the parent profile, it disables the primary user from mounting physical external media. 947 * 948 * <p>The default value is <code>false</code>. 949 * 950 * <p>Key for user restrictions. 951 * <p>Type: Boolean 952 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 953 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 954 * @see #getUserRestrictions() 955 */ 956 public static final String DISALLOW_MOUNT_PHYSICAL_MEDIA = "no_physical_media"; 957 958 /** 959 * Specifies if a user is disallowed from adjusting microphone volume. If set, the microphone 960 * will be muted. 961 * 962 * <p>A device owner and a profile owner can set this restriction, although the restriction has 963 * no effect in a managed profile. When it is set by a device owner, it applies globally. When 964 * it is set by a profile owner on the primary user or by a profile owner of an 965 * organization-owned managed profile on the parent profile, it will disallow the primary user 966 * from adjusting the microphone volume. 967 * 968 * <p>The default value is <code>false</code>. 969 * 970 * <p>Key for user restrictions. 971 * <p>Type: Boolean 972 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 973 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 974 * @see #getUserRestrictions() 975 */ 976 public static final String DISALLOW_UNMUTE_MICROPHONE = "no_unmute_microphone"; 977 978 /** 979 * Specifies if a user is disallowed from adjusting the global volume. If set, the global volume 980 * will be muted. This can be set by device owners from API 21 and profile owners from API 24. 981 * The default value is <code>false</code>. 982 * 983 * <p>When the restriction is set by profile owners, then it only applies to relevant 984 * profiles. 985 * 986 * <p>This restriction has no effect on managed profiles. 987 * <p>Key for user restrictions. 988 * <p>Type: Boolean 989 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 990 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 991 * @see #getUserRestrictions() 992 */ 993 public static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume"; 994 995 /** 996 * Specifies that the user is not allowed to make outgoing phone calls. Emergency calls are 997 * still permitted. 998 * 999 * <p>A device owner and a profile owner can set this restriction, although the restriction has 1000 * no effect in a managed profile. When it is set by a device owner, a profile owner on the 1001 * primary user or by a profile owner of an organization-owned managed profile on the parent 1002 * profile, it disallows the primary user from making outgoing phone calls. 1003 * 1004 * <p>The default value is <code>false</code>. 1005 * 1006 * <p>Key for user restrictions. 1007 * <p>Type: Boolean 1008 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1009 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1010 * @see #getUserRestrictions() 1011 */ 1012 public static final String DISALLOW_OUTGOING_CALLS = "no_outgoing_calls"; 1013 1014 /** 1015 * Specifies that the user is not allowed to send or receive SMS messages. 1016 * 1017 * <p>This restriction can only be set by a device owner, a profile owner on the primary 1018 * user or a profile owner of an organization-owned managed profile on the parent profile. 1019 * When it is set by a device owner, it applies globally. When it is set by a profile owner 1020 * on the primary user or by a profile owner of an organization-owned managed profile on 1021 * the parent profile, it disables the primary user from sending or receiving SMS messages. 1022 * 1023 * <p>The default value is <code>false</code>. 1024 * 1025 * <p>Key for user restrictions. 1026 * <p>Type: Boolean 1027 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1028 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1029 * @see #getUserRestrictions() 1030 */ 1031 public static final String DISALLOW_SMS = "no_sms"; 1032 1033 /** 1034 * Specifies if the user is not allowed to have fun. In some cases, the 1035 * device owner may wish to prevent the user from experiencing amusement or 1036 * joy while using the device. The default value is <code>false</code>. 1037 * 1038 * <p>Key for user restrictions. 1039 * <p>Type: Boolean 1040 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1041 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1042 * @see #getUserRestrictions() 1043 */ 1044 public static final String DISALLOW_FUN = "no_fun"; 1045 1046 /** 1047 * Specifies that windows besides app windows should not be 1048 * created. This will block the creation of the following types of windows. 1049 * <li>{@link LayoutParams#TYPE_TOAST}</li> 1050 * <li>{@link LayoutParams#TYPE_PHONE}</li> 1051 * <li>{@link LayoutParams#TYPE_PRIORITY_PHONE}</li> 1052 * <li>{@link LayoutParams#TYPE_SYSTEM_ALERT}</li> 1053 * <li>{@link LayoutParams#TYPE_SYSTEM_ERROR}</li> 1054 * <li>{@link LayoutParams#TYPE_SYSTEM_OVERLAY}</li> 1055 * <li>{@link LayoutParams#TYPE_APPLICATION_OVERLAY}</li> 1056 * 1057 * <p>This can only be set by device owners and profile owners on the primary user. 1058 * The default value is <code>false</code>. 1059 * 1060 * <p>Key for user restrictions. 1061 * <p>Type: Boolean 1062 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1063 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1064 * @see #getUserRestrictions() 1065 */ 1066 public static final String DISALLOW_CREATE_WINDOWS = "no_create_windows"; 1067 1068 /** 1069 * Specifies that system error dialogs for crashed or unresponsive apps should not be shown. 1070 * In this case, the system will force-stop the app as if the user chooses the "close app" 1071 * option on the UI. A feedback report isn't collected as there is no way for the user to 1072 * provide explicit consent. The default value is <code>false</code>. 1073 * 1074 * <p>When this user restriction is set by device owners, it's applied to all users. When set by 1075 * the profile owner of the primary user or a secondary user, the restriction affects only the 1076 * calling user. This user restriction has no effect on managed profiles. 1077 * 1078 * <p>Key for user restrictions. 1079 * <p>Type: Boolean 1080 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1081 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1082 * @see #getUserRestrictions() 1083 */ 1084 public static final String DISALLOW_SYSTEM_ERROR_DIALOGS = "no_system_error_dialogs"; 1085 1086 /** 1087 * Specifies if the clipboard contents can be exported by pasting the data into other users or 1088 * profiles. This restriction doesn't prevent import, such as someone pasting clipboard data 1089 * from other profiles or users. The default value is {@code false}. 1090 * 1091 * <p><strong>Note</strong>: Because it's possible to extract data from screenshots using 1092 * optical character recognition (OCR), we strongly recommend combining this user restriction 1093 * with {@link DevicePolicyManager#setScreenCaptureDisabled(ComponentName, boolean)}. 1094 * 1095 * <p>Key for user restrictions. 1096 * <p>Type: Boolean 1097 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1098 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1099 * @see #getUserRestrictions() 1100 */ 1101 public static final String DISALLOW_CROSS_PROFILE_COPY_PASTE = "no_cross_profile_copy_paste"; 1102 1103 /** 1104 * Specifies if the user is not allowed to use NFC to beam out data from apps. 1105 * The default value is <code>false</code>. 1106 * 1107 * <p>Key for user restrictions. 1108 * <p>Type: Boolean 1109 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1110 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1111 * @see #getUserRestrictions() 1112 */ 1113 public static final String DISALLOW_OUTGOING_BEAM = "no_outgoing_beam"; 1114 1115 /** 1116 * Hidden user restriction to disallow access to wallpaper manager APIs. This restriction 1117 * generally means that wallpapers are not supported for the particular user. This user 1118 * restriction is always set for managed profiles, because such profiles don't have wallpapers. 1119 * @hide 1120 * @see #DISALLOW_SET_WALLPAPER 1121 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1122 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1123 * @see #getUserRestrictions() 1124 */ 1125 public static final String DISALLOW_WALLPAPER = "no_wallpaper"; 1126 1127 /** 1128 * User restriction to disallow setting a wallpaper. Profile owner and device owner 1129 * are able to set wallpaper regardless of this restriction. 1130 * The default value is <code>false</code>. 1131 * 1132 * <p>Key for user restrictions. 1133 * <p>Type: Boolean 1134 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1135 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1136 * @see #getUserRestrictions() 1137 */ 1138 public static final String DISALLOW_SET_WALLPAPER = "no_set_wallpaper"; 1139 1140 /** 1141 * Specifies if the user is not allowed to reboot the device into safe boot mode. 1142 * 1143 * <p>This restriction can only be set by a device owner, a profile owner on the primary 1144 * user or a profile owner of an organization-owned managed profile on the parent profile. 1145 * When it is set by a device owner, it applies globally. When it is set by a profile owner 1146 * on the primary user or by a profile owner of an organization-owned managed profile on 1147 * the parent profile, it disables the primary user from rebooting the device into safe 1148 * boot mode. 1149 * 1150 * <p>The default value is <code>false</code>. 1151 * 1152 * <p>Key for user restrictions. 1153 * <p>Type: Boolean 1154 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1155 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1156 * @see #getUserRestrictions() 1157 */ 1158 public static final String DISALLOW_SAFE_BOOT = "no_safe_boot"; 1159 1160 /** 1161 * Specifies if a user is not allowed to record audio. This restriction is always enabled for 1162 * background users. The default value is <code>false</code>. 1163 * 1164 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1165 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1166 * @see #getUserRestrictions() 1167 * @hide 1168 */ 1169 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1170 public static final String DISALLOW_RECORD_AUDIO = "no_record_audio"; 1171 1172 /** 1173 * Specifies if a user is not allowed to run in the background and should be stopped during 1174 * user switch. The default value is <code>false</code>. 1175 * 1176 * <p>This restriction can be set by device owners and profile owners. 1177 * 1178 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1179 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1180 * @see #getUserRestrictions() 1181 * @hide 1182 */ 1183 @SystemApi 1184 public static final String DISALLOW_RUN_IN_BACKGROUND = "no_run_in_background"; 1185 1186 /** 1187 * Specifies if a user is not allowed to use the camera. 1188 * 1189 * <p>A device owner and a profile owner can set this restriction. When it is set by a 1190 * device owner, it applies globally - i.e., it disables the use of camera on the entire device 1191 * and all users are affected. When it is set by a profile owner on the primary user or by a 1192 * profile owner of an organization-owned managed profile on the parent profile, it disables 1193 * the primary user from using camera. 1194 * 1195 * <p>The default value is <code>false</code>. 1196 * 1197 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1198 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1199 * @see #getUserRestrictions() 1200 * @hide 1201 */ 1202 public static final String DISALLOW_CAMERA = "no_camera"; 1203 1204 /** 1205 * Specifies if a user is not allowed to unmute the device's global volume. 1206 * 1207 * @see DevicePolicyManager#setMasterVolumeMuted(ComponentName, boolean) 1208 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1209 * @see #getUserRestrictions() 1210 * @hide 1211 */ 1212 public static final String DISALLOW_UNMUTE_DEVICE = "disallow_unmute_device"; 1213 1214 /** 1215 * Specifies if a user is not allowed to use cellular data when roaming. 1216 * 1217 * <p>This restriction can only be set by a device owner, a profile owner on the primary 1218 * user or a profile owner of an organization-owned managed profile on the parent profile. 1219 * When it is set by a device owner, it applies globally. When it is set by a profile owner 1220 * on the primary user or by a profile owner of an organization-owned managed profile on 1221 * the parent profile, it disables the primary user from using cellular data when roaming. 1222 * 1223 * <p>The default value is <code>false</code>. 1224 * 1225 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1226 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1227 * @see #getUserRestrictions() 1228 */ 1229 public static final String DISALLOW_DATA_ROAMING = "no_data_roaming"; 1230 1231 /** 1232 * Specifies if a user is not allowed to change their icon. Device owner and profile owner 1233 * can set this restriction. When it is set by device owner, only the target user will be 1234 * affected. The default value is <code>false</code>. 1235 * 1236 * <p>Key for user restrictions. 1237 * <p>Type: Boolean 1238 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1239 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1240 * @see #getUserRestrictions() 1241 */ 1242 public static final String DISALLOW_SET_USER_ICON = "no_set_user_icon"; 1243 1244 /** 1245 * Specifies if a user is not allowed to enable the oem unlock setting. The default value is 1246 * <code>false</code>. Setting this restriction has no effect if the bootloader is already 1247 * unlocked. 1248 * 1249 * <p>Not for use by third-party applications. 1250 * 1251 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1252 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1253 * @see #getUserRestrictions() 1254 * @deprecated use {@link OemLockManager#setOemUnlockAllowedByCarrier(boolean, byte[])} instead. 1255 * @hide 1256 */ 1257 @Deprecated 1258 @SystemApi 1259 public static final String DISALLOW_OEM_UNLOCK = "no_oem_unlock"; 1260 1261 /** 1262 * Specifies that the managed profile is not allowed to have unified lock screen challenge with 1263 * the primary user. 1264 * 1265 * <p><strong>Note:</strong> Setting this restriction alone doesn't automatically set a 1266 * separate challenge. Profile owner can ask the user to set a new password using 1267 * {@link DevicePolicyManager#ACTION_SET_NEW_PASSWORD} and verify it using 1268 * {@link DevicePolicyManager#isUsingUnifiedPassword(ComponentName)}. 1269 * 1270 * <p>Can be set by profile owners. It only has effect on managed profiles when set by managed 1271 * profile owner. Has no effect on non-managed profiles or users. 1272 * <p>Key for user restrictions. 1273 * <p>Type: Boolean 1274 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1275 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1276 * @see #getUserRestrictions() 1277 */ 1278 public static final String DISALLOW_UNIFIED_PASSWORD = "no_unified_password"; 1279 1280 /** 1281 * Allows apps in the parent profile to handle web links from the managed profile. 1282 * 1283 * This user restriction has an effect only in a managed profile. 1284 * If set: 1285 * Intent filters of activities in the parent profile with action 1286 * {@link android.content.Intent#ACTION_VIEW}, 1287 * category {@link android.content.Intent#CATEGORY_BROWSABLE}, scheme http or https, and which 1288 * define a host can handle intents from the managed profile. 1289 * The default value is <code>false</code>. 1290 * 1291 * <p>Key for user restrictions. 1292 * <p>Type: Boolean 1293 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1294 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1295 * @see #getUserRestrictions() 1296 */ 1297 public static final String ALLOW_PARENT_PROFILE_APP_LINKING 1298 = "allow_parent_profile_app_linking"; 1299 1300 /** 1301 * Specifies if a user is not allowed to use Autofill Services. 1302 * 1303 * <p>Device owner and profile owner can set this restriction. When it is set by device owner, 1304 * only the target user will be affected. 1305 * 1306 * <p>The default value is <code>false</code>. 1307 * 1308 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1309 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1310 * @see #getUserRestrictions() 1311 */ 1312 public static final String DISALLOW_AUTOFILL = "no_autofill"; 1313 1314 /** 1315 * Specifies if the contents of a user's screen is not allowed to be captured for artificial 1316 * intelligence purposes. 1317 * 1318 * <p>A device owner and a profile owner can set this restriction. When it is set by a device 1319 * owner, a profile owner on the primary user or by a profile owner of an organization-owned 1320 * managed profile on the parent profile, it disables the primary user's screen from being 1321 * captured for artificial intelligence purposes. 1322 * 1323 * <p>The default value is <code>false</code>. 1324 * 1325 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1326 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1327 * @see #getUserRestrictions() 1328 */ 1329 public static final String DISALLOW_CONTENT_CAPTURE = "no_content_capture"; 1330 1331 /** 1332 * Specifies if the current user is able to receive content suggestions for selections based on 1333 * the contents of their screen. 1334 * 1335 * <p>A device owner and a profile owner can set this restriction. When it is set by a device 1336 * owner, a profile owner on the primary user or by a profile owner of an organization-owned 1337 * managed profile on the parent profile, it disables the primary user from receiving content 1338 * suggestions for selections based on the contents of their screen. 1339 * 1340 * <p>The default value is <code>false</code>. 1341 * 1342 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1343 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1344 * @see #getUserRestrictions() 1345 */ 1346 public static final String DISALLOW_CONTENT_SUGGESTIONS = "no_content_suggestions"; 1347 1348 /** 1349 * Specifies if user switching is blocked on the current user. 1350 * 1351 * <p> This restriction can only be set by the device owner, it will be applied to all users. 1352 * Device owner can still switch user via 1353 * {@link DevicePolicyManager#switchUser(ComponentName, UserHandle)} when this restriction is 1354 * set. 1355 * 1356 * <p>The default value is <code>false</code>. 1357 * 1358 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1359 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1360 * @see #getUserRestrictions() 1361 */ 1362 public static final String DISALLOW_USER_SWITCH = "no_user_switch"; 1363 1364 /** 1365 * Specifies whether the user can share file / picture / data from the primary user into the 1366 * managed profile, either by sending them from the primary side, or by picking up data within 1367 * an app in the managed profile. 1368 * <p> 1369 * When a managed profile is created, the system allows the user to send data from the primary 1370 * side to the profile by setting up certain default cross profile intent filters. If 1371 * this is undesired, this restriction can be set to disallow it. Note that this restriction 1372 * will not block any sharing allowed by explicit 1373 * {@link DevicePolicyManager#addCrossProfileIntentFilter} calls by the profile owner. 1374 * <p> 1375 * This restriction is only meaningful when set by profile owner. When it is set by device 1376 * owner, it does not have any effect. 1377 * <p> 1378 * The default value is <code>false</code>. 1379 * 1380 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1381 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1382 * @see #getUserRestrictions() 1383 */ 1384 public static final String DISALLOW_SHARE_INTO_MANAGED_PROFILE = "no_sharing_into_profile"; 1385 1386 /** 1387 * Specifies whether the user is allowed to print. 1388 * 1389 * This restriction can be set by device or profile owner. 1390 * 1391 * The default value is {@code false}. 1392 * 1393 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1394 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1395 * @see #getUserRestrictions() 1396 */ 1397 public static final String DISALLOW_PRINTING = "no_printing"; 1398 1399 /** 1400 * Specifies whether the user is allowed to modify private DNS settings. 1401 * 1402 * <p>This restriction can only be set by a device owner or a profile owner of an 1403 * organization-owned managed profile on the parent profile. When it is set by either of these 1404 * owners, it applies globally. 1405 * 1406 * <p>The default value is <code>false</code>. 1407 * 1408 * <p>Key for user restrictions. 1409 * <p>Type: Boolean 1410 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1411 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1412 * @see #getUserRestrictions() 1413 */ 1414 public static final String DISALLOW_CONFIG_PRIVATE_DNS = 1415 "disallow_config_private_dns"; 1416 1417 /** 1418 * Specifies whether the microphone toggle is available to the user. If this restriction is set, 1419 * the user will not be able to block microphone access via the system toggle. If microphone 1420 * access is blocked when the restriction is added, it will be automatically re-enabled. 1421 * 1422 * This restriction can only be set by a device owner. 1423 * 1424 * <p>The default value is <code>false</code>. 1425 * 1426 * @see android.hardware.SensorPrivacyManager 1427 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1428 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1429 * @see #getUserRestrictions() 1430 */ 1431 public static final String DISALLOW_MICROPHONE_TOGGLE = 1432 "disallow_microphone_toggle"; 1433 1434 /** 1435 * Specifies whether the camera toggle is available to the user. If this restriction is set, 1436 * the user will not be able to block camera access via the system toggle. If camera 1437 * access is blocked when the restriction is added, it will be automatically re-enabled. 1438 * 1439 * This restriction can only be set by a device owner. 1440 * 1441 * <p>The default value is <code>false</code>. 1442 * 1443 * @see android.hardware.SensorPrivacyManager 1444 * @see DevicePolicyManager#addUserRestriction(ComponentName, String) 1445 * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) 1446 * @see #getUserRestrictions() 1447 */ 1448 public static final String DISALLOW_CAMERA_TOGGLE = 1449 "disallow_camera_toggle"; 1450 1451 /** 1452 * This is really not a user restriction in the normal sense. This can't be set to a user, 1453 * via UserManager nor via DevicePolicyManager. This is not even set in UserSettingsUtils. 1454 * This is defined here purely for convenience within the settings app. 1455 * 1456 * TODO(b/191306258): Refactor the Settings app to remove the need for this field, and delete it 1457 * 1458 * Specifies whether biometrics are available to the user. This is used internally only, 1459 * as a means of communications between biometric settings and 1460 * {@link com.android.settingslib.enterprise.ActionDisabledByAdminControllerFactory}. 1461 * 1462 * @see {@link android.hardware.biometrics.ParentalControlsUtilsInternal} 1463 * @see {@link com.android.settings.biometrics.ParentalControlsUtils} 1464 * 1465 * @hide 1466 */ 1467 public static final String DISALLOW_BIOMETRIC = "disallow_biometric"; 1468 1469 /** 1470 * Application restriction key that is used to indicate the pending arrival 1471 * of real restrictions for the app. 1472 * 1473 * <p> 1474 * Applications that support restrictions should check for the presence of this key. 1475 * A <code>true</code> value indicates that restrictions may be applied in the near 1476 * future but are not available yet. It is the responsibility of any 1477 * management application that sets this flag to update it when the final 1478 * restrictions are enforced. 1479 * 1480 * <p>Key for application restrictions. 1481 * <p>Type: Boolean 1482 * @see android.app.admin.DevicePolicyManager#setApplicationRestrictions( 1483 * android.content.ComponentName, String, Bundle) 1484 * @see android.app.admin.DevicePolicyManager#getApplicationRestrictions( 1485 * android.content.ComponentName, String) 1486 */ 1487 public static final String KEY_RESTRICTIONS_PENDING = "restrictions_pending"; 1488 1489 /** 1490 * List of key values that can be passed into the various user restriction related methods 1491 * in {@link UserManager} & {@link DevicePolicyManager}. 1492 * Note: This is slightly different from the real set of user restrictions listed in {@link 1493 * com.android.server.pm.UserRestrictionsUtils#USER_RESTRICTIONS}. For example 1494 * {@link #KEY_RESTRICTIONS_PENDING} is not a real user restriction, but is a legitimate 1495 * value that can be passed into {@link #hasUserRestriction(String)}. 1496 * @hide 1497 */ 1498 @StringDef(value = { 1499 DISALLOW_MODIFY_ACCOUNTS, 1500 DISALLOW_CONFIG_WIFI, 1501 DISALLOW_CONFIG_LOCALE, 1502 DISALLOW_INSTALL_APPS, 1503 DISALLOW_UNINSTALL_APPS, 1504 DISALLOW_SHARE_LOCATION, 1505 DISALLOW_AIRPLANE_MODE, 1506 DISALLOW_CONFIG_BRIGHTNESS, 1507 DISALLOW_AMBIENT_DISPLAY, 1508 DISALLOW_CONFIG_SCREEN_TIMEOUT, 1509 DISALLOW_INSTALL_UNKNOWN_SOURCES, 1510 DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, 1511 DISALLOW_CONFIG_BLUETOOTH, 1512 DISALLOW_BLUETOOTH, 1513 DISALLOW_BLUETOOTH_SHARING, 1514 DISALLOW_USB_FILE_TRANSFER, 1515 DISALLOW_CONFIG_CREDENTIALS, 1516 DISALLOW_REMOVE_USER, 1517 DISALLOW_REMOVE_MANAGED_PROFILE, 1518 DISALLOW_DEBUGGING_FEATURES, 1519 DISALLOW_CONFIG_VPN, 1520 DISALLOW_CONFIG_LOCATION, 1521 DISALLOW_CONFIG_DATE_TIME, 1522 DISALLOW_CONFIG_TETHERING, 1523 DISALLOW_NETWORK_RESET, 1524 DISALLOW_FACTORY_RESET, 1525 DISALLOW_ADD_USER, 1526 DISALLOW_ADD_MANAGED_PROFILE, 1527 DISALLOW_ADD_CLONE_PROFILE, 1528 ENSURE_VERIFY_APPS, 1529 DISALLOW_CONFIG_CELL_BROADCASTS, 1530 DISALLOW_CONFIG_MOBILE_NETWORKS, 1531 DISALLOW_APPS_CONTROL, 1532 DISALLOW_MOUNT_PHYSICAL_MEDIA, 1533 DISALLOW_UNMUTE_MICROPHONE, 1534 DISALLOW_ADJUST_VOLUME, 1535 DISALLOW_OUTGOING_CALLS, 1536 DISALLOW_SMS, 1537 DISALLOW_FUN, 1538 DISALLOW_CREATE_WINDOWS, 1539 DISALLOW_SYSTEM_ERROR_DIALOGS, 1540 DISALLOW_CROSS_PROFILE_COPY_PASTE, 1541 DISALLOW_OUTGOING_BEAM, 1542 DISALLOW_WALLPAPER, 1543 DISALLOW_SET_WALLPAPER, 1544 DISALLOW_SAFE_BOOT, 1545 DISALLOW_RECORD_AUDIO, 1546 DISALLOW_RUN_IN_BACKGROUND, 1547 DISALLOW_CAMERA, 1548 DISALLOW_UNMUTE_DEVICE, 1549 DISALLOW_DATA_ROAMING, 1550 DISALLOW_SET_USER_ICON, 1551 DISALLOW_OEM_UNLOCK, 1552 DISALLOW_UNIFIED_PASSWORD, 1553 ALLOW_PARENT_PROFILE_APP_LINKING, 1554 DISALLOW_AUTOFILL, 1555 DISALLOW_CONTENT_CAPTURE, 1556 DISALLOW_CONTENT_SUGGESTIONS, 1557 DISALLOW_USER_SWITCH, 1558 DISALLOW_SHARE_INTO_MANAGED_PROFILE, 1559 DISALLOW_PRINTING, 1560 DISALLOW_CONFIG_PRIVATE_DNS, 1561 DISALLOW_MICROPHONE_TOGGLE, 1562 DISALLOW_CAMERA_TOGGLE, 1563 KEY_RESTRICTIONS_PENDING, 1564 DISALLOW_BIOMETRIC, 1565 DISALLOW_CHANGE_WIFI_STATE, 1566 DISALLOW_WIFI_TETHERING, 1567 DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, 1568 DISALLOW_WIFI_DIRECT, 1569 DISALLOW_ADD_WIFI_CONFIG, 1570 }) 1571 @Retention(RetentionPolicy.SOURCE) 1572 public @interface UserRestrictionKey {} 1573 1574 private static final String ACTION_CREATE_USER = "android.os.action.CREATE_USER"; 1575 1576 /** 1577 * Action to start an activity to create a supervised user. 1578 * Only devices with non-empty config_supervisedUserCreationPackage support this. 1579 * 1580 * @hide 1581 */ 1582 @SystemApi 1583 @RequiresPermission(Manifest.permission.MANAGE_USERS) 1584 public static final String ACTION_CREATE_SUPERVISED_USER = 1585 "android.os.action.CREATE_SUPERVISED_USER"; 1586 1587 /** 1588 * Extra containing a name for the user being created. Optional parameter passed to 1589 * ACTION_CREATE_USER activity. 1590 * @hide 1591 */ 1592 public static final String EXTRA_USER_NAME = "android.os.extra.USER_NAME"; 1593 1594 /** 1595 * Extra containing account name for the user being created. Optional parameter passed to 1596 * ACTION_CREATE_USER activity. 1597 * @hide 1598 */ 1599 public static final String EXTRA_USER_ACCOUNT_NAME = "android.os.extra.USER_ACCOUNT_NAME"; 1600 1601 /** 1602 * Extra containing account type for the user being created. Optional parameter passed to 1603 * ACTION_CREATE_USER activity. 1604 * @hide 1605 */ 1606 public static final String EXTRA_USER_ACCOUNT_TYPE = "android.os.extra.USER_ACCOUNT_TYPE"; 1607 1608 /** 1609 * Extra containing account-specific data for the user being created. Optional parameter passed 1610 * to ACTION_CREATE_USER activity. 1611 * @hide 1612 */ 1613 public static final String EXTRA_USER_ACCOUNT_OPTIONS 1614 = "android.os.extra.USER_ACCOUNT_OPTIONS"; 1615 1616 /** @hide */ 1617 public static final int PIN_VERIFICATION_FAILED_INCORRECT = -3; 1618 /** @hide */ 1619 public static final int PIN_VERIFICATION_FAILED_NOT_SET = -2; 1620 /** @hide */ 1621 public static final int PIN_VERIFICATION_SUCCESS = -1; 1622 1623 /** 1624 * Sent when user restrictions have changed. 1625 * 1626 * @hide 1627 */ 1628 @SystemApi // To allow seeing it from CTS. 1629 public static final String ACTION_USER_RESTRICTIONS_CHANGED = 1630 "android.os.action.USER_RESTRICTIONS_CHANGED"; 1631 1632 /** 1633 * Error result indicating that this user is not allowed to add other users on this device. 1634 * This is a result code returned from the activity created by the intent 1635 * {@link #createUserCreationIntent(String, String, String, PersistableBundle)}. 1636 */ 1637 public static final int USER_CREATION_FAILED_NOT_PERMITTED = Activity.RESULT_FIRST_USER; 1638 1639 /** 1640 * Error result indicating that no more users can be created on this device. 1641 * This is a result code returned from the activity created by the intent 1642 * {@link #createUserCreationIntent(String, String, String, PersistableBundle)}. 1643 */ 1644 public static final int USER_CREATION_FAILED_NO_MORE_USERS = Activity.RESULT_FIRST_USER + 1; 1645 1646 /** 1647 * Indicates that users are switchable. 1648 * @hide 1649 */ 1650 @SystemApi 1651 public static final int SWITCHABILITY_STATUS_OK = 0; 1652 1653 /** 1654 * Indicated that the user is in a phone call. 1655 * @hide 1656 */ 1657 @SystemApi 1658 public static final int SWITCHABILITY_STATUS_USER_IN_CALL = 1 << 0; 1659 1660 /** 1661 * Indicates that user switching is disallowed ({@link #DISALLOW_USER_SWITCH} is set). 1662 * @hide 1663 */ 1664 @SystemApi 1665 public static final int SWITCHABILITY_STATUS_USER_SWITCH_DISALLOWED = 1 << 1; 1666 1667 /** 1668 * Indicates that the system user is locked and user switching is not allowed. 1669 * @hide 1670 */ 1671 @SystemApi 1672 public static final int SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED = 1 << 2; 1673 1674 /** 1675 * Result returned in {@link #getUserSwitchability()} indicating user switchability. 1676 * @hide 1677 */ 1678 @Retention(RetentionPolicy.SOURCE) 1679 @IntDef(flag = true, prefix = { "SWITCHABILITY_STATUS_" }, value = { 1680 SWITCHABILITY_STATUS_OK, 1681 SWITCHABILITY_STATUS_USER_IN_CALL, 1682 SWITCHABILITY_STATUS_USER_SWITCH_DISALLOWED, 1683 SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED 1684 }) 1685 public @interface UserSwitchabilityResult {} 1686 1687 /** 1688 * A response code from {@link #removeUserWhenPossible(UserHandle, boolean)} indicating that 1689 * the specified user has been successfully removed. 1690 * 1691 * @hide 1692 */ 1693 @SystemApi 1694 public static final int REMOVE_RESULT_REMOVED = 0; 1695 1696 /** 1697 * A response code from {@link #removeUserWhenPossible(UserHandle, boolean)} indicating that 1698 * the specified user is marked so that it will be removed when the user is stopped or on boot. 1699 * 1700 * @hide 1701 */ 1702 @SystemApi 1703 public static final int REMOVE_RESULT_DEFERRED = 1; 1704 1705 /** 1706 * A response code from {@link #removeUserWhenPossible(UserHandle, boolean)} indicating that 1707 * the specified user is already in the process of being removed. 1708 * 1709 * @hide 1710 */ 1711 @SystemApi 1712 public static final int REMOVE_RESULT_ALREADY_BEING_REMOVED = 2; 1713 1714 /** 1715 * A response code from {@link #removeUserWhenPossible(UserHandle, boolean)} indicating that 1716 * an unknown error occurred that prevented the user from being removed or set as ephemeral. 1717 * 1718 * @hide 1719 */ 1720 @SystemApi 1721 public static final int REMOVE_RESULT_ERROR_UNKNOWN = -1; 1722 1723 /** 1724 * A response code from {@link #removeUserWhenPossible(UserHandle, boolean)} indicating that 1725 * the user could not be removed due to a {@link #DISALLOW_REMOVE_MANAGED_PROFILE} or 1726 * {@link #DISALLOW_REMOVE_USER} user restriction. 1727 * 1728 * @hide 1729 */ 1730 @SystemApi 1731 public static final int REMOVE_RESULT_ERROR_USER_RESTRICTION = -2; 1732 1733 /** 1734 * A response code from {@link #removeUserWhenPossible(UserHandle, boolean)} indicating that 1735 * user being removed does not exist. 1736 * 1737 * @hide 1738 */ 1739 @SystemApi 1740 public static final int REMOVE_RESULT_ERROR_USER_NOT_FOUND = -3; 1741 1742 /** 1743 * A response code from {@link #removeUserWhenPossible(UserHandle, boolean)} indicating that 1744 * user being removed is a {@link UserHandle#SYSTEM} user which can't be removed. 1745 * 1746 * @hide 1747 */ 1748 @SystemApi 1749 public static final int REMOVE_RESULT_ERROR_SYSTEM_USER = -4; 1750 1751 /** 1752 * Possible response codes from {@link #removeUserWhenPossible(UserHandle, boolean)}. 1753 * 1754 * @hide 1755 */ 1756 @IntDef(prefix = { "REMOVE_RESULT_" }, value = { 1757 REMOVE_RESULT_REMOVED, 1758 REMOVE_RESULT_DEFERRED, 1759 REMOVE_RESULT_ALREADY_BEING_REMOVED, 1760 REMOVE_RESULT_ERROR_USER_RESTRICTION, 1761 REMOVE_RESULT_ERROR_USER_NOT_FOUND, 1762 REMOVE_RESULT_ERROR_SYSTEM_USER, 1763 REMOVE_RESULT_ERROR_UNKNOWN, 1764 }) 1765 @Retention(RetentionPolicy.SOURCE) 1766 public @interface RemoveResult {} 1767 1768 /** 1769 * Indicates user operation is successful. 1770 */ 1771 public static final int USER_OPERATION_SUCCESS = 0; 1772 1773 /** 1774 * Indicates user operation failed for unknown reason. 1775 */ 1776 public static final int USER_OPERATION_ERROR_UNKNOWN = 1; 1777 1778 /** 1779 * Indicates user operation failed because target user is a managed profile. 1780 */ 1781 public static final int USER_OPERATION_ERROR_MANAGED_PROFILE = 2; 1782 1783 /** 1784 * Indicates user operation failed because maximum running user limit has been reached. 1785 */ 1786 public static final int USER_OPERATION_ERROR_MAX_RUNNING_USERS = 3; 1787 1788 /** 1789 * Indicates user operation failed because the target user is in the foreground. 1790 */ 1791 public static final int USER_OPERATION_ERROR_CURRENT_USER = 4; 1792 1793 /** 1794 * Indicates user operation failed because device has low data storage. 1795 */ 1796 public static final int USER_OPERATION_ERROR_LOW_STORAGE = 5; 1797 1798 /** 1799 * Indicates user operation failed because maximum user limit has been reached. 1800 */ 1801 public static final int USER_OPERATION_ERROR_MAX_USERS = 6; 1802 1803 /** 1804 * Indicates user operation failed because a user with that account already exists. 1805 * 1806 * @hide 1807 */ 1808 @SystemApi 1809 public static final int USER_OPERATION_ERROR_USER_ACCOUNT_ALREADY_EXISTS = 7; 1810 1811 /** 1812 * Result returned from various user operations. 1813 * 1814 * @hide 1815 */ 1816 @Retention(RetentionPolicy.SOURCE) 1817 @IntDef(prefix = { "USER_OPERATION_" }, value = { 1818 USER_OPERATION_SUCCESS, 1819 USER_OPERATION_ERROR_UNKNOWN, 1820 USER_OPERATION_ERROR_MANAGED_PROFILE, 1821 USER_OPERATION_ERROR_MAX_RUNNING_USERS, 1822 USER_OPERATION_ERROR_CURRENT_USER, 1823 USER_OPERATION_ERROR_LOW_STORAGE, 1824 USER_OPERATION_ERROR_MAX_USERS, 1825 USER_OPERATION_ERROR_USER_ACCOUNT_ALREADY_EXISTS 1826 }) 1827 public @interface UserOperationResult {} 1828 1829 /** 1830 * Thrown to indicate user operation failed. 1831 */ 1832 public static class UserOperationException extends RuntimeException { 1833 private final @UserOperationResult int mUserOperationResult; 1834 1835 /** 1836 * Constructs a UserOperationException with specific result code. 1837 * 1838 * @param message the detail message 1839 * @param userOperationResult the result code 1840 * @hide 1841 */ UserOperationException(String message, @UserOperationResult int userOperationResult)1842 public UserOperationException(String message, 1843 @UserOperationResult int userOperationResult) { 1844 super(message); 1845 mUserOperationResult = userOperationResult; 1846 } 1847 1848 /** 1849 * Returns the operation result code. 1850 */ getUserOperationResult()1851 public @UserOperationResult int getUserOperationResult() { 1852 return mUserOperationResult; 1853 } 1854 1855 /** 1856 * Returns a UserOperationException containing the same message and error code. 1857 * @hide 1858 */ from(ServiceSpecificException exception)1859 public static UserOperationException from(ServiceSpecificException exception) { 1860 return new UserOperationException(exception.getMessage(), exception.errorCode); 1861 } 1862 } 1863 1864 /** 1865 * Converts the ServiceSpecificException into a UserOperationException or throws null; 1866 * 1867 * @param exception exception to convert. 1868 * @param throwInsteadOfNull if an exception should be thrown or null returned. 1869 * @return null if chosen not to throw exception. 1870 * @throws UserOperationException 1871 */ returnNullOrThrowUserOperationException(ServiceSpecificException exception, boolean throwInsteadOfNull)1872 private <T> T returnNullOrThrowUserOperationException(ServiceSpecificException exception, 1873 boolean throwInsteadOfNull) throws UserOperationException { 1874 if (throwInsteadOfNull) { 1875 throw UserOperationException.from(exception); 1876 } else { 1877 return null; 1878 } 1879 } 1880 1881 /** 1882 * Thrown to indicate user operation failed. (Checked exception) 1883 * @hide 1884 */ 1885 public static class CheckedUserOperationException extends AndroidException { 1886 private final @UserOperationResult int mUserOperationResult; 1887 1888 /** 1889 * Constructs a CheckedUserOperationException with specific result code. 1890 * 1891 * @param message the detail message 1892 * @param userOperationResult the result code 1893 * @hide 1894 */ CheckedUserOperationException(String message, @UserOperationResult int userOperationResult)1895 public CheckedUserOperationException(String message, 1896 @UserOperationResult int userOperationResult) { 1897 super(message); 1898 mUserOperationResult = userOperationResult; 1899 } 1900 1901 /** Returns the operation result code. */ getUserOperationResult()1902 public @UserOperationResult int getUserOperationResult() { 1903 return mUserOperationResult; 1904 } 1905 1906 /** Return a ServiceSpecificException containing the same message and error code. */ toServiceSpecificException()1907 public ServiceSpecificException toServiceSpecificException() { 1908 return new ServiceSpecificException(mUserOperationResult, getMessage()); 1909 } 1910 } 1911 1912 /** 1913 * For apps targeting {@link Build.VERSION_CODES#TIRAMISU} and above, any UserManager API marked 1914 * as {@link android.annotation.UserHandleAware @UserHandleAware} will use the context user 1915 * (rather than the calling user). 1916 * For apps targeting an SDK version <em>below</em> this, the behaviour 1917 * depends on the particular method and when it was first introduced: 1918 * <ul> 1919 * <li> 1920 * if the {@literal @}UserHandleAware specifies a 1921 * {@link android.annotation.UserHandleAware#enabledSinceTargetSdkVersion} of 1922 * {@link Build.VERSION_CODES#TIRAMISU} the <em>calling</em> user is used. 1923 * </li> 1924 * <li> 1925 * if the {@literal @}UserHandleAware doesn't specify a 1926 * {@link android.annotation.UserHandleAware#enabledSinceTargetSdkVersion}, the 1927 * <em>context</em> user is used. 1928 * </li> 1929 * <li>there should currently be no other values used by UserManager for 1930 * {@link android.annotation.UserHandleAware#enabledSinceTargetSdkVersion}, since all 1931 * old implicitly user-dependant APIs were updated in that version and anything 1932 * introduced more recently should already be {@literal @}UserHandleAware. 1933 * </li> 1934 * </ul> 1935 * 1936 * Note that when an API marked with 1937 * {@link android.annotation.UserHandleAware#enabledSinceTargetSdkVersion} is run 1938 * on a device whose OS predates that version, the calling user will be used, since on such a 1939 * device, the API is not {@literal @}UserHandleAware yet. 1940 * 1941 * @hide 1942 */ 1943 @ChangeId 1944 @EnabledSince(targetSdkVersion = Build.VERSION_CODES.TIRAMISU) 1945 public static final long ALWAYS_USE_CONTEXT_USER = 183155436L; 1946 1947 /** 1948 * Returns the context user or the calling user, depending on the target SDK. 1949 * New APIs do not require such gating and therefore should always use mUserId instead. 1950 * @see #ALWAYS_USE_CONTEXT_USER 1951 */ getContextUserIfAppropriate()1952 private @UserIdInt int getContextUserIfAppropriate() { 1953 if (CompatChanges.isChangeEnabled(ALWAYS_USE_CONTEXT_USER)) { 1954 return mUserId; 1955 } else { 1956 final int callingUser = UserHandle.myUserId(); 1957 if (callingUser != mUserId) { 1958 Log.w(TAG, "Using the calling user " + callingUser 1959 + ", rather than the specified context user " + mUserId 1960 + ", because API is only UserHandleAware on higher targetSdkVersions.", 1961 new Throwable()); 1962 } 1963 return callingUser; 1964 } 1965 } 1966 1967 /** @hide */ 1968 @UnsupportedAppUsage get(Context context)1969 public static UserManager get(Context context) { 1970 return (UserManager) context.getSystemService(Context.USER_SERVICE); 1971 } 1972 1973 /** @hide */ UserManager(Context context, IUserManager service)1974 public UserManager(Context context, IUserManager service) { 1975 mService = service; 1976 Context appContext = context.getApplicationContext(); 1977 mContext = (appContext == null ? context : appContext); 1978 mUserId = context.getUserId(); 1979 } 1980 1981 /** 1982 * Returns whether this device supports multiple users with their own login and customizable 1983 * space. 1984 * @return whether the device supports multiple users. 1985 */ supportsMultipleUsers()1986 public static boolean supportsMultipleUsers() { 1987 return getMaxSupportedUsers() > 1 1988 && SystemProperties.getBoolean("fw.show_multiuserui", 1989 Resources.getSystem().getBoolean(R.bool.config_enableMultiUserUI)); 1990 } 1991 1992 /** 1993 * @hide 1994 * @return Whether the device is running with split system user. It means the system user and 1995 * primary user are two separate users. Previously system user and primary user are combined as 1996 * a single owner user. see @link {android.os.UserHandle#USER_OWNER} 1997 */ 1998 @TestApi isSplitSystemUser()1999 public static boolean isSplitSystemUser() { 2000 return RoSystemProperties.FW_SYSTEM_USER_SPLIT; 2001 } 2002 2003 /** 2004 * @return Whether guest user is always ephemeral 2005 * @hide 2006 */ isGuestUserAlwaysEphemeral()2007 public static boolean isGuestUserAlwaysEphemeral() { 2008 return Resources.getSystem() 2009 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral); 2010 } 2011 2012 /** 2013 * @return true, when we want to enable user manager API and UX to allow 2014 * guest user ephemeral state change based on user input 2015 * @hide 2016 */ isGuestUserAllowEphemeralStateChange()2017 public static boolean isGuestUserAllowEphemeralStateChange() { 2018 return Resources.getSystem() 2019 .getBoolean(com.android.internal.R.bool.config_guestUserAllowEphemeralStateChange); 2020 } 2021 2022 /** 2023 * Checks whether the device is running in a headless system user mode. 2024 * 2025 * <p>Headless system user mode means the {@link #isSystemUser() system user} runs system 2026 * services and some system UI, but it is not associated with any real person and additional 2027 * users must be created to be associated with real persons. 2028 * 2029 * @return whether the device is running in a headless system user mode. 2030 */ isHeadlessSystemUserMode()2031 public static boolean isHeadlessSystemUserMode() { 2032 return RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER; 2033 } 2034 2035 /** 2036 * @deprecated use {@link #getUserSwitchability()} instead. 2037 * 2038 * @removed 2039 * @hide 2040 */ 2041 @Deprecated 2042 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 2043 android.Manifest.permission.INTERACT_ACROSS_USERS}) 2044 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 2045 @UserHandleAware canSwitchUsers()2046 public boolean canSwitchUsers() { 2047 try { 2048 return mService.getUserSwitchability(mUserId) == SWITCHABILITY_STATUS_OK; 2049 } catch (RemoteException re) { 2050 throw re.rethrowFromSystemServer(); 2051 } 2052 } 2053 2054 /** 2055 * Returns whether switching users is currently allowed for the context user. 2056 * <p> 2057 * Switching users is not allowed in the following cases: 2058 * <li>the user is in a phone call</li> 2059 * <li>{@link #DISALLOW_USER_SWITCH} is set</li> 2060 * <li>system user hasn't been unlocked yet</li> 2061 * 2062 * @return A {@link UserSwitchabilityResult} flag indicating if the user is switchable. 2063 * @hide 2064 */ 2065 @SystemApi 2066 @RequiresPermission(allOf = {Manifest.permission.READ_PHONE_STATE, 2067 android.Manifest.permission.MANAGE_USERS, 2068 android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) 2069 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) getUserSwitchability()2070 public @UserSwitchabilityResult int getUserSwitchability() { 2071 return getUserSwitchability(UserHandle.of(getContextUserIfAppropriate())); 2072 } 2073 2074 /** 2075 * Returns whether switching users is currently allowed for the provided user. 2076 * <p> 2077 * Switching users is not allowed in the following cases: 2078 * <li>the user is in a phone call</li> 2079 * <li>{@link #DISALLOW_USER_SWITCH} is set</li> 2080 * <li>system user hasn't been unlocked yet</li> 2081 * 2082 * @return A {@link UserSwitchabilityResult} flag indicating if the user is switchable. 2083 * @hide 2084 */ 2085 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 2086 android.Manifest.permission.INTERACT_ACROSS_USERS}) getUserSwitchability(UserHandle userHandle)2087 public @UserSwitchabilityResult int getUserSwitchability(UserHandle userHandle) { 2088 try { 2089 return mService.getUserSwitchability(userHandle.getIdentifier()); 2090 } catch (RemoteException re) { 2091 throw re.rethrowFromSystemServer(); 2092 } 2093 } 2094 2095 /** 2096 * Returns the userId for the context user. 2097 * 2098 * @return the userId of the context user. 2099 * 2100 * @deprecated To get the <em>calling</em> user, use {@link UserHandle#myUserId()}. 2101 * To get the <em>context</em> user, get it directly from the context. 2102 * 2103 * @hide 2104 */ 2105 @Deprecated 2106 @UnsupportedAppUsage 2107 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) 2108 // *** Do NOT use this in UserManager. Instead always use mUserId. *** getUserHandle()2109 public @UserIdInt int getUserHandle() { 2110 return getContextUserIfAppropriate(); 2111 } 2112 2113 /** 2114 * Returns the userId for the user that this process is running under 2115 * (<em>not</em> the context user). 2116 * 2117 * @return the userId of <em>this process</em>. 2118 * 2119 * @deprecated Use {@link UserHandle#myUserId()} 2120 * @hide 2121 */ 2122 @Deprecated 2123 // NOT @UserHandleAware getProcessUserId()2124 public @UserIdInt int getProcessUserId() { 2125 return UserHandle.myUserId(); 2126 } 2127 2128 /** 2129 * @return the user type of the context user. 2130 * @hide 2131 */ 2132 @TestApi 2133 @RequiresPermission(anyOf = { 2134 android.Manifest.permission.MANAGE_USERS, 2135 android.Manifest.permission.CREATE_USERS, 2136 android.Manifest.permission.QUERY_USERS}) 2137 @UserHandleAware getUserType()2138 public @NonNull String getUserType() { 2139 UserInfo userInfo = getUserInfo(mUserId); 2140 return userInfo == null ? "" : userInfo.userType; 2141 } 2142 2143 /** 2144 * Returns the user name of the context user. This call is only available to applications on 2145 * the system image. 2146 * 2147 * @return the user name 2148 */ 2149 @RequiresPermission(anyOf = { 2150 android.Manifest.permission.MANAGE_USERS, 2151 android.Manifest.permission.CREATE_USERS, 2152 android.Manifest.permission.QUERY_USERS, 2153 android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED}) 2154 2155 @UserHandleAware( 2156 requiresAnyOfPermissionsIfNotCaller = { 2157 android.Manifest.permission.MANAGE_USERS, 2158 android.Manifest.permission.CREATE_USERS, 2159 android.Manifest.permission.QUERY_USERS}) getUserName()2160 public @NonNull String getUserName() { 2161 if (UserHandle.myUserId() == mUserId) { 2162 try { 2163 return mService.getUserName(); 2164 } catch (RemoteException re) { 2165 throw re.rethrowFromSystemServer(); 2166 } 2167 } else { 2168 UserInfo userInfo = getUserInfo(mUserId); 2169 if (userInfo != null && userInfo.name != null) { 2170 return userInfo.name; 2171 } 2172 return ""; 2173 } 2174 } 2175 2176 /** 2177 * Returns whether user name has been set. 2178 * <p>This method can be used to check that the value returned by {@link #getUserName()} was 2179 * set by the user and is not a placeholder string provided by the system. 2180 * @hide 2181 */ 2182 @SystemApi 2183 @RequiresPermission(anyOf = { 2184 android.Manifest.permission.MANAGE_USERS, 2185 android.Manifest.permission.CREATE_USERS, 2186 android.Manifest.permission.QUERY_USERS, 2187 android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED}) 2188 @UserHandleAware( 2189 enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU, 2190 requiresAnyOfPermissionsIfNotCaller = { 2191 android.Manifest.permission.MANAGE_USERS, 2192 android.Manifest.permission.CREATE_USERS, 2193 android.Manifest.permission.QUERY_USERS}) isUserNameSet()2194 public boolean isUserNameSet() { 2195 try { 2196 return mService.isUserNameSet(getContextUserIfAppropriate()); 2197 } catch (RemoteException re) { 2198 throw re.rethrowFromSystemServer(); 2199 } 2200 } 2201 2202 /** 2203 * Used to determine whether the user making this call is subject to 2204 * teleportations. 2205 * 2206 * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can 2207 * now automatically identify goats using advanced goat recognition technology.</p> 2208 * 2209 * <p>As of {@link android.os.Build.VERSION_CODES#R}, this method always returns 2210 * {@code false} in order to protect goat privacy.</p> 2211 * 2212 * @return Returns whether the user making this call is a goat. 2213 */ 2214 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) isUserAGoat()2215 public boolean isUserAGoat() { 2216 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) { 2217 return false; 2218 } 2219 // Caution: This is NOT @UserHandleAware (because mContext is getApplicationContext and 2220 // can hold a different userId), but for R+ it returns false, so it doesn't matter anyway. 2221 return mContext.getPackageManager() 2222 .isPackageAvailable("com.coffeestainstudios.goatsimulator"); 2223 } 2224 2225 /** 2226 * Used to check if the context user is the primary user. The primary user 2227 * is the first human user on a device. This is not supported in headless system user mode. 2228 * 2229 * @return whether the context user is the primary user. 2230 * @hide 2231 */ 2232 @SystemApi 2233 @RequiresPermission(anyOf = { 2234 Manifest.permission.MANAGE_USERS, 2235 Manifest.permission.CREATE_USERS, 2236 Manifest.permission.QUERY_USERS}) 2237 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) isPrimaryUser()2238 public boolean isPrimaryUser() { 2239 final UserInfo user = getUserInfo(getContextUserIfAppropriate()); 2240 return user != null && user.isPrimary(); 2241 } 2242 2243 /** 2244 * Used to check if the context user is the system user. The system user 2245 * is the initial user that is implicitly created on first boot and hosts most of the 2246 * system services. 2247 * 2248 * @return whether the context user is the system user. 2249 */ 2250 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) isSystemUser()2251 public boolean isSystemUser() { 2252 return getContextUserIfAppropriate() == UserHandle.USER_SYSTEM; 2253 } 2254 2255 /** 2256 * Used to check if the context user is an admin user. An admin user is allowed to 2257 * modify or configure certain settings that aren't available to non-admin users, 2258 * create and delete additional users, etc. There can be more than one admin users. 2259 * 2260 * @return whether the context user is an admin user. 2261 * @hide 2262 */ 2263 @SystemApi 2264 @RequiresPermission(anyOf = { 2265 Manifest.permission.MANAGE_USERS, 2266 Manifest.permission.CREATE_USERS, 2267 Manifest.permission.QUERY_USERS}) 2268 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) isAdminUser()2269 public boolean isAdminUser() { 2270 return isUserAdmin(getContextUserIfAppropriate()); 2271 } 2272 2273 /** 2274 * @hide 2275 * Returns whether the provided user is an admin user. There can be more than one admin 2276 * user. 2277 */ 2278 @UnsupportedAppUsage 2279 @RequiresPermission(anyOf = { 2280 Manifest.permission.MANAGE_USERS, 2281 Manifest.permission.CREATE_USERS, 2282 Manifest.permission.QUERY_USERS}) isUserAdmin(@serIdInt int userId)2283 public boolean isUserAdmin(@UserIdInt int userId) { 2284 UserInfo user = getUserInfo(userId); 2285 return user != null && user.isAdmin(); 2286 } 2287 2288 /** 2289 * Returns whether the context user is of the given user type. 2290 * 2291 * @param userType the name of the user's user type, e.g. 2292 * {@link UserManager#USER_TYPE_PROFILE_MANAGED}. 2293 * @return true if the user is of the given user type. 2294 * @hide 2295 */ 2296 @SystemApi 2297 @RequiresPermission(anyOf = { 2298 android.Manifest.permission.MANAGE_USERS, 2299 android.Manifest.permission.CREATE_USERS, 2300 android.Manifest.permission.QUERY_USERS}) 2301 @UserHandleAware isUserOfType(@onNull String userType)2302 public boolean isUserOfType(@NonNull String userType) { 2303 try { 2304 return mService.isUserOfType(mUserId, userType); 2305 } catch (RemoteException re) { 2306 throw re.rethrowFromSystemServer(); 2307 } 2308 } 2309 2310 /** 2311 * Returns whether the user type is a 2312 * {@link UserManager#USER_TYPE_PROFILE_MANAGED managed profile}. 2313 * @hide 2314 */ isUserTypeManagedProfile(@ullable String userType)2315 public static boolean isUserTypeManagedProfile(@Nullable String userType) { 2316 return USER_TYPE_PROFILE_MANAGED.equals(userType); 2317 } 2318 2319 /** 2320 * Returns whether the user type is a {@link UserManager#USER_TYPE_FULL_GUEST guest user}. 2321 * @hide 2322 */ isUserTypeGuest(@ullable String userType)2323 public static boolean isUserTypeGuest(@Nullable String userType) { 2324 return USER_TYPE_FULL_GUEST.equals(userType); 2325 } 2326 2327 /** 2328 * Returns whether the user type is a 2329 * {@link UserManager#USER_TYPE_FULL_RESTRICTED restricted user}. 2330 * @hide 2331 */ isUserTypeRestricted(@ullable String userType)2332 public static boolean isUserTypeRestricted(@Nullable String userType) { 2333 return USER_TYPE_FULL_RESTRICTED.equals(userType); 2334 } 2335 2336 /** 2337 * Returns whether the user type is a {@link UserManager#USER_TYPE_FULL_DEMO demo user}. 2338 * @hide 2339 */ isUserTypeDemo(@ullable String userType)2340 public static boolean isUserTypeDemo(@Nullable String userType) { 2341 return USER_TYPE_FULL_DEMO.equals(userType); 2342 } 2343 2344 /** 2345 * Returns whether the user type is a {@link UserManager#USER_TYPE_PROFILE_CLONE clone user}. 2346 * @hide 2347 */ isUserTypeCloneProfile(@ullable String userType)2348 public static boolean isUserTypeCloneProfile(@Nullable String userType) { 2349 return USER_TYPE_PROFILE_CLONE.equals(userType); 2350 } 2351 2352 /** 2353 * Returns the enum defined in the statsd UserLifecycleJourneyReported atom corresponding to the 2354 * user type. 2355 * @hide 2356 */ getUserTypeForStatsd(@onNull String userType)2357 public static int getUserTypeForStatsd(@NonNull String userType) { 2358 switch (userType) { 2359 case USER_TYPE_FULL_SYSTEM: 2360 return FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__FULL_SYSTEM; 2361 case USER_TYPE_FULL_SECONDARY: 2362 return FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__FULL_SECONDARY; 2363 case USER_TYPE_FULL_GUEST: 2364 return FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__FULL_GUEST; 2365 case USER_TYPE_FULL_DEMO: 2366 return FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__FULL_DEMO; 2367 case USER_TYPE_FULL_RESTRICTED: 2368 return FrameworkStatsLog 2369 .USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__FULL_RESTRICTED; 2370 case USER_TYPE_PROFILE_MANAGED: 2371 return FrameworkStatsLog 2372 .USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__PROFILE_MANAGED; 2373 case USER_TYPE_SYSTEM_HEADLESS: 2374 return FrameworkStatsLog 2375 .USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__SYSTEM_HEADLESS; 2376 case USER_TYPE_PROFILE_CLONE: 2377 return FrameworkStatsLog 2378 .USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__PROFILE_CLONE; 2379 default: 2380 return FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__TYPE_UNKNOWN; 2381 } 2382 } 2383 2384 /** 2385 * @hide 2386 * @deprecated Use {@link #isRestrictedProfile()} 2387 */ 2388 @UnsupportedAppUsage 2389 @Deprecated 2390 @UserHandleAware( 2391 enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU, 2392 requiresAnyOfPermissionsIfNotCaller = { 2393 android.Manifest.permission.MANAGE_USERS, 2394 android.Manifest.permission.CREATE_USERS} 2395 ) isLinkedUser()2396 public boolean isLinkedUser() { 2397 return isRestrictedProfile(); 2398 } 2399 2400 /** 2401 * Used to check if the context user is a restricted profile. Restricted profiles 2402 * may have a reduced number of available apps, app restrictions, and account restrictions. 2403 * 2404 * @return whether the context user is a restricted profile. 2405 * @hide 2406 */ 2407 @SystemApi 2408 @UserHandleAware( 2409 enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU, 2410 requiresAnyOfPermissionsIfNotCaller = { 2411 android.Manifest.permission.MANAGE_USERS, 2412 android.Manifest.permission.CREATE_USERS} 2413 ) isRestrictedProfile()2414 public boolean isRestrictedProfile() { 2415 try { 2416 return mService.isRestricted(getContextUserIfAppropriate()); 2417 } catch (RemoteException re) { 2418 throw re.rethrowFromSystemServer(); 2419 } 2420 } 2421 2422 /** 2423 * Check if a user is a restricted profile. Restricted profiles may have a reduced number of 2424 * available apps, app restrictions, and account restrictions. 2425 * 2426 * @param user the user to check 2427 * @return whether the user is a restricted profile. 2428 * @hide 2429 */ 2430 @SystemApi 2431 @RequiresPermission(anyOf = { 2432 Manifest.permission.MANAGE_USERS, 2433 Manifest.permission.CREATE_USERS}, 2434 conditional = true) isRestrictedProfile(@onNull UserHandle user)2435 public boolean isRestrictedProfile(@NonNull UserHandle user) { 2436 try { 2437 return mService.isRestricted(user.getIdentifier()); 2438 } catch (RemoteException re) { 2439 throw re.rethrowFromSystemServer(); 2440 } 2441 } 2442 2443 /** 2444 * Checks if the calling context user can have a restricted profile. 2445 * @return whether the context user can have a restricted profile. 2446 * @hide 2447 */ 2448 @SystemApi 2449 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) 2450 @UserHandleAware canHaveRestrictedProfile()2451 public boolean canHaveRestrictedProfile() { 2452 try { 2453 return mService.canHaveRestrictedProfile(mUserId); 2454 } catch (RemoteException re) { 2455 throw re.rethrowFromSystemServer(); 2456 } 2457 } 2458 2459 /** 2460 * Returns whether the context user has at least one restricted profile associated with it. 2461 * @return whether the user has a restricted profile associated with it 2462 * @hide 2463 */ 2464 @SystemApi 2465 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) 2466 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) hasRestrictedProfiles()2467 public boolean hasRestrictedProfiles() { 2468 try { 2469 return mService.hasRestrictedProfiles(getContextUserIfAppropriate()); 2470 } catch (RemoteException re) { 2471 throw re.rethrowFromSystemServer(); 2472 } 2473 } 2474 2475 /** 2476 * Get the parent of a restricted profile. 2477 * 2478 * @return the parent of the user or {@code null} if the user is not restricted profile 2479 * @hide 2480 */ 2481 @SystemApi 2482 @RequiresPermission(anyOf = { 2483 Manifest.permission.MANAGE_USERS, 2484 Manifest.permission.CREATE_USERS, 2485 Manifest.permission.QUERY_USERS}) 2486 @UserHandleAware getRestrictedProfileParent()2487 public @Nullable UserHandle getRestrictedProfileParent() { 2488 final UserInfo info = getUserInfo(mUserId); 2489 if (info == null) return null; 2490 if (!info.isRestricted()) return null; 2491 final int parent = info.restrictedProfileParentId; 2492 if (parent == UserHandle.USER_NULL) return null; 2493 return UserHandle.of(parent); 2494 } 2495 2496 /** 2497 * Checks if a user is a guest user. 2498 * @return whether user is a guest user. 2499 * @hide 2500 */ 2501 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 2502 @RequiresPermission(anyOf = { 2503 Manifest.permission.MANAGE_USERS, 2504 Manifest.permission.CREATE_USERS, 2505 Manifest.permission.QUERY_USERS}) isGuestUser(@serIdInt int userId)2506 public boolean isGuestUser(@UserIdInt int userId) { 2507 UserInfo user = getUserInfo(userId); 2508 return user != null && user.isGuest(); 2509 } 2510 2511 /** 2512 * Used to check if the context user is a guest user. A guest user may be transient. 2513 * 2514 * @return whether the context user is a guest user. 2515 * @hide 2516 */ 2517 @SystemApi 2518 @RequiresPermission(anyOf = { 2519 Manifest.permission.MANAGE_USERS, 2520 Manifest.permission.CREATE_USERS, 2521 Manifest.permission.QUERY_USERS}) 2522 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) isGuestUser()2523 public boolean isGuestUser() { 2524 UserInfo user = getUserInfo(getContextUserIfAppropriate()); 2525 return user != null && user.isGuest(); 2526 } 2527 2528 2529 /** 2530 * Checks if the context user is a demo user. When running in a demo user, 2531 * apps can be more helpful to the user, or explain their features in more detail. 2532 * 2533 * @return whether the context user is a demo user. 2534 */ 2535 @UserHandleAware( 2536 enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU, 2537 requiresPermissionIfNotCaller = android.Manifest.permission.MANAGE_USERS 2538 ) isDemoUser()2539 public boolean isDemoUser() { 2540 try { 2541 return mService.isDemoUser(getContextUserIfAppropriate()); 2542 } catch (RemoteException re) { 2543 throw re.rethrowFromSystemServer(); 2544 } 2545 } 2546 2547 /** 2548 * Checks if the calling context user is running in a profile. A profile is a user that 2549 * typically has its own separate data but shares its UI with some parent user. For example, a 2550 * {@link #isManagedProfile() managed profile} is a type of profile. 2551 * 2552 * @return whether the caller is in a profile. 2553 */ 2554 @UserHandleAware( 2555 requiresAnyOfPermissionsIfNotCallerProfileGroup = { 2556 android.Manifest.permission.MANAGE_USERS, 2557 android.Manifest.permission.QUERY_USERS, 2558 android.Manifest.permission.INTERACT_ACROSS_USERS}) isProfile()2559 public boolean isProfile() { 2560 return isProfile(mUserId); 2561 } 2562 isProfile(@serIdInt int userId)2563 private boolean isProfile(@UserIdInt int userId) { 2564 final String profileType = getProfileType(userId); 2565 return profileType != null && !profileType.equals(""); 2566 } 2567 2568 /** 2569 * Returns the user type of the context user if it is a profile. 2570 * 2571 * This is a more specific form of {@link #getUserType()} with relaxed permission requirements. 2572 * 2573 * @return the user type of the context user if it is a {@link #isProfile() profile}, 2574 * an empty string if it is not a profile, 2575 * or null if the user doesn't exist. 2576 */ 2577 @UserHandleAware( 2578 requiresAnyOfPermissionsIfNotCallerProfileGroup = { 2579 android.Manifest.permission.MANAGE_USERS, 2580 android.Manifest.permission.QUERY_USERS, 2581 android.Manifest.permission.INTERACT_ACROSS_USERS}) getProfileType()2582 private @Nullable String getProfileType() { 2583 return getProfileType(mUserId); 2584 } 2585 2586 /** @see #getProfileType() */ getProfileType(@serIdInt int userId)2587 private @Nullable String getProfileType(@UserIdInt int userId) { 2588 // First, the typical case (i.e. the *process* user, not necessarily the context user). 2589 // This cache cannot be become invalidated since it's about the calling process itself. 2590 if (userId == UserHandle.myUserId()) { 2591 // No need for synchronization. Once it becomes non-null, it'll be non-null forever. 2592 // Worst case we might end up calling the AIDL method multiple times but that's fine. 2593 if (mProfileTypeOfProcessUser != null) { 2594 return mProfileTypeOfProcessUser; 2595 } 2596 try { 2597 final String profileType = mService.getProfileType(userId); 2598 if (profileType != null) { 2599 return mProfileTypeOfProcessUser = profileType.intern(); 2600 } 2601 } catch (RemoteException re) { 2602 throw re.rethrowFromSystemServer(); 2603 } 2604 } 2605 2606 // The userId is not for the process's user. Use a slower cache that handles invalidation. 2607 return mProfileTypeCache.query(userId); 2608 } 2609 2610 /** 2611 * Checks if the context user is a managed profile. 2612 * 2613 * Note that this applies specifically to <em>managed</em> profiles. For profiles in general, 2614 * use {@link #isProfile()} instead. 2615 * 2616 * @return whether the context user is a managed profile. 2617 */ 2618 @UserHandleAware( 2619 enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU, 2620 requiresAnyOfPermissionsIfNotCallerProfileGroup = { 2621 android.Manifest.permission.MANAGE_USERS, 2622 android.Manifest.permission.QUERY_USERS, 2623 android.Manifest.permission.INTERACT_ACROSS_USERS}) isManagedProfile()2624 public boolean isManagedProfile() { 2625 return isManagedProfile(getContextUserIfAppropriate()); 2626 } 2627 2628 /** 2629 * Checks if the specified user is a managed profile. 2630 * Requires {@link android.Manifest.permission#MANAGE_USERS} or 2631 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS} or 2632 * {@link android.Manifest.permission#QUERY_USERS} permission, otherwise the caller 2633 * must be in the same profile group of specified user. 2634 * 2635 * Note that this applies specifically to <em>managed</em> profiles. For profiles in general, 2636 * use {@link #isProfile()} instead. 2637 * 2638 * @return whether the specified user is a managed profile. 2639 * @hide 2640 */ 2641 @SystemApi 2642 @RequiresPermission(anyOf = { 2643 android.Manifest.permission.MANAGE_USERS, 2644 android.Manifest.permission.QUERY_USERS, 2645 android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) isManagedProfile(@serIdInt int userId)2646 public boolean isManagedProfile(@UserIdInt int userId) { 2647 return isUserTypeManagedProfile(getProfileType(userId)); 2648 } 2649 2650 /** 2651 * Checks if the context user is a clone profile. 2652 * 2653 * @return whether the context user is a clone profile. 2654 * 2655 * @see android.os.UserManager#USER_TYPE_PROFILE_CLONE 2656 * @hide 2657 */ 2658 @SystemApi 2659 @UserHandleAware( 2660 requiresAnyOfPermissionsIfNotCallerProfileGroup = { 2661 android.Manifest.permission.MANAGE_USERS, 2662 android.Manifest.permission.QUERY_USERS, 2663 android.Manifest.permission.INTERACT_ACROSS_USERS}) 2664 @SuppressAutoDoc isCloneProfile()2665 public boolean isCloneProfile() { 2666 return isUserTypeCloneProfile(getProfileType()); 2667 } 2668 2669 /** 2670 * Checks if the context user is an ephemeral user. 2671 * 2672 * @return whether the context user is an ephemeral user. 2673 * @hide 2674 */ 2675 @RequiresPermission(anyOf = { 2676 Manifest.permission.MANAGE_USERS, 2677 Manifest.permission.CREATE_USERS, 2678 Manifest.permission.QUERY_USERS}) 2679 @UserHandleAware isEphemeralUser()2680 public boolean isEphemeralUser() { 2681 return isUserEphemeral(mUserId); 2682 } 2683 2684 /** 2685 * Returns whether the specified user is ephemeral. 2686 * @hide 2687 */ 2688 @RequiresPermission(anyOf = { 2689 Manifest.permission.MANAGE_USERS, 2690 Manifest.permission.CREATE_USERS, 2691 Manifest.permission.QUERY_USERS}) isUserEphemeral(@serIdInt int userId)2692 public boolean isUserEphemeral(@UserIdInt int userId) { 2693 final UserInfo user = getUserInfo(userId); 2694 return user != null && user.isEphemeral(); 2695 } 2696 2697 /** 2698 * Return whether the given user is actively running. This means that 2699 * the user is in the "started" state, not "stopped" -- it is currently 2700 * allowed to run code through scheduled alarms, receiving broadcasts, 2701 * etc. A started user may be either the current foreground user or a 2702 * background user; the result here does not distinguish between the two. 2703 * 2704 * <p>Note prior to Android Nougat MR1 (SDK version <= 24; 2705 * {@link android.os.Build.VERSION_CODES#N}, this API required a system permission 2706 * in order to check other profile's status. 2707 * Since Android Nougat MR1 (SDK version >= 25; 2708 * {@link android.os.Build.VERSION_CODES#N_MR1}), the restriction has been relaxed, and now 2709 * it'll accept any {@link android.os.UserHandle} within the same profile group as the caller. 2710 * 2711 * @param user The user to retrieve the running state for. 2712 */ 2713 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 2714 Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) isUserRunning(UserHandle user)2715 public boolean isUserRunning(UserHandle user) { 2716 return isUserRunning(user.getIdentifier()); 2717 } 2718 2719 /** {@hide} */ 2720 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 2721 Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) isUserRunning(@serIdInt int userId)2722 public boolean isUserRunning(@UserIdInt int userId) { 2723 try { 2724 return mService.isUserRunning(userId); 2725 } catch (RemoteException re) { 2726 throw re.rethrowFromSystemServer(); 2727 } 2728 } 2729 2730 /** 2731 * Return whether the given user is actively running <em>or</em> stopping. 2732 * This is like {@link #isUserRunning(UserHandle)}, but will also return 2733 * true if the user had been running but is in the process of being stopped 2734 * (but is not yet fully stopped, and still running some code). 2735 * 2736 * <p>Note prior to Android Nougat MR1 (SDK version <= 24; 2737 * {@link android.os.Build.VERSION_CODES#N}, this API required a system permission 2738 * in order to check other profile's status. 2739 * Since Android Nougat MR1 (SDK version >= 25; 2740 * {@link android.os.Build.VERSION_CODES#N_MR1}), the restriction has been relaxed, and now 2741 * it'll accept any {@link android.os.UserHandle} within the same profile group as the caller. 2742 * 2743 * @param user The user to retrieve the running state for. 2744 */ 2745 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 2746 Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) isUserRunningOrStopping(UserHandle user)2747 public boolean isUserRunningOrStopping(UserHandle user) { 2748 try { 2749 // TODO: reconcile stopped vs stopping? 2750 return ActivityManager.getService().isUserRunning( 2751 user.getIdentifier(), ActivityManager.FLAG_OR_STOPPED); 2752 } catch (RemoteException re) { 2753 throw re.rethrowFromSystemServer(); 2754 } 2755 } 2756 2757 /** 2758 * Checks if the context user is running in the foreground. 2759 * 2760 * @return whether the context user is running in the foreground. 2761 */ 2762 @UserHandleAware isUserForeground()2763 public boolean isUserForeground() { 2764 try { 2765 return mService.isUserForeground(mUserId); 2766 } catch (RemoteException re) { 2767 throw re.rethrowFromSystemServer(); 2768 } 2769 } 2770 2771 /** 2772 * Return whether the context user is running in an "unlocked" state. 2773 * <p> 2774 * On devices with direct boot, a user is unlocked only after they've 2775 * entered their credentials (such as a lock pattern or PIN). On devices 2776 * without direct boot, a user is unlocked as soon as it starts. 2777 * <p> 2778 * When a user is locked, only device-protected data storage is available. 2779 * When a user is unlocked, both device-protected and credential-protected 2780 * private app data storage is available. 2781 * 2782 * @see Intent#ACTION_USER_UNLOCKED 2783 * @see Context#createDeviceProtectedStorageContext() 2784 */ 2785 @UserHandleAware( 2786 enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU, 2787 requiresAnyOfPermissionsIfNotCallerProfileGroup = { 2788 android.Manifest.permission.MANAGE_USERS, 2789 android.Manifest.permission.INTERACT_ACROSS_USERS} 2790 ) isUserUnlocked()2791 public boolean isUserUnlocked() { 2792 return isUserUnlocked(getContextUserIfAppropriate()); 2793 } 2794 2795 /** 2796 * Return whether the given user is running in an "unlocked" state. 2797 * <p> 2798 * On devices with direct boot, a user is unlocked only after they've 2799 * entered their credentials (such as a lock pattern or PIN). On devices 2800 * without direct boot, a user is unlocked as soon as it starts. 2801 * <p> 2802 * When a user is locked, only device-protected data storage is available. 2803 * When a user is unlocked, both device-protected and credential-protected 2804 * private app data storage is available. 2805 * <p>Requires {@code android.permission.MANAGE_USERS} or 2806 * {@code android.permission.INTERACT_ACROSS_USERS}, otherwise specified {@link UserHandle user} 2807 * must be the calling user or a profile associated with it. 2808 * 2809 * @param user to retrieve the unlocked state for. 2810 * @see Intent#ACTION_USER_UNLOCKED 2811 * @see Context#createDeviceProtectedStorageContext() 2812 */ 2813 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 2814 Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) isUserUnlocked(UserHandle user)2815 public boolean isUserUnlocked(UserHandle user) { 2816 return isUserUnlocked(user.getIdentifier()); 2817 } 2818 2819 private static final String CACHE_KEY_IS_USER_UNLOCKED_PROPERTY = 2820 "cache_key.is_user_unlocked"; 2821 2822 private final PropertyInvalidatedCache<Integer, Boolean> mIsUserUnlockedCache = 2823 new PropertyInvalidatedCache<Integer, Boolean>( 2824 32, CACHE_KEY_IS_USER_UNLOCKED_PROPERTY) { 2825 @Override 2826 public Boolean recompute(Integer query) { 2827 try { 2828 return mService.isUserUnlocked(query); 2829 } catch (RemoteException re) { 2830 throw re.rethrowFromSystemServer(); 2831 } 2832 } 2833 @Override 2834 public boolean bypass(Integer query) { 2835 return query < 0; 2836 } 2837 }; 2838 2839 // Uses IS_USER_UNLOCKED_PROPERTY for invalidation as the APIs have the same dependencies. 2840 private final PropertyInvalidatedCache<Integer, Boolean> mIsUserUnlockingOrUnlockedCache = 2841 new PropertyInvalidatedCache<Integer, Boolean>( 2842 32, CACHE_KEY_IS_USER_UNLOCKED_PROPERTY) { 2843 @Override 2844 public Boolean recompute(Integer query) { 2845 try { 2846 return mService.isUserUnlockingOrUnlocked(query); 2847 } catch (RemoteException re) { 2848 throw re.rethrowFromSystemServer(); 2849 } 2850 } 2851 @Override 2852 public boolean bypass(Integer query) { 2853 return query < 0; 2854 } 2855 }; 2856 2857 /** {@hide} */ 2858 @UnsupportedAppUsage 2859 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 2860 Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) isUserUnlocked(@serIdInt int userId)2861 public boolean isUserUnlocked(@UserIdInt int userId) { 2862 return mIsUserUnlockedCache.query(userId); 2863 } 2864 2865 /** {@hide} */ disableIsUserUnlockedCache()2866 public void disableIsUserUnlockedCache() { 2867 mIsUserUnlockedCache.disableLocal(); 2868 mIsUserUnlockingOrUnlockedCache.disableLocal(); 2869 } 2870 2871 /** {@hide} */ invalidateIsUserUnlockedCache()2872 public static final void invalidateIsUserUnlockedCache() { 2873 PropertyInvalidatedCache.invalidateCache(CACHE_KEY_IS_USER_UNLOCKED_PROPERTY); 2874 } 2875 2876 /** 2877 * Return whether the provided user is already running in an 2878 * "unlocked" state or in the process of unlocking. 2879 * <p> 2880 * On devices with direct boot, a user is unlocked only after they've 2881 * entered their credentials (such as a lock pattern or PIN). On devices 2882 * without direct boot, a user is unlocked as soon as it starts. 2883 * <p> 2884 * When a user is locked, only device-protected data storage is available. 2885 * When a user is unlocked, both device-protected and credential-protected 2886 * private app data storage is available. 2887 * 2888 * <p>Requires {@code android.permission.MANAGE_USERS} or 2889 * {@code android.permission.INTERACT_ACROSS_USERS}, otherwise specified {@link UserHandle user} 2890 * must be the calling user or a profile associated with it. 2891 * 2892 * @hide 2893 */ 2894 @SystemApi 2895 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 2896 Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) isUserUnlockingOrUnlocked(@onNull UserHandle user)2897 public boolean isUserUnlockingOrUnlocked(@NonNull UserHandle user) { 2898 return isUserUnlockingOrUnlocked(user.getIdentifier()); 2899 } 2900 2901 /** {@hide} */ 2902 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 2903 Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) isUserUnlockingOrUnlocked(@serIdInt int userId)2904 public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) { 2905 return mIsUserUnlockingOrUnlockedCache.query(userId); 2906 } 2907 2908 /** 2909 * Return the time when the calling user started in elapsed milliseconds since boot, 2910 * or 0 if not started. 2911 * 2912 * @hide 2913 */ 2914 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 2915 // NOT @UserHandleAware getUserStartRealtime()2916 public long getUserStartRealtime() { 2917 if (getContextUserIfAppropriate() != UserHandle.myUserId()) { 2918 // Note: If we want to support this in the future, also annotate with 2919 // @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) 2920 throw new IllegalArgumentException("Calling from a context differing from the calling " 2921 + "user is not currently supported."); 2922 } 2923 try { 2924 return mService.getUserStartRealtime(); 2925 } catch (RemoteException re) { 2926 throw re.rethrowFromSystemServer(); 2927 } 2928 } 2929 2930 /** 2931 * Return the time when the context user was unlocked elapsed milliseconds since boot, 2932 * or 0 if not unlocked. 2933 * 2934 * @hide 2935 */ 2936 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 2937 // NOT @UserHandleAware getUserUnlockRealtime()2938 public long getUserUnlockRealtime() { 2939 if (getContextUserIfAppropriate() != UserHandle.myUserId()) { 2940 // Note: If we want to support this in the future, also annotate with 2941 // @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) 2942 throw new IllegalArgumentException("Calling from a context differing from the calling " 2943 + "user is not currently supported."); 2944 } 2945 try { 2946 return mService.getUserUnlockRealtime(); 2947 } catch (RemoteException re) { 2948 throw re.rethrowFromSystemServer(); 2949 } 2950 } 2951 2952 /** 2953 * Returns the UserInfo object describing a specific user. 2954 * @param userId the user handle of the user whose information is being requested. 2955 * @return the UserInfo object for a specific user. 2956 * @hide 2957 */ 2958 @UnsupportedAppUsage 2959 @RequiresPermission(anyOf = { 2960 Manifest.permission.MANAGE_USERS, 2961 Manifest.permission.CREATE_USERS, 2962 Manifest.permission.QUERY_USERS}) getUserInfo(@serIdInt int userId)2963 public UserInfo getUserInfo(@UserIdInt int userId) { 2964 try { 2965 return mService.getUserInfo(userId); 2966 } catch (RemoteException re) { 2967 throw re.rethrowFromSystemServer(); 2968 } 2969 } 2970 2971 /** 2972 * @hide 2973 * 2974 * Returns who set a user restriction on a user. 2975 * @param restrictionKey the string key representing the restriction 2976 * @param userHandle the UserHandle of the user for whom to retrieve the restrictions. 2977 * @return The source of user restriction. Any combination of {@link #RESTRICTION_NOT_SET}, 2978 * {@link #RESTRICTION_SOURCE_SYSTEM}, {@link #RESTRICTION_SOURCE_DEVICE_OWNER} 2979 * and {@link #RESTRICTION_SOURCE_PROFILE_OWNER} 2980 * @deprecated use {@link #getUserRestrictionSources(String, int)} instead. 2981 */ 2982 @Deprecated 2983 @SystemApi 2984 @UserRestrictionSource 2985 @RequiresPermission(anyOf = { 2986 Manifest.permission.MANAGE_USERS, 2987 Manifest.permission.QUERY_USERS}) getUserRestrictionSource(@serRestrictionKey String restrictionKey, UserHandle userHandle)2988 public int getUserRestrictionSource(@UserRestrictionKey String restrictionKey, 2989 UserHandle userHandle) { 2990 try { 2991 return mService.getUserRestrictionSource(restrictionKey, userHandle.getIdentifier()); 2992 } catch (RemoteException re) { 2993 throw re.rethrowFromSystemServer(); 2994 } 2995 } 2996 2997 /** 2998 * @hide 2999 * 3000 * Returns a list of users who set a user restriction on a given user. 3001 * @param restrictionKey the string key representing the restriction 3002 * @param userHandle the UserHandle of the user for whom to retrieve the restrictions. 3003 * @return a list of user ids enforcing this restriction. 3004 */ 3005 @SystemApi 3006 @RequiresPermission(anyOf = { 3007 android.Manifest.permission.MANAGE_USERS, 3008 android.Manifest.permission.QUERY_USERS}) getUserRestrictionSources( @serRestrictionKey String restrictionKey, UserHandle userHandle)3009 public List<EnforcingUser> getUserRestrictionSources( 3010 @UserRestrictionKey String restrictionKey, UserHandle userHandle) { 3011 try { 3012 return mService.getUserRestrictionSources(restrictionKey, userHandle.getIdentifier()); 3013 } catch (RemoteException re) { 3014 throw re.rethrowFromSystemServer(); 3015 } 3016 } 3017 3018 /** 3019 * Returns the user-wide restrictions imposed on the context user. 3020 * @return a Bundle containing all the restrictions. 3021 */ 3022 @UserHandleAware( 3023 enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU, 3024 requiresAnyOfPermissionsIfNotCallerProfileGroup = { 3025 android.Manifest.permission.MANAGE_USERS, 3026 android.Manifest.permission.INTERACT_ACROSS_USERS} 3027 ) getUserRestrictions()3028 public Bundle getUserRestrictions() { 3029 try { 3030 return mService.getUserRestrictions(getContextUserIfAppropriate()); 3031 } catch (RemoteException re) { 3032 throw re.rethrowFromSystemServer(); 3033 } 3034 } 3035 3036 /** 3037 * Returns the user-wide restrictions imposed on the user specified by <code>userHandle</code>. 3038 * @param userHandle the UserHandle of the user for whom to retrieve the restrictions. 3039 * @return a Bundle containing all the restrictions. 3040 * 3041 * <p>Requires {@code android.permission.MANAGE_USERS} or 3042 * {@code android.permission.INTERACT_ACROSS_USERS}, otherwise specified {@link UserHandle user} 3043 * must be the calling user or a profile associated with it. 3044 */ 3045 @RequiresPermission(anyOf = { 3046 android.Manifest.permission.MANAGE_USERS, 3047 android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) getUserRestrictions(UserHandle userHandle)3048 public Bundle getUserRestrictions(UserHandle userHandle) { 3049 try { 3050 return mService.getUserRestrictions(userHandle.getIdentifier()); 3051 } catch (RemoteException re) { 3052 throw re.rethrowFromSystemServer(); 3053 } 3054 } 3055 3056 /** 3057 * @hide 3058 * Returns whether the given user has been disallowed from performing certain actions 3059 * or setting certain settings through UserManager (e.g. this type of restriction would prevent 3060 * the guest user from doing certain things, such as making calls). This method disregards 3061 * restrictions set by device policy. 3062 * @param restrictionKey the string key representing the restriction 3063 * @param userHandle the UserHandle of the user for whom to retrieve the restrictions. 3064 */ 3065 @TestApi 3066 @UnsupportedAppUsage 3067 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3068 Manifest.permission.CREATE_USERS}) hasBaseUserRestriction(@serRestrictionKey @onNull String restrictionKey, @NonNull UserHandle userHandle)3069 public boolean hasBaseUserRestriction(@UserRestrictionKey @NonNull String restrictionKey, 3070 @NonNull UserHandle userHandle) { 3071 try { 3072 return mService.hasBaseUserRestriction(restrictionKey, userHandle.getIdentifier()); 3073 } catch (RemoteException re) { 3074 throw re.rethrowFromSystemServer(); 3075 } 3076 } 3077 3078 /** 3079 * This will no longer work. Device owners and profile owners should use 3080 * {@link DevicePolicyManager#addUserRestriction(ComponentName, String)} instead. 3081 */ 3082 // System apps should use UserManager.setUserRestriction() instead. 3083 @Deprecated setUserRestrictions(Bundle restrictions)3084 public void setUserRestrictions(Bundle restrictions) { 3085 throw new UnsupportedOperationException("This method is no longer supported"); 3086 } 3087 3088 /** 3089 * This will no longer work. Device owners and profile owners should use 3090 * {@link DevicePolicyManager#addUserRestriction(ComponentName, String)} instead. 3091 */ 3092 // System apps should use UserManager.setUserRestriction() instead. 3093 @Deprecated setUserRestrictions(Bundle restrictions, UserHandle userHandle)3094 public void setUserRestrictions(Bundle restrictions, UserHandle userHandle) { 3095 throw new UnsupportedOperationException("This method is no longer supported"); 3096 } 3097 3098 /** 3099 * Sets the value of a specific restriction on the context user. 3100 * Requires the MANAGE_USERS permission. 3101 * @param key the key of the restriction 3102 * @param value the value for the restriction 3103 * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction( 3104 * android.content.ComponentName, String)} or 3105 * {@link android.app.admin.DevicePolicyManager#clearUserRestriction( 3106 * android.content.ComponentName, String)} instead. 3107 */ 3108 @Deprecated 3109 @RequiresPermission(Manifest.permission.MANAGE_USERS) 3110 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) setUserRestriction(String key, boolean value)3111 public void setUserRestriction(String key, boolean value) { 3112 try { 3113 mService.setUserRestriction(key, value, getContextUserIfAppropriate()); 3114 } catch (RemoteException re) { 3115 throw re.rethrowFromSystemServer(); 3116 } 3117 } 3118 3119 /** 3120 * @hide 3121 * Sets the value of a specific restriction on a specific user. 3122 * @param key the key of the restriction 3123 * @param value the value for the restriction 3124 * @param userHandle the user whose restriction is to be changed. 3125 * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction( 3126 * android.content.ComponentName, String)} or 3127 * {@link android.app.admin.DevicePolicyManager#clearUserRestriction( 3128 * android.content.ComponentName, String)} instead. 3129 */ 3130 @Deprecated 3131 @RequiresPermission(Manifest.permission.MANAGE_USERS) setUserRestriction(String key, boolean value, UserHandle userHandle)3132 public void setUserRestriction(String key, boolean value, UserHandle userHandle) { 3133 try { 3134 mService.setUserRestriction(key, value, userHandle.getIdentifier()); 3135 } catch (RemoteException re) { 3136 throw re.rethrowFromSystemServer(); 3137 } 3138 } 3139 3140 /** 3141 * Returns whether the context user has been disallowed from performing certain actions 3142 * or setting certain settings. 3143 * 3144 * @param restrictionKey The string key representing the restriction. 3145 * @return {@code true} if the context user has the given restriction, {@code false} otherwise. 3146 */ 3147 @UserHandleAware( 3148 enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU, 3149 requiresAnyOfPermissionsIfNotCallerProfileGroup = { 3150 android.Manifest.permission.MANAGE_USERS, 3151 android.Manifest.permission.INTERACT_ACROSS_USERS} 3152 ) hasUserRestriction(@serRestrictionKey String restrictionKey)3153 public boolean hasUserRestriction(@UserRestrictionKey String restrictionKey) { 3154 return hasUserRestrictionForUser(restrictionKey, getContextUserIfAppropriate()); 3155 } 3156 3157 /** 3158 * @hide 3159 * Returns whether the given user has been disallowed from performing certain actions 3160 * or setting certain settings. 3161 * @param restrictionKey the string key representing the restriction 3162 * @param userHandle the UserHandle of the user for whom to retrieve the restrictions. 3163 * @deprecated Use {@link #hasUserRestrictionForUser(String, UserHandle)} instead. 3164 */ 3165 @UnsupportedAppUsage 3166 @RequiresPermission(anyOf = { 3167 android.Manifest.permission.MANAGE_USERS, 3168 android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) 3169 @Deprecated hasUserRestriction(@serRestrictionKey String restrictionKey, UserHandle userHandle)3170 public boolean hasUserRestriction(@UserRestrictionKey String restrictionKey, 3171 UserHandle userHandle) { 3172 return hasUserRestrictionForUser(restrictionKey, userHandle); 3173 } 3174 3175 /** 3176 * Returns whether the given user has been disallowed from performing certain actions 3177 * or setting certain settings. 3178 * @param restrictionKey the string key representing the restriction 3179 * @param userHandle the UserHandle of the user for whom to retrieve the restrictions. 3180 * 3181 * <p>Requires {@code android.permission.MANAGE_USERS} or 3182 * {@code android.permission.INTERACT_ACROSS_USERS}, otherwise specified {@link UserHandle user} 3183 * must be the calling user or a profile associated with it. 3184 * 3185 * @hide 3186 */ 3187 @SystemApi 3188 @RequiresPermission(anyOf = { 3189 android.Manifest.permission.MANAGE_USERS, 3190 android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) hasUserRestrictionForUser(@onNull @serRestrictionKey String restrictionKey, @NonNull UserHandle userHandle)3191 public boolean hasUserRestrictionForUser(@NonNull @UserRestrictionKey String restrictionKey, 3192 @NonNull UserHandle userHandle) { 3193 return hasUserRestrictionForUser(restrictionKey, userHandle.getIdentifier()); 3194 } 3195 3196 @RequiresPermission(anyOf = { 3197 android.Manifest.permission.MANAGE_USERS, 3198 android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) hasUserRestrictionForUser(@onNull @serRestrictionKey String restrictionKey, @UserIdInt int userId)3199 private boolean hasUserRestrictionForUser(@NonNull @UserRestrictionKey String restrictionKey, 3200 @UserIdInt int userId) { 3201 try { 3202 return mService.hasUserRestriction(restrictionKey, userId); 3203 } catch (RemoteException re) { 3204 throw re.rethrowFromSystemServer(); 3205 } 3206 } 3207 3208 /** 3209 * @hide 3210 * Returns whether any user on the device has the given user restriction set. 3211 */ hasUserRestrictionOnAnyUser(@serRestrictionKey String restrictionKey)3212 public boolean hasUserRestrictionOnAnyUser(@UserRestrictionKey String restrictionKey) { 3213 try { 3214 return mService.hasUserRestrictionOnAnyUser(restrictionKey); 3215 } catch (RemoteException re) { 3216 throw re.rethrowFromSystemServer(); 3217 } 3218 } 3219 3220 /** 3221 * @hide 3222 * 3223 * Checks whether changing the given setting to the given value is prohibited 3224 * by the corresponding user restriction in the given user. 3225 * 3226 * May only be called by the OS itself. 3227 * 3228 * @return {@code true} if the change is prohibited, {@code false} if the change is allowed. 3229 */ isSettingRestrictedForUser(String setting, @UserIdInt int userId, String value, int callingUid)3230 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId, 3231 String value, int callingUid) { 3232 try { 3233 return mService.isSettingRestrictedForUser(setting, userId, value, callingUid); 3234 } catch (RemoteException re) { 3235 throw re.rethrowFromSystemServer(); 3236 } 3237 } 3238 3239 /** 3240 * @hide 3241 * Register a binder callback for user restrictions changes. 3242 * May only be called by the OS itself. 3243 */ addUserRestrictionsListener(final IUserRestrictionsListener listener)3244 public void addUserRestrictionsListener(final IUserRestrictionsListener listener) { 3245 try { 3246 mService.addUserRestrictionsListener(listener); 3247 } catch (RemoteException re) { 3248 throw re.rethrowFromSystemServer(); 3249 } 3250 } 3251 3252 /** 3253 * Return the serial number for a user. This is a device-unique 3254 * number assigned to that user; if the user is deleted and then a new 3255 * user created, the new users will not be given the same serial number. 3256 * @param user The user whose serial number is to be retrieved. 3257 * @return The serial number of the given user; returns -1 if the 3258 * given UserHandle does not exist. 3259 * @see #getUserForSerialNumber(long) 3260 */ getSerialNumberForUser(UserHandle user)3261 public long getSerialNumberForUser(UserHandle user) { 3262 return getUserSerialNumber(user.getIdentifier()); 3263 } 3264 3265 /** 3266 * Return the user associated with a serial number previously 3267 * returned by {@link #getSerialNumberForUser(UserHandle)}. 3268 * @param serialNumber The serial number of the user that is being 3269 * retrieved. 3270 * @return Return the user associated with the serial number, or null 3271 * if there is not one. 3272 * @see #getSerialNumberForUser(UserHandle) 3273 */ getUserForSerialNumber(long serialNumber)3274 public UserHandle getUserForSerialNumber(long serialNumber) { 3275 int ident = getUserHandle((int) serialNumber); 3276 return ident >= 0 ? new UserHandle(ident) : null; 3277 } 3278 3279 /** 3280 * Creates a user with the specified name and options. 3281 * Default user restrictions will be applied. 3282 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission. 3283 * 3284 * @param name the user's name 3285 * @param flags UserInfo flags that identify the type of user and other properties. 3286 * @see UserInfo 3287 * 3288 * @return the UserInfo object for the created user, or null if the user could not be created. 3289 * @throws IllegalArgumentException if flags do not correspond to a valid user type. 3290 * @deprecated Use {@link #createUser(String, String, int)} instead. 3291 * @hide 3292 */ 3293 @UnsupportedAppUsage 3294 @Deprecated createUser(@ullable String name, @UserInfoFlag int flags)3295 public @Nullable UserInfo createUser(@Nullable String name, @UserInfoFlag int flags) { 3296 return createUser(name, UserInfo.getDefaultUserType(flags), flags); 3297 } 3298 3299 /** 3300 * Creates a user with the specified name and options. 3301 * Default user restrictions will be applied. 3302 * 3303 * <p>Requires {@link android.Manifest.permission#MANAGE_USERS}. 3304 * {@link android.Manifest.permission#CREATE_USERS} suffices if flags are in 3305 * com.android.server.pm.UserManagerService#ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION}. 3306 * 3307 * @param name the user's name 3308 * @param userType the type of user, such as {@link UserManager#USER_TYPE_FULL_GUEST}. 3309 * @param flags UserInfo flags that specify user properties. 3310 * @return the {@link UserInfo} object for the created user, or {@code null} if the user 3311 * could not be created. 3312 * 3313 * @see UserInfo 3314 * 3315 * @hide 3316 */ 3317 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3318 Manifest.permission.CREATE_USERS}) 3319 @TestApi createUser(@ullable String name, @NonNull String userType, @UserInfoFlag int flags)3320 public @Nullable UserInfo createUser(@Nullable String name, @NonNull String userType, 3321 @UserInfoFlag int flags) { 3322 try { 3323 return mService.createUserWithThrow(name, userType, flags); 3324 } catch (ServiceSpecificException e) { 3325 return null; 3326 } catch (RemoteException re) { 3327 throw re.rethrowFromSystemServer(); 3328 } 3329 } 3330 3331 /** 3332 * Creates a user with the specified {@link NewUserRequest}. 3333 * 3334 * @param newUserRequest specify the user information 3335 * 3336 * @hide 3337 */ 3338 @SystemApi 3339 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3340 Manifest.permission.CREATE_USERS}) createUser(@onNull NewUserRequest newUserRequest)3341 public @NonNull NewUserResponse createUser(@NonNull NewUserRequest newUserRequest) { 3342 try { 3343 final UserHandle userHandle = mService.createUserWithAttributes( 3344 newUserRequest.getName(), 3345 newUserRequest.getUserType(), 3346 newUserRequest.getFlags(), 3347 newUserRequest.getUserIcon(), 3348 newUserRequest.getAccountName(), 3349 newUserRequest.getAccountType(), 3350 newUserRequest.getAccountOptions()); 3351 3352 return new NewUserResponse(userHandle, USER_OPERATION_SUCCESS); 3353 3354 } catch (ServiceSpecificException e) { 3355 Log.w(TAG, "Exception while creating user " + newUserRequest, e); 3356 return new NewUserResponse(null, e.errorCode); 3357 } catch (RemoteException re) { 3358 throw re.rethrowFromSystemServer(); 3359 } 3360 } 3361 3362 /** 3363 * Pre-creates a user of the specified type. Default user restrictions will be applied. 3364 * 3365 * <p>This method can be used by OEMs to "warm" up the user creation by pre-creating some users 3366 * at the first boot, so they when the "real" user is created (for example, 3367 * by {@link #createUser(String, String, int)} or {@link #createGuest(Context)}), it 3368 * takes less time. 3369 * 3370 * <p>This method completes the majority of work necessary for user creation: it 3371 * creates user data, CE and DE encryption keys, app data directories, initializes the user and 3372 * grants default permissions. When pre-created users become "real" users, only then are 3373 * components notified of new user creation by firing user creation broadcasts. 3374 * 3375 * <p>All pre-created users are removed during system upgrade. 3376 * 3377 * <p>Requires {@link android.Manifest.permission#MANAGE_USERS}. 3378 * {@link android.Manifest.permission#CREATE_USERS} suffices if flags are in 3379 * com.android.server.pm.UserManagerService#ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION}. 3380 * 3381 * @param userType the type of user, such as {@link UserManager#USER_TYPE_FULL_GUEST}. 3382 * @return the {@link UserInfo} object for the created user. 3383 * 3384 * @throws UserOperationException if the user could not be created. 3385 * @hide 3386 */ 3387 @TestApi 3388 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3389 Manifest.permission.CREATE_USERS}) preCreateUser(@onNull String userType)3390 public @NonNull UserInfo preCreateUser(@NonNull String userType) 3391 throws UserOperationException { 3392 try { 3393 return mService.preCreateUserWithThrow(userType); 3394 } catch (ServiceSpecificException e) { 3395 throw UserOperationException.from(e); 3396 } catch (RemoteException re) { 3397 throw re.rethrowFromSystemServer(); 3398 } 3399 } 3400 3401 /** 3402 * Creates a guest user and configures it. 3403 * @param context an application context 3404 * @return the {@link UserInfo} object for the created user, or {@code null} if the user 3405 * could not be created. 3406 * 3407 * @hide 3408 */ 3409 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3410 Manifest.permission.CREATE_USERS}) createGuest(Context context)3411 public UserInfo createGuest(Context context) { 3412 try { 3413 final UserInfo guest = mService.createUserWithThrow(null, USER_TYPE_FULL_GUEST, 0); 3414 if (guest != null) { 3415 Settings.Secure.putStringForUser(context.getContentResolver(), 3416 Settings.Secure.SKIP_FIRST_USE_HINTS, "1", guest.id); 3417 3418 if (UserManager.isGuestUserAllowEphemeralStateChange()) { 3419 // Mark guest as (changeably) ephemeral if REMOVE_GUEST_ON_EXIT is 1 3420 // This is done so that a user via a UI controller can choose to 3421 // make a guest as ephemeral or not. 3422 // Settings.Global.REMOVE_GUEST_ON_EXIT holds the choice on what the guest state 3423 // should be, with default being ephemeral. 3424 boolean resetGuestOnExit = Settings.Global.getInt(context.getContentResolver(), 3425 Settings.Global.REMOVE_GUEST_ON_EXIT, 1) == 1; 3426 3427 if (resetGuestOnExit && !guest.isEphemeral()) { 3428 setUserEphemeral(guest.id, true); 3429 } 3430 } 3431 } 3432 return guest; 3433 } catch (ServiceSpecificException e) { 3434 return null; 3435 } catch (RemoteException re) { 3436 throw re.rethrowFromSystemServer(); 3437 } 3438 } 3439 3440 /** 3441 * Gets the existing guest user if it exists. This does not include guest users that are dying. 3442 * @return The existing guest user if it exists. Null otherwise. 3443 * @hide 3444 */ 3445 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) findCurrentGuestUser()3446 public UserInfo findCurrentGuestUser() { 3447 try { 3448 return mService.findCurrentGuestUser(); 3449 } catch (RemoteException re) { 3450 throw re.rethrowFromSystemServer(); 3451 } 3452 } 3453 3454 /** 3455 * Creates a user with the specified name and options as a profile of the context's user. 3456 * 3457 * @param name the user's name. 3458 * @param userType the type of user, such as {@link UserManager#USER_TYPE_PROFILE_MANAGED}. 3459 * @param disallowedPackages packages to not install for this profile. 3460 * 3461 * @return the {@link android.os.UserHandle} object for the created user, 3462 * or throws {@link UserOperationException} if the user could not be created 3463 * and calling app is targeting {@link android.os.Build.VERSION_CODES#R} or above 3464 * (otherwise returns {@code null}). 3465 * 3466 * @throws UserOperationException if the user could not be created and the calling app is 3467 * targeting {@link android.os.Build.VERSION_CODES#R} or above. 3468 * 3469 * @hide 3470 */ 3471 @SystemApi 3472 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3473 Manifest.permission.CREATE_USERS}) 3474 @UserHandleAware createProfile(@onNull String name, @NonNull String userType, @NonNull Set<String> disallowedPackages)3475 public @Nullable UserHandle createProfile(@NonNull String name, @NonNull String userType, 3476 @NonNull Set<String> disallowedPackages) throws UserOperationException { 3477 try { 3478 return mService.createProfileForUserWithThrow(name, userType, 0, 3479 mUserId, disallowedPackages.toArray( 3480 new String[disallowedPackages.size()])).getUserHandle(); 3481 } catch (ServiceSpecificException e) { 3482 return returnNullOrThrowUserOperationException(e, 3483 mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R); 3484 } catch (RemoteException re) { 3485 throw re.rethrowFromSystemServer(); 3486 } 3487 } 3488 3489 /** 3490 * Creates a user with the specified name and options as a profile of another user. 3491 * <p>Requires MANAGE_USERS. CREATE_USERS suffices for ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION 3492 * 3493 * @param name the user's name 3494 * @param flags flags that identify the type of user and other properties. 3495 * @param userId new user will be a profile of this user. 3496 * 3497 * @return the {@link UserInfo} object for the created user, or null if the user 3498 * could not be created. 3499 * @throws IllegalArgumentException if flags do not correspond to a valid user type. 3500 * @deprecated Use {@link #createProfileForUser(String, String, int, int)} instead. 3501 * @hide 3502 */ 3503 @UnsupportedAppUsage 3504 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3505 Manifest.permission.CREATE_USERS}) 3506 @Deprecated createProfileForUser(String name, @UserInfoFlag int flags, @UserIdInt int userId)3507 public UserInfo createProfileForUser(String name, @UserInfoFlag int flags, 3508 @UserIdInt int userId) { 3509 return createProfileForUser(name, UserInfo.getDefaultUserType(flags), flags, 3510 userId, null); 3511 } 3512 3513 /** 3514 * Creates a user with the specified name and options as a profile of another user. 3515 * 3516 * @param name the user's name 3517 * @param userType the type of user, such as {@link UserManager#USER_TYPE_PROFILE_MANAGED}. 3518 * @param flags UserInfo flags that specify user properties. 3519 * @param userId new user will be a profile of this user. 3520 * 3521 * @return the {@link UserInfo} object for the created user, or null if the user 3522 * could not be created. 3523 * @hide 3524 */ 3525 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3526 Manifest.permission.CREATE_USERS}) createProfileForUser(String name, @NonNull String userType, @UserInfoFlag int flags, @UserIdInt int userId)3527 public UserInfo createProfileForUser(String name, @NonNull String userType, 3528 @UserInfoFlag int flags, @UserIdInt int userId) { 3529 return createProfileForUser(name, userType, flags, userId, null); 3530 } 3531 3532 /** 3533 * Version of {@link #createProfileForUser(String, String, int, int)} that allows you to specify 3534 * any packages that should not be installed in the new profile by default, these packages can 3535 * still be installed later by the user if needed. 3536 * 3537 * @param name the user's name 3538 * @param userType the type of user, such as {@link UserManager#USER_TYPE_PROFILE_MANAGED}. 3539 * @param flags UserInfo flags that specify user properties. 3540 * @param userId new user will be a profile of this user. 3541 * @param disallowedPackages packages that will not be installed in the profile being created. 3542 * 3543 * @return the {@link UserInfo} object for the created user, or {@code null} if the user could 3544 * not be created. 3545 * 3546 * @hide 3547 */ 3548 @TestApi 3549 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3550 Manifest.permission.CREATE_USERS}) createProfileForUser(@ullable String name, @NonNull String userType, @UserInfoFlag int flags, @UserIdInt int userId, @Nullable String[] disallowedPackages)3551 public @Nullable UserInfo createProfileForUser(@Nullable String name, @NonNull String userType, 3552 @UserInfoFlag int flags, @UserIdInt int userId, @Nullable String[] disallowedPackages) { 3553 try { 3554 return mService.createProfileForUserWithThrow(name, userType, flags, userId, 3555 disallowedPackages); 3556 } catch (ServiceSpecificException e) { 3557 return null; 3558 } catch (RemoteException re) { 3559 throw re.rethrowFromSystemServer(); 3560 } 3561 } 3562 3563 /** 3564 * Similar to {@link #createProfileForUser(String, String, int, int, String[])} 3565 * except bypassing the checking of {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}. 3566 * 3567 * @see #createProfileForUser(String, String, int, int, String[]) 3568 * @hide 3569 */ 3570 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3571 Manifest.permission.CREATE_USERS}) createProfileForUserEvenWhenDisallowed(String name, @NonNull String userType, @UserInfoFlag int flags, @UserIdInt int userId, String[] disallowedPackages)3572 public UserInfo createProfileForUserEvenWhenDisallowed(String name, 3573 @NonNull String userType, @UserInfoFlag int flags, @UserIdInt int userId, 3574 String[] disallowedPackages) { 3575 try { 3576 return mService.createProfileForUserEvenWhenDisallowedWithThrow(name, userType, flags, 3577 userId, disallowedPackages); 3578 } catch (ServiceSpecificException e) { 3579 return null; 3580 } catch (RemoteException re) { 3581 throw re.rethrowFromSystemServer(); 3582 } 3583 } 3584 3585 /** 3586 * Creates a restricted profile with the specified name. This method also sets necessary 3587 * restrictions and adds shared accounts (with the context user). 3588 * 3589 * @param name profile's name 3590 * @return the {@link UserInfo} object for the created user, or {@code null} if the user 3591 * could not be created. 3592 * 3593 * @hide 3594 */ 3595 @TestApi 3596 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 3597 Manifest.permission.CREATE_USERS}) 3598 @UserHandleAware createRestrictedProfile(@ullable String name)3599 public @Nullable UserInfo createRestrictedProfile(@Nullable String name) { 3600 try { 3601 final int parentUserId = mUserId; 3602 final UserInfo profile = mService.createRestrictedProfileWithThrow(name, parentUserId); 3603 if (profile != null) { 3604 final UserHandle parentUserHandle = UserHandle.of(parentUserId); 3605 AccountManager.get(mContext).addSharedAccountsFromParentUser(parentUserHandle, 3606 UserHandle.of(profile.id)); 3607 } 3608 return profile; 3609 } catch (ServiceSpecificException e) { 3610 return null; 3611 } catch (RemoteException re) { 3612 throw re.rethrowFromSystemServer(); 3613 } 3614 } 3615 3616 /** 3617 * Returns an intent to create a user for the provided name and account name. The name 3618 * and account name will be used when the setup process for the new user is started. 3619 * <p> 3620 * The intent should be launched using startActivityForResult and the return result will 3621 * indicate if the user consented to adding a new user and if the operation succeeded. Any 3622 * errors in creating the user will be returned in the result code. If the user cancels the 3623 * request, the return result will be {@link Activity#RESULT_CANCELED}. On success, the 3624 * result code will be {@link Activity#RESULT_OK}. 3625 * <p> 3626 * Use {@link #supportsMultipleUsers()} to first check if the device supports this operation 3627 * at all. 3628 * <p> 3629 * The new user is created but not initialized. After switching into the user for the first 3630 * time, the preferred user name and account information are used by the setup process for that 3631 * user. 3632 * 3633 * @param userName Optional name to assign to the user. 3634 * @param accountName Optional account name that will be used by the setup wizard to initialize 3635 * the user. 3636 * @param accountType Optional account type for the account to be created. This is required 3637 * if the account name is specified. 3638 * @param accountOptions Optional bundle of data to be passed in during account creation in the 3639 * new user via {@link AccountManager#addAccount(String, String, String[], 3640 * Bundle, android.app.Activity, android.accounts.AccountManagerCallback, 3641 * Handler)}. 3642 * @return An Intent that can be launched from an Activity. 3643 * @see #USER_CREATION_FAILED_NOT_PERMITTED 3644 * @see #USER_CREATION_FAILED_NO_MORE_USERS 3645 * @see #supportsMultipleUsers 3646 */ createUserCreationIntent(@ullable String userName, @Nullable String accountName, @Nullable String accountType, @Nullable PersistableBundle accountOptions)3647 public static Intent createUserCreationIntent(@Nullable String userName, 3648 @Nullable String accountName, 3649 @Nullable String accountType, @Nullable PersistableBundle accountOptions) { 3650 Intent intent = new Intent(ACTION_CREATE_USER); 3651 if (userName != null) { 3652 intent.putExtra(EXTRA_USER_NAME, userName); 3653 } 3654 if (accountName != null && accountType == null) { 3655 throw new IllegalArgumentException("accountType must be specified if accountName is " 3656 + "specified"); 3657 } 3658 if (accountName != null) { 3659 intent.putExtra(EXTRA_USER_ACCOUNT_NAME, accountName); 3660 } 3661 if (accountType != null) { 3662 intent.putExtra(EXTRA_USER_ACCOUNT_TYPE, accountType); 3663 } 3664 if (accountOptions != null) { 3665 intent.putExtra(EXTRA_USER_ACCOUNT_OPTIONS, accountOptions); 3666 } 3667 return intent; 3668 } 3669 3670 /** 3671 * Returns the list of the system packages that would be installed on this type of user upon 3672 * its creation. 3673 * 3674 * Returns {@code null} if all system packages would be installed. 3675 * 3676 * @hide 3677 */ 3678 @TestApi 3679 @SuppressLint("NullableCollection") 3680 @RequiresPermission(anyOf = { 3681 android.Manifest.permission.MANAGE_USERS, 3682 android.Manifest.permission.CREATE_USERS 3683 }) getPreInstallableSystemPackages(@onNull String userType)3684 public @Nullable Set<String> getPreInstallableSystemPackages(@NonNull String userType) { 3685 try { 3686 final String[] installableSystemPackages 3687 = mService.getPreInstallableSystemPackages(userType); 3688 if (installableSystemPackages == null) { 3689 return null; 3690 } 3691 return new ArraySet<>(installableSystemPackages); 3692 } catch (RemoteException re) { 3693 throw re.rethrowFromSystemServer(); 3694 } 3695 } 3696 3697 /** 3698 * @hide 3699 * 3700 * Returns the preferred account name for the context user's creation. 3701 */ 3702 @SystemApi 3703 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) 3704 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) getSeedAccountName()3705 public String getSeedAccountName() { 3706 try { 3707 return mService.getSeedAccountName(getContextUserIfAppropriate()); 3708 } catch (RemoteException re) { 3709 throw re.rethrowFromSystemServer(); 3710 } 3711 } 3712 3713 /** 3714 * @hide 3715 * 3716 * Returns the preferred account type for the context user's creation. 3717 */ 3718 @SystemApi 3719 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) 3720 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) getSeedAccountType()3721 public String getSeedAccountType() { 3722 try { 3723 return mService.getSeedAccountType(getContextUserIfAppropriate()); 3724 } catch (RemoteException re) { 3725 throw re.rethrowFromSystemServer(); 3726 } 3727 } 3728 3729 /** 3730 * @hide 3731 * 3732 * Returns the preferred account's options bundle for user creation. 3733 * @return Any options set by the requestor that created the context user. 3734 */ 3735 @SystemApi 3736 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) 3737 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) getSeedAccountOptions()3738 public PersistableBundle getSeedAccountOptions() { 3739 try { 3740 return mService.getSeedAccountOptions(getContextUserIfAppropriate()); 3741 } catch (RemoteException re) { 3742 throw re.rethrowFromSystemServer(); 3743 } 3744 } 3745 3746 /** 3747 * @hide 3748 * 3749 * Called by a system activity to set the seed account information of a user created 3750 * through the user creation intent. 3751 * @param userId 3752 * @param accountName 3753 * @param accountType 3754 * @param accountOptions 3755 * @see #createUserCreationIntent(String, String, String, PersistableBundle) 3756 */ 3757 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) setSeedAccountData(int userId, String accountName, String accountType, PersistableBundle accountOptions)3758 public void setSeedAccountData(int userId, String accountName, String accountType, 3759 PersistableBundle accountOptions) { 3760 try { 3761 mService.setSeedAccountData(userId, accountName, accountType, accountOptions, 3762 /* persist= */ true); 3763 } catch (RemoteException re) { 3764 throw re.rethrowFromSystemServer(); 3765 } 3766 } 3767 3768 /** 3769 * @hide 3770 * Clears the seed information used to create the context user. 3771 */ 3772 @SystemApi 3773 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) 3774 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) clearSeedAccountData()3775 public void clearSeedAccountData() { 3776 try { 3777 mService.clearSeedAccountData(getContextUserIfAppropriate()); 3778 } catch (RemoteException re) { 3779 throw re.rethrowFromSystemServer(); 3780 } 3781 } 3782 3783 /** 3784 * @hide 3785 * Marks the guest user for deletion to allow a new guest to be created before deleting 3786 * the current user who is a guest. 3787 * @param userId 3788 * @return 3789 */ 3790 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) markGuestForDeletion(@serIdInt int userId)3791 public boolean markGuestForDeletion(@UserIdInt int userId) { 3792 try { 3793 return mService.markGuestForDeletion(userId); 3794 } catch (RemoteException re) { 3795 throw re.rethrowFromSystemServer(); 3796 } 3797 } 3798 3799 /** 3800 * Sets the user as enabled, if such an user exists. 3801 * 3802 * <p>Note that the default is true, it's only that managed profiles might not be enabled. 3803 * Also ephemeral users can be disabled to indicate that their removal is in progress and they 3804 * shouldn't be re-entered. Therefore ephemeral users should not be re-enabled once disabled. 3805 * 3806 * @param userId the id of the profile to enable 3807 * @hide 3808 */ 3809 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) setUserEnabled(@serIdInt int userId)3810 public void setUserEnabled(@UserIdInt int userId) { 3811 try { 3812 mService.setUserEnabled(userId); 3813 } catch (RemoteException re) { 3814 throw re.rethrowFromSystemServer(); 3815 } 3816 } 3817 3818 /** 3819 * Assigns admin privileges to the user, if such a user exists. 3820 * 3821 * <p>Note that this does not alter the user's pre-existing user restrictions. 3822 * 3823 * @param userId the id of the user to become admin 3824 * @hide 3825 */ 3826 @RequiresPermission(allOf = { 3827 Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3828 Manifest.permission.MANAGE_USERS 3829 }) setUserAdmin(@serIdInt int userId)3830 public void setUserAdmin(@UserIdInt int userId) { 3831 try { 3832 mService.setUserAdmin(userId); 3833 } catch (RemoteException re) { 3834 throw re.rethrowFromSystemServer(); 3835 } 3836 } 3837 3838 /** 3839 * Evicts the user's credential encryption key from memory by stopping and restarting the user. 3840 * 3841 * @hide 3842 */ 3843 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) evictCredentialEncryptionKey(@serIdInt int userId)3844 public void evictCredentialEncryptionKey(@UserIdInt int userId) { 3845 try { 3846 mService.evictCredentialEncryptionKey(userId); 3847 } catch (RemoteException re) { 3848 throw re.rethrowFromSystemServer(); 3849 } 3850 } 3851 3852 /** 3853 * Return the number of users currently created on the device. 3854 */ 3855 @RequiresPermission(anyOf = { 3856 android.Manifest.permission.MANAGE_USERS, 3857 android.Manifest.permission.CREATE_USERS 3858 }) getUserCount()3859 public int getUserCount() { 3860 List<UserInfo> users = getUsers(); 3861 return users != null ? users.size() : 1; 3862 } 3863 3864 /** 3865 * Returns information for all fully-created users on this device, including ones marked for 3866 * deletion. 3867 * 3868 * <p>To retrieve only users that are not marked for deletion, use {@link #getAliveUsers()}. 3869 * 3870 * <p>To retrieve *all* users (including partial and pre-created users), use 3871 * {@link #getUsers(boolean, boolean, boolean)) getUsers(false, false, false)}. 3872 * 3873 * <p>To retrieve a more specific list of users, use 3874 * {@link #getUsers(boolean, boolean, boolean)}. 3875 * 3876 * @return the list of users that were created. 3877 * 3878 * @hide 3879 */ 3880 @UnsupportedAppUsage 3881 @RequiresPermission(anyOf = { 3882 android.Manifest.permission.MANAGE_USERS, 3883 android.Manifest.permission.CREATE_USERS 3884 }) getUsers()3885 public List<UserInfo> getUsers() { 3886 return getUsers(/*excludePartial= */ true, /* excludeDying= */ false, 3887 /* excludePreCreated= */ true); 3888 } 3889 3890 /** 3891 * Returns information for all "usable" users on this device (i.e, it excludes users that are 3892 * marked for deletion, pre-created users, etc...). 3893 * 3894 * <p>To retrieve all fully-created users, use {@link #getUsers()}. 3895 * 3896 * <p>To retrieve a more specific list of users, use 3897 * {@link #getUsers(boolean, boolean, boolean)}. 3898 * 3899 * @return the list of users that were created. 3900 * @hide 3901 */ 3902 @RequiresPermission(anyOf = { 3903 android.Manifest.permission.MANAGE_USERS, 3904 android.Manifest.permission.CREATE_USERS 3905 }) getAliveUsers()3906 public @NonNull List<UserInfo> getAliveUsers() { 3907 return getUsers(/*excludePartial= */ true, /* excludeDying= */ true, 3908 /* excludePreCreated= */ true); 3909 } 3910 3911 /** 3912 * @deprecated use {@link #getAliveUsers()} for {@code getUsers(true)}, or 3913 * {@link #getUsers()} for @code getUsers(false)}. 3914 * 3915 * @hide 3916 */ 3917 @Deprecated 3918 @UnsupportedAppUsage 3919 @RequiresPermission(anyOf = { 3920 android.Manifest.permission.MANAGE_USERS, 3921 android.Manifest.permission.CREATE_USERS 3922 }) getUsers(boolean excludeDying)3923 public @NonNull List<UserInfo> getUsers(boolean excludeDying) { 3924 return getUsers(/*excludePartial= */ true, excludeDying, 3925 /* excludePreCreated= */ true); 3926 } 3927 3928 /** 3929 * Returns information for all users on this device, based on the filtering parameters. 3930 * 3931 * @hide 3932 */ 3933 @TestApi 3934 @RequiresPermission(anyOf = { 3935 android.Manifest.permission.MANAGE_USERS, 3936 android.Manifest.permission.CREATE_USERS 3937 }) getUsers(boolean excludePartial, boolean excludeDying, boolean excludePreCreated)3938 public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying, 3939 boolean excludePreCreated) { 3940 try { 3941 return mService.getUsers(excludePartial, excludeDying, excludePreCreated); 3942 } catch (RemoteException re) { 3943 throw re.rethrowFromSystemServer(); 3944 } 3945 } 3946 3947 /** 3948 * Returns the user handles for all users on this device, based on the filtering parameters. 3949 * 3950 * @param excludeDying specify if the list should exclude users being removed. 3951 * @return the list of user handles. 3952 * @hide 3953 */ 3954 @SystemApi 3955 @RequiresPermission(anyOf = { 3956 android.Manifest.permission.MANAGE_USERS, 3957 android.Manifest.permission.CREATE_USERS 3958 }) getUserHandles(boolean excludeDying)3959 public @NonNull List<UserHandle> getUserHandles(boolean excludeDying) { 3960 List<UserInfo> users = getUsers(/* excludePartial= */ true, excludeDying, 3961 /* excludePreCreated= */ true); 3962 List<UserHandle> result = new ArrayList<>(users.size()); 3963 for (UserInfo user : users) { 3964 result.add(user.getUserHandle()); 3965 } 3966 return result; 3967 } 3968 3969 /** 3970 * Returns serial numbers of all users on this device. 3971 * 3972 * @param excludeDying specify if the list should exclude users being removed. 3973 * @return the list of serial numbers of users that exist on the device. 3974 * @hide 3975 */ 3976 @SystemApi 3977 @RequiresPermission(anyOf = { 3978 android.Manifest.permission.MANAGE_USERS, 3979 android.Manifest.permission.CREATE_USERS 3980 }) getSerialNumbersOfUsers(boolean excludeDying)3981 public long[] getSerialNumbersOfUsers(boolean excludeDying) { 3982 List<UserInfo> users = getUsers(/* excludePartial= */ true, excludeDying, 3983 /* excludePreCreated= */ true); 3984 long[] result = new long[users.size()]; 3985 for (int i = 0; i < result.length; i++) { 3986 result[i] = users.get(i).serialNumber; 3987 } 3988 return result; 3989 } 3990 3991 /** 3992 * @return the user's account name, null if not found. 3993 * @hide 3994 */ 3995 @RequiresPermission( allOf = { 3996 Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3997 Manifest.permission.MANAGE_USERS 3998 }) getUserAccount(@serIdInt int userId)3999 public @Nullable String getUserAccount(@UserIdInt int userId) { 4000 try { 4001 return mService.getUserAccount(userId); 4002 } catch (RemoteException re) { 4003 throw re.rethrowFromSystemServer(); 4004 } 4005 } 4006 4007 /** 4008 * Set account name for the given user. 4009 * @hide 4010 */ 4011 @RequiresPermission( allOf = { 4012 Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4013 Manifest.permission.MANAGE_USERS 4014 }) setUserAccount(@serIdInt int userId, @Nullable String accountName)4015 public void setUserAccount(@UserIdInt int userId, @Nullable String accountName) { 4016 try { 4017 mService.setUserAccount(userId, accountName); 4018 } catch (RemoteException re) { 4019 throw re.rethrowFromSystemServer(); 4020 } 4021 } 4022 4023 /** 4024 * Returns information for Primary user. 4025 * 4026 * @return the Primary user, null if not found. 4027 * @hide 4028 */ 4029 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) getPrimaryUser()4030 public @Nullable UserInfo getPrimaryUser() { 4031 try { 4032 return mService.getPrimaryUser(); 4033 } catch (RemoteException re) { 4034 throw re.rethrowFromSystemServer(); 4035 } 4036 } 4037 4038 /** 4039 * Checks whether it's possible to add more users. 4040 * 4041 * @return true if more users can be added, false if limit has been reached. 4042 * 4043 * @deprecated use {@link #canAddMoreUsers(String)} instead. 4044 * 4045 * @hide 4046 */ 4047 @Deprecated 4048 @RequiresPermission(anyOf = { 4049 android.Manifest.permission.MANAGE_USERS, 4050 android.Manifest.permission.CREATE_USERS 4051 }) canAddMoreUsers()4052 public boolean canAddMoreUsers() { 4053 // TODO(b/142482943): UMS has different logic, excluding Demo and Profile from counting. Why 4054 // not here? The logic is inconsistent. See UMS.canAddMoreManagedProfiles 4055 final List<UserInfo> users = getAliveUsers(); 4056 final int totalUserCount = users.size(); 4057 int aliveUserCount = 0; 4058 for (int i = 0; i < totalUserCount; i++) { 4059 UserInfo user = users.get(i); 4060 if (!user.isGuest()) { 4061 aliveUserCount++; 4062 } 4063 } 4064 return aliveUserCount < getMaxSupportedUsers(); 4065 } 4066 4067 /** 4068 * Checks whether it is possible to add more users of the given user type. 4069 * 4070 * @param userType the type of user, such as {@link UserManager#USER_TYPE_FULL_SECONDARY}. 4071 * @return true if more users of the given type can be added, otherwise false. 4072 * @hide 4073 */ 4074 @RequiresPermission(anyOf = { 4075 android.Manifest.permission.MANAGE_USERS, 4076 android.Manifest.permission.CREATE_USERS 4077 }) canAddMoreUsers(@onNull String userType)4078 public boolean canAddMoreUsers(@NonNull String userType) { 4079 try { 4080 return canAddMoreUsers() && mService.canAddMoreUsersOfType(userType); 4081 } catch (RemoteException re) { 4082 throw re.rethrowFromSystemServer(); 4083 } 4084 } 4085 4086 /** 4087 * Returns the remaining number of users of the given type that can be created. 4088 * 4089 * @param userType the type of user, such as {@link UserManager#USER_TYPE_FULL_SECONDARY}. 4090 * @return how many additional users can be created. 4091 * @hide 4092 */ 4093 @SystemApi 4094 @RequiresPermission(anyOf = { 4095 android.Manifest.permission.MANAGE_USERS, 4096 android.Manifest.permission.CREATE_USERS, 4097 android.Manifest.permission.QUERY_USERS 4098 }) getRemainingCreatableUserCount(@onNull String userType)4099 public int getRemainingCreatableUserCount(@NonNull String userType) { 4100 Objects.requireNonNull(userType, "userType must not be null"); 4101 try { 4102 return mService.getRemainingCreatableUserCount(userType); 4103 } catch (RemoteException re) { 4104 throw re.rethrowFromSystemServer(); 4105 } 4106 } 4107 4108 /** 4109 * Returns the remaining number of profiles that can be added to the context user. 4110 * <p>Note that is applicable to any profile type (currently not including Restricted profiles). 4111 * 4112 * @param userType the type of profile, such as {@link UserManager#USER_TYPE_PROFILE_MANAGED}. 4113 * @return how many additional profiles can be created. 4114 * @hide 4115 */ 4116 @SystemApi 4117 @RequiresPermission(anyOf = { 4118 android.Manifest.permission.MANAGE_USERS, 4119 android.Manifest.permission.CREATE_USERS, 4120 android.Manifest.permission.QUERY_USERS 4121 }) 4122 @UserHandleAware getRemainingCreatableProfileCount(@onNull String userType)4123 public int getRemainingCreatableProfileCount(@NonNull String userType) { 4124 Objects.requireNonNull(userType, "userType must not be null"); 4125 try { 4126 // TODO(b/142482943): Perhaps let the following code apply to restricted users too. 4127 return mService.getRemainingCreatableProfileCount(userType, mUserId); 4128 } catch (RemoteException re) { 4129 throw re.rethrowFromSystemServer(); 4130 } 4131 } 4132 4133 /** 4134 * Checks whether it's possible to add more managed profiles. 4135 * if allowedToRemoveOne is true and if the user already has a managed profile, then return if 4136 * we could add a new managed profile to this user after removing the existing one. 4137 * 4138 * @return true if more managed profiles can be added, false if limit has been reached. 4139 * @hide 4140 */ 4141 @RequiresPermission(anyOf = { 4142 android.Manifest.permission.MANAGE_USERS, 4143 android.Manifest.permission.CREATE_USERS, 4144 android.Manifest.permission.QUERY_USERS 4145 }) canAddMoreManagedProfiles(@serIdInt int userId, boolean allowedToRemoveOne)4146 public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) { 4147 try { 4148 return mService.canAddMoreManagedProfiles(userId, allowedToRemoveOne); 4149 } catch (RemoteException re) { 4150 throw re.rethrowFromSystemServer(); 4151 } 4152 } 4153 4154 /** 4155 * Checks whether it's possible to add more profiles of the given type to the given user. 4156 * 4157 * @param userType the type of user, such as {@link UserManager#USER_TYPE_PROFILE_MANAGED}. 4158 * @return true if more profiles can be added, false if limit has been reached. 4159 * @hide 4160 */ 4161 @RequiresPermission(anyOf = { 4162 android.Manifest.permission.MANAGE_USERS, 4163 android.Manifest.permission.CREATE_USERS, 4164 android.Manifest.permission.QUERY_USERS 4165 }) canAddMoreProfilesToUser(@onNull String userType, @UserIdInt int userId)4166 public boolean canAddMoreProfilesToUser(@NonNull String userType, @UserIdInt int userId) { 4167 try { 4168 return mService.canAddMoreProfilesToUser(userType, userId, false); 4169 } catch (RemoteException re) { 4170 throw re.rethrowFromSystemServer(); 4171 } 4172 } 4173 4174 /** 4175 * Checks whether this device supports users of the given user type. 4176 * 4177 * @param userType the type of user, such as {@link UserManager#USER_TYPE_FULL_SECONDARY}. 4178 * @return true if the creation of users of the given user type is enabled on this device. 4179 * @hide 4180 */ 4181 @RequiresPermission(anyOf = { 4182 android.Manifest.permission.MANAGE_USERS, 4183 android.Manifest.permission.CREATE_USERS 4184 }) isUserTypeEnabled(@onNull String userType)4185 public boolean isUserTypeEnabled(@NonNull String userType) { 4186 try { 4187 return mService.isUserTypeEnabled(userType); 4188 } catch (RemoteException re) { 4189 throw re.rethrowFromSystemServer(); 4190 } 4191 } 4192 4193 /** 4194 * Returns list of the profiles of userId including userId itself. 4195 * Note that this returns both enabled and not enabled profiles. See 4196 * {@link #getEnabledProfiles(int)} if you need only the enabled ones. 4197 * <p>Note that this includes all profile types (not including Restricted profiles). 4198 * 4199 * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} or 4200 * {@link android.Manifest.permission#CREATE_USERS} or 4201 * {@link android.Manifest.permission#QUERY_USERS} if userId is not the calling user. 4202 * @param userId profiles of this user will be returned. 4203 * @return the list of profiles. 4204 * @hide 4205 */ 4206 @UnsupportedAppUsage 4207 @RequiresPermission(anyOf = { 4208 Manifest.permission.MANAGE_USERS, 4209 Manifest.permission.CREATE_USERS, 4210 Manifest.permission.QUERY_USERS}, conditional = true) getProfiles(@serIdInt int userId)4211 public List<UserInfo> getProfiles(@UserIdInt int userId) { 4212 try { 4213 return mService.getProfiles(userId, false /* enabledOnly */); 4214 } catch (RemoteException re) { 4215 throw re.rethrowFromSystemServer(); 4216 } 4217 } 4218 4219 /** 4220 * Checks if the 2 provided user handles belong to the same profile group. 4221 * 4222 * @param user one of the two user handles to check. 4223 * @param otherUser one of the two user handles to check. 4224 * @return true if the two users are in the same profile group. 4225 * 4226 * @hide 4227 */ 4228 @SystemApi 4229 @RequiresPermission(anyOf = { 4230 android.Manifest.permission.MANAGE_USERS, 4231 android.Manifest.permission.QUERY_USERS}) isSameProfileGroup(@onNull UserHandle user, @NonNull UserHandle otherUser)4232 public boolean isSameProfileGroup(@NonNull UserHandle user, @NonNull UserHandle otherUser) { 4233 return isSameProfileGroup(user.getIdentifier(), otherUser.getIdentifier()); 4234 } 4235 4236 /** 4237 * Checks if the 2 provided user ids belong to the same profile group. 4238 * @param userId one of the two user ids to check. 4239 * @param otherUserId one of the two user ids to check. 4240 * @return true if the two user ids are in the same profile group. 4241 * @hide 4242 */ 4243 @RequiresPermission(anyOf = { 4244 android.Manifest.permission.MANAGE_USERS, 4245 android.Manifest.permission.QUERY_USERS}) isSameProfileGroup(@serIdInt int userId, int otherUserId)4246 public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) { 4247 try { 4248 return mService.isSameProfileGroup(userId, otherUserId); 4249 } catch (RemoteException re) { 4250 throw re.rethrowFromSystemServer(); 4251 } 4252 } 4253 4254 /** 4255 * Returns list of the profiles of userId including userId itself. 4256 * Note that this returns only enabled. 4257 * <p>Note that this includes all profile types (not including Restricted profiles). 4258 * 4259 * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} or 4260 * {@link android.Manifest.permission#CREATE_USERS} or 4261 * {@link android.Manifest.permission#QUERY_USERS} if userId is not the calling user. 4262 * @param userId profiles of this user will be returned. 4263 * @return the list of profiles. 4264 * @deprecated use {@link #getUserProfiles()} instead. 4265 * 4266 * @hide 4267 */ 4268 @Deprecated 4269 @UnsupportedAppUsage 4270 @RequiresPermission(anyOf = { 4271 Manifest.permission.MANAGE_USERS, 4272 Manifest.permission.CREATE_USERS, 4273 Manifest.permission.QUERY_USERS}, conditional = true) getEnabledProfiles(@serIdInt int userId)4274 public List<UserInfo> getEnabledProfiles(@UserIdInt int userId) { 4275 try { 4276 return mService.getProfiles(userId, true /* enabledOnly */); 4277 } catch (RemoteException re) { 4278 throw re.rethrowFromSystemServer(); 4279 } 4280 } 4281 4282 /** 4283 * Returns a list of UserHandles for profiles associated with the context user, including the 4284 * user itself. 4285 * <p>Note that this includes all profile types (not including Restricted profiles). 4286 * 4287 * @return A non-empty list of UserHandles associated with the context user. 4288 */ 4289 @UserHandleAware( 4290 enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU, 4291 requiresAnyOfPermissionsIfNotCaller = { 4292 Manifest.permission.MANAGE_USERS, 4293 Manifest.permission.CREATE_USERS, 4294 Manifest.permission.QUERY_USERS}) getUserProfiles()4295 public List<UserHandle> getUserProfiles() { 4296 int[] userIds = getProfileIds(getContextUserIfAppropriate(), true /* enabledOnly */); 4297 return convertUserIdsToUserHandles(userIds); 4298 } 4299 4300 /** 4301 * Returns a list of ids for enabled profiles associated with the context user including the 4302 * user itself. 4303 * <p>Note that this includes all profile types (not including Restricted profiles). 4304 * 4305 * @return A non-empty list of UserHandles associated with the context user. 4306 * @hide 4307 */ 4308 @SystemApi 4309 @UserHandleAware( 4310 requiresAnyOfPermissionsIfNotCaller = { 4311 Manifest.permission.MANAGE_USERS, 4312 Manifest.permission.CREATE_USERS, 4313 Manifest.permission.QUERY_USERS}) getEnabledProfiles()4314 public @NonNull List<UserHandle> getEnabledProfiles() { 4315 return getProfiles(true); 4316 } 4317 4318 /** 4319 * Returns a list of ids for all profiles associated with the context user including the user 4320 * itself. 4321 * <p>Note that this includes all profile types (not including Restricted profiles). 4322 * 4323 * @return A non-empty list of UserHandles associated with the context user. 4324 * @hide 4325 */ 4326 @SystemApi 4327 @UserHandleAware( 4328 requiresAnyOfPermissionsIfNotCaller = { 4329 Manifest.permission.MANAGE_USERS, 4330 Manifest.permission.CREATE_USERS, 4331 Manifest.permission.QUERY_USERS}) getAllProfiles()4332 public @NonNull List<UserHandle> getAllProfiles() { 4333 return getProfiles(false); 4334 } 4335 4336 /** 4337 * Returns a list of ids for profiles associated with the context user including the user 4338 * itself. 4339 * <p>Note that this includes all profile types (not including Restricted profiles). 4340 * 4341 * @param enabledOnly whether to return only {@link UserInfo#isEnabled() enabled} profiles 4342 * @return A non-empty list of UserHandles associated with the context user. 4343 */ 4344 @UserHandleAware( 4345 requiresAnyOfPermissionsIfNotCaller = { 4346 Manifest.permission.MANAGE_USERS, 4347 Manifest.permission.CREATE_USERS, 4348 Manifest.permission.QUERY_USERS}) getProfiles(boolean enabledOnly)4349 private @NonNull List<UserHandle> getProfiles(boolean enabledOnly) { 4350 final int[] userIds = getProfileIds(mUserId, enabledOnly); 4351 return convertUserIdsToUserHandles(userIds); 4352 } 4353 4354 /** Converts the given array of userIds to a List of UserHandles. */ convertUserIdsToUserHandles(@onNull int[] userIds)4355 private @NonNull List<UserHandle> convertUserIdsToUserHandles(@NonNull int[] userIds) { 4356 final List<UserHandle> result = new ArrayList<>(userIds.length); 4357 for (int userId : userIds) { 4358 result.add(UserHandle.of(userId)); 4359 } 4360 return result; 4361 } 4362 4363 /** 4364 * Returns a list of ids for profiles associated with the specified user including the user 4365 * itself. 4366 * <p>Note that this includes all profile types (not including Restricted profiles). 4367 * 4368 * @param userId id of the user to return profiles for 4369 * @param enabledOnly whether return only {@link UserInfo#isEnabled() enabled} profiles 4370 * @return A non-empty list of ids of profiles associated with the specified user. 4371 * 4372 * @hide 4373 */ 4374 @RequiresPermission(anyOf = { 4375 Manifest.permission.MANAGE_USERS, 4376 Manifest.permission.CREATE_USERS, 4377 Manifest.permission.QUERY_USERS}, conditional = true) getProfileIds(@serIdInt int userId, boolean enabledOnly)4378 public @NonNull int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) { 4379 try { 4380 return mService.getProfileIds(userId, enabledOnly); 4381 } catch (RemoteException re) { 4382 throw re.rethrowFromSystemServer(); 4383 } 4384 } 4385 4386 /** 4387 * @see #getProfileIds(int, boolean) 4388 * @hide 4389 */ 4390 @UnsupportedAppUsage 4391 @RequiresPermission(anyOf = { 4392 Manifest.permission.MANAGE_USERS, 4393 Manifest.permission.CREATE_USERS, 4394 Manifest.permission.QUERY_USERS}, conditional = true) getProfileIdsWithDisabled(@serIdInt int userId)4395 public int[] getProfileIdsWithDisabled(@UserIdInt int userId) { 4396 return getProfileIds(userId, false /* enabledOnly */); 4397 } 4398 4399 /** 4400 * @see #getProfileIds(int, boolean) 4401 * @hide 4402 */ 4403 @RequiresPermission(anyOf = { 4404 Manifest.permission.MANAGE_USERS, 4405 Manifest.permission.CREATE_USERS, 4406 Manifest.permission.QUERY_USERS}, conditional = true) getEnabledProfileIds(@serIdInt int userId)4407 public int[] getEnabledProfileIds(@UserIdInt int userId) { 4408 return getProfileIds(userId, true /* enabledOnly */); 4409 } 4410 4411 /** 4412 * Returns the device credential owner id of the profile from 4413 * which this method is called, or userId if called from a user that 4414 * is not a profile. 4415 * 4416 * @hide 4417 */ 4418 @RequiresPermission(Manifest.permission.MANAGE_USERS) getCredentialOwnerProfile(@serIdInt int userId)4419 public int getCredentialOwnerProfile(@UserIdInt int userId) { 4420 try { 4421 return mService.getCredentialOwnerProfile(userId); 4422 } catch (RemoteException re) { 4423 throw re.rethrowFromSystemServer(); 4424 } 4425 } 4426 4427 /** 4428 * Returns the parent of the profile which this method is called from 4429 * or null if called from a user that is not a profile. 4430 * 4431 * @hide 4432 */ 4433 @UnsupportedAppUsage 4434 @RequiresPermission(anyOf = { 4435 android.Manifest.permission.MANAGE_USERS, 4436 android.Manifest.permission.INTERACT_ACROSS_USERS 4437 }) getProfileParent(@serIdInt int userId)4438 public UserInfo getProfileParent(@UserIdInt int userId) { 4439 try { 4440 return mService.getProfileParent(userId); 4441 } catch (RemoteException re) { 4442 throw re.rethrowFromSystemServer(); 4443 } 4444 } 4445 4446 /** 4447 * Get the parent of a user profile. 4448 * 4449 * @param user the handle of the user profile 4450 * 4451 * @return the parent of the user or {@code null} if the user is not profile 4452 * 4453 * @hide 4454 */ 4455 @SystemApi 4456 @RequiresPermission(anyOf = { 4457 android.Manifest.permission.MANAGE_USERS, 4458 android.Manifest.permission.INTERACT_ACROSS_USERS 4459 }) getProfileParent(@onNull UserHandle user)4460 public @Nullable UserHandle getProfileParent(@NonNull UserHandle user) { 4461 UserInfo info = getProfileParent(user.getIdentifier()); 4462 4463 if (info == null) { 4464 return null; 4465 } 4466 4467 return UserHandle.of(info.id); 4468 } 4469 4470 /** 4471 * Enables or disables quiet mode for a managed profile. If quiet mode is enabled, apps in a 4472 * managed profile don't run, generate notifications, or consume data or battery. 4473 * <p> 4474 * If a user's credential is needed to turn off quiet mode, a confirm credential screen will be 4475 * shown to the user. 4476 * <p> 4477 * The change may not happen instantly, however apps can listen for 4478 * {@link Intent#ACTION_MANAGED_PROFILE_AVAILABLE} and 4479 * {@link Intent#ACTION_MANAGED_PROFILE_UNAVAILABLE} broadcasts in order to be notified of 4480 * the change of the quiet mode. Apps can also check the current state of quiet mode by 4481 * calling {@link #isQuietModeEnabled(UserHandle)}. 4482 * <p> 4483 * The caller must either be the foreground default launcher or have one of these permissions: 4484 * {@code MANAGE_USERS} or {@code MODIFY_QUIET_MODE}. 4485 * 4486 * @param enableQuietMode whether quiet mode should be enabled or disabled 4487 * @param userHandle user handle of the profile 4488 * @return {@code false} if user's credential is needed in order to turn off quiet mode, 4489 * {@code true} otherwise 4490 * @throws SecurityException if the caller is invalid 4491 * @throws IllegalArgumentException if {@code userHandle} is not a managed profile 4492 * 4493 * @see #isQuietModeEnabled(UserHandle) 4494 */ 4495 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 4496 Manifest.permission.MODIFY_QUIET_MODE}, conditional = true) requestQuietModeEnabled(boolean enableQuietMode, @NonNull UserHandle userHandle)4497 public boolean requestQuietModeEnabled(boolean enableQuietMode, @NonNull UserHandle userHandle) { 4498 return requestQuietModeEnabled(enableQuietMode, userHandle, null); 4499 } 4500 4501 /** 4502 * Perform the same operation as {@link #requestQuietModeEnabled(boolean, UserHandle)}, but 4503 * with a flag to tweak the behavior of the request. 4504 * 4505 * @param enableQuietMode whether quiet mode should be enabled or disabled 4506 * @param userHandle user handle of the profile 4507 * @param flags Can be 0 or {@link #QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED}. 4508 * @return {@code false} if user's credential is needed in order to turn off quiet mode, 4509 * {@code true} otherwise 4510 * @throws SecurityException if the caller is invalid 4511 * @throws IllegalArgumentException if {@code userHandle} is not a managed profile 4512 * 4513 * @see #isQuietModeEnabled(UserHandle) 4514 */ requestQuietModeEnabled(boolean enableQuietMode, @NonNull UserHandle userHandle, @QuietModeFlag int flags)4515 public boolean requestQuietModeEnabled(boolean enableQuietMode, @NonNull UserHandle userHandle, 4516 @QuietModeFlag int flags) { 4517 return requestQuietModeEnabled(enableQuietMode, userHandle, null, flags); 4518 } 4519 4520 /** 4521 * Similar to {@link #requestQuietModeEnabled(boolean, UserHandle)}, except you can specify 4522 * a target to start when user is unlocked. If {@code target} is specified, caller must have 4523 * the {@link android.Manifest.permission#MANAGE_USERS} permission. 4524 * 4525 * @see {@link #requestQuietModeEnabled(boolean, UserHandle)} 4526 * @hide 4527 */ 4528 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) requestQuietModeEnabled( boolean enableQuietMode, @NonNull UserHandle userHandle, IntentSender target)4529 public boolean requestQuietModeEnabled( 4530 boolean enableQuietMode, @NonNull UserHandle userHandle, IntentSender target) { 4531 return requestQuietModeEnabled(enableQuietMode, userHandle, target, 0); 4532 } 4533 4534 /** 4535 * Similar to {@link #requestQuietModeEnabled(boolean, UserHandle)}, except you can specify 4536 * a target to start when user is unlocked. If {@code target} is specified, caller must have 4537 * the {@link android.Manifest.permission#MANAGE_USERS} permission. 4538 * 4539 * @see #requestQuietModeEnabled(boolean, UserHandle) 4540 * @hide 4541 */ requestQuietModeEnabled( boolean enableQuietMode, @NonNull UserHandle userHandle, IntentSender target, int flags)4542 public boolean requestQuietModeEnabled( 4543 boolean enableQuietMode, @NonNull UserHandle userHandle, IntentSender target, 4544 int flags) { 4545 try { 4546 return mService.requestQuietModeEnabled( 4547 mContext.getPackageName(), enableQuietMode, userHandle.getIdentifier(), target, 4548 flags); 4549 } catch (RemoteException re) { 4550 throw re.rethrowFromSystemServer(); 4551 } 4552 } 4553 4554 /** 4555 * Returns whether the given profile is in quiet mode or not. 4556 * Notes: Quiet mode is only supported for managed profiles. 4557 * 4558 * @param userHandle The user handle of the profile to be queried. 4559 * @return true if the profile is in quiet mode, false otherwise. 4560 */ isQuietModeEnabled(UserHandle userHandle)4561 public boolean isQuietModeEnabled(UserHandle userHandle) { 4562 try { 4563 return mService.isQuietModeEnabled(userHandle.getIdentifier()); 4564 } catch (RemoteException re) { 4565 throw re.rethrowFromSystemServer(); 4566 } 4567 } 4568 4569 /** 4570 * Returns whether the given user has a badge (generally to put on profiles' icons). 4571 * 4572 * @param userId userId of the user in question 4573 * @return true if the user's icons should display a badge; false otherwise. 4574 * 4575 * @see #getBadgedIconForUser more information about badging in general 4576 * @hide 4577 */ hasBadge(@serIdInt int userId)4578 public boolean hasBadge(@UserIdInt int userId) { 4579 if (!isProfile(userId)) { 4580 // Since currently only profiles actually have badges, we can do this optimization. 4581 return false; 4582 } 4583 try { 4584 return mService.hasBadge(userId); 4585 } catch (RemoteException re) { 4586 throw re.rethrowFromSystemServer(); 4587 } 4588 } 4589 4590 /** 4591 * Returns whether the user associated with the context has a badge (generally to put on 4592 * profiles' icons). 4593 * 4594 * @return true if the user's icons should display a badge; false otherwise. 4595 * @see #getBadgedIconForUser more information about badging in general 4596 * @hide 4597 */ 4598 @UserHandleAware hasBadge()4599 public boolean hasBadge() { 4600 return hasBadge(mUserId); 4601 } 4602 4603 /** 4604 * Returns the light theme badge color for the given user (generally to color a profile's 4605 * icon's badge). 4606 * 4607 * <p>To check whether a badge color is expected for the user, first call {@link #hasBadge}. 4608 * 4609 * @return the color (not the resource ID) to be used for the user's badge 4610 * @throws Resources.NotFoundException if no valid badge color exists for this user 4611 * 4612 * @see #getBadgedIconForUser more information about badging in general 4613 * @hide 4614 */ getUserBadgeColor(@serIdInt int userId)4615 public @ColorInt int getUserBadgeColor(@UserIdInt int userId) { 4616 try { 4617 final int resourceId = mService.getUserBadgeColorResId(userId); 4618 return Resources.getSystem().getColor(resourceId, null); 4619 } catch (RemoteException re) { 4620 throw re.rethrowFromSystemServer(); 4621 } 4622 } 4623 4624 /** 4625 * Returns the dark theme badge color for the given user (generally to color a profile's icon's 4626 * badge). 4627 * 4628 * <p>To check whether a badge color is expected for the user, first call {@link #hasBadge}. 4629 * 4630 * @return the color (not the resource ID) to be used for the user's badge 4631 * @throws Resources.NotFoundException if no valid badge color exists for this user 4632 * 4633 * @see #getBadgedIconForUser more information about badging in general 4634 * @hide 4635 */ getUserBadgeDarkColor(@serIdInt int userId)4636 public @ColorInt int getUserBadgeDarkColor(@UserIdInt int userId) { 4637 try { 4638 final int resourceId = mService.getUserBadgeDarkColorResId(userId); 4639 return Resources.getSystem().getColor(resourceId, null); 4640 } catch (RemoteException re) { 4641 throw re.rethrowFromSystemServer(); 4642 } 4643 } 4644 4645 /** 4646 * Returns the Resource ID of the user's icon badge. 4647 * 4648 * @return the Resource ID of the user's icon badge if it has one; otherwise 4649 * {@link Resources#ID_NULL}. 4650 * 4651 * @see #getBadgedIconForUser more information about badging in general 4652 * @hide 4653 */ getUserIconBadgeResId(@serIdInt int userId)4654 public @DrawableRes int getUserIconBadgeResId(@UserIdInt int userId) { 4655 try { 4656 return mService.getUserIconBadgeResId(userId); 4657 } catch (RemoteException re) { 4658 throw re.rethrowFromSystemServer(); 4659 } 4660 } 4661 4662 /** 4663 * Returns the Resource ID of the user's badge. 4664 * 4665 * @return the Resource ID of the user's badge if it has one; otherwise 4666 * {@link Resources#ID_NULL}. 4667 * 4668 * @see #getBadgedIconForUser more information about badging in general 4669 * @hide 4670 */ getUserBadgeResId(@serIdInt int userId)4671 public @DrawableRes int getUserBadgeResId(@UserIdInt int userId) { 4672 try { 4673 return mService.getUserBadgeResId(userId); 4674 } catch (RemoteException re) { 4675 throw re.rethrowFromSystemServer(); 4676 } 4677 } 4678 4679 /** 4680 * Returns the Resource ID of the user's badge without a background. 4681 * 4682 * @return the Resource ID of the user's no-background badge if it has one; otherwise 4683 * {@link Resources#ID_NULL}. 4684 * 4685 * @see #getBadgedIconForUser more information about badging in general 4686 * @hide 4687 */ getUserBadgeNoBackgroundResId(@serIdInt int userId)4688 public @DrawableRes int getUserBadgeNoBackgroundResId(@UserIdInt int userId) { 4689 try { 4690 return mService.getUserBadgeNoBackgroundResId(userId); 4691 } catch (RemoteException re) { 4692 throw re.rethrowFromSystemServer(); 4693 } 4694 } 4695 4696 /** 4697 * If the target user is a profile of the calling user or the caller 4698 * is itself a profile, then this returns a badged copy of the given 4699 * icon to be able to distinguish it from the original icon. For badging an 4700 * arbitrary drawable use {@link #getBadgedDrawableForUser( 4701 * android.graphics.drawable.Drawable, UserHandle, android.graphics.Rect, int)}. 4702 * <p> 4703 * If the original drawable is a BitmapDrawable and the backing bitmap is 4704 * mutable as per {@link android.graphics.Bitmap#isMutable()}, the badging 4705 * is performed in place and the original drawable is returned. 4706 * </p> 4707 * 4708 * @param icon The icon to badge. 4709 * @param user The target user. 4710 * @return A drawable that combines the original icon and a badge as 4711 * determined by the system. 4712 * @removed 4713 */ getBadgedIconForUser(Drawable icon, UserHandle user)4714 public Drawable getBadgedIconForUser(Drawable icon, UserHandle user) { 4715 return mContext.getPackageManager().getUserBadgedIcon(icon, user); 4716 } 4717 4718 /** 4719 * If the target user is a profile of the calling user or the caller 4720 * is itself a profile, then this returns a badged copy of the given 4721 * drawable allowing the user to distinguish it from the original drawable. 4722 * The caller can specify the location in the bounds of the drawable to be 4723 * badged where the badge should be applied as well as the density of the 4724 * badge to be used. 4725 * <p> 4726 * If the original drawable is a BitmapDrawable and the backing bitmap is 4727 * mutable as per {@link android.graphics.Bitmap#isMutable()}, the badging 4728 * is performed in place and the original drawable is returned. 4729 * </p> 4730 * 4731 * @param badgedDrawable The drawable to badge. 4732 * @param user The target user. 4733 * @param badgeLocation Where in the bounds of the badged drawable to place 4734 * the badge. If it's {@code null}, the badge is applied on top of the entire 4735 * drawable being badged. 4736 * @param badgeDensity The optional desired density for the badge as per 4737 * {@link android.util.DisplayMetrics#densityDpi}. If it's not positive, 4738 * the density of the display is used. 4739 * @return A drawable that combines the original drawable and a badge as 4740 * determined by the system. 4741 * @removed 4742 */ getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user, Rect badgeLocation, int badgeDensity)4743 public Drawable getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user, 4744 Rect badgeLocation, int badgeDensity) { 4745 return mContext.getPackageManager().getUserBadgedDrawableForDensity(badgedDrawable, user, 4746 badgeLocation, badgeDensity); 4747 } 4748 4749 /** 4750 * If the target user is a profile of the calling user or the caller 4751 * is itself a profile, then this returns a copy of the label with 4752 * badging for accessibility services like talkback. E.g. passing in "Email" 4753 * and it might return "Work Email" for Email in the work profile. 4754 * 4755 * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} or 4756 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS} permission, otherwise the caller 4757 * must be in the same profile group of specified user. 4758 * 4759 * @param label The label to change. 4760 * @param user The target user. 4761 * @return A label that combines the original label and a badge as 4762 * determined by the system. 4763 * @removed 4764 */ getBadgedLabelForUser(CharSequence label, UserHandle user)4765 public CharSequence getBadgedLabelForUser(CharSequence label, UserHandle user) { 4766 final int userId = user.getIdentifier(); 4767 if (!hasBadge(userId)) { 4768 return label; 4769 } 4770 DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class); 4771 return dpm.getResources().getString( 4772 getUpdatableUserBadgedLabelId(userId), 4773 () -> getDefaultUserBadgedLabel(label, userId), 4774 /* formatArgs= */ label); 4775 } 4776 getUpdatableUserBadgedLabelId(int userId)4777 private String getUpdatableUserBadgedLabelId(int userId) { 4778 return isManagedProfile(userId) ? WORK_PROFILE_BADGED_LABEL : UNDEFINED; 4779 } 4780 getDefaultUserBadgedLabel(CharSequence label, int userId)4781 private String getDefaultUserBadgedLabel(CharSequence label, int userId) { 4782 try { 4783 final int resourceId = mService.getUserBadgeLabelResId(userId); 4784 return Resources.getSystem().getString(resourceId, label); 4785 } catch (RemoteException re) { 4786 throw re.rethrowFromSystemServer(); 4787 } 4788 } 4789 4790 /** 4791 * If the user is a {@link UserManager#isProfile profile}, checks if the user 4792 * shares media with its parent user (the user that created this profile). 4793 * Returns false for any other type of user. 4794 * 4795 * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} or 4796 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS} permission, otherwise the 4797 * caller must be in the same profile group as the user. 4798 * 4799 * @return true if the user shares media with its parent user, false otherwise. 4800 * @hide 4801 */ 4802 @SystemApi 4803 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 4804 Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) 4805 @UserHandleAware 4806 @SuppressAutoDoc isMediaSharedWithParent()4807 public boolean isMediaSharedWithParent() { 4808 try { 4809 return mService.isMediaSharedWithParent(mUserId); 4810 } catch (RemoteException re) { 4811 throw re.rethrowFromSystemServer(); 4812 } 4813 } 4814 4815 /** 4816 * Returns whether the user can have shared lockscreen credential with its parent user. 4817 * 4818 * This API only works for {@link UserManager#isProfile() profiles} 4819 * and will always return false for any other user type. 4820 * 4821 * @hide 4822 */ 4823 @SystemApi 4824 @UserHandleAware( 4825 requiresAnyOfPermissionsIfNotCallerProfileGroup = { 4826 Manifest.permission.MANAGE_USERS, 4827 Manifest.permission.INTERACT_ACROSS_USERS}) 4828 @SuppressAutoDoc isCredentialSharableWithParent()4829 public boolean isCredentialSharableWithParent() { 4830 try { 4831 return mService.isCredentialSharableWithParent(mUserId); 4832 } catch (RemoteException re) { 4833 throw re.rethrowFromSystemServer(); 4834 } 4835 } 4836 4837 /** 4838 * Removes a user and all associated data. 4839 * @param userId the integer handle of the user. 4840 * @hide 4841 */ 4842 @UnsupportedAppUsage 4843 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 4844 Manifest.permission.CREATE_USERS}) removeUser(@serIdInt int userId)4845 public boolean removeUser(@UserIdInt int userId) { 4846 try { 4847 return mService.removeUser(userId); 4848 } catch (RemoteException re) { 4849 throw re.rethrowFromSystemServer(); 4850 } 4851 } 4852 4853 /** 4854 * Removes a user and all associated data. 4855 * 4856 * @param user the user that needs to be removed. 4857 * @return {@code true} if the user was successfully removed, {@code false} otherwise. 4858 * @throws IllegalArgumentException if {@code user} is {@code null} 4859 * @hide 4860 */ 4861 @SystemApi 4862 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 4863 Manifest.permission.CREATE_USERS}) removeUser(@onNull UserHandle user)4864 public boolean removeUser(@NonNull UserHandle user) { 4865 if (user == null) { 4866 throw new IllegalArgumentException("user cannot be null"); 4867 } 4868 return removeUser(user.getIdentifier()); 4869 } 4870 4871 4872 /** 4873 * Similar to {@link #removeUser(int)} except bypassing the checking of 4874 * {@link UserManager#DISALLOW_REMOVE_USER} 4875 * or {@link UserManager#DISALLOW_REMOVE_MANAGED_PROFILE}. 4876 * 4877 * @see {@link #removeUser(int)} 4878 * @hide 4879 */ 4880 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 4881 Manifest.permission.CREATE_USERS}) removeUserEvenWhenDisallowed(@serIdInt int userId)4882 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userId) { 4883 try { 4884 return mService.removeUserEvenWhenDisallowed(userId); 4885 } catch (RemoteException re) { 4886 throw re.rethrowFromSystemServer(); 4887 } 4888 } 4889 4890 /** 4891 * Immediately removes the user or, if the user cannot be removed, such as when the user is 4892 * the current user, then set the user as ephemeral so that it will be removed when it is 4893 * stopped. 4894 * 4895 * @param overrideDevicePolicy when {@code true}, user is removed even if the caller has 4896 * the {@link #DISALLOW_REMOVE_USER} or {@link #DISALLOW_REMOVE_MANAGED_PROFILE} restriction 4897 * 4898 * @return the {@link RemoveResult} code: {@link #REMOVE_RESULT_REMOVED}, 4899 * {@link #REMOVE_RESULT_DEFERRED}, {@link #REMOVE_RESULT_ALREADY_BEING_REMOVED}, 4900 * {@link #REMOVE_RESULT_ERROR_USER_RESTRICTION}, {@link #REMOVE_RESULT_ERROR_USER_NOT_FOUND}, 4901 * {@link #REMOVE_RESULT_ERROR_SYSTEM_USER}, or {@link #REMOVE_RESULT_ERROR_UNKNOWN}. All error 4902 * codes have negative values. 4903 * 4904 * @hide 4905 */ 4906 @SystemApi 4907 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 4908 Manifest.permission.CREATE_USERS}) removeUserWhenPossible(@onNull UserHandle user, boolean overrideDevicePolicy)4909 public @RemoveResult int removeUserWhenPossible(@NonNull UserHandle user, 4910 boolean overrideDevicePolicy) { 4911 try { 4912 return mService.removeUserWhenPossible(user.getIdentifier(), overrideDevicePolicy); 4913 } catch (RemoteException re) { 4914 throw re.rethrowFromSystemServer(); 4915 } 4916 } 4917 4918 /** 4919 * Check if {@link #removeUserWhenPossible} returned a success code which means that the user 4920 * has been removed or is slated for removal. 4921 * 4922 * @param result is {@link #RemoveResult} code return by {@link #removeUserWhenPossible}. 4923 * @return {@code true} if it is a success code. 4924 * @hide 4925 */ 4926 @SystemApi isRemoveResultSuccessful(@emoveResult int result)4927 public static boolean isRemoveResultSuccessful(@RemoveResult int result) { 4928 return result >= 0; 4929 } 4930 4931 /** 4932 * Updates the user's name. 4933 * 4934 * @param userId the user's integer id 4935 * @param name the new name for the user 4936 * @hide 4937 */ 4938 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) setUserName(@serIdInt int userId, String name)4939 public void setUserName(@UserIdInt int userId, String name) { 4940 try { 4941 mService.setUserName(userId, name); 4942 } catch (RemoteException re) { 4943 throw re.rethrowFromSystemServer(); 4944 } 4945 } 4946 4947 /** 4948 * Set the user as ephemeral or non-ephemeral. 4949 * 4950 * If the user was initially created as ephemeral then this 4951 * method has no effect and false is returned. 4952 * 4953 * @param userId the user's integer id 4954 * @param enableEphemeral true: change user state to ephemeral, 4955 * false: change user state to non-ephemeral 4956 * @return true: user now has the desired ephemeral state, 4957 * false: desired user ephemeral state could not be set 4958 * 4959 * @hide 4960 */ 4961 @RequiresPermission(anyOf = { 4962 android.Manifest.permission.MANAGE_USERS, 4963 android.Manifest.permission.CREATE_USERS}) setUserEphemeral(@serIdInt int userId, boolean enableEphemeral)4964 public boolean setUserEphemeral(@UserIdInt int userId, boolean enableEphemeral) { 4965 try { 4966 return mService.setUserEphemeral(userId, enableEphemeral); 4967 } catch (RemoteException re) { 4968 throw re.rethrowFromSystemServer(); 4969 } 4970 } 4971 4972 /** 4973 * Updates the context user's name. 4974 * 4975 * @param name the new name for the user 4976 * @hide 4977 */ 4978 @SystemApi 4979 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) 4980 @UserHandleAware setUserName(@ullable String name)4981 public void setUserName(@Nullable String name) { 4982 setUserName(mUserId, name); 4983 } 4984 4985 /** 4986 * Sets the user's photo. 4987 * @param userId the user for whom to change the photo. 4988 * @param icon the bitmap to set as the photo. 4989 * 4990 * @hide 4991 */ 4992 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) setUserIcon(@serIdInt int userId, @NonNull Bitmap icon)4993 public void setUserIcon(@UserIdInt int userId, @NonNull Bitmap icon) { 4994 try { 4995 mService.setUserIcon(userId, icon); 4996 } catch (ServiceSpecificException e) { 4997 return; 4998 } catch (RemoteException re) { 4999 throw re.rethrowFromSystemServer(); 5000 } 5001 } 5002 5003 /** 5004 * Sets the context user's photo. 5005 * 5006 * @param icon the bitmap to set as the photo. 5007 * 5008 * @throws UserOperationException according to the function signature, but may not actually 5009 * throw it in practice. Catch RuntimeException instead. 5010 * 5011 * @hide 5012 */ 5013 @SystemApi 5014 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) 5015 @UserHandleAware setUserIcon(@onNull Bitmap icon)5016 public void setUserIcon(@NonNull Bitmap icon) throws UserOperationException { 5017 setUserIcon(mUserId, icon); 5018 } 5019 5020 /** 5021 * Returns a bitmap of the user's photo 5022 * @param userId the user whose photo we want to read. 5023 * @return a {@link Bitmap} of the user's photo, or null if there's no photo. 5024 * @see com.android.internal.util.UserIcons#getDefaultUserIcon for a default. 5025 * @hide 5026 */ 5027 @UnsupportedAppUsage 5028 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 5029 android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED}) getUserIcon(@serIdInt int userId)5030 public Bitmap getUserIcon(@UserIdInt int userId) { 5031 try { 5032 ParcelFileDescriptor fd = mService.getUserIcon(userId); 5033 if (fd != null) { 5034 try { 5035 return BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor()); 5036 } finally { 5037 try { 5038 fd.close(); 5039 } catch (IOException e) { 5040 } 5041 } 5042 } 5043 } catch (RemoteException re) { 5044 throw re.rethrowFromSystemServer(); 5045 } 5046 return null; 5047 } 5048 5049 /** 5050 * Returns a Bitmap for the context user's photo. 5051 * 5052 * @return a {@link Bitmap} of the user's photo, or null if there's no photo. 5053 * @see com.android.internal.util.UserIcons#getDefaultUserIcon for a default. 5054 * @hide 5055 */ 5056 @SystemApi 5057 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, 5058 android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED}) 5059 @UserHandleAware getUserIcon()5060 public @Nullable Bitmap getUserIcon() { 5061 return getUserIcon(mUserId); 5062 } 5063 5064 /** 5065 * Returns the maximum number of users that can be created on this device. A return value 5066 * of 1 means that it is a single user device. 5067 * @hide 5068 * @return a value greater than or equal to 1 5069 */ 5070 @UnsupportedAppUsage getMaxSupportedUsers()5071 public static int getMaxSupportedUsers() { 5072 // Don't allow multiple users on certain builds 5073 if (android.os.Build.ID.startsWith("JVP")) return 1; 5074 return Math.max(1, SystemProperties.getInt("fw.max_users", 5075 Resources.getSystem().getInteger(R.integer.config_multiuserMaximumUsers))); 5076 } 5077 5078 /** 5079 * Returns true if the user switcher is enabled (regardless of whether there is anything 5080 * interesting for it to show). 5081 * 5082 * @return true if user switcher is enabled 5083 * @hide 5084 */ 5085 @RequiresPermission(anyOf = { 5086 android.Manifest.permission.MANAGE_USERS, 5087 android.Manifest.permission.CREATE_USERS // And INTERACT_ if diff profile group 5088 }) 5089 @UserHandleAware isUserSwitcherEnabled()5090 public boolean isUserSwitcherEnabled() { 5091 return isUserSwitcherEnabled(true); 5092 } 5093 5094 /** 5095 * Returns true if the user switcher should be shown. 5096 * 5097 * @param showEvenIfNotActionable value to return if the feature is enabled but there is nothing 5098 * actionable for the user to do anyway 5099 * @return true if user switcher should be shown. 5100 * @hide 5101 */ 5102 @RequiresPermission(anyOf = { 5103 android.Manifest.permission.MANAGE_USERS, 5104 android.Manifest.permission.CREATE_USERS // And INTERACT_ if diff profile group 5105 }) 5106 @UserHandleAware isUserSwitcherEnabled(boolean showEvenIfNotActionable)5107 public boolean isUserSwitcherEnabled(boolean showEvenIfNotActionable) { 5108 5109 try { 5110 if (!mService.isUserSwitcherEnabled(mUserId)) { 5111 return false; 5112 } 5113 } catch (RemoteException re) { 5114 throw re.rethrowFromSystemServer(); 5115 } 5116 5117 // The feature is enabled. But is it worth showing? 5118 return showEvenIfNotActionable 5119 || areThereUsersToWhichToSwitch() // There are switchable users. 5120 || !hasUserRestrictionForUser(DISALLOW_ADD_USER, mUserId); // New users can be added 5121 } 5122 5123 /** Returns whether there are any users (other than the current user) to which to switch. */ 5124 @RequiresPermission(anyOf = { 5125 android.Manifest.permission.MANAGE_USERS, 5126 android.Manifest.permission.CREATE_USERS 5127 }) areThereUsersToWhichToSwitch()5128 private boolean areThereUsersToWhichToSwitch() { 5129 final List<UserInfo> users = getAliveUsers(); 5130 if (users == null) { 5131 return false; 5132 } 5133 int switchableUserCount = 0; 5134 for (UserInfo user : users) { 5135 if (user.supportsSwitchToByUser()) { 5136 ++switchableUserCount; 5137 } 5138 } 5139 return switchableUserCount > 1; 5140 } 5141 5142 /** 5143 * @hide 5144 */ 5145 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) isDeviceInDemoMode(Context context)5146 public static boolean isDeviceInDemoMode(Context context) { 5147 return Settings.Global.getInt(context.getContentResolver(), 5148 Settings.Global.DEVICE_DEMO_MODE, 0) > 0; 5149 } 5150 5151 /** 5152 * Returns a serial number on this device for a given userId. User handles can be recycled 5153 * when deleting and creating users, but serial numbers are not reused until the device is wiped. 5154 * @param userId 5155 * @return a serial number associated with that user, or -1 if the userId is not valid. 5156 * @hide 5157 */ 5158 @UnsupportedAppUsage getUserSerialNumber(@serIdInt int userId)5159 public int getUserSerialNumber(@UserIdInt int userId) { 5160 try { 5161 return mService.getUserSerialNumber(userId); 5162 } catch (RemoteException re) { 5163 throw re.rethrowFromSystemServer(); 5164 } 5165 } 5166 5167 /** 5168 * Returns a userId on this device for a given user serial number. User handles can be 5169 * recycled when deleting and creating users, but serial numbers are not reused until the device 5170 * is wiped. 5171 * @param userSerialNumber 5172 * @return the userId associated with that user serial number, or -1 if the serial number 5173 * is not valid. 5174 * @hide 5175 */ 5176 @UnsupportedAppUsage getUserHandle(int userSerialNumber)5177 public @UserIdInt int getUserHandle(int userSerialNumber) { 5178 try { 5179 return mService.getUserHandle(userSerialNumber); 5180 } catch (RemoteException re) { 5181 throw re.rethrowFromSystemServer(); 5182 } 5183 } 5184 5185 /** 5186 * Returns a {@link Bundle} containing any saved application restrictions for the context user, 5187 * for the given package name. Only an application with this package name can call this method. 5188 * 5189 * <p>The returned {@link Bundle} consists of key-value pairs, as defined by the application, 5190 * where the types of values may be: 5191 * <ul> 5192 * <li>{@code boolean} 5193 * <li>{@code int} 5194 * <li>{@code String} or {@code String[]} 5195 * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]} 5196 * </ul> 5197 * 5198 * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread 5199 * 5200 * @param packageName the package name of the calling application 5201 * @return a {@link Bundle} with the restrictions for that package, or an empty {@link Bundle} 5202 * if there are no saved restrictions. 5203 * 5204 * @see #KEY_RESTRICTIONS_PENDING 5205 */ 5206 @WorkerThread 5207 @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) getApplicationRestrictions(String packageName)5208 public Bundle getApplicationRestrictions(String packageName) { 5209 try { 5210 return mService.getApplicationRestrictionsForUser(packageName, 5211 getContextUserIfAppropriate()); 5212 } catch (RemoteException re) { 5213 throw re.rethrowFromSystemServer(); 5214 } 5215 } 5216 5217 /** 5218 * @hide 5219 */ 5220 @WorkerThread getApplicationRestrictions(String packageName, UserHandle user)5221 public Bundle getApplicationRestrictions(String packageName, UserHandle user) { 5222 try { 5223 return mService.getApplicationRestrictionsForUser(packageName, user.getIdentifier()); 5224 } catch (RemoteException re) { 5225 throw re.rethrowFromSystemServer(); 5226 } 5227 } 5228 5229 /** 5230 * @hide 5231 */ 5232 @WorkerThread setApplicationRestrictions(String packageName, Bundle restrictions, UserHandle user)5233 public void setApplicationRestrictions(String packageName, Bundle restrictions, 5234 UserHandle user) { 5235 try { 5236 mService.setApplicationRestrictions(packageName, restrictions, user.getIdentifier()); 5237 } catch (RemoteException re) { 5238 throw re.rethrowFromSystemServer(); 5239 } 5240 } 5241 5242 /** 5243 * Sets a new challenge PIN for restrictions. This is only for use by pre-installed 5244 * apps and requires the MANAGE_USERS permission. 5245 * @param newPin the PIN to use for challenge dialogs. 5246 * @return Returns true if the challenge PIN was set successfully. 5247 * @deprecated The restrictions PIN functionality is no longer provided by the system. 5248 * This method is preserved for backwards compatibility reasons and always returns false. 5249 */ 5250 @Deprecated setRestrictionsChallenge(String newPin)5251 public boolean setRestrictionsChallenge(String newPin) { 5252 return false; 5253 } 5254 5255 /** 5256 * @hide 5257 * Set restrictions that should apply to any future guest user that's created. 5258 */ 5259 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) setDefaultGuestRestrictions(Bundle restrictions)5260 public void setDefaultGuestRestrictions(Bundle restrictions) { 5261 try { 5262 mService.setDefaultGuestRestrictions(restrictions); 5263 } catch (RemoteException re) { 5264 throw re.rethrowFromSystemServer(); 5265 } 5266 } 5267 5268 /** 5269 * @hide 5270 * Gets the default guest restrictions. 5271 */ 5272 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) getDefaultGuestRestrictions()5273 public Bundle getDefaultGuestRestrictions() { 5274 try { 5275 return mService.getDefaultGuestRestrictions(); 5276 } catch (RemoteException re) { 5277 throw re.rethrowFromSystemServer(); 5278 } 5279 } 5280 5281 /** 5282 * Returns creation time of the given user. The given user must be the calling user or 5283 * a profile associated with it. 5284 * @param userHandle user handle of the calling user or a profile associated with the 5285 * calling user. 5286 * @return creation time in milliseconds since Epoch time. 5287 */ getUserCreationTime(UserHandle userHandle)5288 public long getUserCreationTime(UserHandle userHandle) { 5289 try { 5290 return mService.getUserCreationTime(userHandle.getIdentifier()); 5291 } catch (RemoteException re) { 5292 throw re.rethrowFromSystemServer(); 5293 } 5294 } 5295 5296 /** 5297 * Checks if any uninitialized user has the specific seed account name and type. 5298 * 5299 * @param accountName The account name to check for 5300 * @param accountType The account type of the account to check for 5301 * @return whether the seed account was found 5302 * @hide 5303 */ 5304 @RequiresPermission(android.Manifest.permission.MANAGE_USERS) someUserHasSeedAccount(String accountName, String accountType)5305 public boolean someUserHasSeedAccount(String accountName, String accountType) { 5306 try { 5307 return mService.someUserHasSeedAccount(accountName, accountType); 5308 } catch (RemoteException re) { 5309 throw re.rethrowFromSystemServer(); 5310 } 5311 } 5312 5313 /** 5314 * Checks if any initialized or uninitialized user has the specific account name and type. 5315 * 5316 * @param accountName The account name to check for 5317 * @param accountType The account type of the account to check for 5318 * @return whether the account was found 5319 * @hide 5320 */ 5321 @SystemApi 5322 @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, 5323 Manifest.permission.CREATE_USERS}) someUserHasAccount( @onNull String accountName, @NonNull String accountType)5324 public boolean someUserHasAccount( 5325 @NonNull String accountName, @NonNull String accountType) { 5326 Objects.requireNonNull(accountName, "accountName must not be null"); 5327 Objects.requireNonNull(accountType, "accountType must not be null"); 5328 5329 try { 5330 return mService.someUserHasAccount(accountName, accountType); 5331 } catch (RemoteException re) { 5332 throw re.rethrowFromSystemServer(); 5333 } 5334 } 5335 5336 /* Cache key for anything that assumes that userIds cannot be re-used without rebooting. */ 5337 private static final String CACHE_KEY_STATIC_USER_PROPERTIES = "cache_key.static_user_props"; 5338 5339 private final PropertyInvalidatedCache<Integer, String> mProfileTypeCache = 5340 new PropertyInvalidatedCache<Integer, String>(32, CACHE_KEY_STATIC_USER_PROPERTIES) { 5341 @Override 5342 public String recompute(Integer query) { 5343 try { 5344 // Will be null (and not cached) if invalid user; otherwise cache the type. 5345 String profileType = mService.getProfileType(query); 5346 if (profileType != null) profileType = profileType.intern(); 5347 return profileType; 5348 } catch (RemoteException re) { 5349 throw re.rethrowFromSystemServer(); 5350 } 5351 } 5352 @Override 5353 public boolean bypass(Integer query) { 5354 return query < 0; 5355 } 5356 }; 5357 5358 /** {@hide} */ invalidateStaticUserProperties()5359 public static final void invalidateStaticUserProperties() { 5360 PropertyInvalidatedCache.invalidateCache(CACHE_KEY_STATIC_USER_PROPERTIES); 5361 } 5362 5363 /** 5364 * @hide 5365 * User that enforces a restriction. 5366 * 5367 * @see #getUserRestrictionSources(String, UserHandle) 5368 */ 5369 @SystemApi 5370 public static final class EnforcingUser implements Parcelable { 5371 private final @UserIdInt int userId; 5372 private final @UserRestrictionSource int userRestrictionSource; 5373 5374 /** 5375 * @hide 5376 */ EnforcingUser( @serIdInt int userId, @UserRestrictionSource int userRestrictionSource)5377 public EnforcingUser( 5378 @UserIdInt int userId, @UserRestrictionSource int userRestrictionSource) { 5379 this.userId = userId; 5380 this.userRestrictionSource = userRestrictionSource; 5381 } 5382 EnforcingUser(Parcel in)5383 private EnforcingUser(Parcel in) { 5384 userId = in.readInt(); 5385 userRestrictionSource = in.readInt(); 5386 } 5387 5388 public static final @android.annotation.NonNull Creator<EnforcingUser> CREATOR = new Creator<EnforcingUser>() { 5389 @Override 5390 public EnforcingUser createFromParcel(Parcel in) { 5391 return new EnforcingUser(in); 5392 } 5393 5394 @Override 5395 public EnforcingUser[] newArray(int size) { 5396 return new EnforcingUser[size]; 5397 } 5398 }; 5399 5400 @Override describeContents()5401 public int describeContents() { 5402 return 0; 5403 } 5404 5405 @Override writeToParcel(Parcel dest, int flags)5406 public void writeToParcel(Parcel dest, int flags) { 5407 dest.writeInt(userId); 5408 dest.writeInt(userRestrictionSource); 5409 } 5410 5411 /** 5412 * Returns an id of the enforcing user. 5413 * 5414 * <p> Will be UserHandle.USER_NULL when restriction is set by the system. 5415 */ getUserHandle()5416 public UserHandle getUserHandle() { 5417 return UserHandle.of(userId); 5418 } 5419 5420 /** 5421 * Returns the status of the enforcing user. 5422 * 5423 * <p> One of {@link #RESTRICTION_SOURCE_SYSTEM}, 5424 * {@link #RESTRICTION_SOURCE_DEVICE_OWNER} and 5425 * {@link #RESTRICTION_SOURCE_PROFILE_OWNER} 5426 */ getUserRestrictionSource()5427 public @UserRestrictionSource int getUserRestrictionSource() { 5428 return userRestrictionSource; 5429 } 5430 } 5431 } 5432