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 android.Manifest;
20 import android.accounts.AccountManager;
21 import android.annotation.IntDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.RequiresPermission;
25 import android.annotation.SystemApi;
26 import android.annotation.SystemService;
27 import android.annotation.TestApi;
28 import android.annotation.UserIdInt;
29 import android.annotation.WorkerThread;
30 import android.app.Activity;
31 import android.app.ActivityManager;
32 import android.app.admin.DevicePolicyManager;
33 import android.compat.annotation.UnsupportedAppUsage;
34 import android.content.ComponentName;
35 import android.content.Context;
36 import android.content.Intent;
37 import android.content.IntentFilter;
38 import android.content.IntentSender;
39 import android.content.pm.UserInfo;
40 import android.content.pm.UserInfo.UserInfoFlag;
41 import android.content.res.Configuration;
42 import android.content.res.Resources;
43 import android.graphics.Bitmap;
44 import android.graphics.BitmapFactory;
45 import android.graphics.Rect;
46 import android.graphics.drawable.Drawable;
47 import android.provider.Settings;
48 import android.telephony.TelephonyManager;
49 import android.view.WindowManager.LayoutParams;
50 
51 import com.android.internal.R;
52 import com.android.internal.os.RoSystemProperties;
53 
54 import java.io.IOException;
55 import java.lang.annotation.Retention;
56 import java.lang.annotation.RetentionPolicy;
57 import java.util.ArrayList;
58 import java.util.List;
59 
60 /**
61  * Manages users and user details on a multi-user system. There are two major categories of
62  * users: fully customizable users with their own login, and managed profiles that share a workspace
63  * with a related user.
64  * <p>
65  * Users are different from accounts, which are managed by
66  * {@link AccountManager}. Each user can have their own set of accounts.
67  * <p>
68  * See {@link DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE} for more on managed profiles.
69  */
70 @SystemService(Context.USER_SERVICE)
71 public class UserManager {
72 
73     private static final String TAG = "UserManager";
74     @UnsupportedAppUsage
75     private final IUserManager mService;
76     private final Context mContext;
77 
78     private Boolean mIsManagedProfileCached;
79 
80     /**
81      * @hide
82      * No user restriction.
83      */
84     @SystemApi
85     public static final int RESTRICTION_NOT_SET = 0x0;
86 
87     /**
88      * @hide
89      * User restriction set by system/user.
90      */
91     @SystemApi
92     public static final int RESTRICTION_SOURCE_SYSTEM = 0x1;
93 
94     /**
95      * @hide
96      * User restriction set by a device owner.
97      */
98     @SystemApi
99     public static final int RESTRICTION_SOURCE_DEVICE_OWNER = 0x2;
100 
101     /**
102      * @hide
103      * User restriction set by a profile owner.
104      */
105     @SystemApi
106     public static final int RESTRICTION_SOURCE_PROFILE_OWNER = 0x4;
107 
108     /** @hide */
109     @Retention(RetentionPolicy.SOURCE)
110     @IntDef(flag = true, prefix = { "RESTRICTION_" }, value = {
111             RESTRICTION_NOT_SET,
112             RESTRICTION_SOURCE_SYSTEM,
113             RESTRICTION_SOURCE_DEVICE_OWNER,
114             RESTRICTION_SOURCE_PROFILE_OWNER
115     })
116     @SystemApi
117     public @interface UserRestrictionSource {}
118 
119     /**
120      * Specifies if a user is disallowed from adding and removing accounts, unless they are
121      * {@link android.accounts.AccountManager#addAccountExplicitly programmatically} added by
122      * Authenticator.
123      * The default value is <code>false</code>.
124      *
125      * <p>From {@link android.os.Build.VERSION_CODES#N} a profile or device owner app can still
126      * use {@link android.accounts.AccountManager} APIs to add or remove accounts when account
127      * management is disallowed.
128      *
129      * <p>Key for user restrictions.
130      * <p>Type: Boolean
131      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
132      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
133      * @see #getUserRestrictions()
134      */
135     public static final String DISALLOW_MODIFY_ACCOUNTS = "no_modify_accounts";
136 
137     /**
138      * Specifies if a user is disallowed from changing Wi-Fi
139      * access points. The default value is <code>false</code>.
140      * <p>This restriction has no effect in a managed profile.
141      *
142      * <p>Key for user restrictions.
143      * <p>Type: Boolean
144      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
145      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
146      * @see #getUserRestrictions()
147      */
148     public static final String DISALLOW_CONFIG_WIFI = "no_config_wifi";
149 
150     /**
151      * Specifies if a user is disallowed from changing the device
152      * language. The default value is <code>false</code>.
153      *
154      * <p>Key for user restrictions.
155      * <p>Type: Boolean
156      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
157      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
158      * @see #getUserRestrictions()
159      */
160     public static final String DISALLOW_CONFIG_LOCALE = "no_config_locale";
161 
162     /**
163      * Specifies if a user is disallowed from installing applications. This user restriction also
164      * prevents device owners and profile owners installing apps. The default value is
165      * {@code false}.
166      *
167      * <p>Key for user restrictions.
168      * <p>Type: Boolean
169      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
170      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
171      * @see #getUserRestrictions()
172      */
173     public static final String DISALLOW_INSTALL_APPS = "no_install_apps";
174 
175     /**
176      * Specifies if a user is disallowed from uninstalling applications.
177      * The default value is <code>false</code>.
178      *
179      * <p>Key for user restrictions.
180      * <p>Type: Boolean
181      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
182      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
183      * @see #getUserRestrictions()
184      */
185     public static final String DISALLOW_UNINSTALL_APPS = "no_uninstall_apps";
186 
187     /**
188      * Specifies if a user is disallowed from turning on location sharing.
189      * The default value is <code>false</code>.
190      * <p>In a managed profile, location sharing always reflects the primary user's setting, but
191      * can be overridden and forced off by setting this restriction to true in the managed profile.
192      *
193      * <p>Key for user restrictions.
194      * <p>Type: Boolean
195      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
196      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
197      * @see #getUserRestrictions()
198      */
199     public static final String DISALLOW_SHARE_LOCATION = "no_share_location";
200 
201     /**
202      * Specifies if airplane mode is disallowed on the device.
203      *
204      * <p> This restriction can only be set by the device owner and the profile owner on the
205      * primary user and it applies globally - i.e. it disables airplane mode on the entire device.
206      * <p>The default value is <code>false</code>.
207      *
208      * <p>Key for user restrictions.
209      * <p>Type: Boolean
210      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
211      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
212      * @see #getUserRestrictions()
213      */
214     public static final String DISALLOW_AIRPLANE_MODE = "no_airplane_mode";
215 
216     /**
217      * Specifies if a user is disallowed from configuring brightness. When device owner sets it,
218      * it'll only be applied on the target(system) user.
219      *
220      * <p>The default value is <code>false</code>.
221      *
222      * <p>This user restriction has no effect on managed profiles.
223      * <p>Key for user restrictions.
224      * <p>Type: Boolean
225      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
226      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
227      * @see #getUserRestrictions()
228      */
229     public static final String DISALLOW_CONFIG_BRIGHTNESS = "no_config_brightness";
230 
231     /**
232      * Specifies if ambient display is disallowed for the user.
233      *
234      * <p>The default value is <code>false</code>.
235      *
236      * <p>This user restriction has no effect on managed profiles.
237      * <p>Key for user restrictions.
238      * <p>Type: Boolean
239      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
240      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
241      * @see #getUserRestrictions()
242      */
243     public static final String DISALLOW_AMBIENT_DISPLAY = "no_ambient_display";
244 
245     /**
246      * Specifies if a user is disallowed from changing screen off timeout.
247      *
248      * <p>The default value is <code>false</code>.
249      *
250      * <p>This user restriction has no effect on managed profiles.
251      * <p>Key for user restrictions.
252      * <p>Type: Boolean
253      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
254      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
255      * @see #getUserRestrictions()
256      */
257     public static final String DISALLOW_CONFIG_SCREEN_TIMEOUT = "no_config_screen_timeout";
258 
259     /**
260      * Specifies if a user is disallowed from enabling the
261      * "Unknown Sources" setting, that allows installation of apps from unknown sources.
262      * Unknown sources exclude adb and special apps such as trusted app stores.
263      * The default value is <code>false</code>.
264      *
265      * <p>Key for user restrictions.
266      * <p>Type: Boolean
267      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
268      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
269      * @see #getUserRestrictions()
270      */
271     public static final String DISALLOW_INSTALL_UNKNOWN_SOURCES = "no_install_unknown_sources";
272 
273     /**
274      * This restriction is a device-wide version of {@link #DISALLOW_INSTALL_UNKNOWN_SOURCES}.
275      *
276      * Specifies if all users on the device are disallowed from enabling the
277      * "Unknown Sources" setting, that allows installation of apps from unknown sources.
278      *
279      * This restriction can be enabled by the profile owner, in which case all accounts and
280      * profiles will be affected.
281      *
282      * The default value is <code>false</code>.
283      *
284      * <p>Key for user restrictions.
285      * <p>Type: Boolean
286      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
287      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
288      * @see #getUserRestrictions()
289      */
290     public static final String DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY =
291             "no_install_unknown_sources_globally";
292 
293     /**
294      * Specifies if a user is disallowed from configuring bluetooth.
295      * This does <em>not</em> restrict the user from turning bluetooth on or off.
296      * The default value is <code>false</code>.
297      * <p>This restriction doesn't prevent the user from using bluetooth. For disallowing usage of
298      * bluetooth completely on the device, use {@link #DISALLOW_BLUETOOTH}.
299      * <p>This restriction has no effect in a managed profile.
300      *
301      * <p>Key for user restrictions.
302      * <p>Type: Boolean
303      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
304      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
305      * @see #getUserRestrictions()
306      */
307     public static final String DISALLOW_CONFIG_BLUETOOTH = "no_config_bluetooth";
308 
309     /**
310      * Specifies if bluetooth is disallowed on the device.
311      *
312      * <p> This restriction can only be set by the device owner and the profile owner on the
313      * primary user and it applies globally - i.e. it disables bluetooth on the entire device.
314      * <p>The default value is <code>false</code>.
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_BLUETOOTH = "no_bluetooth";
322 
323     /**
324      * Specifies if outgoing bluetooth sharing is disallowed on the device. Device owner and profile
325      * owner can set this restriction. When it is set by device owner, all users on this device will
326      * be affected.
327      *
328      * <p>Default is <code>true</code> for managed profiles and false for otherwise. When a device
329      * upgrades to {@link android.os.Build.VERSION_CODES#O}, the system sets it for all existing
330      * managed profiles.
331      *
332      * <p>Key for user restrictions.
333      * <p>Type: Boolean
334      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
335      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
336      * @see #getUserRestrictions()
337      */
338     public static final String DISALLOW_BLUETOOTH_SHARING = "no_bluetooth_sharing";
339 
340     /**
341      * Specifies if a user is disallowed from transferring files over
342      * USB. This can only be set by device owners and profile owners on the primary user.
343      * The default value is <code>false</code>.
344      *
345      * <p>Key for user restrictions.
346      * <p>Type: Boolean
347      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
348      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
349      * @see #getUserRestrictions()
350      */
351     public static final String DISALLOW_USB_FILE_TRANSFER = "no_usb_file_transfer";
352 
353     /**
354      * Specifies if a user is disallowed from configuring user
355      * credentials. The default value is <code>false</code>.
356      *
357      * <p>Key for user restrictions.
358      * <p>Type: Boolean
359      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
360      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
361      * @see #getUserRestrictions()
362      */
363     public static final String DISALLOW_CONFIG_CREDENTIALS = "no_config_credentials";
364 
365     /**
366      * When set on the primary user this specifies if the user can remove other users.
367      * When set on a secondary user, this specifies if the user can remove itself.
368      * This restriction has no effect on managed profiles.
369      * The default value is <code>false</code>.
370      *
371      * <p>Key for user restrictions.
372      * <p>Type: Boolean
373      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
374      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
375      * @see #getUserRestrictions()
376      */
377     public static final String DISALLOW_REMOVE_USER = "no_remove_user";
378 
379     /**
380      * Specifies if managed profiles of this user can be removed, other than by its profile owner.
381      * The default value is <code>false</code>.
382      * <p>
383      * This restriction has no effect on managed profiles.
384      *
385      * <p>Key for user restrictions.
386      * <p>Type: Boolean
387      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
388      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
389      * @see #getUserRestrictions()
390      */
391     public static final String DISALLOW_REMOVE_MANAGED_PROFILE = "no_remove_managed_profile";
392 
393     /**
394      * Specifies if a user is disallowed from enabling or accessing debugging features. When set on
395      * the primary user, disables debugging features altogether, including USB debugging. When set
396      * on a managed profile or a secondary user, blocks debugging for that user only, including
397      * starting activities, making service calls, accessing content providers, sending broadcasts,
398      * installing/uninstalling packages, clearing user data, etc.
399      * The default value is <code>false</code>.
400      *
401      * <p>Key for user restrictions.
402      * <p>Type: Boolean
403      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
404      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
405      * @see #getUserRestrictions()
406      */
407     public static final String DISALLOW_DEBUGGING_FEATURES = "no_debugging_features";
408 
409     /**
410      * Specifies if a user is disallowed from configuring a VPN. The default value is
411      * <code>false</code>. This restriction has an effect when set by device owners and, in Android
412      * 6.0 ({@linkplain android.os.Build.VERSION_CODES#M API level 23}) or higher, profile owners.
413      * <p>This restriction also prevents VPNs from starting. However, in Android 7.0
414      * ({@linkplain android.os.Build.VERSION_CODES#N API level 24}) or higher, the system does
415      * start always-on VPNs created by the device or profile owner.
416      *
417      * <p>Key for user restrictions.
418      * <p>Type: Boolean
419      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
420      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
421      * @see #getUserRestrictions()
422      */
423     public static final String DISALLOW_CONFIG_VPN = "no_config_vpn";
424 
425     /**
426      * Specifies if a user is disallowed from enabling or disabling location providers. As a
427      * result, user is disallowed from turning on or off location. Device owner and profile owners
428      * can set this restriction and it only applies on the managed user.
429      *
430      * <p>In a managed profile, location sharing is forced off when it's off on primary user, so
431      * user can still turn off location sharing on managed profile when the restriction is set by
432      * profile owner on managed profile.
433      *
434      * <p>This user restriction is different from {@link #DISALLOW_SHARE_LOCATION},
435      * as the device owner or profile owner can still enable or disable location mode via
436      * {@link DevicePolicyManager#setSecureSetting} when this restriction is on.
437      *
438      * <p>The default value is <code>false</code>.
439      *
440      * <p>Key for user restrictions.
441      * <p>Type: Boolean
442      * @see android.location.LocationManager#isProviderEnabled(String)
443      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
444      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
445      * @see #getUserRestrictions()
446      */
447     public static final String DISALLOW_CONFIG_LOCATION = "no_config_location";
448 
449     /**
450      * Specifies if date, time and timezone configuring is disallowed.
451      *
452      * <p>When restriction is set by device owners, it applies globally - i.e., it disables date,
453      * time and timezone setting on the entire device and all users will be affected. When it's set
454      * by profile owners, it's only applied to the managed user.
455      * <p>The default value is <code>false</code>.
456      *
457      * <p>This user restriction has no effect on managed profiles.
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_CONFIG_DATE_TIME = "no_config_date_time";
465 
466     /**
467      * Specifies if a user is disallowed from configuring Tethering
468      * & portable hotspots. This can only be set by device owners and profile owners on the
469      * primary user. The default value is <code>false</code>.
470      * <p>In Android 9.0 or higher, if tethering is enabled when this restriction is set,
471      * tethering will be automatically turned off.
472      *
473      * <p>Key for user restrictions.
474      * <p>Type: Boolean
475      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
476      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
477      * @see #getUserRestrictions()
478      */
479     public static final String DISALLOW_CONFIG_TETHERING = "no_config_tethering";
480 
481     /**
482      * Specifies if a user is disallowed from resetting network settings
483      * from Settings. This can only be set by device owners and profile owners on the primary user.
484      * The default value is <code>false</code>.
485      * <p>This restriction has no effect on secondary users and managed profiles since only the
486      * primary user can reset the network settings of the device.
487      *
488      * <p>Key for user restrictions.
489      * <p>Type: Boolean
490      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
491      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
492      * @see #getUserRestrictions()
493      */
494     public static final String DISALLOW_NETWORK_RESET = "no_network_reset";
495 
496     /**
497      * Specifies if a user is disallowed from factory resetting
498      * from Settings. This can only be set by device owners and profile owners on the primary user.
499      * The default value is <code>false</code>.
500      * <p>This restriction has no effect on secondary users and managed profiles since only the
501      * primary user can factory reset the device.
502      *
503      * <p>Key for user restrictions.
504      * <p>Type: Boolean
505      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
506      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
507      * @see #getUserRestrictions()
508      */
509     public static final String DISALLOW_FACTORY_RESET = "no_factory_reset";
510 
511     /**
512      * Specifies if a user is disallowed from adding new users. This can only be set by device
513      * owners and profile owners on the primary user.
514      * The default value is <code>false</code>.
515      * <p>This restriction has no effect on secondary users and managed profiles since only the
516      * primary user can add other users.
517      *
518      * <p>Key for user restrictions.
519      * <p>Type: Boolean
520      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
521      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
522      * @see #getUserRestrictions()
523      */
524     public static final String DISALLOW_ADD_USER = "no_add_user";
525 
526     /**
527      * Specifies if a user is disallowed from adding managed profiles.
528      * <p>The default value for an unmanaged user is <code>false</code>.
529      * For users with a device owner set, the default is <code>true</code>.
530      * <p>This restriction has no effect on managed profiles.
531      *
532      * <p>Key for user restrictions.
533      * <p>Type: Boolean
534      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
535      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
536      * @see #getUserRestrictions()
537      */
538     public static final String DISALLOW_ADD_MANAGED_PROFILE = "no_add_managed_profile";
539 
540     /**
541      * Specifies if a user is disallowed from disabling application verification. The default
542      * value is <code>false</code>.
543      *
544      * <p>In Android 8.0 ({@linkplain android.os.Build.VERSION_CODES#O API level 26}) and higher,
545      * this is a global user restriction. If a device owner or profile owner sets this restriction,
546      * the system enforces app verification across all users on the device. Running in earlier
547      * Android versions, this restriction affects only the profile that sets it.
548      *
549      * <p>Key for user restrictions.
550      * <p>Type: Boolean
551      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
552      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
553      * @see #getUserRestrictions()
554      */
555     public static final String ENSURE_VERIFY_APPS = "ensure_verify_apps";
556 
557     /**
558      * Specifies if a user is disallowed from configuring cell
559      * broadcasts. This can only be set by device owners and profile owners on the primary user.
560      * The default value is <code>false</code>.
561      * <p>This restriction has no effect on secondary users and managed profiles since only the
562      * primary user can configure cell broadcasts.
563      *
564      * <p>Key for user restrictions.
565      * <p>Type: Boolean
566      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
567      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
568      * @see #getUserRestrictions()
569      */
570     public static final String DISALLOW_CONFIG_CELL_BROADCASTS = "no_config_cell_broadcasts";
571 
572     /**
573      * Specifies if a user is disallowed from configuring mobile
574      * networks. This can only be set by device owners and profile owners on the primary user.
575      * The default value is <code>false</code>.
576      * <p>This restriction has no effect on secondary users and managed profiles since only the
577      * primary user can configure mobile networks.
578      *
579      * <p>Key for user restrictions.
580      * <p>Type: Boolean
581      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
582      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
583      * @see #getUserRestrictions()
584      */
585     public static final String DISALLOW_CONFIG_MOBILE_NETWORKS = "no_config_mobile_networks";
586 
587     /**
588      * Specifies if a user is disallowed from modifying
589      * applications in Settings or launchers. The following actions will not be allowed when this
590      * restriction is enabled:
591      * <li>uninstalling apps</li>
592      * <li>disabling apps</li>
593      * <li>clearing app caches</li>
594      * <li>clearing app data</li>
595      * <li>force stopping apps</li>
596      * <li>clearing app defaults</li>
597      * <p>
598      * The default value is <code>false</code>.
599      *
600      * <p><strong>Note:</strong> The user will still be able to perform those actions via other
601      * means (such as adb). Third party apps will also be able to uninstall apps via the
602      * {@link android.content.pm.PackageInstaller}. {@link #DISALLOW_UNINSTALL_APPS} or
603      * {@link DevicePolicyManager#setUninstallBlocked(ComponentName, String, boolean)} should be
604      * used to prevent the user from uninstalling apps completely, and
605      * {@link DevicePolicyManager#addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}
606      * to add a default intent handler for a given intent filter.
607      *
608      * <p>Key for user restrictions.
609      * <p>Type: Boolean
610      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
611      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
612      * @see #getUserRestrictions()
613      */
614     public static final String DISALLOW_APPS_CONTROL = "no_control_apps";
615 
616     /**
617      * Specifies if a user is disallowed from mounting
618      * physical external media. This can only be set by device owners and profile owners on the
619      * primary user. The default value is <code>false</code>.
620      *
621      * <p>Key for user restrictions.
622      * <p>Type: Boolean
623      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
624      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
625      * @see #getUserRestrictions()
626      */
627     public static final String DISALLOW_MOUNT_PHYSICAL_MEDIA = "no_physical_media";
628 
629     /**
630      * Specifies if a user is disallowed from adjusting microphone volume. If set, the microphone
631      * will be muted. This can be set by device owners and profile owners. The default value is
632      * <code>false</code>.
633      *
634      * <p>This restriction has no effect on managed profiles.
635      * <p>Key for user restrictions.
636      * <p>Type: Boolean
637      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
638      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
639      * @see #getUserRestrictions()
640      */
641     public static final String DISALLOW_UNMUTE_MICROPHONE = "no_unmute_microphone";
642 
643     /**
644      * Specifies if a user is disallowed from adjusting the master volume. If set, the master volume
645      * will be muted. This can be set by device owners from API 21 and profile owners from API 24.
646      * The default value is <code>false</code>.
647      *
648      * <p>When the restriction is set by profile owners, then it only applies to relevant
649      * profiles.
650      *
651      * <p>This restriction has no effect on managed profiles.
652      * <p>Key for user restrictions.
653      * <p>Type: Boolean
654      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
655      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
656      * @see #getUserRestrictions()
657      */
658     public static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume";
659 
660     /**
661      * Specifies that the user is not allowed to make outgoing
662      * phone calls. Emergency calls are still permitted.
663      * The default value is <code>false</code>.
664      * <p>This restriction has no effect on managed profiles.
665      *
666      * <p>Key for user restrictions.
667      * <p>Type: Boolean
668      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
669      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
670      * @see #getUserRestrictions()
671      */
672     public static final String DISALLOW_OUTGOING_CALLS = "no_outgoing_calls";
673 
674     /**
675      * Specifies that the user is not allowed to send or receive
676      * SMS messages. The default value is <code>false</code>.
677      *
678      * <p>Key for user restrictions.
679      * <p>Type: Boolean
680      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
681      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
682      * @see #getUserRestrictions()
683      */
684     public static final String DISALLOW_SMS = "no_sms";
685 
686     /**
687      * Specifies if the user is not allowed to have fun. In some cases, the
688      * device owner may wish to prevent the user from experiencing amusement or
689      * joy while using the device. The default value is <code>false</code>.
690      *
691      * <p>Key for user restrictions.
692      * <p>Type: Boolean
693      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
694      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
695      * @see #getUserRestrictions()
696      */
697     public static final String DISALLOW_FUN = "no_fun";
698 
699     /**
700      * Specifies that windows besides app windows should not be
701      * created. This will block the creation of the following types of windows.
702      * <li>{@link LayoutParams#TYPE_TOAST}</li>
703      * <li>{@link LayoutParams#TYPE_PHONE}</li>
704      * <li>{@link LayoutParams#TYPE_PRIORITY_PHONE}</li>
705      * <li>{@link LayoutParams#TYPE_SYSTEM_ALERT}</li>
706      * <li>{@link LayoutParams#TYPE_SYSTEM_ERROR}</li>
707      * <li>{@link LayoutParams#TYPE_SYSTEM_OVERLAY}</li>
708      * <li>{@link LayoutParams#TYPE_APPLICATION_OVERLAY}</li>
709      *
710      * <p>This can only be set by device owners and profile owners on the primary user.
711      * The default value is <code>false</code>.
712      *
713      * <p>Key for user restrictions.
714      * <p>Type: Boolean
715      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
716      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
717      * @see #getUserRestrictions()
718      */
719     public static final String DISALLOW_CREATE_WINDOWS = "no_create_windows";
720 
721     /**
722      * Specifies that system error dialogs for crashed or unresponsive apps should not be shown.
723      * In this case, the system will force-stop the app as if the user chooses the "close app"
724      * option on the UI. A feedback report isn't collected as there is no way for the user to
725      * provide explicit consent. The default value is <code>false</code>.
726      *
727      * <p>When this user restriction is set by device owners, it's applied to all users. When set by
728      * the profile owner of the primary user or a secondary user, the restriction affects only the
729      * calling user. This user restriction has no effect on managed profiles.
730      *
731      * <p>Key for user restrictions.
732      * <p>Type: Boolean
733      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
734      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
735      * @see #getUserRestrictions()
736      */
737     public static final String DISALLOW_SYSTEM_ERROR_DIALOGS = "no_system_error_dialogs";
738 
739     /**
740      * Specifies if the clipboard contents can be exported by pasting the data into other users or
741      * profiles. This restriction doesn't prevent import, such as someone pasting clipboard data
742      * from other profiles or users. The default value is {@code false}.
743      *
744      * <p><strong>Note</strong>: Because it's possible to extract data from screenshots using
745      * optical character recognition (OCR), we strongly recommend combining this user restriction
746      * with {@link DevicePolicyManager#setScreenCaptureDisabled(ComponentName, boolean)}.
747      *
748      * <p>Key for user restrictions.
749      * <p>Type: Boolean
750      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
751      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
752      * @see #getUserRestrictions()
753      */
754     public static final String DISALLOW_CROSS_PROFILE_COPY_PASTE = "no_cross_profile_copy_paste";
755 
756     /**
757      * Specifies if the user is not allowed to use NFC to beam out data from apps.
758      * The default value is <code>false</code>.
759      *
760      * <p>Key for user restrictions.
761      * <p>Type: Boolean
762      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
763      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
764      * @see #getUserRestrictions()
765      */
766     public static final String DISALLOW_OUTGOING_BEAM = "no_outgoing_beam";
767 
768     /**
769      * Hidden user restriction to disallow access to wallpaper manager APIs. This restriction
770      * generally means that wallpapers are not supported for the particular user. This user
771      * restriction is always set for managed profiles, because such profiles don't have wallpapers.
772      * @hide
773      * @see #DISALLOW_SET_WALLPAPER
774      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
775      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
776      * @see #getUserRestrictions()
777      */
778     public static final String DISALLOW_WALLPAPER = "no_wallpaper";
779 
780     /**
781      * User restriction to disallow setting a wallpaper. Profile owner and device owner
782      * are able to set wallpaper regardless of this restriction.
783      * The default value is <code>false</code>.
784      *
785      * <p>Key for user restrictions.
786      * <p>Type: Boolean
787      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
788      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
789      * @see #getUserRestrictions()
790      */
791     public static final String DISALLOW_SET_WALLPAPER = "no_set_wallpaper";
792 
793     /**
794      * Specifies if the user is not allowed to reboot the device into safe boot mode.
795      * This can only be set by device owners and profile owners on the primary user.
796      * The default value is <code>false</code>.
797      *
798      * <p>Key for user restrictions.
799      * <p>Type: Boolean
800      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
801      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
802      * @see #getUserRestrictions()
803      */
804     public static final String DISALLOW_SAFE_BOOT = "no_safe_boot";
805 
806     /**
807      * Specifies if a user is not allowed to record audio. This restriction is always enabled for
808      * background users. The default value is <code>false</code>.
809      *
810      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
811      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
812      * @see #getUserRestrictions()
813      * @hide
814      */
815     @UnsupportedAppUsage
816     public static final String DISALLOW_RECORD_AUDIO = "no_record_audio";
817 
818     /**
819      * Specifies if a user is not allowed to run in the background and should be stopped during
820      * user switch. The default value is <code>false</code>.
821      *
822      * <p>This restriction can be set by device owners and profile owners.
823      *
824      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
825      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
826      * @see #getUserRestrictions()
827      * @hide
828      */
829     @SystemApi
830     public static final String DISALLOW_RUN_IN_BACKGROUND = "no_run_in_background";
831 
832     /**
833      * Specifies if a user is not allowed to use the camera.
834      *
835      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
836      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
837      * @see #getUserRestrictions()
838      * @hide
839      */
840     public static final String DISALLOW_CAMERA = "no_camera";
841 
842     /**
843      * Specifies if a user is not allowed to unmute the device's master volume.
844      *
845      * @see DevicePolicyManager#setMasterVolumeMuted(ComponentName, boolean)
846      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
847      * @see #getUserRestrictions()
848      * @hide
849      */
850     public static final String DISALLOW_UNMUTE_DEVICE = "disallow_unmute_device";
851 
852     /**
853      * Specifies if a user is not allowed to use cellular data when roaming. This can only be set by
854      * device owners. The default value is <code>false</code>.
855      *
856      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
857      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
858      * @see #getUserRestrictions()
859      */
860     public static final String DISALLOW_DATA_ROAMING = "no_data_roaming";
861 
862     /**
863      * Specifies if a user is not allowed to change their icon. Device owner and profile owner
864      * can set this restriction. When it is set by device owner, only the target user will be
865      * affected. The default value is <code>false</code>.
866      *
867      * <p>Key for user restrictions.
868      * <p>Type: Boolean
869      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
870      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
871      * @see #getUserRestrictions()
872      */
873     public static final String DISALLOW_SET_USER_ICON = "no_set_user_icon";
874 
875     /**
876      * Specifies if a user is not allowed to enable the oem unlock setting. The default value is
877      * <code>false</code>. Setting this restriction has no effect if the bootloader is already
878      * unlocked.
879      *
880      * <p>Not for use by third-party applications.
881      *
882      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
883      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
884      * @see #getUserRestrictions()
885      * @deprecated use {@link OemLockManager#setOemUnlockAllowedByCarrier(boolean, byte[])} instead.
886      * @hide
887      */
888     @Deprecated
889     @SystemApi
890     public static final String DISALLOW_OEM_UNLOCK = "no_oem_unlock";
891 
892     /**
893      * Specifies that the managed profile is not allowed to have unified lock screen challenge with
894      * the primary user.
895      *
896      * <p><strong>Note:</strong> Setting this restriction alone doesn't automatically set a
897      * separate challenge. Profile owner can ask the user to set a new password using
898      * {@link DevicePolicyManager#ACTION_SET_NEW_PASSWORD} and verify it using
899      * {@link DevicePolicyManager#isUsingUnifiedPassword(ComponentName)}.
900      *
901      * <p>Can be set by profile owners. It only has effect on managed profiles when set by managed
902      * profile owner. Has no effect on non-managed profiles or users.
903      * <p>Key for user restrictions.
904      * <p>Type: Boolean
905      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
906      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
907      * @see #getUserRestrictions()
908      */
909     public static final String DISALLOW_UNIFIED_PASSWORD = "no_unified_password";
910 
911     /**
912      * Allows apps in the parent profile to handle web links from the managed profile.
913      *
914      * This user restriction has an effect only in a managed profile.
915      * If set:
916      * Intent filters of activities in the parent profile with action
917      * {@link android.content.Intent#ACTION_VIEW},
918      * category {@link android.content.Intent#CATEGORY_BROWSABLE}, scheme http or https, and which
919      * define a host can handle intents from the managed profile.
920      * The default value is <code>false</code>.
921      *
922      * <p>Key for user restrictions.
923      * <p>Type: Boolean
924      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
925      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
926      * @see #getUserRestrictions()
927      */
928     public static final String ALLOW_PARENT_PROFILE_APP_LINKING
929             = "allow_parent_profile_app_linking";
930 
931     /**
932      * Specifies if a user is not allowed to use Autofill Services.
933      *
934      * <p>Device owner and profile owner can set this restriction. When it is set by device owner,
935      * only the target user will be affected.
936      *
937      * <p>The default value is <code>false</code>.
938      *
939      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
940      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
941      * @see #getUserRestrictions()
942      */
943     public static final String DISALLOW_AUTOFILL = "no_autofill";
944 
945     /**
946      * Specifies if the contents of a user's screen is not allowed to be captured for artificial
947      * intelligence purposes.
948      *
949      * <p>Device owner and profile owner can set this restriction. When it is set by device owner,
950      * only the target user will be affected.
951      *
952      * <p>The default value is <code>false</code>.
953      *
954      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
955      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
956      * @see #getUserRestrictions()
957      */
958     public static final String DISALLOW_CONTENT_CAPTURE = "no_content_capture";
959 
960     /**
961      * Specifies if the current user is able to receive content suggestions for selections based on
962      * the contents of their screen.
963      *
964      * <p>Device owner and profile owner can set this restriction. When it is set by device owner,
965      * only the target user will be affected.
966      *
967      * <p>The default value is <code>false</code>.
968      *
969      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
970      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
971      * @see #getUserRestrictions()
972      */
973     public static final String DISALLOW_CONTENT_SUGGESTIONS = "no_content_suggestions";
974 
975     /**
976      * Specifies if user switching is blocked on the current user.
977      *
978      * <p> This restriction can only be set by the device owner, it will be applied to all users.
979      * Device owner can still switch user via
980      * {@link DevicePolicyManager#switchUser(ComponentName, UserHandle)} when this restriction is
981      * set.
982      *
983      * <p>The default value is <code>false</code>.
984      *
985      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
986      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
987      * @see #getUserRestrictions()
988      */
989     public static final String DISALLOW_USER_SWITCH = "no_user_switch";
990 
991     /**
992      * Specifies whether the user can share file / picture / data from the primary user into the
993      * managed profile, either by sending them from the primary side, or by picking up data within
994      * an app in the managed profile.
995      * <p>
996      * When a managed profile is created, the system allows the user to send data from the primary
997      * side to the profile by setting up certain default cross profile intent filters. If
998      * this is undesired, this restriction can be set to disallow it. Note that this restriction
999      * will not block any sharing allowed by explicit
1000      * {@link DevicePolicyManager#addCrossProfileIntentFilter} calls by the profile owner.
1001      * <p>
1002      * This restriction is only meaningful when set by profile owner. When it is set by device
1003      * owner, it does not have any effect.
1004      * <p>
1005      * The default value is <code>false</code>.
1006      *
1007      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
1008      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
1009      * @see #getUserRestrictions()
1010      */
1011     public static final String DISALLOW_SHARE_INTO_MANAGED_PROFILE = "no_sharing_into_profile";
1012 
1013     /**
1014      * Specifies whether the user is allowed to print.
1015      *
1016      * This restriction can be set by device or profile owner.
1017      *
1018      * The default value is {@code false}.
1019      *
1020      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
1021      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
1022      * @see #getUserRestrictions()
1023      */
1024     public static final String DISALLOW_PRINTING = "no_printing";
1025 
1026     /**
1027      * Specifies whether the user is allowed to modify private DNS settings.
1028      *
1029      * <p>The default value is <code>false</code>.
1030      *
1031      * <p>This user restriction can only be applied by the Device Owner.
1032      * <p>Key for user restrictions.
1033      * <p>Type: Boolean
1034      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
1035      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
1036      * @see #getUserRestrictions()
1037      */
1038     public static final String DISALLOW_CONFIG_PRIVATE_DNS =
1039             "disallow_config_private_dns";
1040 
1041     /**
1042      * Application restriction key that is used to indicate the pending arrival
1043      * of real restrictions for the app.
1044      *
1045      * <p>
1046      * Applications that support restrictions should check for the presence of this key.
1047      * A <code>true</code> value indicates that restrictions may be applied in the near
1048      * future but are not available yet. It is the responsibility of any
1049      * management application that sets this flag to update it when the final
1050      * restrictions are enforced.
1051      *
1052      * <p>Key for application restrictions.
1053      * <p>Type: Boolean
1054      * @see android.app.admin.DevicePolicyManager#setApplicationRestrictions(
1055      *      android.content.ComponentName, String, Bundle)
1056      * @see android.app.admin.DevicePolicyManager#getApplicationRestrictions(
1057      *      android.content.ComponentName, String)
1058      */
1059     public static final String KEY_RESTRICTIONS_PENDING = "restrictions_pending";
1060 
1061     private static final String ACTION_CREATE_USER = "android.os.action.CREATE_USER";
1062 
1063     /**
1064      * Extra containing a name for the user being created. Optional parameter passed to
1065      * ACTION_CREATE_USER activity.
1066      * @hide
1067      */
1068     public static final String EXTRA_USER_NAME = "android.os.extra.USER_NAME";
1069 
1070     /**
1071      * Extra containing account name for the user being created. Optional parameter passed to
1072      * ACTION_CREATE_USER activity.
1073      * @hide
1074      */
1075     public static final String EXTRA_USER_ACCOUNT_NAME = "android.os.extra.USER_ACCOUNT_NAME";
1076 
1077     /**
1078      * Extra containing account type for the user being created. Optional parameter passed to
1079      * ACTION_CREATE_USER activity.
1080      * @hide
1081      */
1082     public static final String EXTRA_USER_ACCOUNT_TYPE = "android.os.extra.USER_ACCOUNT_TYPE";
1083 
1084     /**
1085      * Extra containing account-specific data for the user being created. Optional parameter passed
1086      * to ACTION_CREATE_USER activity.
1087      * @hide
1088      */
1089     public static final String EXTRA_USER_ACCOUNT_OPTIONS
1090             = "android.os.extra.USER_ACCOUNT_OPTIONS";
1091 
1092     /** @hide */
1093     public static final int PIN_VERIFICATION_FAILED_INCORRECT = -3;
1094     /** @hide */
1095     public static final int PIN_VERIFICATION_FAILED_NOT_SET = -2;
1096     /** @hide */
1097     public static final int PIN_VERIFICATION_SUCCESS = -1;
1098 
1099     /**
1100      * Sent when user restrictions have changed.
1101      *
1102      * @hide
1103      */
1104     @SystemApi
1105     @TestApi // To allow seeing it from CTS.
1106     public static final String ACTION_USER_RESTRICTIONS_CHANGED =
1107             "android.os.action.USER_RESTRICTIONS_CHANGED";
1108 
1109     /**
1110      * Error result indicating that this user is not allowed to add other users on this device.
1111      * This is a result code returned from the activity created by the intent
1112      * {@link #createUserCreationIntent(String, String, String, PersistableBundle)}.
1113      */
1114     public static final int USER_CREATION_FAILED_NOT_PERMITTED = Activity.RESULT_FIRST_USER;
1115 
1116     /**
1117      * Error result indicating that no more users can be created on this device.
1118      * This is a result code returned from the activity created by the intent
1119      * {@link #createUserCreationIntent(String, String, String, PersistableBundle)}.
1120      */
1121     public static final int USER_CREATION_FAILED_NO_MORE_USERS = Activity.RESULT_FIRST_USER + 1;
1122 
1123     /**
1124      * Indicates that users are switchable.
1125      * @hide
1126      */
1127     @SystemApi
1128     public static final int SWITCHABILITY_STATUS_OK = 0;
1129 
1130     /**
1131      * Indicated that the user is in a phone call.
1132      * @hide
1133      */
1134     @SystemApi
1135     public static final int SWITCHABILITY_STATUS_USER_IN_CALL = 1 << 0;
1136 
1137     /**
1138      * Indicates that user switching is disallowed ({@link #DISALLOW_USER_SWITCH} is set).
1139      * @hide
1140      */
1141     @SystemApi
1142     public static final int SWITCHABILITY_STATUS_USER_SWITCH_DISALLOWED = 1 << 1;
1143 
1144     /**
1145      * Indicates that the system user is locked and user switching is not allowed.
1146      * @hide
1147      */
1148     @SystemApi
1149     public static final int SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED = 1 << 2;
1150 
1151     /**
1152      * Result returned in {@link #getUserSwitchability()} indicating user swichability.
1153      * @hide
1154      */
1155     @Retention(RetentionPolicy.SOURCE)
1156     @IntDef(flag = true, prefix = { "SWITCHABILITY_STATUS_" }, value = {
1157             SWITCHABILITY_STATUS_OK,
1158             SWITCHABILITY_STATUS_USER_IN_CALL,
1159             SWITCHABILITY_STATUS_USER_SWITCH_DISALLOWED,
1160             SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED
1161     })
1162     public @interface UserSwitchabilityResult {}
1163 
1164     /**
1165      * Indicates user operation is successful.
1166      */
1167     public static final int USER_OPERATION_SUCCESS = 0;
1168 
1169     /**
1170      * Indicates user operation failed for unknown reason.
1171      */
1172     public static final int USER_OPERATION_ERROR_UNKNOWN = 1;
1173 
1174     /**
1175      * Indicates user operation failed because target user is a managed profile.
1176      */
1177     public static final int USER_OPERATION_ERROR_MANAGED_PROFILE = 2;
1178 
1179     /**
1180      * Indicates user operation failed because maximum running user limit has been reached.
1181      */
1182     public static final int USER_OPERATION_ERROR_MAX_RUNNING_USERS = 3;
1183 
1184     /**
1185      * Indicates user operation failed because the target user is in the foreground.
1186      */
1187     public static final int USER_OPERATION_ERROR_CURRENT_USER = 4;
1188 
1189     /**
1190      * Indicates user operation failed because device has low data storage.
1191      */
1192     public static final int USER_OPERATION_ERROR_LOW_STORAGE = 5;
1193 
1194     /**
1195      * Indicates user operation failed because maximum user limit has been reached.
1196      */
1197     public static final int USER_OPERATION_ERROR_MAX_USERS = 6;
1198 
1199     /**
1200      * Result returned from various user operations.
1201      *
1202      * @hide
1203      */
1204     @Retention(RetentionPolicy.SOURCE)
1205     @IntDef(prefix = { "USER_OPERATION_" }, value = {
1206             USER_OPERATION_SUCCESS,
1207             USER_OPERATION_ERROR_UNKNOWN,
1208             USER_OPERATION_ERROR_MANAGED_PROFILE,
1209             USER_OPERATION_ERROR_MAX_RUNNING_USERS,
1210             USER_OPERATION_ERROR_CURRENT_USER,
1211             USER_OPERATION_ERROR_LOW_STORAGE,
1212             USER_OPERATION_ERROR_MAX_USERS
1213     })
1214     public @interface UserOperationResult {}
1215 
1216     /**
1217      * Thrown to indicate user operation failed.
1218      */
1219     public static class UserOperationException extends RuntimeException {
1220         private final @UserOperationResult int mUserOperationResult;
1221 
1222         /**
1223          * Constructs a UserOperationException with specific result code.
1224          *
1225          * @param message the detail message
1226          * @param userOperationResult the result code
1227          * @hide
1228          */
UserOperationException(String message, @UserOperationResult int userOperationResult)1229         public UserOperationException(String message,
1230                 @UserOperationResult int userOperationResult) {
1231             super(message);
1232             mUserOperationResult = userOperationResult;
1233         }
1234 
1235         /**
1236          * Returns the operation result code.
1237          */
getUserOperationResult()1238         public @UserOperationResult int getUserOperationResult() {
1239             return mUserOperationResult;
1240         }
1241     }
1242 
1243     /** @hide */
1244     @UnsupportedAppUsage
get(Context context)1245     public static UserManager get(Context context) {
1246         return (UserManager) context.getSystemService(Context.USER_SERVICE);
1247     }
1248 
1249     /** @hide */
UserManager(Context context, IUserManager service)1250     public UserManager(Context context, IUserManager service) {
1251         mService = service;
1252         mContext = context.getApplicationContext();
1253     }
1254 
1255     /**
1256      * Returns whether this device supports multiple users with their own login and customizable
1257      * space.
1258      * @return whether the device supports multiple users.
1259      */
supportsMultipleUsers()1260     public static boolean supportsMultipleUsers() {
1261         return getMaxSupportedUsers() > 1
1262                 && SystemProperties.getBoolean("fw.show_multiuserui",
1263                 Resources.getSystem().getBoolean(R.bool.config_enableMultiUserUI));
1264     }
1265 
1266     /**
1267      * @hide
1268      * @return Whether the device is running with split system user. It means the system user and
1269      * primary user are two separate users. Previously system user and primary user are combined as
1270      * a single owner user.  see @link {android.os.UserHandle#USER_OWNER}
1271      */
1272     @TestApi
isSplitSystemUser()1273     public static boolean isSplitSystemUser() {
1274         return RoSystemProperties.FW_SYSTEM_USER_SPLIT;
1275     }
1276 
1277     /**
1278      * @hide
1279      * @return Whether the device is running in a headless system user mode. It means the headless
1280      * user (system user) runs system services and system UI, but is not associated with any real
1281      * person. Secondary users can be created to be associated with real person.
1282      */
isHeadlessSystemUserMode()1283     public static boolean isHeadlessSystemUserMode() {
1284         return RoSystemProperties.MULTIUSER_HEADLESS_SYSTEM_USER;
1285     }
1286 
1287     /**
1288      * @return Whether guest user is always ephemeral
1289      * @hide
1290      */
isGuestUserEphemeral()1291     public static boolean isGuestUserEphemeral() {
1292         return Resources.getSystem()
1293                 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
1294     }
1295 
1296     /**
1297      * @deprecated use {@link #getUserSwitchability()} instead.
1298      *
1299      * @removed
1300      * @hide
1301      */
1302     @Deprecated
1303     @UnsupportedAppUsage
canSwitchUsers()1304     public boolean canSwitchUsers() {
1305         boolean allowUserSwitchingWhenSystemUserLocked = Settings.Global.getInt(
1306                 mContext.getContentResolver(),
1307                 Settings.Global.ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED, 0) != 0;
1308         boolean isSystemUserUnlocked = isUserUnlocked(UserHandle.SYSTEM);
1309         boolean inCall = false;
1310         TelephonyManager telephonyManager = mContext.getSystemService(TelephonyManager.class);
1311         if (telephonyManager != null) {
1312             inCall = telephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE;
1313         }
1314         boolean isUserSwitchDisallowed = hasUserRestriction(DISALLOW_USER_SWITCH);
1315         return (allowUserSwitchingWhenSystemUserLocked || isSystemUserUnlocked) && !inCall
1316                 && !isUserSwitchDisallowed;
1317     }
1318 
1319     /**
1320      * Returns whether switching users is currently allowed.
1321      * <p>
1322      * Switching users is not allowed in the following cases:
1323      * <li>the user is in a phone call</li>
1324      * <li>{@link #DISALLOW_USER_SWITCH} is set</li>
1325      * <li>system user hasn't been unlocked yet</li>
1326      *
1327      * @return A {@link UserSwitchabilityResult} flag indicating if the user is switchable.
1328      * @hide
1329      */
1330     @SystemApi
1331     @RequiresPermission(allOf = {Manifest.permission.READ_PHONE_STATE,
1332             android.Manifest.permission.MANAGE_USERS,
1333             android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true)
getUserSwitchability()1334     public @UserSwitchabilityResult int getUserSwitchability() {
1335         final boolean allowUserSwitchingWhenSystemUserLocked = Settings.Global.getInt(
1336                 mContext.getContentResolver(),
1337                 Settings.Global.ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED, 0) != 0;
1338         final boolean systemUserUnlocked = isUserUnlocked(UserHandle.SYSTEM);
1339         final TelephonyManager tm =
1340                 (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
1341 
1342         int flags = SWITCHABILITY_STATUS_OK;
1343         if (tm.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
1344             flags |= SWITCHABILITY_STATUS_USER_IN_CALL;
1345         }
1346         if (hasUserRestriction(DISALLOW_USER_SWITCH)) {
1347             flags |= SWITCHABILITY_STATUS_USER_SWITCH_DISALLOWED;
1348         }
1349         if (!allowUserSwitchingWhenSystemUserLocked && !systemUserUnlocked) {
1350             flags |= SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED;
1351         }
1352         return flags;
1353     }
1354 
1355     /**
1356      * Returns the user handle for the user that this process is running under.
1357      *
1358      * @return the user handle of this process.
1359      * @hide
1360      */
1361     @UnsupportedAppUsage
getUserHandle()1362     public @UserIdInt int getUserHandle() {
1363         return UserHandle.myUserId();
1364     }
1365 
1366     /**
1367      * Returns the user name of the user making this call.  This call is only
1368      * available to applications on the system image; it requires the
1369      * {@code android.permission.MANAGE_USERS} or {@code android.permission.GET_ACCOUNTS_PRIVILEGED}
1370      * permissions.
1371      * @return the user name
1372      */
getUserName()1373     public String getUserName() {
1374         try {
1375             return mService.getUserName();
1376         } catch (RemoteException re) {
1377             throw re.rethrowFromSystemServer();
1378         }
1379     }
1380 
1381     /**
1382      * Returns whether user name has been set.
1383      * <p>This method can be used to check that the value returned by {@link #getUserName()} was
1384      * set by the user and is not a placeholder string provided by the system.
1385      * @hide
1386      */
isUserNameSet()1387     public boolean isUserNameSet() {
1388         try {
1389             return mService.isUserNameSet(getUserHandle());
1390         } catch (RemoteException re) {
1391             throw re.rethrowFromSystemServer();
1392         }
1393     }
1394 
1395     /**
1396      * Used to determine whether the user making this call is subject to
1397      * teleportations.
1398      *
1399      * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
1400      * now automatically identify goats using advanced goat recognition technology.</p>
1401      *
1402      * @return Returns true if the user making this call is a goat.
1403      */
isUserAGoat()1404     public boolean isUserAGoat() {
1405         return mContext.getPackageManager()
1406                 .isPackageAvailable("com.coffeestainstudios.goatsimulator");
1407     }
1408 
1409     /**
1410      * Used to check if this process is running under the primary user. The primary user
1411      * is the first human user on a device.
1412      *
1413      * @return whether this process is running under the primary user.
1414      * @hide
1415      */
1416     @SystemApi
1417     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isPrimaryUser()1418     public boolean isPrimaryUser() {
1419         UserInfo user = getUserInfo(UserHandle.myUserId());
1420         return user != null && user.isPrimary();
1421     }
1422 
1423     /**
1424      * Used to check if this process is running under the system user. The system user
1425      * is the initial user that is implicitly created on first boot and hosts most of the
1426      * system services.
1427      *
1428      * @return whether this process is running under the system user.
1429      */
isSystemUser()1430     public boolean isSystemUser() {
1431         return UserHandle.myUserId() == UserHandle.USER_SYSTEM;
1432     }
1433 
1434     /**
1435      * Used to check if this process is running as an admin user. An admin user is allowed to
1436      * modify or configure certain settings that aren't available to non-admin users,
1437      * create and delete additional users, etc. There can be more than one admin users.
1438      *
1439      * @return whether this process is running under an admin user.
1440      * @hide
1441      */
1442     @SystemApi
1443     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isAdminUser()1444     public boolean isAdminUser() {
1445         return isUserAdmin(UserHandle.myUserId());
1446     }
1447 
1448     /**
1449      * @hide
1450      * Returns whether the provided user is an admin user. There can be more than one admin
1451      * user.
1452      */
1453     @UnsupportedAppUsage
isUserAdmin(@serIdInt int userId)1454     public boolean isUserAdmin(@UserIdInt int userId) {
1455         UserInfo user = getUserInfo(userId);
1456         return user != null && user.isAdmin();
1457     }
1458 
1459     /**
1460      * @hide
1461      * @deprecated Use {@link #isRestrictedProfile()}
1462      */
1463     @UnsupportedAppUsage
1464     @Deprecated
isLinkedUser()1465     public boolean isLinkedUser() {
1466         return isRestrictedProfile();
1467     }
1468 
1469     /**
1470      * Used to check if this process is running under a restricted profile. Restricted profiles
1471      * may have a reduced number of available apps, app restrictions, and account restrictions.
1472      *
1473      * @return whether this process is running under a restricted profile.
1474      * @hide
1475      */
1476     @SystemApi
1477     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isRestrictedProfile()1478     public boolean isRestrictedProfile() {
1479         try {
1480             return mService.isRestricted();
1481         } catch (RemoteException re) {
1482             throw re.rethrowFromSystemServer();
1483         }
1484     }
1485 
1486     /**
1487      * Check if a user is a restricted profile. Restricted profiles may have a reduced number of
1488      * available apps, app restrictions, and account restrictions.
1489      *
1490      * @param user the user to check
1491      * @return whether the user is a restricted profile.
1492      * @hide
1493      */
1494     @SystemApi
1495     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isRestrictedProfile(@onNull UserHandle user)1496     public boolean isRestrictedProfile(@NonNull UserHandle user) {
1497         try {
1498             return mService.getUserInfo(user.getIdentifier()).isRestricted();
1499         } catch (RemoteException re) {
1500             throw re.rethrowFromSystemServer();
1501         }
1502     }
1503 
1504     /**
1505      * Checks if specified user can have restricted profile.
1506      * @hide
1507      */
canHaveRestrictedProfile(@serIdInt int userId)1508     public boolean canHaveRestrictedProfile(@UserIdInt int userId) {
1509         try {
1510             return mService.canHaveRestrictedProfile(userId);
1511         } catch (RemoteException re) {
1512             throw re.rethrowFromSystemServer();
1513         }
1514     }
1515 
1516     /**
1517      * Returns whether the calling user has at least one restricted profile associated with it.
1518      * @return
1519      * @hide
1520      */
1521     @SystemApi
hasRestrictedProfiles()1522     public boolean hasRestrictedProfiles() {
1523         try {
1524             return mService.hasRestrictedProfiles();
1525         } catch (RemoteException re) {
1526             throw re.rethrowFromSystemServer();
1527         }
1528     }
1529 
1530     /**
1531      * Checks if a user is a guest user.
1532      * @return whether user is a guest user.
1533      * @hide
1534      */
1535     @UnsupportedAppUsage
isGuestUser(int id)1536     public boolean isGuestUser(int id) {
1537         UserInfo user = getUserInfo(id);
1538         return user != null && user.isGuest();
1539     }
1540 
1541     /**
1542      * Used to check if this process is running under a guest user. A guest user may be transient.
1543      *
1544      * @return whether this process is running under a guest user.
1545      * @hide
1546      */
1547     @SystemApi
1548     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isGuestUser()1549     public boolean isGuestUser() {
1550         UserInfo user = getUserInfo(UserHandle.myUserId());
1551         return user != null && user.isGuest();
1552     }
1553 
1554 
1555     /**
1556      * Checks if the calling app is running in a demo user. When running in a demo user,
1557      * apps can be more helpful to the user, or explain their features in more detail.
1558      *
1559      * @return whether the caller is a demo user.
1560      */
isDemoUser()1561     public boolean isDemoUser() {
1562         try {
1563             return mService.isDemoUser(UserHandle.myUserId());
1564         } catch (RemoteException re) {
1565             throw re.rethrowFromSystemServer();
1566         }
1567     }
1568 
1569     /**
1570      * Checks if the calling app is running in a managed profile.
1571      *
1572      * @return whether the caller is in a managed profile.
1573      * @hide
1574      */
1575     @SystemApi
1576     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isManagedProfile()1577     public boolean isManagedProfile() {
1578         // No need for synchronization.  Once it becomes non-null, it'll be non-null forever.
1579         // Worst case we might end up calling the AIDL method multiple times but that's fine.
1580         if (mIsManagedProfileCached != null) {
1581             return mIsManagedProfileCached;
1582         }
1583         try {
1584             mIsManagedProfileCached = mService.isManagedProfile(UserHandle.myUserId());
1585             return mIsManagedProfileCached;
1586         } catch (RemoteException re) {
1587             throw re.rethrowFromSystemServer();
1588         }
1589     }
1590 
1591     /**
1592      * Checks if the specified user is a managed profile.
1593      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission, otherwise the caller
1594      * must be in the same profile group of specified user.
1595      *
1596      * @return whether the specified user is a managed profile.
1597      * @hide
1598      */
1599     @SystemApi
1600     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isManagedProfile(@serIdInt int userId)1601     public boolean isManagedProfile(@UserIdInt int userId) {
1602         if (userId == UserHandle.myUserId()) {
1603             return isManagedProfile();
1604         }
1605         try {
1606             return mService.isManagedProfile(userId);
1607         } catch (RemoteException re) {
1608             throw re.rethrowFromSystemServer();
1609         }
1610     }
1611 
1612     /**
1613      * Gets badge for a managed profile.
1614      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission, otherwise the caller
1615      * must be in the same profile group of specified user.
1616      *
1617      * @return which badge to use for the managed profile badge id will be less than
1618      *         UserManagerService.getMaxManagedProfiles()
1619      * @hide
1620      */
getManagedProfileBadge(@serIdInt int userId)1621     public int getManagedProfileBadge(@UserIdInt int userId) {
1622         try {
1623             return mService.getManagedProfileBadge(userId);
1624         } catch (RemoteException re) {
1625             throw re.rethrowFromSystemServer();
1626         }
1627     }
1628 
1629     /**
1630      * Checks if the calling app is running as an ephemeral user.
1631      *
1632      * @return whether the caller is an ephemeral user.
1633      * @hide
1634      */
isEphemeralUser()1635     public boolean isEphemeralUser() {
1636         return isUserEphemeral(UserHandle.myUserId());
1637     }
1638 
1639     /**
1640      * Returns whether the specified user is ephemeral.
1641      * @hide
1642      */
isUserEphemeral(@serIdInt int userId)1643     public boolean isUserEphemeral(@UserIdInt int userId) {
1644         final UserInfo user = getUserInfo(userId);
1645         return user != null && user.isEphemeral();
1646     }
1647 
1648     /**
1649      * Return whether the given user is actively running.  This means that
1650      * the user is in the "started" state, not "stopped" -- it is currently
1651      * allowed to run code through scheduled alarms, receiving broadcasts,
1652      * etc.  A started user may be either the current foreground user or a
1653      * background user; the result here does not distinguish between the two.
1654      *
1655      * <p>Note prior to Android Nougat MR1 (SDK version <= 24;
1656      * {@link android.os.Build.VERSION_CODES#N}, this API required a system permission
1657      * in order to check other profile's status.
1658      * Since Android Nougat MR1 (SDK version >= 25;
1659      * {@link android.os.Build.VERSION_CODES#N_MR1}), the restriction has been relaxed, and now
1660      * it'll accept any {@link android.os.UserHandle} within the same profile group as the caller.
1661      *
1662      * @param user The user to retrieve the running state for.
1663      */
1664     // Note this requires either INTERACT_ACROSS_USERS or MANAGE_USERS.
isUserRunning(UserHandle user)1665     public boolean isUserRunning(UserHandle user) {
1666         return isUserRunning(user.getIdentifier());
1667     }
1668 
1669     /** {@hide} */
isUserRunning(@serIdInt int userId)1670     public boolean isUserRunning(@UserIdInt int userId) {
1671         try {
1672             return mService.isUserRunning(userId);
1673         } catch (RemoteException re) {
1674             throw re.rethrowFromSystemServer();
1675         }
1676     }
1677 
1678     /**
1679      * Return whether the given user is actively running <em>or</em> stopping.
1680      * This is like {@link #isUserRunning(UserHandle)}, but will also return
1681      * true if the user had been running but is in the process of being stopped
1682      * (but is not yet fully stopped, and still running some code).
1683      *
1684      * <p>Note prior to Android Nougat MR1 (SDK version <= 24;
1685      * {@link android.os.Build.VERSION_CODES#N}, this API required a system permission
1686      * in order to check other profile's status.
1687      * Since Android Nougat MR1 (SDK version >= 25;
1688      * {@link android.os.Build.VERSION_CODES#N_MR1}), the restriction has been relaxed, and now
1689      * it'll accept any {@link android.os.UserHandle} within the same profile group as the caller.
1690      *
1691      * @param user The user to retrieve the running state for.
1692      */
1693     // Note this requires either INTERACT_ACROSS_USERS or MANAGE_USERS.
isUserRunningOrStopping(UserHandle user)1694     public boolean isUserRunningOrStopping(UserHandle user) {
1695         try {
1696             // TODO: reconcile stopped vs stopping?
1697             return ActivityManager.getService().isUserRunning(
1698                     user.getIdentifier(), ActivityManager.FLAG_OR_STOPPED);
1699         } catch (RemoteException re) {
1700             throw re.rethrowFromSystemServer();
1701         }
1702     }
1703 
1704     /**
1705      * Return whether the calling user is running in an "unlocked" state.
1706      * <p>
1707      * On devices with direct boot, a user is unlocked only after they've
1708      * entered their credentials (such as a lock pattern or PIN). On devices
1709      * without direct boot, a user is unlocked as soon as it starts.
1710      * <p>
1711      * When a user is locked, only device-protected data storage is available.
1712      * When a user is unlocked, both device-protected and credential-protected
1713      * private app data storage is available.
1714      *
1715      * @see Intent#ACTION_USER_UNLOCKED
1716      * @see Context#createDeviceProtectedStorageContext()
1717      */
isUserUnlocked()1718     public boolean isUserUnlocked() {
1719         return isUserUnlocked(Process.myUserHandle());
1720     }
1721 
1722     /**
1723      * Return whether the given user is running in an "unlocked" state.
1724      * <p>
1725      * On devices with direct boot, a user is unlocked only after they've
1726      * entered their credentials (such as a lock pattern or PIN). On devices
1727      * without direct boot, a user is unlocked as soon as it starts.
1728      * <p>
1729      * When a user is locked, only device-protected data storage is available.
1730      * When a user is unlocked, both device-protected and credential-protected
1731      * private app data storage is available.
1732      * <p>Requires {@code android.permission.MANAGE_USERS} or
1733      * {@code android.permission.INTERACT_ACROSS_USERS}, otherwise specified {@link UserHandle user}
1734      * must be the calling user or a managed profile associated with it.
1735      *
1736      * @param user to retrieve the unlocked state for.
1737      * @see Intent#ACTION_USER_UNLOCKED
1738      * @see Context#createDeviceProtectedStorageContext()
1739      */
isUserUnlocked(UserHandle user)1740     public boolean isUserUnlocked(UserHandle user) {
1741         return isUserUnlocked(user.getIdentifier());
1742     }
1743 
1744     /** {@hide} */
1745     @UnsupportedAppUsage
isUserUnlocked(@serIdInt int userId)1746     public boolean isUserUnlocked(@UserIdInt int userId) {
1747         try {
1748             return mService.isUserUnlocked(userId);
1749         } catch (RemoteException re) {
1750             throw re.rethrowFromSystemServer();
1751         }
1752     }
1753 
1754     /** {@hide} */
isUserUnlockingOrUnlocked(UserHandle user)1755     public boolean isUserUnlockingOrUnlocked(UserHandle user) {
1756         return isUserUnlockingOrUnlocked(user.getIdentifier());
1757     }
1758 
1759     /** {@hide} */
isUserUnlockingOrUnlocked(@serIdInt int userId)1760     public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
1761         try {
1762             return mService.isUserUnlockingOrUnlocked(userId);
1763         } catch (RemoteException re) {
1764             throw re.rethrowFromSystemServer();
1765         }
1766     }
1767 
1768     /**
1769      * Return the time when the calling user started in elapsed milliseconds since boot,
1770      * or 0 if not started.
1771      *
1772      * @hide
1773      */
1774     @UnsupportedAppUsage
getUserStartRealtime()1775     public long getUserStartRealtime() {
1776         try {
1777             return mService.getUserStartRealtime();
1778         } catch (RemoteException re) {
1779             throw re.rethrowFromSystemServer();
1780         }
1781     }
1782 
1783     /**
1784      * Return the time when the calling user was unlocked elapsed milliseconds since boot,
1785      * or 0 if not unlocked.
1786      *
1787      * @hide
1788      */
1789     @UnsupportedAppUsage
getUserUnlockRealtime()1790     public long getUserUnlockRealtime() {
1791         try {
1792             return mService.getUserUnlockRealtime();
1793         } catch (RemoteException re) {
1794             throw re.rethrowFromSystemServer();
1795         }
1796     }
1797 
1798     /**
1799      * Returns the UserInfo object describing a specific user.
1800      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1801      * @param userHandle the user handle of the user whose information is being requested.
1802      * @return the UserInfo object for a specific user.
1803      * @hide
1804      */
1805     @UnsupportedAppUsage
getUserInfo(@serIdInt int userHandle)1806     public UserInfo getUserInfo(@UserIdInt int userHandle) {
1807         try {
1808             return mService.getUserInfo(userHandle);
1809         } catch (RemoteException re) {
1810             throw re.rethrowFromSystemServer();
1811         }
1812     }
1813 
1814     /**
1815      * @hide
1816      *
1817      * Returns who set a user restriction on a user.
1818      * @param restrictionKey the string key representing the restriction
1819      * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1820      * @return The source of user restriction. Any combination of {@link #RESTRICTION_NOT_SET},
1821      *         {@link #RESTRICTION_SOURCE_SYSTEM}, {@link #RESTRICTION_SOURCE_DEVICE_OWNER}
1822      *         and {@link #RESTRICTION_SOURCE_PROFILE_OWNER}
1823      * @deprecated use {@link #getUserRestrictionSources(String, int)} instead.
1824      */
1825     @Deprecated
1826     @SystemApi
1827     @UserRestrictionSource
1828     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getUserRestrictionSource(String restrictionKey, UserHandle userHandle)1829     public int getUserRestrictionSource(String restrictionKey, UserHandle userHandle) {
1830         try {
1831             return mService.getUserRestrictionSource(restrictionKey, userHandle.getIdentifier());
1832         } catch (RemoteException re) {
1833             throw re.rethrowFromSystemServer();
1834         }
1835     }
1836 
1837     /**
1838      * @hide
1839      *
1840      * Returns a list of users who set a user restriction on a given user.
1841      * @param restrictionKey the string key representing the restriction
1842      * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1843      * @return a list of user ids enforcing this restriction.
1844      */
1845     @SystemApi
1846     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getUserRestrictionSources( String restrictionKey, UserHandle userHandle)1847     public List<EnforcingUser> getUserRestrictionSources(
1848             String restrictionKey, UserHandle userHandle) {
1849         try {
1850             return mService.getUserRestrictionSources(restrictionKey, userHandle.getIdentifier());
1851         } catch (RemoteException re) {
1852             throw re.rethrowFromSystemServer();
1853         }
1854     }
1855 
1856     /**
1857      * Returns the user-wide restrictions imposed on this user.
1858      * @return a Bundle containing all the restrictions.
1859      */
getUserRestrictions()1860     public Bundle getUserRestrictions() {
1861         return getUserRestrictions(Process.myUserHandle());
1862     }
1863 
1864     /**
1865      * Returns the user-wide restrictions imposed on the user specified by <code>userHandle</code>.
1866      * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1867      * @return a Bundle containing all the restrictions.
1868      */
getUserRestrictions(UserHandle userHandle)1869     public Bundle getUserRestrictions(UserHandle userHandle) {
1870         try {
1871             return mService.getUserRestrictions(userHandle.getIdentifier());
1872         } catch (RemoteException re) {
1873             throw re.rethrowFromSystemServer();
1874         }
1875     }
1876 
1877      /**
1878      * @hide
1879      * Returns whether the given user has been disallowed from performing certain actions
1880      * or setting certain settings through UserManager (e.g. this type of restriction would prevent
1881      * the guest user from doing certain things, such as making calls). This method disregards
1882      * restrictions set by device policy.
1883      * @param restrictionKey the string key representing the restriction
1884      * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1885      */
1886     @UnsupportedAppUsage
hasBaseUserRestriction(String restrictionKey, UserHandle userHandle)1887     public boolean hasBaseUserRestriction(String restrictionKey, UserHandle userHandle) {
1888         try {
1889             return mService.hasBaseUserRestriction(restrictionKey, userHandle.getIdentifier());
1890         } catch (RemoteException re) {
1891             throw re.rethrowFromSystemServer();
1892         }
1893     }
1894 
1895     /**
1896      * This will no longer work.  Device owners and profile owners should use
1897      * {@link DevicePolicyManager#addUserRestriction(ComponentName, String)} instead.
1898      */
1899     // System apps should use UserManager.setUserRestriction() instead.
1900     @Deprecated
setUserRestrictions(Bundle restrictions)1901     public void setUserRestrictions(Bundle restrictions) {
1902         throw new UnsupportedOperationException("This method is no longer supported");
1903     }
1904 
1905     /**
1906      * This will no longer work.  Device owners and profile owners should use
1907      * {@link DevicePolicyManager#addUserRestriction(ComponentName, String)} instead.
1908      */
1909     // System apps should use UserManager.setUserRestriction() instead.
1910     @Deprecated
setUserRestrictions(Bundle restrictions, UserHandle userHandle)1911     public void setUserRestrictions(Bundle restrictions, UserHandle userHandle) {
1912         throw new UnsupportedOperationException("This method is no longer supported");
1913     }
1914 
1915     /**
1916      * Sets the value of a specific restriction.
1917      * Requires the MANAGE_USERS permission.
1918      * @param key the key of the restriction
1919      * @param value the value for the restriction
1920      * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
1921      * android.content.ComponentName, String)} or
1922      * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
1923      * android.content.ComponentName, String)} instead.
1924      */
1925     @Deprecated
setUserRestriction(String key, boolean value)1926     public void setUserRestriction(String key, boolean value) {
1927         setUserRestriction(key, value, Process.myUserHandle());
1928     }
1929 
1930     /**
1931      * @hide
1932      * Sets the value of a specific restriction on a specific user.
1933      * Requires the MANAGE_USERS permission.
1934      * @param key the key of the restriction
1935      * @param value the value for the restriction
1936      * @param userHandle the user whose restriction is to be changed.
1937      * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
1938      * android.content.ComponentName, String)} or
1939      * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
1940      * android.content.ComponentName, String)} instead.
1941      */
1942     @Deprecated
setUserRestriction(String key, boolean value, UserHandle userHandle)1943     public void setUserRestriction(String key, boolean value, UserHandle userHandle) {
1944         try {
1945             mService.setUserRestriction(key, value, userHandle.getIdentifier());
1946         } catch (RemoteException re) {
1947             throw re.rethrowFromSystemServer();
1948         }
1949     }
1950 
1951     /**
1952      * Returns whether the current user has been disallowed from performing certain actions
1953      * or setting certain settings.
1954      *
1955      * @param restrictionKey The string key representing the restriction.
1956      * @return {@code true} if the current user has the given restriction, {@code false} otherwise.
1957      */
hasUserRestriction(String restrictionKey)1958     public boolean hasUserRestriction(String restrictionKey) {
1959         return hasUserRestriction(restrictionKey, Process.myUserHandle());
1960     }
1961 
1962     /**
1963      * @hide
1964      * Returns whether the given user has been disallowed from performing certain actions
1965      * or setting certain settings.
1966      * @param restrictionKey the string key representing the restriction
1967      * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1968      */
1969     @UnsupportedAppUsage
hasUserRestriction(String restrictionKey, UserHandle userHandle)1970     public boolean hasUserRestriction(String restrictionKey, UserHandle userHandle) {
1971         try {
1972             return mService.hasUserRestriction(restrictionKey,
1973                     userHandle.getIdentifier());
1974         } catch (RemoteException re) {
1975             throw re.rethrowFromSystemServer();
1976         }
1977     }
1978 
1979     /**
1980      * @hide
1981      * Returns whether any user on the device has the given user restriction set.
1982      */
hasUserRestrictionOnAnyUser(String restrictionKey)1983     public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1984         try {
1985             return mService.hasUserRestrictionOnAnyUser(restrictionKey);
1986         } catch (RemoteException re) {
1987             throw re.rethrowFromSystemServer();
1988         }
1989     }
1990 
1991     /**
1992      * Return the serial number for a user.  This is a device-unique
1993      * number assigned to that user; if the user is deleted and then a new
1994      * user created, the new users will not be given the same serial number.
1995      * @param user The user whose serial number is to be retrieved.
1996      * @return The serial number of the given user; returns -1 if the
1997      * given UserHandle does not exist.
1998      * @see #getUserForSerialNumber(long)
1999      */
getSerialNumberForUser(UserHandle user)2000     public long getSerialNumberForUser(UserHandle user) {
2001         return getUserSerialNumber(user.getIdentifier());
2002     }
2003 
2004     /**
2005      * Return the user associated with a serial number previously
2006      * returned by {@link #getSerialNumberForUser(UserHandle)}.
2007      * @param serialNumber The serial number of the user that is being
2008      * retrieved.
2009      * @return Return the user associated with the serial number, or null
2010      * if there is not one.
2011      * @see #getSerialNumberForUser(UserHandle)
2012      */
getUserForSerialNumber(long serialNumber)2013     public UserHandle getUserForSerialNumber(long serialNumber) {
2014         int ident = getUserHandle((int) serialNumber);
2015         return ident >= 0 ? new UserHandle(ident) : null;
2016     }
2017 
2018     /**
2019      * Creates a user with the specified name and options. For non-admin users, default user
2020      * restrictions will be applied.
2021      *
2022      * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2023      *
2024      * @param name the user's name
2025      * @param flags UserInfo flags that identify the type of user and other properties.
2026      * @see UserInfo
2027      *
2028      * @return the UserInfo object for the created user, or {@code null} if the user could not be
2029      * created.
2030      * @hide
2031      */
2032     @UnsupportedAppUsage
createUser(@ullable String name, @UserInfoFlag int flags)2033     public @Nullable UserInfo createUser(@Nullable String name, @UserInfoFlag int flags) {
2034         UserInfo user = null;
2035         try {
2036             user = mService.createUser(name, flags);
2037             // TODO: Keep this in sync with
2038             // UserManagerService.LocalService.createUserEvenWhenDisallowed
2039             if (user != null && !user.isAdmin() && !user.isDemo()) {
2040                 mService.setUserRestriction(DISALLOW_SMS, true, user.id);
2041                 mService.setUserRestriction(DISALLOW_OUTGOING_CALLS, true, user.id);
2042             }
2043         } catch (RemoteException re) {
2044             throw re.rethrowFromSystemServer();
2045         }
2046         return user;
2047     }
2048 
2049     /**
2050      * Pre-creates a user with the specified name and options. For non-admin users, default user
2051      * restrictions will be applied.
2052      *
2053      * <p>This method can be used by OEMs to "warm" up the user creation by pre-creating some users
2054      * at the first boot, so they when the "real" user is created (for example,
2055      * by {@link #createUser(String, int)} or {@link #createGuest(Context, String)}), it takes
2056      * less time.
2057      *
2058      * <p>This method completes the majority of work necessary for user creation: it
2059      * creates user data, CE and DE encryption keys, app data directories, initializes the user and
2060      * grants default permissions. When pre-created users become "real" users, only then are
2061      * components notified of new user creation by firing user creation broadcasts.
2062      *
2063      * <p>All pre-created users are removed during system upgrade.
2064      *
2065      * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2066      *
2067      * @param flags UserInfo flags that identify the type of user and other properties.
2068      * @see UserInfo
2069      *
2070      * @return the UserInfo object for the created user, or {@code null} if the user could not be
2071      * created.
2072      *
2073      * @throw {@link IllegalArgumentException} if {@code flags} contains
2074      * {@link UserInfo#FLAG_MANAGED_PROFILE}.
2075      *
2076      * @hide
2077      */
2078     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
preCreateUser(@serInfoFlag int flags)2079     public @Nullable UserInfo preCreateUser(@UserInfoFlag int flags) {
2080         try {
2081             return mService.preCreateUser(flags);
2082         } catch (RemoteException re) {
2083             throw re.rethrowFromSystemServer();
2084         }
2085     }
2086 
2087     /**
2088      * Creates a guest user and configures it.
2089      * @param context an application context
2090      * @param name the name to set for the user
2091      * @hide
2092      */
createGuest(Context context, String name)2093     public UserInfo createGuest(Context context, String name) {
2094         UserInfo guest = null;
2095         try {
2096             guest = mService.createUser(name, UserInfo.FLAG_GUEST);
2097             if (guest != null) {
2098                 Settings.Secure.putStringForUser(context.getContentResolver(),
2099                         Settings.Secure.SKIP_FIRST_USE_HINTS, "1", guest.id);
2100             }
2101         } catch (RemoteException re) {
2102             throw re.rethrowFromSystemServer();
2103         }
2104         return guest;
2105     }
2106 
2107     /**
2108      * Creates a user with the specified name and options as a profile of another user.
2109      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2110      *
2111      * @param name the user's name
2112      * @param flags flags that identify the type of user and other properties.
2113      * @param userHandle new user will be a profile of this user.
2114      *
2115      * @return the {@link UserInfo} object for the created user, or null if the user
2116      *         could not be created.
2117      * @hide
2118      */
2119     @UnsupportedAppUsage
createProfileForUser(String name, int flags, @UserIdInt int userHandle)2120     public UserInfo createProfileForUser(String name, int flags, @UserIdInt int userHandle) {
2121         return createProfileForUser(name, flags, userHandle, null);
2122     }
2123 
2124     /**
2125      * Version of {@link #createProfileForUser(String, int, int)} that allows you to specify
2126      * any packages that should not be installed in the new profile by default, these packages can
2127      * still be installed later by the user if needed.
2128      *
2129      * @param name the user's name
2130      * @param flags flags that identify the type of user and other properties.
2131      * @param userHandle new user will be a profile of this user.
2132      * @param disallowedPackages packages that will not be installed in the profile being created.
2133      *
2134      * @return the {@link UserInfo} object for the created user, or null if the user
2135      *         could not be created.
2136      * @hide
2137      */
createProfileForUser(String name, int flags, @UserIdInt int userHandle, String[] disallowedPackages)2138     public UserInfo createProfileForUser(String name, int flags, @UserIdInt int userHandle,
2139             String[] disallowedPackages) {
2140         try {
2141             return mService.createProfileForUser(name, flags, userHandle, disallowedPackages);
2142         } catch (RemoteException re) {
2143             throw re.rethrowFromSystemServer();
2144         }
2145     }
2146 
2147     /**
2148      * Similar to {@link #createProfileForUser(String, int, int, String[])}
2149      * except bypassing the checking of {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
2150      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2151      *
2152      * @see #createProfileForUser(String, int, int, String[])
2153      * @hide
2154      */
createProfileForUserEvenWhenDisallowed(String name, int flags, @UserIdInt int userHandle, String[] disallowedPackages)2155     public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags,
2156             @UserIdInt int userHandle, String[] disallowedPackages) {
2157         try {
2158             return mService.createProfileForUserEvenWhenDisallowed(name, flags, userHandle,
2159                     disallowedPackages);
2160         } catch (RemoteException re) {
2161             throw re.rethrowFromSystemServer();
2162         }
2163     }
2164 
2165     /**
2166      * Creates a restricted profile with the specified name. This method also sets necessary
2167      * restrictions and adds shared accounts.
2168      *
2169      * @param name profile's name
2170      * @return UserInfo object for the created user, or null if the user could not be created.
2171      * @hide
2172      */
createRestrictedProfile(String name)2173     public UserInfo createRestrictedProfile(String name) {
2174         try {
2175             UserHandle parentUserHandle = Process.myUserHandle();
2176             UserInfo user = mService.createRestrictedProfile(name,
2177                     parentUserHandle.getIdentifier());
2178             if (user != null) {
2179                 AccountManager.get(mContext).addSharedAccountsFromParentUser(parentUserHandle,
2180                         UserHandle.of(user.id));
2181             }
2182             return user;
2183         } catch (RemoteException re) {
2184             throw re.rethrowFromSystemServer();
2185         }
2186     }
2187 
2188     /**
2189      * Returns an intent to create a user for the provided name and account name. The name
2190      * and account name will be used when the setup process for the new user is started.
2191      * <p>
2192      * The intent should be launched using startActivityForResult and the return result will
2193      * indicate if the user consented to adding a new user and if the operation succeeded. Any
2194      * errors in creating the user will be returned in the result code. If the user cancels the
2195      * request, the return result will be {@link Activity#RESULT_CANCELED}. On success, the
2196      * result code will be {@link Activity#RESULT_OK}.
2197      * <p>
2198      * Use {@link #supportsMultipleUsers()} to first check if the device supports this operation
2199      * at all.
2200      * <p>
2201      * The new user is created but not initialized. After switching into the user for the first
2202      * time, the preferred user name and account information are used by the setup process for that
2203      * user.
2204      *
2205      * @param userName Optional name to assign to the user.
2206      * @param accountName Optional account name that will be used by the setup wizard to initialize
2207      *                    the user.
2208      * @param accountType Optional account type for the account to be created. This is required
2209      *                    if the account name is specified.
2210      * @param accountOptions Optional bundle of data to be passed in during account creation in the
2211      *                       new user via {@link AccountManager#addAccount(String, String, String[],
2212      *                       Bundle, android.app.Activity, android.accounts.AccountManagerCallback,
2213      *                       Handler)}.
2214      * @return An Intent that can be launched from an Activity.
2215      * @see #USER_CREATION_FAILED_NOT_PERMITTED
2216      * @see #USER_CREATION_FAILED_NO_MORE_USERS
2217      * @see #supportsMultipleUsers
2218      */
createUserCreationIntent(@ullable String userName, @Nullable String accountName, @Nullable String accountType, @Nullable PersistableBundle accountOptions)2219     public static Intent createUserCreationIntent(@Nullable String userName,
2220             @Nullable String accountName,
2221             @Nullable String accountType, @Nullable PersistableBundle accountOptions) {
2222         Intent intent = new Intent(ACTION_CREATE_USER);
2223         if (userName != null) {
2224             intent.putExtra(EXTRA_USER_NAME, userName);
2225         }
2226         if (accountName != null && accountType == null) {
2227             throw new IllegalArgumentException("accountType must be specified if accountName is "
2228                     + "specified");
2229         }
2230         if (accountName != null) {
2231             intent.putExtra(EXTRA_USER_ACCOUNT_NAME, accountName);
2232         }
2233         if (accountType != null) {
2234             intent.putExtra(EXTRA_USER_ACCOUNT_TYPE, accountType);
2235         }
2236         if (accountOptions != null) {
2237             intent.putExtra(EXTRA_USER_ACCOUNT_OPTIONS, accountOptions);
2238         }
2239         return intent;
2240     }
2241 
2242     /**
2243      * @hide
2244      *
2245      * Returns the preferred account name for user creation.
2246      */
2247     @SystemApi
2248     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getSeedAccountName()2249     public String getSeedAccountName() {
2250         try {
2251             return mService.getSeedAccountName();
2252         } catch (RemoteException re) {
2253             throw re.rethrowFromSystemServer();
2254         }
2255     }
2256 
2257     /**
2258      * @hide
2259      *
2260      * Returns the preferred account type for user creation.
2261      */
2262     @SystemApi
2263     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getSeedAccountType()2264     public String getSeedAccountType() {
2265         try {
2266             return mService.getSeedAccountType();
2267         } catch (RemoteException re) {
2268             throw re.rethrowFromSystemServer();
2269         }
2270     }
2271 
2272     /**
2273      * @hide
2274      *
2275      * Returns the preferred account's options bundle for user creation.
2276      * @return Any options set by the requestor that created the user.
2277      */
2278     @SystemApi
2279     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getSeedAccountOptions()2280     public PersistableBundle getSeedAccountOptions() {
2281         try {
2282             return mService.getSeedAccountOptions();
2283         } catch (RemoteException re) {
2284             throw re.rethrowFromSystemServer();
2285         }
2286     }
2287 
2288     /**
2289      * @hide
2290      *
2291      * Called by a system activity to set the seed account information of a user created
2292      * through the user creation intent.
2293      * @param userId
2294      * @param accountName
2295      * @param accountType
2296      * @param accountOptions
2297      * @see #createUserCreationIntent(String, String, String, PersistableBundle)
2298      */
setSeedAccountData(int userId, String accountName, String accountType, PersistableBundle accountOptions)2299     public void setSeedAccountData(int userId, String accountName, String accountType,
2300             PersistableBundle accountOptions) {
2301         try {
2302             mService.setSeedAccountData(userId, accountName, accountType, accountOptions,
2303                     /* persist= */ true);
2304         } catch (RemoteException re) {
2305             throw re.rethrowFromSystemServer();
2306         }
2307     }
2308 
2309     /**
2310      * @hide
2311      * Clears the seed information used to create this user.
2312      */
2313     @SystemApi
2314     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
clearSeedAccountData()2315     public void clearSeedAccountData() {
2316         try {
2317             mService.clearSeedAccountData();
2318         } catch (RemoteException re) {
2319             throw re.rethrowFromSystemServer();
2320         }
2321     }
2322 
2323     /**
2324      * @hide
2325      * Marks the guest user for deletion to allow a new guest to be created before deleting
2326      * the current user who is a guest.
2327      * @param userHandle
2328      * @return
2329      */
markGuestForDeletion(@serIdInt int userHandle)2330     public boolean markGuestForDeletion(@UserIdInt int userHandle) {
2331         try {
2332             return mService.markGuestForDeletion(userHandle);
2333         } catch (RemoteException re) {
2334             throw re.rethrowFromSystemServer();
2335         }
2336     }
2337 
2338     /**
2339      * Sets the user as enabled, if such an user exists.
2340      *
2341      * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2342      *
2343      * <p>Note that the default is true, it's only that managed profiles might not be enabled.
2344      * Also ephemeral users can be disabled to indicate that their removal is in progress and they
2345      * shouldn't be re-entered. Therefore ephemeral users should not be re-enabled once disabled.
2346      *
2347      * @param userId the id of the profile to enable
2348      * @hide
2349      */
setUserEnabled(@serIdInt int userId)2350     public void setUserEnabled(@UserIdInt int userId) {
2351         try {
2352             mService.setUserEnabled(userId);
2353         } catch (RemoteException re) {
2354             throw re.rethrowFromSystemServer();
2355         }
2356     }
2357 
2358     /**
2359      * Assigns admin privileges to the user, if such a user exists.
2360      *
2361      * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} and
2362      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permissions.
2363      *
2364      * @param userHandle the id of the user to become admin
2365      * @hide
2366      */
2367     @RequiresPermission(allOf = {
2368             Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2369             Manifest.permission.MANAGE_USERS
2370     })
setUserAdmin(@serIdInt int userHandle)2371     public void setUserAdmin(@UserIdInt int userHandle) {
2372         try {
2373             mService.setUserAdmin(userHandle);
2374         } catch (RemoteException re) {
2375             throw re.rethrowFromSystemServer();
2376         }
2377     }
2378 
2379     /**
2380      * Evicts the user's credential encryption key from memory by stopping and restarting the user.
2381      *
2382      * @hide
2383      */
evictCredentialEncryptionKey(@serIdInt int userHandle)2384     public void evictCredentialEncryptionKey(@UserIdInt int userHandle) {
2385         try {
2386             mService.evictCredentialEncryptionKey(userHandle);
2387         } catch (RemoteException re) {
2388             throw re.rethrowFromSystemServer();
2389         }
2390     }
2391 
2392     /**
2393      * Return the number of users currently created on the device.
2394      * <p>This API is not for use by third-party apps. It requires the {@code MANAGE_USERS}
2395      * permission.</p>
2396      */
getUserCount()2397     public int getUserCount() {
2398         List<UserInfo> users = getUsers();
2399         return users != null ? users.size() : 1;
2400     }
2401 
2402     /**
2403      * Returns information for all users on this device, including ones marked for deletion.
2404      * To retrieve only users that are alive, use {@link #getUsers(boolean)}.
2405      *
2406      * @return the list of users that exist on the device.
2407      * @hide
2408      */
2409     @UnsupportedAppUsage
2410     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getUsers()2411     public List<UserInfo> getUsers() {
2412         return getUsers(/* excludeDying= */ false);
2413     }
2414 
2415     /**
2416      * Returns information for all users on this device, based on the filtering parameters.
2417      *
2418      * @hide
2419      */
2420     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getUsers(boolean excludePartial, boolean excludeDying, boolean excludePreCreated)2421     public List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
2422             boolean excludePreCreated) {
2423         try {
2424             return mService.getUsers(excludePartial, excludeDying, excludePreCreated);
2425         } catch (RemoteException re) {
2426             throw re.rethrowFromSystemServer();
2427         }
2428     }
2429 
2430     /**
2431      * Returns serial numbers of all users on this device.
2432      *
2433      * @param excludeDying specify if the list should exclude users being removed.
2434      * @return the list of serial numbers of users that exist on the device.
2435      * @hide
2436      */
2437     @SystemApi
2438     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getSerialNumbersOfUsers(boolean excludeDying)2439     public long[] getSerialNumbersOfUsers(boolean excludeDying) {
2440         List<UserInfo> users = getUsers(excludeDying);
2441         long[] result = new long[users.size()];
2442         for (int i = 0; i < result.length; i++) {
2443             result[i] = users.get(i).serialNumber;
2444         }
2445         return result;
2446     }
2447 
2448     /**
2449      * @return the user's account name, null if not found.
2450      * @hide
2451      */
2452     @RequiresPermission( allOf = {
2453             Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2454             Manifest.permission.MANAGE_USERS
2455     })
getUserAccount(@serIdInt int userHandle)2456     public @Nullable String getUserAccount(@UserIdInt int userHandle) {
2457         try {
2458             return mService.getUserAccount(userHandle);
2459         } catch (RemoteException re) {
2460             throw re.rethrowFromSystemServer();
2461         }
2462     }
2463 
2464     /**
2465      * Set account name for the given user.
2466      * @hide
2467      */
2468     @RequiresPermission( allOf = {
2469             Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2470             Manifest.permission.MANAGE_USERS
2471     })
setUserAccount(@serIdInt int userHandle, @Nullable String accountName)2472     public void setUserAccount(@UserIdInt int userHandle, @Nullable String accountName) {
2473         try {
2474             mService.setUserAccount(userHandle, accountName);
2475         } catch (RemoteException re) {
2476             throw re.rethrowFromSystemServer();
2477         }
2478     }
2479 
2480     /**
2481      * Returns information for Primary user.
2482      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2483      *
2484      * @return the Primary user, null if not found.
2485      * @hide
2486      */
getPrimaryUser()2487     public @Nullable UserInfo getPrimaryUser() {
2488         try {
2489             return mService.getPrimaryUser();
2490         } catch (RemoteException re) {
2491             throw re.rethrowFromSystemServer();
2492         }
2493     }
2494 
2495     /**
2496      * Checks whether it's possible to add more users. Caller must hold the MANAGE_USERS
2497      * permission.
2498      *
2499      * @return true if more users can be added, false if limit has been reached.
2500      * @hide
2501      */
canAddMoreUsers()2502     public boolean canAddMoreUsers() {
2503         final List<UserInfo> users = getUsers(true);
2504         final int totalUserCount = users.size();
2505         int aliveUserCount = 0;
2506         for (int i = 0; i < totalUserCount; i++) {
2507             UserInfo user = users.get(i);
2508             if (!user.isGuest()) {
2509                 aliveUserCount++;
2510             }
2511         }
2512         return aliveUserCount < getMaxSupportedUsers();
2513     }
2514 
2515     /**
2516      * Checks whether it's possible to add more managed profiles. Caller must hold the MANAGE_USERS
2517      * permission.
2518      * if allowedToRemoveOne is true and if the user already has a managed profile, then return if
2519      * we could add a new managed profile to this user after removing the existing one.
2520      *
2521      * @return true if more managed profiles can be added, false if limit has been reached.
2522      * @hide
2523      */
canAddMoreManagedProfiles(@serIdInt int userId, boolean allowedToRemoveOne)2524     public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
2525         try {
2526             return mService.canAddMoreManagedProfiles(userId, allowedToRemoveOne);
2527         } catch (RemoteException re) {
2528             throw re.rethrowFromSystemServer();
2529         }
2530     }
2531 
2532     /**
2533      * Returns list of the profiles of userHandle including
2534      * userHandle itself.
2535      * Note that this returns both enabled and not enabled profiles. See
2536      * {@link #getEnabledProfiles(int)} if you need only the enabled ones.
2537      *
2538      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2539      * @param userHandle profiles of this user will be returned.
2540      * @return the list of profiles.
2541      * @hide
2542      */
2543     @UnsupportedAppUsage
getProfiles(@serIdInt int userHandle)2544     public List<UserInfo> getProfiles(@UserIdInt int userHandle) {
2545         try {
2546             return mService.getProfiles(userHandle, false /* enabledOnly */);
2547         } catch (RemoteException re) {
2548             throw re.rethrowFromSystemServer();
2549         }
2550     }
2551 
2552     /**
2553      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2554      * @param userId one of the two user ids to check.
2555      * @param otherUserId one of the two user ids to check.
2556      * @return true if the two user ids are in the same profile group.
2557      * @hide
2558      */
isSameProfileGroup(@serIdInt int userId, int otherUserId)2559     public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) {
2560         try {
2561             return mService.isSameProfileGroup(userId, otherUserId);
2562         } catch (RemoteException re) {
2563             throw re.rethrowFromSystemServer();
2564         }
2565     }
2566 
2567     /**
2568      * Returns list of the profiles of userHandle including
2569      * userHandle itself.
2570      * Note that this returns only enabled.
2571      *
2572      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2573      * @param userHandle profiles of this user will be returned.
2574      * @return the list of profiles.
2575      * @hide
2576      */
2577     @UnsupportedAppUsage
getEnabledProfiles(@serIdInt int userHandle)2578     public List<UserInfo> getEnabledProfiles(@UserIdInt int userHandle) {
2579         try {
2580             return mService.getProfiles(userHandle, true /* enabledOnly */);
2581         } catch (RemoteException re) {
2582             throw re.rethrowFromSystemServer();
2583         }
2584     }
2585 
2586     /**
2587      * Returns a list of UserHandles for profiles associated with the user that the calling process
2588      * is running on, including the user itself.
2589      *
2590      * @return A non-empty list of UserHandles associated with the calling user.
2591      */
getUserProfiles()2592     public List<UserHandle> getUserProfiles() {
2593         int[] userIds = getProfileIds(UserHandle.myUserId(), true /* enabledOnly */);
2594         List<UserHandle> result = new ArrayList<>(userIds.length);
2595         for (int userId : userIds) {
2596             result.add(UserHandle.of(userId));
2597         }
2598         return result;
2599     }
2600 
2601     /**
2602      * Returns a list of ids for profiles associated with the specified user including the user
2603      * itself.
2604      *
2605      * @param userId      id of the user to return profiles for
2606      * @param enabledOnly whether return only {@link UserInfo#isEnabled() enabled} profiles
2607      * @return A non-empty list of ids of profiles associated with the specified user.
2608      *
2609      * @hide
2610      */
2611     @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS,
2612             Manifest.permission.CREATE_USERS}, conditional = true)
getProfileIds(@serIdInt int userId, boolean enabledOnly)2613     public @NonNull int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) {
2614         try {
2615             return mService.getProfileIds(userId, enabledOnly);
2616         } catch (RemoteException re) {
2617             throw re.rethrowFromSystemServer();
2618         }
2619     }
2620 
2621     /**
2622      * @see #getProfileIds(int, boolean)
2623      * @hide
2624      */
2625     @UnsupportedAppUsage
getProfileIdsWithDisabled(@serIdInt int userId)2626     public int[] getProfileIdsWithDisabled(@UserIdInt int userId) {
2627         return getProfileIds(userId, false /* enabledOnly */);
2628     }
2629 
2630     /**
2631      * @see #getProfileIds(int, boolean)
2632      * @hide
2633      */
getEnabledProfileIds(@serIdInt int userId)2634     public int[] getEnabledProfileIds(@UserIdInt int userId) {
2635         return getProfileIds(userId, true /* enabledOnly */);
2636     }
2637 
2638     /**
2639      * Returns the device credential owner id of the profile from
2640      * which this method is called, or userHandle if called from a user that
2641      * is not a profile.
2642      *
2643      * @hide
2644      */
getCredentialOwnerProfile(@serIdInt int userHandle)2645     public int getCredentialOwnerProfile(@UserIdInt int userHandle) {
2646         try {
2647             return mService.getCredentialOwnerProfile(userHandle);
2648         } catch (RemoteException re) {
2649             throw re.rethrowFromSystemServer();
2650         }
2651     }
2652 
2653     /**
2654      * Returns the parent of the profile which this method is called from
2655      * or null if called from a user that is not a profile.
2656      *
2657      * @hide
2658      */
2659     @UnsupportedAppUsage
getProfileParent(@serIdInt int userHandle)2660     public UserInfo getProfileParent(@UserIdInt int userHandle) {
2661         try {
2662             return mService.getProfileParent(userHandle);
2663         } catch (RemoteException re) {
2664             throw re.rethrowFromSystemServer();
2665         }
2666     }
2667 
2668     /**
2669      * Get the parent of a user profile.
2670      *
2671      * @param user the handle of the user profile
2672      *
2673      * @return the parent of the user or {@code null} if the user is not profile
2674      *
2675      * @hide
2676      */
2677     @SystemApi
2678     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getProfileParent(@onNull UserHandle user)2679     public @Nullable UserHandle getProfileParent(@NonNull UserHandle user) {
2680         UserInfo info = getProfileParent(user.getIdentifier());
2681 
2682         if (info == null) {
2683             return null;
2684         }
2685 
2686         return UserHandle.of(info.id);
2687     }
2688 
2689     /**
2690      * Enables or disables quiet mode for a managed profile. If quiet mode is enabled, apps in a
2691      * managed profile don't run, generate notifications, or consume data or battery.
2692      * <p>
2693      * If a user's credential is needed to turn off quiet mode, a confirm credential screen will be
2694      * shown to the user.
2695      * <p>
2696      * The change may not happen instantly, however apps can listen for
2697      * {@link Intent#ACTION_MANAGED_PROFILE_AVAILABLE} and
2698      * {@link Intent#ACTION_MANAGED_PROFILE_UNAVAILABLE} broadcasts in order to be notified of
2699      * the change of the quiet mode. Apps can also check the current state of quiet mode by
2700      * calling {@link #isQuietModeEnabled(UserHandle)}.
2701      * <p>
2702      * The caller must either be the foreground default launcher or have one of these permissions:
2703      * {@code MANAGE_USERS} or {@code MODIFY_QUIET_MODE}.
2704      *
2705      * @param enableQuietMode whether quiet mode should be enabled or disabled
2706      * @param userHandle user handle of the profile
2707      * @return {@code false} if user's credential is needed in order to turn off quiet mode,
2708      *         {@code true} otherwise
2709      * @throws SecurityException if the caller is invalid
2710      * @throws IllegalArgumentException if {@code userHandle} is not a managed profile
2711      *
2712      * @see #isQuietModeEnabled(UserHandle)
2713      */
requestQuietModeEnabled(boolean enableQuietMode, @NonNull UserHandle userHandle)2714     public boolean requestQuietModeEnabled(boolean enableQuietMode, @NonNull UserHandle userHandle) {
2715         return requestQuietModeEnabled(enableQuietMode, userHandle, null);
2716     }
2717 
2718     /**
2719      * Similar to {@link #requestQuietModeEnabled(boolean, UserHandle)}, except you can specify
2720      * a target to start when user is unlocked. If {@code target} is specified, caller must have
2721      * the {@link android.Manifest.permission#MANAGE_USERS} permission.
2722      *
2723      * @see {@link #requestQuietModeEnabled(boolean, UserHandle)}
2724      * @hide
2725      */
requestQuietModeEnabled( boolean enableQuietMode, @NonNull UserHandle userHandle, IntentSender target)2726     public boolean requestQuietModeEnabled(
2727             boolean enableQuietMode, @NonNull UserHandle userHandle, IntentSender target) {
2728         try {
2729             return mService.requestQuietModeEnabled(
2730                     mContext.getPackageName(), enableQuietMode, userHandle.getIdentifier(), target);
2731         } catch (RemoteException re) {
2732             throw re.rethrowFromSystemServer();
2733         }
2734     }
2735 
2736     /**
2737      * Returns whether the given profile is in quiet mode or not.
2738      * Notes: Quiet mode is only supported for managed profiles.
2739      *
2740      * @param userHandle The user handle of the profile to be queried.
2741      * @return true if the profile is in quiet mode, false otherwise.
2742      */
isQuietModeEnabled(UserHandle userHandle)2743     public boolean isQuietModeEnabled(UserHandle userHandle) {
2744         try {
2745             return mService.isQuietModeEnabled(userHandle.getIdentifier());
2746         } catch (RemoteException re) {
2747             throw re.rethrowFromSystemServer();
2748         }
2749     }
2750 
2751     /**
2752      * If the target user is a managed profile of the calling user or the caller
2753      * is itself a managed profile, then this returns a badged copy of the given
2754      * icon to be able to distinguish it from the original icon. For badging an
2755      * arbitrary drawable use {@link #getBadgedDrawableForUser(
2756      * android.graphics.drawable.Drawable, UserHandle, android.graphics.Rect, int)}.
2757      * <p>
2758      * If the original drawable is a BitmapDrawable and the backing bitmap is
2759      * mutable as per {@link android.graphics.Bitmap#isMutable()}, the badging
2760      * is performed in place and the original drawable is returned.
2761      * </p>
2762      *
2763      * @param icon The icon to badge.
2764      * @param user The target user.
2765      * @return A drawable that combines the original icon and a badge as
2766      *         determined by the system.
2767      * @removed
2768      */
getBadgedIconForUser(Drawable icon, UserHandle user)2769     public Drawable getBadgedIconForUser(Drawable icon, UserHandle user) {
2770         return mContext.getPackageManager().getUserBadgedIcon(icon, user);
2771     }
2772 
2773     /**
2774      * If the target user is a managed profile of the calling user or the caller
2775      * is itself a managed profile, then this returns a badged copy of the given
2776      * drawable allowing the user to distinguish it from the original drawable.
2777      * The caller can specify the location in the bounds of the drawable to be
2778      * badged where the badge should be applied as well as the density of the
2779      * badge to be used.
2780      * <p>
2781      * If the original drawable is a BitmapDrawable and the backing bitmap is
2782      * mutable as per {@link android.graphics.Bitmap#isMutable()}, the badging
2783      * is performed in place and the original drawable is returned.
2784      * </p>
2785      *
2786      * @param badgedDrawable The drawable to badge.
2787      * @param user The target user.
2788      * @param badgeLocation Where in the bounds of the badged drawable to place
2789      *         the badge. If it's {@code null}, the badge is applied on top of the entire
2790      *         drawable being badged.
2791      * @param badgeDensity The optional desired density for the badge as per
2792      *         {@link android.util.DisplayMetrics#densityDpi}. If it's not positive,
2793      *         the density of the display is used.
2794      * @return A drawable that combines the original drawable and a badge as
2795      *         determined by the system.
2796      * @removed
2797      */
getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user, Rect badgeLocation, int badgeDensity)2798     public Drawable getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user,
2799             Rect badgeLocation, int badgeDensity) {
2800         return mContext.getPackageManager().getUserBadgedDrawableForDensity(badgedDrawable, user,
2801                 badgeLocation, badgeDensity);
2802     }
2803 
2804     /**
2805      * If the target user is a managed profile of the calling user or the caller
2806      * is itself a managed profile, then this returns a copy of the label with
2807      * badging for accessibility services like talkback. E.g. passing in "Email"
2808      * and it might return "Work Email" for Email in the work profile.
2809      *
2810      * @param label The label to change.
2811      * @param user The target user.
2812      * @return A label that combines the original label and a badge as
2813      *         determined by the system.
2814      * @removed
2815      */
getBadgedLabelForUser(CharSequence label, UserHandle user)2816     public CharSequence getBadgedLabelForUser(CharSequence label, UserHandle user) {
2817         return mContext.getPackageManager().getUserBadgedLabel(label, user);
2818     }
2819 
2820     /**
2821      * Returns information for all users on this device. Requires
2822      * {@link android.Manifest.permission#MANAGE_USERS} permission.
2823      *
2824      * @param excludeDying specify if the list should exclude users being
2825      *            removed.
2826      * @return the list of users that were created.
2827      * @hide
2828      */
2829     @UnsupportedAppUsage
getUsers(boolean excludeDying)2830     public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
2831         return getUsers(/*excludePartial= */ true, excludeDying,
2832                 /* excludePreCreated= */ true);
2833     }
2834 
2835     /**
2836      * Removes a user and all associated data.
2837      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2838      * @param userHandle the integer handle of the user, where 0 is the primary user.
2839      * @hide
2840      */
2841     @UnsupportedAppUsage
removeUser(@serIdInt int userHandle)2842     public boolean removeUser(@UserIdInt int userHandle) {
2843         try {
2844             return mService.removeUser(userHandle);
2845         } catch (RemoteException re) {
2846             throw re.rethrowFromSystemServer();
2847         }
2848     }
2849 
2850     /**
2851      * Removes a user and all associated data.
2852      *
2853      * @param user the user that needs to be removed.
2854      * @return {@code true} if the user was successfully removed, {@code false} otherwise.
2855      * @throws IllegalArgumentException if {@code user} is {@code null}
2856      * @hide
2857      */
2858     @SystemApi
2859     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
removeUser(@onNull UserHandle user)2860     public boolean removeUser(@NonNull UserHandle user) {
2861         if (user == null) {
2862             throw new IllegalArgumentException("user cannot be null");
2863         }
2864         return removeUser(user.getIdentifier());
2865     }
2866 
2867 
2868     /**
2869      * Similar to {@link #removeUser(int)} except bypassing the checking of
2870      * {@link UserManager#DISALLOW_REMOVE_USER}
2871      * or {@link UserManager#DISALLOW_REMOVE_MANAGED_PROFILE}.
2872      *
2873      * @see {@link #removeUser(int)}
2874      * @hide
2875      */
removeUserEvenWhenDisallowed(@serIdInt int userHandle)2876     public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2877         try {
2878             return mService.removeUserEvenWhenDisallowed(userHandle);
2879         } catch (RemoteException re) {
2880             throw re.rethrowFromSystemServer();
2881         }
2882     }
2883 
2884     /**
2885      * Updates the user's name.
2886      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2887      *
2888      * @param userHandle the user's integer handle
2889      * @param name the new name for the user
2890      * @hide
2891      */
setUserName(@serIdInt int userHandle, String name)2892     public void setUserName(@UserIdInt int userHandle, String name) {
2893         try {
2894             mService.setUserName(userHandle, name);
2895         } catch (RemoteException re) {
2896             throw re.rethrowFromSystemServer();
2897         }
2898     }
2899 
2900     /**
2901      * Updates the calling user's name.
2902      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2903      *
2904      * @param name the new name for the user
2905      * @hide
2906      */
2907     @SystemApi
2908     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setUserName(@ullable String name)2909     public void setUserName(@Nullable String name) {
2910         setUserName(getUserHandle(), name);
2911     }
2912 
2913     /**
2914      * Sets the user's photo.
2915      * @param userHandle the user for whom to change the photo.
2916      * @param icon the bitmap to set as the photo.
2917      * @hide
2918      */
setUserIcon(@serIdInt int userHandle, Bitmap icon)2919     public void setUserIcon(@UserIdInt int userHandle, Bitmap icon) {
2920         try {
2921             mService.setUserIcon(userHandle, icon);
2922         } catch (RemoteException re) {
2923             throw re.rethrowFromSystemServer();
2924         }
2925     }
2926 
2927     /**
2928      * Sets the calling user's photo.
2929      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2930      *
2931      * @param icon the bitmap to set as the photo.
2932      * @hide
2933      */
2934     @SystemApi
2935     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setUserIcon(@onNull Bitmap icon)2936     public void setUserIcon(@NonNull Bitmap icon) {
2937         setUserIcon(getUserHandle(), icon);
2938     }
2939 
2940     /**
2941      * Returns a file descriptor for the user's photo. PNG data can be read from this file.
2942      * @param userHandle the user whose photo we want to read.
2943      * @return a {@link Bitmap} of the user's photo, or null if there's no photo.
2944      * @see com.android.internal.util.UserIcons#getDefaultUserIcon for a default.
2945      * @hide
2946      */
2947     @UnsupportedAppUsage
getUserIcon(@serIdInt int userHandle)2948     public Bitmap getUserIcon(@UserIdInt int userHandle) {
2949         try {
2950             ParcelFileDescriptor fd = mService.getUserIcon(userHandle);
2951             if (fd != null) {
2952                 try {
2953                     return BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
2954                 } finally {
2955                     try {
2956                         fd.close();
2957                     } catch (IOException e) {
2958                     }
2959                 }
2960             }
2961         } catch (RemoteException re) {
2962             throw re.rethrowFromSystemServer();
2963         }
2964         return null;
2965     }
2966 
2967     /**
2968      * Returns a Bitmap for the calling user's photo.
2969      * Requires {@link android.Manifest.permission#MANAGE_USERS}
2970      * or {@link android.Manifest.permission#GET_ACCOUNTS_PRIVILEGED} permissions.
2971      *
2972      * @return a {@link Bitmap} of the user's photo, or null if there's no photo.
2973      * @see com.android.internal.util.UserIcons#getDefaultUserIcon for a default.
2974      * @hide
2975      */
2976     @SystemApi
2977     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
2978             android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED})
getUserIcon()2979     public @Nullable Bitmap getUserIcon() {
2980         return getUserIcon(getUserHandle());
2981     }
2982 
2983     /**
2984      * Returns the maximum number of users that can be created on this device. A return value
2985      * of 1 means that it is a single user device.
2986      * @hide
2987      * @return a value greater than or equal to 1
2988      */
2989     @UnsupportedAppUsage
getMaxSupportedUsers()2990     public static int getMaxSupportedUsers() {
2991         // Don't allow multiple users on certain builds
2992         if (android.os.Build.ID.startsWith("JVP")) return 1;
2993         if (ActivityManager.isLowRamDeviceStatic()) {
2994             // Low-ram devices are Svelte. Most of the time they don't get multi-user.
2995             if ((Resources.getSystem().getConfiguration().uiMode & Configuration.UI_MODE_TYPE_MASK)
2996                     != Configuration.UI_MODE_TYPE_TELEVISION) {
2997                 return 1;
2998             }
2999         }
3000         return SystemProperties.getInt("fw.max_users",
3001                 Resources.getSystem().getInteger(R.integer.config_multiuserMaximumUsers));
3002     }
3003 
3004     /**
3005      * Returns true if the user switcher should be shown, this will be if device supports multi-user
3006      * and there are at least 2 users available that are not managed profiles.
3007      * @hide
3008      * @return true if user switcher should be shown.
3009      */
isUserSwitcherEnabled()3010     public boolean isUserSwitcherEnabled() {
3011         if (!supportsMultipleUsers()) {
3012             return false;
3013         }
3014         if (hasUserRestriction(DISALLOW_USER_SWITCH)) {
3015             return false;
3016         }
3017         // If Demo Mode is on, don't show user switcher
3018         if (isDeviceInDemoMode(mContext)) {
3019             return false;
3020         }
3021         // If user disabled this feature, don't show switcher
3022         final boolean userSwitcherEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3023                 Settings.Global.USER_SWITCHER_ENABLED, 1) != 0;
3024         if (!userSwitcherEnabled) {
3025             return false;
3026         }
3027         List<UserInfo> users = getUsers(true);
3028         if (users == null) {
3029            return false;
3030         }
3031         int switchableUserCount = 0;
3032         for (UserInfo user : users) {
3033             if (user.supportsSwitchToByUser()) {
3034                 ++switchableUserCount;
3035             }
3036         }
3037         final boolean guestEnabled = !mContext.getSystemService(DevicePolicyManager.class)
3038                 .getGuestUserDisabled(null);
3039         return switchableUserCount > 1 || guestEnabled;
3040     }
3041 
3042     /**
3043      * @hide
3044      */
3045     @UnsupportedAppUsage
isDeviceInDemoMode(Context context)3046     public static boolean isDeviceInDemoMode(Context context) {
3047         return Settings.Global.getInt(context.getContentResolver(),
3048                 Settings.Global.DEVICE_DEMO_MODE, 0) > 0;
3049     }
3050 
3051     /**
3052      * Returns a serial number on this device for a given userHandle. User handles can be recycled
3053      * when deleting and creating users, but serial numbers are not reused until the device is wiped.
3054      * @param userHandle
3055      * @return a serial number associated with that user, or -1 if the userHandle is not valid.
3056      * @hide
3057      */
3058     @UnsupportedAppUsage
getUserSerialNumber(@serIdInt int userHandle)3059     public int getUserSerialNumber(@UserIdInt int userHandle) {
3060         try {
3061             return mService.getUserSerialNumber(userHandle);
3062         } catch (RemoteException re) {
3063             throw re.rethrowFromSystemServer();
3064         }
3065     }
3066 
3067     /**
3068      * Returns a userHandle on this device for a given user serial number. User handles can be
3069      * recycled when deleting and creating users, but serial numbers are not reused until the device
3070      * is wiped.
3071      * @param userSerialNumber
3072      * @return the userHandle associated with that user serial number, or -1 if the serial number
3073      * is not valid.
3074      * @hide
3075      */
3076     @UnsupportedAppUsage
getUserHandle(int userSerialNumber)3077     public @UserIdInt int getUserHandle(int userSerialNumber) {
3078         try {
3079             return mService.getUserHandle(userSerialNumber);
3080         } catch (RemoteException re) {
3081             throw re.rethrowFromSystemServer();
3082         }
3083     }
3084 
3085     /**
3086      * Returns a {@link Bundle} containing any saved application restrictions for this user, for the
3087      * given package name. Only an application with this package name can call this method.
3088      *
3089      * <p>The returned {@link Bundle} consists of key-value pairs, as defined by the application,
3090      * where the types of values may be:
3091      * <ul>
3092      * <li>{@code boolean}
3093      * <li>{@code int}
3094      * <li>{@code String} or {@code String[]}
3095      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
3096      * </ul>
3097      *
3098      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
3099      *
3100      * @param packageName the package name of the calling application
3101      * @return a {@link Bundle} with the restrictions for that package, or an empty {@link Bundle}
3102      * if there are no saved restrictions.
3103      *
3104      * @see #KEY_RESTRICTIONS_PENDING
3105      */
3106     @WorkerThread
getApplicationRestrictions(String packageName)3107     public Bundle getApplicationRestrictions(String packageName) {
3108         try {
3109             return mService.getApplicationRestrictions(packageName);
3110         } catch (RemoteException re) {
3111             throw re.rethrowFromSystemServer();
3112         }
3113     }
3114 
3115     /**
3116      * @hide
3117      */
3118     @WorkerThread
getApplicationRestrictions(String packageName, UserHandle user)3119     public Bundle getApplicationRestrictions(String packageName, UserHandle user) {
3120         try {
3121             return mService.getApplicationRestrictionsForUser(packageName, user.getIdentifier());
3122         } catch (RemoteException re) {
3123             throw re.rethrowFromSystemServer();
3124         }
3125     }
3126 
3127     /**
3128      * @hide
3129      */
3130     @WorkerThread
setApplicationRestrictions(String packageName, Bundle restrictions, UserHandle user)3131     public void setApplicationRestrictions(String packageName, Bundle restrictions,
3132             UserHandle user) {
3133         try {
3134             mService.setApplicationRestrictions(packageName, restrictions, user.getIdentifier());
3135         } catch (RemoteException re) {
3136             throw re.rethrowFromSystemServer();
3137         }
3138     }
3139 
3140     /**
3141      * Sets a new challenge PIN for restrictions. This is only for use by pre-installed
3142      * apps and requires the MANAGE_USERS permission.
3143      * @param newPin the PIN to use for challenge dialogs.
3144      * @return Returns true if the challenge PIN was set successfully.
3145      * @deprecated The restrictions PIN functionality is no longer provided by the system.
3146      * This method is preserved for backwards compatibility reasons and always returns false.
3147      */
3148     @Deprecated
setRestrictionsChallenge(String newPin)3149     public boolean setRestrictionsChallenge(String newPin) {
3150         return false;
3151     }
3152 
3153     /**
3154      * @hide
3155      * Set restrictions that should apply to any future guest user that's created.
3156      */
setDefaultGuestRestrictions(Bundle restrictions)3157     public void setDefaultGuestRestrictions(Bundle restrictions) {
3158         try {
3159             mService.setDefaultGuestRestrictions(restrictions);
3160         } catch (RemoteException re) {
3161             throw re.rethrowFromSystemServer();
3162         }
3163     }
3164 
3165     /**
3166      * @hide
3167      * Gets the default guest restrictions.
3168      */
getDefaultGuestRestrictions()3169     public Bundle getDefaultGuestRestrictions() {
3170         try {
3171             return mService.getDefaultGuestRestrictions();
3172         } catch (RemoteException re) {
3173             throw re.rethrowFromSystemServer();
3174         }
3175     }
3176 
3177     /**
3178      * Returns creation time of the user or of a managed profile associated with the calling user.
3179      * @param userHandle user handle of the user or a managed profile associated with the
3180      *                   calling user.
3181      * @return creation time in milliseconds since Epoch time.
3182      */
getUserCreationTime(UserHandle userHandle)3183     public long getUserCreationTime(UserHandle userHandle) {
3184         try {
3185             return mService.getUserCreationTime(userHandle.getIdentifier());
3186         } catch (RemoteException re) {
3187             throw re.rethrowFromSystemServer();
3188         }
3189     }
3190 
3191     /**
3192      * @hide
3193      * Checks if any uninitialized user has the specific seed account name and type.
3194      *
3195      * @param accountName The account name to check for
3196      * @param accountType The account type of the account to check for
3197      * @return whether the seed account was found
3198      */
someUserHasSeedAccount(String accountName, String accountType)3199     public boolean someUserHasSeedAccount(String accountName, String accountType) {
3200         try {
3201             return mService.someUserHasSeedAccount(accountName, accountType);
3202         } catch (RemoteException re) {
3203             throw re.rethrowFromSystemServer();
3204         }
3205     }
3206 
3207     /**
3208      * @hide
3209      * User that enforces a restriction.
3210      *
3211      * @see #getUserRestrictionSources(String, UserHandle)
3212      */
3213     @SystemApi
3214     public static final class EnforcingUser implements Parcelable {
3215         private final @UserIdInt int userId;
3216         private final @UserRestrictionSource int userRestrictionSource;
3217 
3218         /**
3219          * @hide
3220          */
EnforcingUser( @serIdInt int userId, @UserRestrictionSource int userRestrictionSource)3221         public EnforcingUser(
3222                 @UserIdInt int userId, @UserRestrictionSource int userRestrictionSource) {
3223             this.userId = userId;
3224             this.userRestrictionSource = userRestrictionSource;
3225         }
3226 
EnforcingUser(Parcel in)3227         private EnforcingUser(Parcel in) {
3228             userId = in.readInt();
3229             userRestrictionSource = in.readInt();
3230         }
3231 
3232         public static final @android.annotation.NonNull Creator<EnforcingUser> CREATOR = new Creator<EnforcingUser>() {
3233             @Override
3234             public EnforcingUser createFromParcel(Parcel in) {
3235                 return new EnforcingUser(in);
3236             }
3237 
3238             @Override
3239             public EnforcingUser[] newArray(int size) {
3240                 return new EnforcingUser[size];
3241             }
3242         };
3243 
3244         @Override
describeContents()3245         public int describeContents() {
3246             return 0;
3247         }
3248 
3249         @Override
writeToParcel(Parcel dest, int flags)3250         public void writeToParcel(Parcel dest, int flags) {
3251             dest.writeInt(userId);
3252             dest.writeInt(userRestrictionSource);
3253         }
3254 
3255         /**
3256          * Returns an id of the enforcing user.
3257          *
3258          * <p> Will be UserHandle.USER_NULL when restriction is set by the system.
3259          */
getUserHandle()3260         public UserHandle getUserHandle() {
3261             return UserHandle.of(userId);
3262         }
3263 
3264         /**
3265          * Returns the status of the enforcing user.
3266          *
3267          * <p> One of {@link #RESTRICTION_SOURCE_SYSTEM},
3268          * {@link #RESTRICTION_SOURCE_DEVICE_OWNER} and
3269          * {@link #RESTRICTION_SOURCE_PROFILE_OWNER}
3270          */
getUserRestrictionSource()3271         public @UserRestrictionSource int getUserRestrictionSource() {
3272             return userRestrictionSource;
3273         }
3274     }
3275 }
3276