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
17package android.os;
18
19import android.Manifest;
20import android.accounts.AccountManager;
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.annotation.RequiresPermission;
25import android.annotation.SystemApi;
26import android.annotation.SystemService;
27import android.annotation.TestApi;
28import android.annotation.UserIdInt;
29import android.annotation.WorkerThread;
30import android.app.Activity;
31import android.app.ActivityManager;
32import android.app.admin.DevicePolicyManager;
33import android.content.ComponentName;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.IntentSender;
38import android.content.pm.UserInfo;
39import android.content.res.Resources;
40import android.graphics.Bitmap;
41import android.graphics.BitmapFactory;
42import android.graphics.Rect;
43import android.graphics.drawable.Drawable;
44import android.provider.Settings;
45import android.telephony.TelephonyManager;
46import android.view.WindowManager.LayoutParams;
47
48import com.android.internal.R;
49import com.android.internal.os.RoSystemProperties;
50
51import java.io.IOException;
52import java.lang.annotation.Retention;
53import java.lang.annotation.RetentionPolicy;
54import java.util.ArrayList;
55import java.util.List;
56
57/**
58 * Manages users and user details on a multi-user system. There are two major categories of
59 * users: fully customizable users with their own login, and managed profiles that share a workspace
60 * with a related user.
61 * <p>
62 * Users are different from accounts, which are managed by
63 * {@link AccountManager}. Each user can have their own set of accounts.
64 * <p>
65 * See {@link DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE} for more on managed profiles.
66 */
67@SystemService(Context.USER_SERVICE)
68public class UserManager {
69
70    private static final String TAG = "UserManager";
71    private final IUserManager mService;
72    private final Context mContext;
73
74    private Boolean mIsManagedProfileCached;
75
76    /**
77     * @hide
78     * No user restriction.
79     */
80    @SystemApi
81    public static final int RESTRICTION_NOT_SET = 0x0;
82
83    /**
84     * @hide
85     * User restriction set by system/user.
86     */
87    @SystemApi
88    public static final int RESTRICTION_SOURCE_SYSTEM = 0x1;
89
90    /**
91     * @hide
92     * User restriction set by a device owner.
93     */
94    @SystemApi
95    public static final int RESTRICTION_SOURCE_DEVICE_OWNER = 0x2;
96
97    /**
98     * @hide
99     * User restriction set by a profile owner.
100     */
101    @SystemApi
102    public static final int RESTRICTION_SOURCE_PROFILE_OWNER = 0x4;
103
104    /** @hide */
105    @Retention(RetentionPolicy.SOURCE)
106    @IntDef(flag=true, value={RESTRICTION_NOT_SET, RESTRICTION_SOURCE_SYSTEM,
107            RESTRICTION_SOURCE_DEVICE_OWNER, RESTRICTION_SOURCE_PROFILE_OWNER})
108    @SystemApi
109    public @interface UserRestrictionSource {}
110
111    /**
112     * Specifies if a user is disallowed from adding and removing accounts, unless they are
113     * {@link android.accounts.AccountManager#addAccountExplicitly programmatically} added by
114     * Authenticator.
115     * The default value is <code>false</code>.
116     *
117     * <p>From {@link android.os.Build.VERSION_CODES#N} a profile or device owner app can still
118     * use {@link android.accounts.AccountManager} APIs to add or remove accounts when account
119     * management is disallowed.
120     *
121     * <p>Key for user restrictions.
122     * <p>Type: Boolean
123     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
124     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
125     * @see #getUserRestrictions()
126     */
127    public static final String DISALLOW_MODIFY_ACCOUNTS = "no_modify_accounts";
128
129    /**
130     * Specifies if a user is disallowed from changing Wi-Fi
131     * access points. The default value is <code>false</code>.
132     * <p>This restriction has no effect in a managed profile.
133     *
134     * <p>Key for user restrictions.
135     * <p>Type: Boolean
136     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
137     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
138     * @see #getUserRestrictions()
139     */
140    public static final String DISALLOW_CONFIG_WIFI = "no_config_wifi";
141
142    /**
143     * Specifies if a user is disallowed from installing applications.
144     * The default value is <code>false</code>.
145     *
146     * <p>Key for user restrictions.
147     * <p>Type: Boolean
148     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
149     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
150     * @see #getUserRestrictions()
151     */
152    public static final String DISALLOW_INSTALL_APPS = "no_install_apps";
153
154    /**
155     * Specifies if a user is disallowed from uninstalling applications.
156     * The default value is <code>false</code>.
157     *
158     * <p>Key for user restrictions.
159     * <p>Type: Boolean
160     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
161     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
162     * @see #getUserRestrictions()
163     */
164    public static final String DISALLOW_UNINSTALL_APPS = "no_uninstall_apps";
165
166    /**
167     * Specifies if a user is disallowed from turning on location sharing.
168     * The default value is <code>false</code>.
169     * <p>In a managed profile, location sharing always reflects the primary user's setting, but
170     * can be overridden and forced off by setting this restriction to true in the managed profile.
171     *
172     * <p>Key for user restrictions.
173     * <p>Type: Boolean
174     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
175     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
176     * @see #getUserRestrictions()
177     */
178    public static final String DISALLOW_SHARE_LOCATION = "no_share_location";
179
180    /**
181     * Specifies if a user is disallowed from enabling the
182     * "Unknown Sources" setting, that allows installation of apps from unknown sources.
183     * The default value is <code>false</code>.
184     *
185     * <p>Key for user restrictions.
186     * <p>Type: Boolean
187     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
188     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
189     * @see #getUserRestrictions()
190     */
191    public static final String DISALLOW_INSTALL_UNKNOWN_SOURCES = "no_install_unknown_sources";
192
193    /**
194     * Specifies if a user is disallowed from configuring bluetooth.
195     * This does <em>not</em> restrict the user from turning bluetooth on or off.
196     * The default value is <code>false</code>.
197     * <p>This restriction doesn't prevent the user from using bluetooth. For disallowing usage of
198     * bluetooth completely on the device, use {@link #DISALLOW_BLUETOOTH}.
199     * <p>This restriction has no effect in a managed profile.
200     *
201     * <p>Key for user restrictions.
202     * <p>Type: Boolean
203     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
204     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
205     * @see #getUserRestrictions()
206     */
207    public static final String DISALLOW_CONFIG_BLUETOOTH = "no_config_bluetooth";
208
209    /**
210     * Specifies if bluetooth is disallowed on the device.
211     *
212     * <p> This restriction can only be set by the device owner and the profile owner on the
213     * primary user and it applies globally - i.e. it disables bluetooth on the entire device.
214     * <p>The default value is <code>false</code>.
215     * <p>Key for user restrictions.
216     * <p>Type: Boolean
217     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
218     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
219     * @see #getUserRestrictions()
220     */
221    public static final String DISALLOW_BLUETOOTH = "no_bluetooth";
222
223    /**
224     * Specifies if outgoing bluetooth sharing is disallowed on the device. Device owner and profile
225     * owner can set this restriction. When it is set by device owner, all users on this device will
226     * be affected.
227     *
228     * <p>Default is <code>true</code> for managed profiles and false for otherwise. When a device
229     * upgrades to {@link android.os.Build.VERSION_CODES#O}, the system sets it for all existing
230     * managed profiles.
231     *
232     * <p>Key for user restrictions.
233     * <p>Type: Boolean
234     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
235     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
236     * @see #getUserRestrictions()
237     */
238    public static final String DISALLOW_BLUETOOTH_SHARING = "no_bluetooth_sharing";
239
240    /**
241     * Specifies if a user is disallowed from transferring files over
242     * USB. This can only be set by device owners and profile owners on the primary user.
243     * The default value is <code>false</code>.
244     *
245     * <p>Key for user restrictions.
246     * <p>Type: Boolean
247     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
248     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
249     * @see #getUserRestrictions()
250     */
251    public static final String DISALLOW_USB_FILE_TRANSFER = "no_usb_file_transfer";
252
253    /**
254     * Specifies if a user is disallowed from configuring user
255     * credentials. The default value is <code>false</code>.
256     *
257     * <p>Key for user restrictions.
258     * <p>Type: Boolean
259     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
260     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
261     * @see #getUserRestrictions()
262     */
263    public static final String DISALLOW_CONFIG_CREDENTIALS = "no_config_credentials";
264
265    /**
266     * When set on the primary user this specifies if the user can remove other users.
267     * When set on a secondary user, this specifies if the user can remove itself.
268     * This restriction has no effect on managed profiles.
269     * The default value is <code>false</code>.
270     *
271     * <p>Key for user restrictions.
272     * <p>Type: Boolean
273     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
274     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
275     * @see #getUserRestrictions()
276     */
277    public static final String DISALLOW_REMOVE_USER = "no_remove_user";
278
279    /**
280     * Specifies if managed profiles of this user can be removed, other than by its profile owner.
281     * The default value is <code>false</code>.
282     * <p>
283     * This restriction has no effect on managed profiles.
284     *
285     * <p>Key for user restrictions.
286     * <p>Type: Boolean
287     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
288     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
289     * @see #getUserRestrictions()
290     */
291    public static final String DISALLOW_REMOVE_MANAGED_PROFILE = "no_remove_managed_profile";
292
293    /**
294     * Specifies if a user is disallowed from enabling or
295     * accessing debugging features. The default value is <code>false</code>.
296     *
297     * <p>Key for user restrictions.
298     * <p>Type: Boolean
299     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
300     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
301     * @see #getUserRestrictions()
302     */
303    public static final String DISALLOW_DEBUGGING_FEATURES = "no_debugging_features";
304
305    /**
306     * Specifies if a user is disallowed from configuring VPN.
307     * The default value is <code>false</code>.
308     * This restriction has an effect in a managed profile only from
309     * {@link android.os.Build.VERSION_CODES#M}
310     *
311     * <p>Key for user restrictions.
312     * <p>Type: Boolean
313     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
314     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
315     * @see #getUserRestrictions()
316     */
317    public static final String DISALLOW_CONFIG_VPN = "no_config_vpn";
318
319    /**
320     * Specifies if a user is disallowed from configuring Tethering
321     * & portable hotspots. This can only be set by device owners and profile owners on the
322     * primary user. The default value is <code>false</code>.
323     *
324     * <p>Key for user restrictions.
325     * <p>Type: Boolean
326     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
327     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
328     * @see #getUserRestrictions()
329     */
330    public static final String DISALLOW_CONFIG_TETHERING = "no_config_tethering";
331
332    /**
333     * Specifies if a user is disallowed from resetting network settings
334     * from Settings. This can only be set by device owners and profile owners on the primary user.
335     * The default value is <code>false</code>.
336     * <p>This restriction has no effect on secondary users and managed profiles since only the
337     * primary user can reset the network settings of the device.
338     *
339     * <p>Key for user restrictions.
340     * <p>Type: Boolean
341     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
342     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
343     * @see #getUserRestrictions()
344     */
345    public static final String DISALLOW_NETWORK_RESET = "no_network_reset";
346
347    /**
348     * Specifies if a user is disallowed from factory resetting
349     * from Settings. This can only be set by device owners and profile owners on the primary user.
350     * The default value is <code>false</code>.
351     * <p>This restriction has no effect on secondary users and managed profiles since only the
352     * primary user can factory reset the device.
353     *
354     * <p>Key for user restrictions.
355     * <p>Type: Boolean
356     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
357     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
358     * @see #getUserRestrictions()
359     */
360    public static final String DISALLOW_FACTORY_RESET = "no_factory_reset";
361
362    /**
363     * Specifies if a user is disallowed from adding new users. This can only be set by device
364     * owners and profile owners on the primary user.
365     * The default value is <code>false</code>.
366     * <p>This restriction has no effect on secondary users and managed profiles since only the
367     * primary user can add other users.
368     *
369     * <p>Key for user restrictions.
370     * <p>Type: Boolean
371     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
372     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
373     * @see #getUserRestrictions()
374     */
375    public static final String DISALLOW_ADD_USER = "no_add_user";
376
377    /**
378     * Specifies if a user is disallowed from adding managed profiles.
379     * <p>The default value for an unmanaged user is <code>false</code>.
380     * For users with a device owner set, the default is <code>true</code>.
381     * <p>This restriction has no effect on managed profiles.
382     *
383     * <p>Key for user restrictions.
384     * <p>Type: Boolean
385     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
386     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
387     * @see #getUserRestrictions()
388     */
389    public static final String DISALLOW_ADD_MANAGED_PROFILE = "no_add_managed_profile";
390
391    /**
392     * Specifies if a user is disallowed from disabling application verification.
393     * Starting from {@link android.os.Build.VERSION_CODES#O}, application verification
394     * is enforced across all users on the device if a profile owner or device owner sets
395     * this restriction to <code>true</code>. The default value is <code>false</code>.
396     *
397     * <p>Key for user restrictions.
398     * <p>Type: Boolean
399     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
400     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
401     * @see #getUserRestrictions()
402     */
403    public static final String ENSURE_VERIFY_APPS = "ensure_verify_apps";
404
405    /**
406     * Specifies if a user is disallowed from configuring cell
407     * broadcasts. This can only be set by device owners and profile owners on the primary user.
408     * The default value is <code>false</code>.
409     * <p>This restriction has no effect on secondary users and managed profiles since only the
410     * primary user can configure cell broadcasts.
411     *
412     * <p>Key for user restrictions.
413     * <p>Type: Boolean
414     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
415     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
416     * @see #getUserRestrictions()
417     */
418    public static final String DISALLOW_CONFIG_CELL_BROADCASTS = "no_config_cell_broadcasts";
419
420    /**
421     * Specifies if a user is disallowed from configuring mobile
422     * networks. This can only be set by device owners and profile owners on the primary user.
423     * The default value is <code>false</code>.
424     * <p>This restriction has no effect on secondary users and managed profiles since only the
425     * primary user can configure mobile networks.
426     *
427     * <p>Key for user restrictions.
428     * <p>Type: Boolean
429     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
430     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
431     * @see #getUserRestrictions()
432     */
433    public static final String DISALLOW_CONFIG_MOBILE_NETWORKS = "no_config_mobile_networks";
434
435    /**
436     * Specifies if a user is disallowed from modifying
437     * applications in Settings or launchers. The following actions will not be allowed when this
438     * restriction is enabled:
439     * <li>uninstalling apps</li>
440     * <li>disabling apps</li>
441     * <li>clearing app caches</li>
442     * <li>clearing app data</li>
443     * <li>force stopping apps</li>
444     * <li>clearing app defaults</li>
445     * <p>
446     * The default value is <code>false</code>.
447     *
448     * <p><strong>Note:</strong> The user will still be able to perform those actions via other
449     * means (such as adb). Third party apps will also be able to uninstall apps via the
450     * {@link android.content.pm.PackageInstaller}. {@link #DISALLOW_UNINSTALL_APPS} or
451     * {@link DevicePolicyManager#setUninstallBlocked(ComponentName, String, boolean)} should be
452     * used to prevent the user from uninstalling apps completely, and
453     * {@link DevicePolicyManager#addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}
454     * to add a default intent handler for a given intent filter.
455     *
456     * <p>Key for user restrictions.
457     * <p>Type: Boolean
458     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
459     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
460     * @see #getUserRestrictions()
461     */
462    public static final String DISALLOW_APPS_CONTROL = "no_control_apps";
463
464    /**
465     * Specifies if a user is disallowed from mounting
466     * physical external media. This can only be set by device owners and profile owners on the
467     * primary user. The default value is <code>false</code>.
468     *
469     * <p>Key for user restrictions.
470     * <p>Type: Boolean
471     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
472     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
473     * @see #getUserRestrictions()
474     */
475    public static final String DISALLOW_MOUNT_PHYSICAL_MEDIA = "no_physical_media";
476
477    /**
478     * Specifies if a user is disallowed from adjusting microphone volume. If set, the microphone
479     * will be muted. This can be set by device owners and profile owners. The default value is
480     * <code>false</code>.
481     *
482     * <p>This restriction has no effect on managed profiles.
483     * <p>Key for user restrictions.
484     * <p>Type: Boolean
485     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
486     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
487     * @see #getUserRestrictions()
488     */
489    public static final String DISALLOW_UNMUTE_MICROPHONE = "no_unmute_microphone";
490
491    /**
492     * Specifies if a user is disallowed from adjusting the master volume. If set, the master volume
493     * will be muted. This can be set by device owners and profile owners. The default value is
494     * <code>false</code>.
495     *
496     * <p>This restriction has no effect on managed profiles.
497     * <p>Key for user restrictions.
498     * <p>Type: Boolean
499     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
500     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
501     * @see #getUserRestrictions()
502     */
503    public static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume";
504
505    /**
506     * Specifies that the user is not allowed to make outgoing
507     * phone calls. Emergency calls are still permitted.
508     * The default value is <code>false</code>.
509     * <p>This restriction has no effect on managed profiles.
510     *
511     * <p>Key for user restrictions.
512     * <p>Type: Boolean
513     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
514     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
515     * @see #getUserRestrictions()
516     */
517    public static final String DISALLOW_OUTGOING_CALLS = "no_outgoing_calls";
518
519    /**
520     * Specifies that the user is not allowed to send or receive
521     * SMS messages. The default value is <code>false</code>.
522     *
523     * <p>Key for user restrictions.
524     * <p>Type: Boolean
525     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
526     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
527     * @see #getUserRestrictions()
528     */
529    public static final String DISALLOW_SMS = "no_sms";
530
531    /**
532     * Specifies if the user is not allowed to have fun. In some cases, the
533     * device owner may wish to prevent the user from experiencing amusement or
534     * joy while using the device. The default value is <code>false</code>.
535     *
536     * <p>Key for user restrictions.
537     * <p>Type: Boolean
538     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
539     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
540     * @see #getUserRestrictions()
541     */
542    public static final String DISALLOW_FUN = "no_fun";
543
544    /**
545     * Specifies that windows besides app windows should not be
546     * created. This will block the creation of the following types of windows.
547     * <li>{@link LayoutParams#TYPE_TOAST}</li>
548     * <li>{@link LayoutParams#TYPE_PHONE}</li>
549     * <li>{@link LayoutParams#TYPE_PRIORITY_PHONE}</li>
550     * <li>{@link LayoutParams#TYPE_SYSTEM_ALERT}</li>
551     * <li>{@link LayoutParams#TYPE_SYSTEM_ERROR}</li>
552     * <li>{@link LayoutParams#TYPE_SYSTEM_OVERLAY}</li>
553     * <li>{@link LayoutParams#TYPE_APPLICATION_OVERLAY}</li>
554     *
555     * <p>This can only be set by device owners and profile owners on the primary user.
556     * The default value is <code>false</code>.
557     *
558     * <p>Key for user restrictions.
559     * <p>Type: Boolean
560     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
561     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
562     * @see #getUserRestrictions()
563     */
564    public static final String DISALLOW_CREATE_WINDOWS = "no_create_windows";
565
566    /**
567     * Specifies if what is copied in the clipboard of this profile can
568     * be pasted in related profiles. Does not restrict if the clipboard of related profiles can be
569     * pasted in this profile.
570     * The default value is <code>false</code>.
571     *
572     * <p>Key for user restrictions.
573     * <p>Type: Boolean
574     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
575     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
576     * @see #getUserRestrictions()
577     */
578    public static final String DISALLOW_CROSS_PROFILE_COPY_PASTE = "no_cross_profile_copy_paste";
579
580    /**
581     * Specifies if the user is not allowed to use NFC to beam out data from apps.
582     * The default value is <code>false</code>.
583     *
584     * <p>Key for user restrictions.
585     * <p>Type: Boolean
586     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
587     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
588     * @see #getUserRestrictions()
589     */
590    public static final String DISALLOW_OUTGOING_BEAM = "no_outgoing_beam";
591
592    /**
593     * Hidden user restriction to disallow access to wallpaper manager APIs. This restriction
594     * generally means that wallpapers are not supported for the particular user. This user
595     * restriction is always set for managed profiles, because such profiles don't have wallpapers.
596     * @hide
597     * @see #DISALLOW_SET_WALLPAPER
598     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
599     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
600     * @see #getUserRestrictions()
601     */
602    public static final String DISALLOW_WALLPAPER = "no_wallpaper";
603
604    /**
605     * User restriction to disallow setting a wallpaper. Profile owner and device owner
606     * are able to set wallpaper regardless of this restriction.
607     * The default value is <code>false</code>.
608     *
609     * <p>Key for user restrictions.
610     * <p>Type: Boolean
611     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
612     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
613     * @see #getUserRestrictions()
614     */
615    public static final String DISALLOW_SET_WALLPAPER = "no_set_wallpaper";
616
617    /**
618     * Specifies if the user is not allowed to reboot the device into safe boot mode.
619     * This can only be set by device owners and profile owners on the primary user.
620     * The default value is <code>false</code>.
621     *
622     * <p>Key for user restrictions.
623     * <p>Type: Boolean
624     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
625     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
626     * @see #getUserRestrictions()
627     */
628    public static final String DISALLOW_SAFE_BOOT = "no_safe_boot";
629
630    /**
631     * Specifies if a user is not allowed to record audio. This restriction is always enabled for
632     * background users. The default value is <code>false</code>.
633     *
634     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
635     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
636     * @see #getUserRestrictions()
637     * @hide
638     */
639    public static final String DISALLOW_RECORD_AUDIO = "no_record_audio";
640
641    /**
642     * Specifies if a user is not allowed to run in the background and should be stopped during
643     * user switch. The default value is <code>false</code>.
644     *
645     * <p>This restriction can be set by device owners and profile owners.
646     *
647     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
648     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
649     * @see #getUserRestrictions()
650     * @hide
651     */
652    public static final String DISALLOW_RUN_IN_BACKGROUND = "no_run_in_background";
653
654    /**
655     * Specifies if a user is not allowed to use the camera.
656     *
657     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
658     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
659     * @see #getUserRestrictions()
660     * @hide
661     */
662    public static final String DISALLOW_CAMERA = "no_camera";
663
664    /**
665     * Specifies if a user is not allowed to unmute the device's master volume.
666     *
667     * @see DevicePolicyManager#setMasterVolumeMuted(ComponentName, boolean)
668     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
669     * @see #getUserRestrictions()
670     * @hide
671     */
672    public static final String DISALLOW_UNMUTE_DEVICE = "disallow_unmute_device";
673
674    /**
675     * Specifies if a user is not allowed to use cellular data when roaming. This can only be set by
676     * device owners. The default value is <code>false</code>.
677     *
678     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
679     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
680     * @see #getUserRestrictions()
681     */
682    public static final String DISALLOW_DATA_ROAMING = "no_data_roaming";
683
684    /**
685     * Specifies if a user is not allowed to change their icon. Device owner and profile owner
686     * can set this restriction. When it is set by device owner, only the target user will be
687     * affected. The default value is <code>false</code>.
688     *
689     * <p>Key for user restrictions.
690     * <p>Type: Boolean
691     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
692     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
693     * @see #getUserRestrictions()
694     */
695    public static final String DISALLOW_SET_USER_ICON = "no_set_user_icon";
696
697    /**
698     * Specifies if a user is not allowed to enable the oem unlock setting. The default value is
699     * <code>false</code>. Setting this restriction has no effect if the bootloader is already
700     * unlocked.
701     *
702     * <p>Not for use by third-party applications.
703     *
704     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
705     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
706     * @see #getUserRestrictions()
707     * @deprecated use {@link OemLockManager#setOemUnlockAllowedByCarrier(boolean, byte[])} instead.
708     * @hide
709     */
710    @Deprecated
711    @SystemApi
712    public static final String DISALLOW_OEM_UNLOCK = "no_oem_unlock";
713
714    /**
715     * Allows apps in the parent profile to handle web links from the managed profile.
716     *
717     * This user restriction has an effect only in a managed profile.
718     * If set:
719     * Intent filters of activities in the parent profile with action
720     * {@link android.content.Intent#ACTION_VIEW},
721     * category {@link android.content.Intent#CATEGORY_BROWSABLE}, scheme http or https, and which
722     * define a host can handle intents from the managed profile.
723     * The default value is <code>false</code>.
724     *
725     * <p>Key for user restrictions.
726     * <p>Type: Boolean
727     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
728     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
729     * @see #getUserRestrictions()
730     */
731    public static final String ALLOW_PARENT_PROFILE_APP_LINKING
732            = "allow_parent_profile_app_linking";
733
734    /**
735     * Specifies if a user is not allowed to use Autofill Services.
736     *
737     * <p>Device owner and profile owner can set this restriction. When it is set by device owner,
738     * only the target user will be affected.
739     *
740     * <p>The default value is <code>false</code>.
741     *
742     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
743     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
744     * @see #getUserRestrictions()
745     */
746    public static final String DISALLOW_AUTOFILL = "no_autofill";
747
748    /**
749     * Application restriction key that is used to indicate the pending arrival
750     * of real restrictions for the app.
751     *
752     * <p>
753     * Applications that support restrictions should check for the presence of this key.
754     * A <code>true</code> value indicates that restrictions may be applied in the near
755     * future but are not available yet. It is the responsibility of any
756     * management application that sets this flag to update it when the final
757     * restrictions are enforced.
758     *
759     * <p>Key for application restrictions.
760     * <p>Type: Boolean
761     * @see android.app.admin.DevicePolicyManager#setApplicationRestrictions(
762     *      android.content.ComponentName, String, Bundle)
763     * @see android.app.admin.DevicePolicyManager#getApplicationRestrictions(
764     *      android.content.ComponentName, String)
765     */
766    public static final String KEY_RESTRICTIONS_PENDING = "restrictions_pending";
767
768    private static final String ACTION_CREATE_USER = "android.os.action.CREATE_USER";
769
770    /**
771     * Extra containing a name for the user being created. Optional parameter passed to
772     * ACTION_CREATE_USER activity.
773     * @hide
774     */
775    public static final String EXTRA_USER_NAME = "android.os.extra.USER_NAME";
776
777    /**
778     * Extra containing account name for the user being created. Optional parameter passed to
779     * ACTION_CREATE_USER activity.
780     * @hide
781     */
782    public static final String EXTRA_USER_ACCOUNT_NAME = "android.os.extra.USER_ACCOUNT_NAME";
783
784    /**
785     * Extra containing account type for the user being created. Optional parameter passed to
786     * ACTION_CREATE_USER activity.
787     * @hide
788     */
789    public static final String EXTRA_USER_ACCOUNT_TYPE = "android.os.extra.USER_ACCOUNT_TYPE";
790
791    /**
792     * Extra containing account-specific data for the user being created. Optional parameter passed
793     * to ACTION_CREATE_USER activity.
794     * @hide
795     */
796    public static final String EXTRA_USER_ACCOUNT_OPTIONS
797            = "android.os.extra.USER_ACCOUNT_OPTIONS";
798
799    /** @hide */
800    public static final int PIN_VERIFICATION_FAILED_INCORRECT = -3;
801    /** @hide */
802    public static final int PIN_VERIFICATION_FAILED_NOT_SET = -2;
803    /** @hide */
804    public static final int PIN_VERIFICATION_SUCCESS = -1;
805
806    /**
807     * Sent when user restrictions have changed.
808     *
809     * @hide
810     */
811    @SystemApi
812    @TestApi // To allow seeing it from CTS.
813    public static final String ACTION_USER_RESTRICTIONS_CHANGED =
814            "android.os.action.USER_RESTRICTIONS_CHANGED";
815
816    /**
817     * Error result indicating that this user is not allowed to add other users on this device.
818     * This is a result code returned from the activity created by the intent
819     * {@link #createUserCreationIntent(String, String, String, PersistableBundle)}.
820     */
821    public static final int USER_CREATION_FAILED_NOT_PERMITTED = Activity.RESULT_FIRST_USER;
822
823    /**
824     * Error result indicating that no more users can be created on this device.
825     * This is a result code returned from the activity created by the intent
826     * {@link #createUserCreationIntent(String, String, String, PersistableBundle)}.
827     */
828    public static final int USER_CREATION_FAILED_NO_MORE_USERS = Activity.RESULT_FIRST_USER + 1;
829
830    /** @hide */
831    public static UserManager get(Context context) {
832        return (UserManager) context.getSystemService(Context.USER_SERVICE);
833    }
834
835    /** @hide */
836    public UserManager(Context context, IUserManager service) {
837        mService = service;
838        mContext = context.getApplicationContext();
839    }
840
841    /**
842     * Returns whether this device supports multiple users with their own login and customizable
843     * space.
844     * @return whether the device supports multiple users.
845     */
846    public static boolean supportsMultipleUsers() {
847        return getMaxSupportedUsers() > 1
848                && SystemProperties.getBoolean("fw.show_multiuserui",
849                Resources.getSystem().getBoolean(R.bool.config_enableMultiUserUI));
850    }
851
852    /**
853     * @hide
854     * @return Whether the device is running with split system user. It means the system user and
855     * primary user are two separate users. Previously system user and primary user are combined as
856     * a single owner user.  see @link {android.os.UserHandle#USER_OWNER}
857     */
858    public static boolean isSplitSystemUser() {
859        return RoSystemProperties.FW_SYSTEM_USER_SPLIT;
860    }
861
862    /**
863     * @return Whether guest user is always ephemeral
864     * @hide
865     */
866    public static boolean isGuestUserEphemeral() {
867        return Resources.getSystem()
868                .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
869    }
870
871    /**
872     * Returns whether switching users is currently allowed.
873     * <p>For instance switching users is not allowed if the current user is in a phone call,
874     * or system user hasn't been unlocked yet
875     * @hide
876     */
877    public boolean canSwitchUsers() {
878        boolean allowUserSwitchingWhenSystemUserLocked = Settings.Global.getInt(
879                mContext.getContentResolver(),
880                Settings.Global.ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED, 0) != 0;
881        boolean isSystemUserUnlocked = isUserUnlocked(UserHandle.SYSTEM);
882        boolean inCall = TelephonyManager.getDefault().getCallState()
883                != TelephonyManager.CALL_STATE_IDLE;
884        return (allowUserSwitchingWhenSystemUserLocked || isSystemUserUnlocked) && !inCall;
885    }
886
887    /**
888     * Returns the user handle for the user that this process is running under.
889     *
890     * @return the user handle of this process.
891     * @hide
892     */
893    public @UserIdInt int getUserHandle() {
894        return UserHandle.myUserId();
895    }
896
897    /**
898     * Returns the user name of the user making this call.  This call is only
899     * available to applications on the system image; it requires the
900     * MANAGE_USERS permission.
901     * @return the user name
902     */
903    public String getUserName() {
904        try {
905            return mService.getUserInfo(getUserHandle()).name;
906        } catch (RemoteException re) {
907            throw re.rethrowFromSystemServer();
908        }
909    }
910
911    /**
912     * Returns whether user name has been set.
913     * <p>This method can be used to check that the value returned by {@link #getUserName()} was
914     * set by the user and is not a placeholder string provided by the system.
915     * @hide
916     */
917    public boolean isUserNameSet() {
918        try {
919            return mService.isUserNameSet(getUserHandle());
920        } catch (RemoteException re) {
921            throw re.rethrowFromSystemServer();
922        }
923    }
924
925    /**
926     * Used to determine whether the user making this call is subject to
927     * teleportations.
928     *
929     * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
930     * now automatically identify goats using advanced goat recognition technology.</p>
931     *
932     * @return Returns true if the user making this call is a goat.
933     */
934    public boolean isUserAGoat() {
935        return mContext.getPackageManager()
936                .isPackageAvailable("com.coffeestainstudios.goatsimulator");
937    }
938
939    /**
940     * Used to check if this process is running under the primary user. The primary user
941     * is the first human user on a device.
942     *
943     * @return whether this process is running under the primary user.
944     * @hide
945     */
946    public boolean isPrimaryUser() {
947        UserInfo user = getUserInfo(UserHandle.myUserId());
948        return user != null && user.isPrimary();
949    }
950
951    /**
952     * Used to check if this process is running under the system user. The system user
953     * is the initial user that is implicitly created on first boot and hosts most of the
954     * system services.
955     *
956     * @return whether this process is running under the system user.
957     */
958    public boolean isSystemUser() {
959        return UserHandle.myUserId() == UserHandle.USER_SYSTEM;
960    }
961
962    /**
963     * @hide
964     * Returns whether the caller is running as an admin user. There can be more than one admin
965     * user.
966     */
967    public boolean isAdminUser() {
968        return isUserAdmin(UserHandle.myUserId());
969    }
970
971    /**
972     * @hide
973     * Returns whether the provided user is an admin user. There can be more than one admin
974     * user.
975     */
976    public boolean isUserAdmin(@UserIdInt int userId) {
977        UserInfo user = getUserInfo(userId);
978        return user != null && user.isAdmin();
979    }
980
981    /**
982     * Used to check if the user making this call is linked to another user. Linked users may have
983     * a reduced number of available apps, app restrictions and account restrictions.
984     * @return whether the user making this call is a linked user
985     * @hide
986     */
987    public boolean isLinkedUser() {
988        try {
989            return mService.isRestricted();
990        } catch (RemoteException re) {
991            throw re.rethrowFromSystemServer();
992        }
993    }
994
995    /**
996     * Checks if specified user can have restricted profile.
997     * @hide
998     */
999    public boolean canHaveRestrictedProfile(@UserIdInt int userId) {
1000        try {
1001            return mService.canHaveRestrictedProfile(userId);
1002        } catch (RemoteException re) {
1003            throw re.rethrowFromSystemServer();
1004        }
1005    }
1006
1007    /**
1008     * Checks if a user is a guest user.
1009     * @return whether user is a guest user.
1010     * @hide
1011     */
1012    public boolean isGuestUser(int id) {
1013        UserInfo user = getUserInfo(id);
1014        return user != null && user.isGuest();
1015    }
1016
1017    /**
1018     * Checks if the calling app is running as a guest user.
1019     * @return whether the caller is a guest user.
1020     * @hide
1021     */
1022    public boolean isGuestUser() {
1023        UserInfo user = getUserInfo(UserHandle.myUserId());
1024        return user != null && user.isGuest();
1025    }
1026
1027    /**
1028     * Checks if the calling app is running in a demo user. When running in a demo user,
1029     * apps can be more helpful to the user, or explain their features in more detail.
1030     *
1031     * @return whether the caller is a demo user.
1032     */
1033    public boolean isDemoUser() {
1034        try {
1035            return mService.isDemoUser(UserHandle.myUserId());
1036        } catch (RemoteException re) {
1037            throw re.rethrowFromSystemServer();
1038        }
1039    }
1040
1041    /**
1042     * Checks if the calling app is running in a managed profile.
1043     *
1044     * @return whether the caller is in a managed profile.
1045     * @hide
1046     */
1047    @SystemApi
1048    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
1049    public boolean isManagedProfile() {
1050        // No need for synchronization.  Once it becomes non-null, it'll be non-null forever.
1051        // Worst case we might end up calling the AIDL method multiple times but that's fine.
1052        if (mIsManagedProfileCached != null) {
1053            return mIsManagedProfileCached;
1054        }
1055        try {
1056            mIsManagedProfileCached = mService.isManagedProfile(UserHandle.myUserId());
1057            return mIsManagedProfileCached;
1058        } catch (RemoteException re) {
1059            throw re.rethrowFromSystemServer();
1060        }
1061    }
1062
1063    /**
1064     * Checks if the specified user is a managed profile.
1065     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission, otherwise the caller
1066     * must be in the same profile group of specified user.
1067     *
1068     * @return whether the specified user is a managed profile.
1069     * @hide
1070     */
1071    @SystemApi
1072    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
1073    public boolean isManagedProfile(@UserIdInt int userId) {
1074        if (userId == UserHandle.myUserId()) {
1075            return isManagedProfile();
1076        }
1077        try {
1078            return mService.isManagedProfile(userId);
1079        } catch (RemoteException re) {
1080            throw re.rethrowFromSystemServer();
1081        }
1082    }
1083
1084    /**
1085     * Gets badge for a managed profile.
1086     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission, otherwise the caller
1087     * must be in the same profile group of specified user.
1088     *
1089     * @return which badge to use for the managed profile badge id will be less than
1090     *         UserManagerService.getMaxManagedProfiles()
1091     * @hide
1092     */
1093    public int getManagedProfileBadge(@UserIdInt int userId) {
1094        try {
1095            return mService.getManagedProfileBadge(userId);
1096        } catch (RemoteException re) {
1097            throw re.rethrowFromSystemServer();
1098        }
1099    }
1100
1101    /**
1102     * Checks if the calling app is running as an ephemeral user.
1103     *
1104     * @return whether the caller is an ephemeral user.
1105     * @hide
1106     */
1107    public boolean isEphemeralUser() {
1108        return isUserEphemeral(UserHandle.myUserId());
1109    }
1110
1111    /**
1112     * Returns whether the specified user is ephemeral.
1113     * @hide
1114     */
1115    public boolean isUserEphemeral(@UserIdInt int userId) {
1116        final UserInfo user = getUserInfo(userId);
1117        return user != null && user.isEphemeral();
1118    }
1119
1120    /**
1121     * Return whether the given user is actively running.  This means that
1122     * the user is in the "started" state, not "stopped" -- it is currently
1123     * allowed to run code through scheduled alarms, receiving broadcasts,
1124     * etc.  A started user may be either the current foreground user or a
1125     * background user; the result here does not distinguish between the two.
1126     *
1127     * <p>Note prior to Android Nougat MR1 (SDK version <= 24;
1128     * {@link android.os.Build.VERSION_CODES#N), this API required a system permission
1129     * in order to check other profile's status.
1130     * Since Android Nougat MR1 (SDK version >= 25;
1131     * {@link android.os.Build.VERSION_CODES#N_MR1)), the restriction has been relaxed, and now
1132     * it'll accept any {@link UserHandle} within the same profile group as the caller.
1133     *
1134     * @param user The user to retrieve the running state for.
1135     */
1136    // Note this requires either INTERACT_ACROSS_USERS or MANAGE_USERS.
1137    public boolean isUserRunning(UserHandle user) {
1138        return isUserRunning(user.getIdentifier());
1139    }
1140
1141    /** {@hide} */
1142    public boolean isUserRunning(@UserIdInt int userId) {
1143        try {
1144            return mService.isUserRunning(userId);
1145        } catch (RemoteException re) {
1146            throw re.rethrowFromSystemServer();
1147        }
1148    }
1149
1150    /**
1151     * Return whether the given user is actively running <em>or</em> stopping.
1152     * This is like {@link #isUserRunning(UserHandle)}, but will also return
1153     * true if the user had been running but is in the process of being stopped
1154     * (but is not yet fully stopped, and still running some code).
1155     *
1156     * <p>Note prior to Android Nougat MR1 (SDK version <= 24;
1157     * {@link android.os.Build.VERSION_CODES#N), this API required a system permission
1158     * in order to check other profile's status.
1159     * Since Android Nougat MR1 (SDK version >= 25;
1160     * {@link android.os.Build.VERSION_CODES#N_MR1)), the restriction has been relaxed, and now
1161     * it'll accept any {@link UserHandle} within the same profile group as the caller.
1162     *
1163     * @param user The user to retrieve the running state for.
1164     */
1165    // Note this requires either INTERACT_ACROSS_USERS or MANAGE_USERS.
1166    public boolean isUserRunningOrStopping(UserHandle user) {
1167        try {
1168            // TODO: reconcile stopped vs stopping?
1169            return ActivityManager.getService().isUserRunning(
1170                    user.getIdentifier(), ActivityManager.FLAG_OR_STOPPED);
1171        } catch (RemoteException re) {
1172            throw re.rethrowFromSystemServer();
1173        }
1174    }
1175
1176    /**
1177     * Return whether the calling user is running in an "unlocked" state.
1178     * <p>
1179     * On devices with direct boot, a user is unlocked only after they've
1180     * entered their credentials (such as a lock pattern or PIN). On devices
1181     * without direct boot, a user is unlocked as soon as it starts.
1182     * <p>
1183     * When a user is locked, only device-protected data storage is available.
1184     * When a user is unlocked, both device-protected and credential-protected
1185     * private app data storage is available.
1186     *
1187     * @see Intent#ACTION_USER_UNLOCKED
1188     * @see Context#createDeviceProtectedStorageContext()
1189     */
1190    public boolean isUserUnlocked() {
1191        return isUserUnlocked(Process.myUserHandle());
1192    }
1193
1194    /**
1195     * Return whether the given user is running in an "unlocked" state.
1196     * <p>
1197     * On devices with direct boot, a user is unlocked only after they've
1198     * entered their credentials (such as a lock pattern or PIN). On devices
1199     * without direct boot, a user is unlocked as soon as it starts.
1200     * <p>
1201     * When a user is locked, only device-protected data storage is available.
1202     * When a user is unlocked, both device-protected and credential-protected
1203     * private app data storage is available.
1204     * <p>Requires {@code android.permission.MANAGE_USERS} or
1205     * {@code android.permission.INTERACT_ACROSS_USERS}, otherwise specified {@link UserHandle user}
1206     * must be the calling user or a managed profile associated with it.
1207     *
1208     * @param user to retrieve the unlocked state for.
1209     * @see Intent#ACTION_USER_UNLOCKED
1210     * @see Context#createDeviceProtectedStorageContext()
1211     */
1212    public boolean isUserUnlocked(UserHandle user) {
1213        return isUserUnlocked(user.getIdentifier());
1214    }
1215
1216    /** {@hide} */
1217    public boolean isUserUnlocked(@UserIdInt int userId) {
1218        try {
1219            return mService.isUserUnlocked(userId);
1220        } catch (RemoteException re) {
1221            throw re.rethrowFromSystemServer();
1222        }
1223    }
1224
1225    /** {@hide} */
1226    public boolean isUserUnlockingOrUnlocked(UserHandle user) {
1227        return isUserUnlockingOrUnlocked(user.getIdentifier());
1228    }
1229
1230    /** {@hide} */
1231    public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
1232        try {
1233            return mService.isUserUnlockingOrUnlocked(userId);
1234        } catch (RemoteException re) {
1235            throw re.rethrowFromSystemServer();
1236        }
1237    }
1238
1239    /**
1240     * Returns the UserInfo object describing a specific user.
1241     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1242     * @param userHandle the user handle of the user whose information is being requested.
1243     * @return the UserInfo object for a specific user.
1244     * @hide
1245     */
1246    public UserInfo getUserInfo(@UserIdInt int userHandle) {
1247        try {
1248            return mService.getUserInfo(userHandle);
1249        } catch (RemoteException re) {
1250            throw re.rethrowFromSystemServer();
1251        }
1252    }
1253
1254    /**
1255     * @hide
1256     *
1257     * Returns who set a user restriction on a user.
1258     * @param restrictionKey the string key representing the restriction
1259     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1260     * @return The source of user restriction. Any combination of {@link #RESTRICTION_NOT_SET},
1261     *         {@link #RESTRICTION_SOURCE_SYSTEM}, {@link #RESTRICTION_SOURCE_DEVICE_OWNER}
1262     *         and {@link #RESTRICTION_SOURCE_PROFILE_OWNER}
1263     * @deprecated use {@link #getUserRestrictionSources(String, int)} instead.
1264     */
1265    @Deprecated
1266    @SystemApi
1267    @UserRestrictionSource
1268    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
1269    public int getUserRestrictionSource(String restrictionKey, UserHandle userHandle) {
1270        try {
1271            return mService.getUserRestrictionSource(restrictionKey, userHandle.getIdentifier());
1272        } catch (RemoteException re) {
1273            throw re.rethrowFromSystemServer();
1274        }
1275    }
1276
1277    /**
1278     * @hide
1279     *
1280     * Returns a list of users who set a user restriction on a given user.
1281     * @param restrictionKey the string key representing the restriction
1282     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1283     * @return a list of user ids enforcing this restriction.
1284     */
1285    @SystemApi
1286    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
1287    public List<EnforcingUser> getUserRestrictionSources(
1288            String restrictionKey, UserHandle userHandle) {
1289        try {
1290            return mService.getUserRestrictionSources(restrictionKey, userHandle.getIdentifier());
1291        } catch (RemoteException re) {
1292            throw re.rethrowFromSystemServer();
1293        }
1294    }
1295
1296    /**
1297     * Returns the user-wide restrictions imposed on this user.
1298     * @return a Bundle containing all the restrictions.
1299     */
1300    public Bundle getUserRestrictions() {
1301        return getUserRestrictions(Process.myUserHandle());
1302    }
1303
1304    /**
1305     * Returns the user-wide restrictions imposed on the user specified by <code>userHandle</code>.
1306     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1307     * @return a Bundle containing all the restrictions.
1308     */
1309    public Bundle getUserRestrictions(UserHandle userHandle) {
1310        try {
1311            return mService.getUserRestrictions(userHandle.getIdentifier());
1312        } catch (RemoteException re) {
1313            throw re.rethrowFromSystemServer();
1314        }
1315    }
1316
1317     /**
1318     * @hide
1319     * Returns whether the given user has been disallowed from performing certain actions
1320     * or setting certain settings through UserManager. This method disregards restrictions
1321     * set by device policy.
1322     * @param restrictionKey the string key representing the restriction
1323     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1324     */
1325    public boolean hasBaseUserRestriction(String restrictionKey, UserHandle userHandle) {
1326        try {
1327            return mService.hasBaseUserRestriction(restrictionKey, userHandle.getIdentifier());
1328        } catch (RemoteException re) {
1329            throw re.rethrowFromSystemServer();
1330        }
1331    }
1332
1333    /**
1334     * This will no longer work.  Device owners and profile owners should use
1335     * {@link DevicePolicyManager#addUserRestriction(ComponentName, String)} instead.
1336     */
1337    // System apps should use UserManager.setUserRestriction() instead.
1338    @Deprecated
1339    public void setUserRestrictions(Bundle restrictions) {
1340        throw new UnsupportedOperationException("This method is no longer supported");
1341    }
1342
1343    /**
1344     * This will no longer work.  Device owners and profile owners should use
1345     * {@link DevicePolicyManager#addUserRestriction(ComponentName, String)} instead.
1346     */
1347    // System apps should use UserManager.setUserRestriction() instead.
1348    @Deprecated
1349    public void setUserRestrictions(Bundle restrictions, UserHandle userHandle) {
1350        throw new UnsupportedOperationException("This method is no longer supported");
1351    }
1352
1353    /**
1354     * Sets the value of a specific restriction.
1355     * Requires the MANAGE_USERS permission.
1356     * @param key the key of the restriction
1357     * @param value the value for the restriction
1358     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
1359     * android.content.ComponentName, String)} or
1360     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
1361     * android.content.ComponentName, String)} instead.
1362     */
1363    @Deprecated
1364    public void setUserRestriction(String key, boolean value) {
1365        setUserRestriction(key, value, Process.myUserHandle());
1366    }
1367
1368    /**
1369     * @hide
1370     * Sets the value of a specific restriction on a specific user.
1371     * Requires the MANAGE_USERS permission.
1372     * @param key the key of the restriction
1373     * @param value the value for the restriction
1374     * @param userHandle the user whose restriction is to be changed.
1375     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
1376     * android.content.ComponentName, String)} or
1377     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
1378     * android.content.ComponentName, String)} instead.
1379     */
1380    @Deprecated
1381    public void setUserRestriction(String key, boolean value, UserHandle userHandle) {
1382        try {
1383            mService.setUserRestriction(key, value, userHandle.getIdentifier());
1384        } catch (RemoteException re) {
1385            throw re.rethrowFromSystemServer();
1386        }
1387    }
1388
1389    /**
1390     * Returns whether the current user has been disallowed from performing certain actions
1391     * or setting certain settings.
1392     *
1393     * @param restrictionKey The string key representing the restriction.
1394     * @return {@code true} if the current user has the given restriction, {@code false} otherwise.
1395     */
1396    public boolean hasUserRestriction(String restrictionKey) {
1397        return hasUserRestriction(restrictionKey, Process.myUserHandle());
1398    }
1399
1400    /**
1401     * @hide
1402     * Returns whether the given user has been disallowed from performing certain actions
1403     * or setting certain settings.
1404     * @param restrictionKey the string key representing the restriction
1405     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1406     */
1407    public boolean hasUserRestriction(String restrictionKey, UserHandle userHandle) {
1408        try {
1409            return mService.hasUserRestriction(restrictionKey,
1410                    userHandle.getIdentifier());
1411        } catch (RemoteException re) {
1412            throw re.rethrowFromSystemServer();
1413        }
1414    }
1415
1416    /**
1417     * Return the serial number for a user.  This is a device-unique
1418     * number assigned to that user; if the user is deleted and then a new
1419     * user created, the new users will not be given the same serial number.
1420     * @param user The user whose serial number is to be retrieved.
1421     * @return The serial number of the given user; returns -1 if the
1422     * given UserHandle does not exist.
1423     * @see #getUserForSerialNumber(long)
1424     */
1425    public long getSerialNumberForUser(UserHandle user) {
1426        return getUserSerialNumber(user.getIdentifier());
1427    }
1428
1429    /**
1430     * Return the user associated with a serial number previously
1431     * returned by {@link #getSerialNumberForUser(UserHandle)}.
1432     * @param serialNumber The serial number of the user that is being
1433     * retrieved.
1434     * @return Return the user associated with the serial number, or null
1435     * if there is not one.
1436     * @see #getSerialNumberForUser(UserHandle)
1437     */
1438    public UserHandle getUserForSerialNumber(long serialNumber) {
1439        int ident = getUserHandle((int) serialNumber);
1440        return ident >= 0 ? new UserHandle(ident) : null;
1441    }
1442
1443    /**
1444     * Creates a user with the specified name and options. For non-admin users, default user
1445     * restrictions are going to be applied.
1446     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1447     *
1448     * @param name the user's name
1449     * @param flags flags that identify the type of user and other properties.
1450     * @see UserInfo
1451     *
1452     * @return the UserInfo object for the created user, or null if the user could not be created.
1453     * @hide
1454     */
1455    public UserInfo createUser(String name, int flags) {
1456        UserInfo user = null;
1457        try {
1458            user = mService.createUser(name, flags);
1459            // TODO: Keep this in sync with
1460            // UserManagerService.LocalService.createUserEvenWhenDisallowed
1461            if (user != null && !user.isAdmin()) {
1462                mService.setUserRestriction(DISALLOW_SMS, true, user.id);
1463                mService.setUserRestriction(DISALLOW_OUTGOING_CALLS, true, user.id);
1464            }
1465        } catch (RemoteException re) {
1466            throw re.rethrowFromSystemServer();
1467        }
1468        return user;
1469    }
1470
1471    /**
1472     * Creates a guest user and configures it.
1473     * @param context an application context
1474     * @param name the name to set for the user
1475     * @hide
1476     */
1477    public UserInfo createGuest(Context context, String name) {
1478        UserInfo guest = null;
1479        try {
1480            guest = mService.createUser(name, UserInfo.FLAG_GUEST);
1481            if (guest != null) {
1482                Settings.Secure.putStringForUser(context.getContentResolver(),
1483                        Settings.Secure.SKIP_FIRST_USE_HINTS, "1", guest.id);
1484            }
1485        } catch (RemoteException re) {
1486            throw re.rethrowFromSystemServer();
1487        }
1488        return guest;
1489    }
1490
1491    /**
1492     * Creates a user with the specified name and options as a profile of another user.
1493     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1494     *
1495     * @param name the user's name
1496     * @param flags flags that identify the type of user and other properties.
1497     * @param userHandle new user will be a profile of this user.
1498     *
1499     * @return the {@link UserInfo} object for the created user, or null if the user
1500     *         could not be created.
1501     * @hide
1502     */
1503    public UserInfo createProfileForUser(String name, int flags, @UserIdInt int userHandle) {
1504        return createProfileForUser(name, flags, userHandle, null);
1505    }
1506
1507    /**
1508     * Version of {@link #createProfileForUser(String, int, int)} that allows you to specify
1509     * any packages that should not be installed in the new profile by default, these packages can
1510     * still be installed later by the user if needed.
1511     *
1512     * @param name the user's name
1513     * @param flags flags that identify the type of user and other properties.
1514     * @param userHandle new user will be a profile of this user.
1515     * @param disallowedPackages packages that will not be installed in the profile being created.
1516     *
1517     * @return the {@link UserInfo} object for the created user, or null if the user
1518     *         could not be created.
1519     * @hide
1520     */
1521    public UserInfo createProfileForUser(String name, int flags, @UserIdInt int userHandle,
1522            String[] disallowedPackages) {
1523        try {
1524            return mService.createProfileForUser(name, flags, userHandle, disallowedPackages);
1525        } catch (RemoteException re) {
1526            throw re.rethrowFromSystemServer();
1527        }
1528    }
1529
1530    /**
1531     * Similar to {@link #createProfileForUser(String, int, int, String[])}
1532     * except bypassing the checking of {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
1533     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1534     *
1535     * @see #createProfileForUser(String, int, int, String[])
1536     * @hide
1537     */
1538    public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags,
1539            @UserIdInt int userHandle, String[] disallowedPackages) {
1540        try {
1541            return mService.createProfileForUserEvenWhenDisallowed(name, flags, userHandle,
1542                    disallowedPackages);
1543        } catch (RemoteException re) {
1544            throw re.rethrowFromSystemServer();
1545        }
1546    }
1547
1548    /**
1549     * Creates a restricted profile with the specified name. This method also sets necessary
1550     * restrictions and adds shared accounts.
1551     *
1552     * @param name profile's name
1553     * @return UserInfo object for the created user, or null if the user could not be created.
1554     * @hide
1555     */
1556    public UserInfo createRestrictedProfile(String name) {
1557        try {
1558            UserHandle parentUserHandle = Process.myUserHandle();
1559            UserInfo user = mService.createRestrictedProfile(name,
1560                    parentUserHandle.getIdentifier());
1561            if (user != null) {
1562                AccountManager.get(mContext).addSharedAccountsFromParentUser(parentUserHandle,
1563                        UserHandle.of(user.id));
1564            }
1565            return user;
1566        } catch (RemoteException re) {
1567            throw re.rethrowFromSystemServer();
1568        }
1569    }
1570
1571    /**
1572     * Returns an intent to create a user for the provided name and account name. The name
1573     * and account name will be used when the setup process for the new user is started.
1574     * <p>
1575     * The intent should be launched using startActivityForResult and the return result will
1576     * indicate if the user consented to adding a new user and if the operation succeeded. Any
1577     * errors in creating the user will be returned in the result code. If the user cancels the
1578     * request, the return result will be {@link Activity#RESULT_CANCELED}. On success, the
1579     * result code will be {@link Activity#RESULT_OK}.
1580     * <p>
1581     * Use {@link #supportsMultipleUsers()} to first check if the device supports this operation
1582     * at all.
1583     * <p>
1584     * The new user is created but not initialized. After switching into the user for the first
1585     * time, the preferred user name and account information are used by the setup process for that
1586     * user.
1587     *
1588     * @param userName Optional name to assign to the user.
1589     * @param accountName Optional account name that will be used by the setup wizard to initialize
1590     *                    the user.
1591     * @param accountType Optional account type for the account to be created. This is required
1592     *                    if the account name is specified.
1593     * @param accountOptions Optional bundle of data to be passed in during account creation in the
1594     *                       new user via {@link AccountManager#addAccount(String, String, String[],
1595     *                       Bundle, android.app.Activity, android.accounts.AccountManagerCallback,
1596     *                       Handler)}.
1597     * @return An Intent that can be launched from an Activity.
1598     * @see #USER_CREATION_FAILED_NOT_PERMITTED
1599     * @see #USER_CREATION_FAILED_NO_MORE_USERS
1600     * @see #supportsMultipleUsers
1601     */
1602    public static Intent createUserCreationIntent(@Nullable String userName,
1603            @Nullable String accountName,
1604            @Nullable String accountType, @Nullable PersistableBundle accountOptions) {
1605        Intent intent = new Intent(ACTION_CREATE_USER);
1606        if (userName != null) {
1607            intent.putExtra(EXTRA_USER_NAME, userName);
1608        }
1609        if (accountName != null && accountType == null) {
1610            throw new IllegalArgumentException("accountType must be specified if accountName is "
1611                    + "specified");
1612        }
1613        if (accountName != null) {
1614            intent.putExtra(EXTRA_USER_ACCOUNT_NAME, accountName);
1615        }
1616        if (accountType != null) {
1617            intent.putExtra(EXTRA_USER_ACCOUNT_TYPE, accountType);
1618        }
1619        if (accountOptions != null) {
1620            intent.putExtra(EXTRA_USER_ACCOUNT_OPTIONS, accountOptions);
1621        }
1622        return intent;
1623    }
1624
1625    /**
1626     * @hide
1627     *
1628     * Returns the preferred account name for user creation.
1629     */
1630    @SystemApi
1631    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
1632    public String getSeedAccountName() {
1633        try {
1634            return mService.getSeedAccountName();
1635        } catch (RemoteException re) {
1636            throw re.rethrowFromSystemServer();
1637        }
1638    }
1639
1640    /**
1641     * @hide
1642     *
1643     * Returns the preferred account type for user creation.
1644     */
1645    @SystemApi
1646    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
1647    public String getSeedAccountType() {
1648        try {
1649            return mService.getSeedAccountType();
1650        } catch (RemoteException re) {
1651            throw re.rethrowFromSystemServer();
1652        }
1653    }
1654
1655    /**
1656     * @hide
1657     *
1658     * Returns the preferred account's options bundle for user creation.
1659     * @return Any options set by the requestor that created the user.
1660     */
1661    @SystemApi
1662    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
1663    public PersistableBundle getSeedAccountOptions() {
1664        try {
1665            return mService.getSeedAccountOptions();
1666        } catch (RemoteException re) {
1667            throw re.rethrowFromSystemServer();
1668        }
1669    }
1670
1671    /**
1672     * @hide
1673     *
1674     * Called by a system activity to set the seed account information of a user created
1675     * through the user creation intent.
1676     * @param userId
1677     * @param accountName
1678     * @param accountType
1679     * @param accountOptions
1680     * @see #createUserCreationIntent(String, String, String, PersistableBundle)
1681     */
1682    public void setSeedAccountData(int userId, String accountName, String accountType,
1683            PersistableBundle accountOptions) {
1684        try {
1685            mService.setSeedAccountData(userId, accountName, accountType, accountOptions,
1686                    /* persist= */ true);
1687        } catch (RemoteException re) {
1688            throw re.rethrowFromSystemServer();
1689        }
1690    }
1691
1692    /**
1693     * @hide
1694     * Clears the seed information used to create this user.
1695     */
1696    @SystemApi
1697    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
1698    public void clearSeedAccountData() {
1699        try {
1700            mService.clearSeedAccountData();
1701        } catch (RemoteException re) {
1702            throw re.rethrowFromSystemServer();
1703        }
1704    }
1705
1706    /**
1707     * @hide
1708     * Marks the guest user for deletion to allow a new guest to be created before deleting
1709     * the current user who is a guest.
1710     * @param userHandle
1711     * @return
1712     */
1713    public boolean markGuestForDeletion(@UserIdInt int userHandle) {
1714        try {
1715            return mService.markGuestForDeletion(userHandle);
1716        } catch (RemoteException re) {
1717            throw re.rethrowFromSystemServer();
1718        }
1719    }
1720
1721    /**
1722     * Sets the user as enabled, if such an user exists.
1723     *
1724     * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1725     *
1726     * <p>Note that the default is true, it's only that managed profiles might not be enabled.
1727     * Also ephemeral users can be disabled to indicate that their removal is in progress and they
1728     * shouldn't be re-entered. Therefore ephemeral users should not be re-enabled once disabled.
1729     *
1730     * @param userHandle the id of the profile to enable
1731     * @hide
1732     */
1733    public void setUserEnabled(@UserIdInt int userHandle) {
1734        try {
1735            mService.setUserEnabled(userHandle);
1736        } catch (RemoteException re) {
1737            throw re.rethrowFromSystemServer();
1738        }
1739    }
1740
1741    /**
1742     * Evicts the user's credential encryption key from memory by stopping and restarting the user.
1743     *
1744     * @hide
1745     */
1746    public void evictCredentialEncryptionKey(@UserIdInt int userHandle) {
1747        try {
1748            mService.evictCredentialEncryptionKey(userHandle);
1749        } catch (RemoteException re) {
1750            throw re.rethrowFromSystemServer();
1751        }
1752    }
1753
1754    /**
1755     * Return the number of users currently created on the device.
1756     */
1757    public int getUserCount() {
1758        List<UserInfo> users = getUsers();
1759        return users != null ? users.size() : 1;
1760    }
1761
1762    /**
1763     * Returns information for all users on this device, including ones marked for deletion.
1764     * To retrieve only users that are alive, use {@link #getUsers(boolean)}.
1765     * <p>
1766     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1767     * @return the list of users that exist on the device.
1768     * @hide
1769     */
1770    public List<UserInfo> getUsers() {
1771        try {
1772            return mService.getUsers(false);
1773        } catch (RemoteException re) {
1774            throw re.rethrowFromSystemServer();
1775        }
1776    }
1777
1778    /**
1779     * Returns serial numbers of all users on this device.
1780     *
1781     * @param excludeDying specify if the list should exclude users being removed.
1782     * @return the list of serial numbers of users that exist on the device.
1783     * @hide
1784     */
1785    @SystemApi
1786    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
1787    public long[] getSerialNumbersOfUsers(boolean excludeDying) {
1788        try {
1789            List<UserInfo> users = mService.getUsers(excludeDying);
1790            long[] result = new long[users.size()];
1791            for (int i = 0; i < result.length; i++) {
1792                result[i] = users.get(i).serialNumber;
1793            }
1794            return result;
1795        } catch (RemoteException re) {
1796            throw re.rethrowFromSystemServer();
1797        }
1798    }
1799
1800    /**
1801     * @return the user's account name, null if not found.
1802     * @hide
1803     */
1804    @RequiresPermission( allOf = {
1805            Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1806            Manifest.permission.MANAGE_USERS
1807    })
1808    public @Nullable String getUserAccount(@UserIdInt int userHandle) {
1809        try {
1810            return mService.getUserAccount(userHandle);
1811        } catch (RemoteException re) {
1812            throw re.rethrowFromSystemServer();
1813        }
1814    }
1815
1816    /**
1817     * Set account name for the given user.
1818     * @hide
1819     */
1820    @RequiresPermission( allOf = {
1821            Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1822            Manifest.permission.MANAGE_USERS
1823    })
1824    public void setUserAccount(@UserIdInt int userHandle, @Nullable String accountName) {
1825        try {
1826            mService.setUserAccount(userHandle, accountName);
1827        } catch (RemoteException re) {
1828            throw re.rethrowFromSystemServer();
1829        }
1830    }
1831
1832    /**
1833     * Returns information for Primary user.
1834     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1835     *
1836     * @return the Primary user, null if not found.
1837     * @hide
1838     */
1839    public @Nullable UserInfo getPrimaryUser() {
1840        try {
1841            return mService.getPrimaryUser();
1842        } catch (RemoteException re) {
1843            throw re.rethrowFromSystemServer();
1844        }
1845    }
1846
1847    /**
1848     * Checks whether it's possible to add more users. Caller must hold the MANAGE_USERS
1849     * permission.
1850     *
1851     * @return true if more users can be added, false if limit has been reached.
1852     * @hide
1853     */
1854    public boolean canAddMoreUsers() {
1855        final List<UserInfo> users = getUsers(true);
1856        final int totalUserCount = users.size();
1857        int aliveUserCount = 0;
1858        for (int i = 0; i < totalUserCount; i++) {
1859            UserInfo user = users.get(i);
1860            if (!user.isGuest()) {
1861                aliveUserCount++;
1862            }
1863        }
1864        return aliveUserCount < getMaxSupportedUsers();
1865    }
1866
1867    /**
1868     * Checks whether it's possible to add more managed profiles. Caller must hold the MANAGE_USERS
1869     * permission.
1870     * if allowedToRemoveOne is true and if the user already has a managed profile, then return if
1871     * we could add a new managed profile to this user after removing the existing one.
1872     *
1873     * @return true if more managed profiles can be added, false if limit has been reached.
1874     * @hide
1875     */
1876    public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
1877        try {
1878            return mService.canAddMoreManagedProfiles(userId, allowedToRemoveOne);
1879        } catch (RemoteException re) {
1880            throw re.rethrowFromSystemServer();
1881        }
1882    }
1883
1884    /**
1885     * Returns list of the profiles of userHandle including
1886     * userHandle itself.
1887     * Note that this returns both enabled and not enabled profiles. See
1888     * {@link #getEnabledProfiles(int)} if you need only the enabled ones.
1889     *
1890     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1891     * @param userHandle profiles of this user will be returned.
1892     * @return the list of profiles.
1893     * @hide
1894     */
1895    public List<UserInfo> getProfiles(@UserIdInt int userHandle) {
1896        try {
1897            return mService.getProfiles(userHandle, false /* enabledOnly */);
1898        } catch (RemoteException re) {
1899            throw re.rethrowFromSystemServer();
1900        }
1901    }
1902
1903    /**
1904     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1905     * @param userId one of the two user ids to check.
1906     * @param otherUserId one of the two user ids to check.
1907     * @return true if the two user ids are in the same profile group.
1908     * @hide
1909     */
1910    public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) {
1911        try {
1912            return mService.isSameProfileGroup(userId, otherUserId);
1913        } catch (RemoteException re) {
1914            throw re.rethrowFromSystemServer();
1915        }
1916    }
1917
1918    /**
1919     * Returns list of the profiles of userHandle including
1920     * userHandle itself.
1921     * Note that this returns only enabled.
1922     *
1923     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1924     * @param userHandle profiles of this user will be returned.
1925     * @return the list of profiles.
1926     * @hide
1927     */
1928    public List<UserInfo> getEnabledProfiles(@UserIdInt int userHandle) {
1929        try {
1930            return mService.getProfiles(userHandle, true /* enabledOnly */);
1931        } catch (RemoteException re) {
1932            throw re.rethrowFromSystemServer();
1933        }
1934    }
1935
1936    /**
1937     * Returns a list of UserHandles for profiles associated with the user that the calling process
1938     * is running on, including the user itself.
1939     *
1940     * @return A non-empty list of UserHandles associated with the calling user.
1941     */
1942    public List<UserHandle> getUserProfiles() {
1943        int[] userIds = getProfileIds(UserHandle.myUserId(), true /* enabledOnly */);
1944        List<UserHandle> result = new ArrayList<>(userIds.length);
1945        for (int userId : userIds) {
1946            result.add(UserHandle.of(userId));
1947        }
1948        return result;
1949    }
1950
1951    /**
1952     * Returns a list of ids for profiles associated with the specified user including the user
1953     * itself.
1954     *
1955     * @param userId      id of the user to return profiles for
1956     * @param enabledOnly whether return only {@link UserInfo#isEnabled() enabled} profiles
1957     * @return A non-empty list of ids of profiles associated with the specified user.
1958     *
1959     * @hide
1960     */
1961    public int[] getProfileIds(@UserIdInt int userId, boolean enabledOnly) {
1962        try {
1963            return mService.getProfileIds(userId, enabledOnly);
1964        } catch (RemoteException re) {
1965            throw re.rethrowFromSystemServer();
1966        }
1967    }
1968
1969    /**
1970     * @see #getProfileIds(int, boolean)
1971     * @hide
1972     */
1973    public int[] getProfileIdsWithDisabled(@UserIdInt int userId) {
1974        return getProfileIds(userId, false /* enabledOnly */);
1975    }
1976
1977    /**
1978     * @see #getProfileIds(int, boolean)
1979     * @hide
1980     */
1981    public int[] getEnabledProfileIds(@UserIdInt int userId) {
1982        return getProfileIds(userId, true /* enabledOnly */);
1983    }
1984
1985    /**
1986     * Returns the device credential owner id of the profile from
1987     * which this method is called, or userHandle if called from a user that
1988     * is not a profile.
1989     *
1990     * @hide
1991     */
1992    public int getCredentialOwnerProfile(@UserIdInt int userHandle) {
1993        try {
1994            return mService.getCredentialOwnerProfile(userHandle);
1995        } catch (RemoteException re) {
1996            throw re.rethrowFromSystemServer();
1997        }
1998    }
1999
2000    /**
2001     * Returns the parent of the profile which this method is called from
2002     * or null if called from a user that is not a profile.
2003     *
2004     * @hide
2005     */
2006    public UserInfo getProfileParent(@UserIdInt int userHandle) {
2007        try {
2008            return mService.getProfileParent(userHandle);
2009        } catch (RemoteException re) {
2010            throw re.rethrowFromSystemServer();
2011        }
2012    }
2013
2014    /**
2015     * Set quiet mode of a managed profile.
2016     *
2017     * @param userHandle The user handle of the profile.
2018     * @param enableQuietMode Whether quiet mode should be enabled or disabled.
2019     * @hide
2020     */
2021    public void setQuietModeEnabled(@UserIdInt int userHandle, boolean enableQuietMode) {
2022        try {
2023            mService.setQuietModeEnabled(userHandle, enableQuietMode);
2024        } catch (RemoteException re) {
2025            throw re.rethrowFromSystemServer();
2026        }
2027    }
2028
2029    /**
2030     * Returns whether the given profile is in quiet mode or not.
2031     * Notes: Quiet mode is only supported for managed profiles.
2032     *
2033     * @param userHandle The user handle of the profile to be queried.
2034     * @return true if the profile is in quiet mode, false otherwise.
2035     */
2036    public boolean isQuietModeEnabled(UserHandle userHandle) {
2037        try {
2038            return mService.isQuietModeEnabled(userHandle.getIdentifier());
2039        } catch (RemoteException re) {
2040            throw re.rethrowFromSystemServer();
2041        }
2042    }
2043
2044    /**
2045     * Tries disabling quiet mode for a given user. If the user is still locked, we unlock the user
2046     * first by showing the confirm credentials screen and disable quiet mode upon successful
2047     * unlocking. If the user is already unlocked, we call through to {@link #setQuietModeEnabled}
2048     * directly.
2049     *
2050     * @return true if the quiet mode was disabled immediately
2051     * @hide
2052     */
2053    public boolean trySetQuietModeDisabled(@UserIdInt int userHandle, IntentSender target) {
2054        try {
2055            return mService.trySetQuietModeDisabled(userHandle, target);
2056        } catch (RemoteException re) {
2057            throw re.rethrowFromSystemServer();
2058        }
2059    }
2060
2061    /**
2062     * If the target user is a managed profile of the calling user or the caller
2063     * is itself a managed profile, then this returns a badged copy of the given
2064     * icon to be able to distinguish it from the original icon. For badging an
2065     * arbitrary drawable use {@link #getBadgedDrawableForUser(
2066     * android.graphics.drawable.Drawable, UserHandle, android.graphics.Rect, int)}.
2067     * <p>
2068     * If the original drawable is a BitmapDrawable and the backing bitmap is
2069     * mutable as per {@link android.graphics.Bitmap#isMutable()}, the badging
2070     * is performed in place and the original drawable is returned.
2071     * </p>
2072     *
2073     * @param icon The icon to badge.
2074     * @param user The target user.
2075     * @return A drawable that combines the original icon and a badge as
2076     *         determined by the system.
2077     * @removed
2078     */
2079    public Drawable getBadgedIconForUser(Drawable icon, UserHandle user) {
2080        return mContext.getPackageManager().getUserBadgedIcon(icon, user);
2081    }
2082
2083    /**
2084     * If the target user is a managed profile of the calling user or the caller
2085     * is itself a managed profile, then this returns a badged copy of the given
2086     * drawable allowing the user to distinguish it from the original drawable.
2087     * The caller can specify the location in the bounds of the drawable to be
2088     * badged where the badge should be applied as well as the density of the
2089     * badge to be used.
2090     * <p>
2091     * If the original drawable is a BitmapDrawable and the backing bitmap is
2092     * mutable as per {@link android.graphics.Bitmap#isMutable()}, the badging
2093     * is performed in place and the original drawable is returned.
2094     * </p>
2095     *
2096     * @param badgedDrawable The drawable to badge.
2097     * @param user The target user.
2098     * @param badgeLocation Where in the bounds of the badged drawable to place
2099     *         the badge. If it's {@code null}, the badge is applied on top of the entire
2100     *         drawable being badged.
2101     * @param badgeDensity The optional desired density for the badge as per
2102     *         {@link android.util.DisplayMetrics#densityDpi}. If it's not positive,
2103     *         the density of the display is used.
2104     * @return A drawable that combines the original drawable and a badge as
2105     *         determined by the system.
2106     * @removed
2107     */
2108    public Drawable getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user,
2109            Rect badgeLocation, int badgeDensity) {
2110        return mContext.getPackageManager().getUserBadgedDrawableForDensity(badgedDrawable, user,
2111                badgeLocation, badgeDensity);
2112    }
2113
2114    /**
2115     * If the target user is a managed profile of the calling user or the caller
2116     * is itself a managed profile, then this returns a copy of the label with
2117     * badging for accessibility services like talkback. E.g. passing in "Email"
2118     * and it might return "Work Email" for Email in the work profile.
2119     *
2120     * @param label The label to change.
2121     * @param user The target user.
2122     * @return A label that combines the original label and a badge as
2123     *         determined by the system.
2124     * @removed
2125     */
2126    public CharSequence getBadgedLabelForUser(CharSequence label, UserHandle user) {
2127        return mContext.getPackageManager().getUserBadgedLabel(label, user);
2128    }
2129
2130    /**
2131     * Returns information for all users on this device. Requires
2132     * {@link android.Manifest.permission#MANAGE_USERS} permission.
2133     *
2134     * @param excludeDying specify if the list should exclude users being
2135     *            removed.
2136     * @return the list of users that were created.
2137     * @hide
2138     */
2139    public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
2140        try {
2141            return mService.getUsers(excludeDying);
2142        } catch (RemoteException re) {
2143            throw re.rethrowFromSystemServer();
2144        }
2145    }
2146
2147    /**
2148     * Removes a user and all associated data.
2149     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2150     * @param userHandle the integer handle of the user, where 0 is the primary user.
2151     * @hide
2152     */
2153    public boolean removeUser(@UserIdInt int userHandle) {
2154        try {
2155            return mService.removeUser(userHandle);
2156        } catch (RemoteException re) {
2157            throw re.rethrowFromSystemServer();
2158        }
2159    }
2160
2161    /**
2162     * Similar to {@link #removeUser(int)} except bypassing the checking of
2163     * {@link UserManager#DISALLOW_REMOVE_USER}
2164     * or {@link UserManager#DISALLOW_REMOVE_MANAGED_PROFILE}.
2165     *
2166     * @see {@link #removeUser(int)}
2167     * @hide
2168     */
2169    public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2170        try {
2171            return mService.removeUserEvenWhenDisallowed(userHandle);
2172        } catch (RemoteException re) {
2173            throw re.rethrowFromSystemServer();
2174        }
2175    }
2176
2177    /**
2178     * Updates the user's name.
2179     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
2180     *
2181     * @param userHandle the user's integer handle
2182     * @param name the new name for the user
2183     * @hide
2184     */
2185    public void setUserName(@UserIdInt int userHandle, String name) {
2186        try {
2187            mService.setUserName(userHandle, name);
2188        } catch (RemoteException re) {
2189            throw re.rethrowFromSystemServer();
2190        }
2191    }
2192
2193    /**
2194     * Sets the user's photo.
2195     * @param userHandle the user for whom to change the photo.
2196     * @param icon the bitmap to set as the photo.
2197     * @hide
2198     */
2199    public void setUserIcon(@UserIdInt int userHandle, Bitmap icon) {
2200        try {
2201            mService.setUserIcon(userHandle, icon);
2202        } catch (RemoteException re) {
2203            throw re.rethrowFromSystemServer();
2204        }
2205    }
2206
2207    /**
2208     * Returns a file descriptor for the user's photo. PNG data can be read from this file.
2209     * @param userHandle the user whose photo we want to read.
2210     * @return a {@link Bitmap} of the user's photo, or null if there's no photo.
2211     * @see com.android.internal.util.UserIcons#getDefaultUserIcon for a default.
2212     * @hide
2213     */
2214    public Bitmap getUserIcon(@UserIdInt int userHandle) {
2215        try {
2216            ParcelFileDescriptor fd = mService.getUserIcon(userHandle);
2217            if (fd != null) {
2218                try {
2219                    return BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
2220                } finally {
2221                    try {
2222                        fd.close();
2223                    } catch (IOException e) {
2224                    }
2225                }
2226            }
2227        } catch (RemoteException re) {
2228            throw re.rethrowFromSystemServer();
2229        }
2230        return null;
2231    }
2232
2233    /**
2234     * Returns the maximum number of users that can be created on this device. A return value
2235     * of 1 means that it is a single user device.
2236     * @hide
2237     * @return a value greater than or equal to 1
2238     */
2239    public static int getMaxSupportedUsers() {
2240        // Don't allow multiple users on certain builds
2241        if (android.os.Build.ID.startsWith("JVP")) return 1;
2242        // Svelte devices don't get multi-user.
2243        if (ActivityManager.isLowRamDeviceStatic()) return 1;
2244        return SystemProperties.getInt("fw.max_users",
2245                Resources.getSystem().getInteger(R.integer.config_multiuserMaximumUsers));
2246    }
2247
2248    /**
2249     * Returns true if the user switcher should be shown, this will be if device supports multi-user
2250     * and there are at least 2 users available that are not managed profiles.
2251     * @hide
2252     * @return true if user switcher should be shown.
2253     */
2254    public boolean isUserSwitcherEnabled() {
2255        if (!supportsMultipleUsers()) {
2256            return false;
2257        }
2258        // If Demo Mode is on, don't show user switcher
2259        if (isDeviceInDemoMode(mContext)) {
2260            return false;
2261        }
2262        List<UserInfo> users = getUsers(true);
2263        if (users == null) {
2264           return false;
2265        }
2266        int switchableUserCount = 0;
2267        for (UserInfo user : users) {
2268            if (user.supportsSwitchToByUser()) {
2269                ++switchableUserCount;
2270            }
2271        }
2272        final boolean guestEnabled = !mContext.getSystemService(DevicePolicyManager.class)
2273                .getGuestUserDisabled(null);
2274        return switchableUserCount > 1 || guestEnabled;
2275    }
2276
2277    /**
2278     * @hide
2279     */
2280    public static boolean isDeviceInDemoMode(Context context) {
2281        return Settings.Global.getInt(context.getContentResolver(),
2282                Settings.Global.DEVICE_DEMO_MODE, 0) > 0;
2283    }
2284
2285    /**
2286     * Returns a serial number on this device for a given userHandle. User handles can be recycled
2287     * when deleting and creating users, but serial numbers are not reused until the device is wiped.
2288     * @param userHandle
2289     * @return a serial number associated with that user, or -1 if the userHandle is not valid.
2290     * @hide
2291     */
2292    public int getUserSerialNumber(@UserIdInt int userHandle) {
2293        try {
2294            return mService.getUserSerialNumber(userHandle);
2295        } catch (RemoteException re) {
2296            throw re.rethrowFromSystemServer();
2297        }
2298    }
2299
2300    /**
2301     * Returns a userHandle on this device for a given user serial number. User handles can be
2302     * recycled when deleting and creating users, but serial numbers are not reused until the device
2303     * is wiped.
2304     * @param userSerialNumber
2305     * @return the userHandle associated with that user serial number, or -1 if the serial number
2306     * is not valid.
2307     * @hide
2308     */
2309    public @UserIdInt int getUserHandle(int userSerialNumber) {
2310        try {
2311            return mService.getUserHandle(userSerialNumber);
2312        } catch (RemoteException re) {
2313            throw re.rethrowFromSystemServer();
2314        }
2315    }
2316
2317    /**
2318     * Returns a {@link Bundle} containing any saved application restrictions for this user, for the
2319     * given package name. Only an application with this package name can call this method.
2320     *
2321     * <p>The returned {@link Bundle} consists of key-value pairs, as defined by the application,
2322     * where the types of values may be:
2323     * <ul>
2324     * <li>{@code boolean}
2325     * <li>{@code int}
2326     * <li>{@code String} or {@code String[]}
2327     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
2328     * </ul>
2329     *
2330     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
2331     *
2332     * @param packageName the package name of the calling application
2333     * @return a {@link Bundle} with the restrictions for that package, or an empty {@link Bundle}
2334     * if there are no saved restrictions.
2335     *
2336     * @see #KEY_RESTRICTIONS_PENDING
2337     */
2338    @WorkerThread
2339    public Bundle getApplicationRestrictions(String packageName) {
2340        try {
2341            return mService.getApplicationRestrictions(packageName);
2342        } catch (RemoteException re) {
2343            throw re.rethrowFromSystemServer();
2344        }
2345    }
2346
2347    /**
2348     * @hide
2349     */
2350    @WorkerThread
2351    public Bundle getApplicationRestrictions(String packageName, UserHandle user) {
2352        try {
2353            return mService.getApplicationRestrictionsForUser(packageName, user.getIdentifier());
2354        } catch (RemoteException re) {
2355            throw re.rethrowFromSystemServer();
2356        }
2357    }
2358
2359    /**
2360     * @hide
2361     */
2362    @WorkerThread
2363    public void setApplicationRestrictions(String packageName, Bundle restrictions,
2364            UserHandle user) {
2365        try {
2366            mService.setApplicationRestrictions(packageName, restrictions, user.getIdentifier());
2367        } catch (RemoteException re) {
2368            throw re.rethrowFromSystemServer();
2369        }
2370    }
2371
2372    /**
2373     * Sets a new challenge PIN for restrictions. This is only for use by pre-installed
2374     * apps and requires the MANAGE_USERS permission.
2375     * @param newPin the PIN to use for challenge dialogs.
2376     * @return Returns true if the challenge PIN was set successfully.
2377     * @deprecated The restrictions PIN functionality is no longer provided by the system.
2378     * This method is preserved for backwards compatibility reasons and always returns false.
2379     */
2380    @Deprecated
2381    public boolean setRestrictionsChallenge(String newPin) {
2382        return false;
2383    }
2384
2385    /**
2386     * @hide
2387     * Set restrictions that should apply to any future guest user that's created.
2388     */
2389    public void setDefaultGuestRestrictions(Bundle restrictions) {
2390        try {
2391            mService.setDefaultGuestRestrictions(restrictions);
2392        } catch (RemoteException re) {
2393            throw re.rethrowFromSystemServer();
2394        }
2395    }
2396
2397    /**
2398     * @hide
2399     * Gets the default guest restrictions.
2400     */
2401    public Bundle getDefaultGuestRestrictions() {
2402        try {
2403            return mService.getDefaultGuestRestrictions();
2404        } catch (RemoteException re) {
2405            throw re.rethrowFromSystemServer();
2406        }
2407    }
2408
2409    /**
2410     * Returns creation time of the user or of a managed profile associated with the calling user.
2411     * @param userHandle user handle of the user or a managed profile associated with the
2412     *                   calling user.
2413     * @return creation time in milliseconds since Epoch time.
2414     */
2415    public long getUserCreationTime(UserHandle userHandle) {
2416        try {
2417            return mService.getUserCreationTime(userHandle.getIdentifier());
2418        } catch (RemoteException re) {
2419            throw re.rethrowFromSystemServer();
2420        }
2421    }
2422
2423    /**
2424     * @hide
2425     * Checks if any uninitialized user has the specific seed account name and type.
2426     *
2427     * @param accountName The account name to check for
2428     * @param accountType The account type of the account to check for
2429     * @return whether the seed account was found
2430     */
2431    public boolean someUserHasSeedAccount(String accountName, String accountType) {
2432        try {
2433            return mService.someUserHasSeedAccount(accountName, accountType);
2434        } catch (RemoteException re) {
2435            throw re.rethrowFromSystemServer();
2436        }
2437    }
2438
2439    /**
2440     * @hide
2441     * User that enforces a restriction.
2442     *
2443     * @see #getUserRestrictionSources(String, UserHandle)
2444     */
2445    @SystemApi
2446    public static final class EnforcingUser implements Parcelable {
2447        private final @UserIdInt int userId;
2448        private final @UserRestrictionSource int userRestrictionSource;
2449
2450        /**
2451         * @hide
2452         */
2453        public EnforcingUser(
2454                @UserIdInt int userId, @UserRestrictionSource int userRestrictionSource) {
2455            this.userId = userId;
2456            this.userRestrictionSource = userRestrictionSource;
2457        }
2458
2459        private EnforcingUser(Parcel in) {
2460            userId = in.readInt();
2461            userRestrictionSource = in.readInt();
2462        }
2463
2464        public static final Creator<EnforcingUser> CREATOR = new Creator<EnforcingUser>() {
2465            @Override
2466            public EnforcingUser createFromParcel(Parcel in) {
2467                return new EnforcingUser(in);
2468            }
2469
2470            @Override
2471            public EnforcingUser[] newArray(int size) {
2472                return new EnforcingUser[size];
2473            }
2474        };
2475
2476        @Override
2477        public int describeContents() {
2478            return 0;
2479        }
2480
2481        @Override
2482        public void writeToParcel(Parcel dest, int flags) {
2483            dest.writeInt(userId);
2484            dest.writeInt(userRestrictionSource);
2485        }
2486
2487        /**
2488         * Returns an id of the enforcing user.
2489         *
2490         * <p> Will be UserHandle.USER_NULL when restriction is set by the system.
2491         */
2492        public UserHandle getUserHandle() {
2493            return UserHandle.of(userId);
2494        }
2495
2496        /**
2497         * Returns the status of the enforcing user.
2498         *
2499         * <p> One of {@link #RESTRICTION_SOURCE_SYSTEM},
2500         * {@link #RESTRICTION_SOURCE_DEVICE_OWNER} and
2501         * {@link #RESTRICTION_SOURCE_PROFILE_OWNER}
2502         */
2503        public @UserRestrictionSource int getUserRestrictionSource() {
2504            return userRestrictionSource;
2505        }
2506    }
2507}
2508