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