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