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 package android.os;
17 
18 import android.annotation.SystemApi;
19 import android.app.ActivityManager;
20 import android.app.ActivityManagerNative;
21 import android.content.Context;
22 import android.content.pm.UserInfo;
23 import android.content.res.Resources;
24 import android.graphics.Bitmap;
25 import android.graphics.Rect;
26 import android.graphics.drawable.Drawable;
27 import android.provider.Settings;
28 import android.util.Log;
29 import android.view.WindowManager.LayoutParams;
30 
31 import com.android.internal.R;
32 
33 import java.util.ArrayList;
34 import java.util.List;
35 
36 /**
37  * Manages users and user details on a multi-user system.
38  */
39 public class UserManager {
40 
41     private static String TAG = "UserManager";
42     private final IUserManager mService;
43     private final Context mContext;
44 
45     /**
46      * Specifies if a user is disallowed from adding and removing accounts.
47      * The default value is <code>false</code>.
48      *
49      * <p/>Key for user restrictions.
50      * <p/>Type: Boolean
51      * @see #setUserRestrictions(Bundle)
52      * @see #getUserRestrictions()
53      */
54     public static final String DISALLOW_MODIFY_ACCOUNTS = "no_modify_accounts";
55 
56     /**
57      * Specifies if a user is disallowed from changing Wi-Fi
58      * access points. The default value is <code>false</code>.
59      * <p/>This restriction has no effect in a managed profile.
60      *
61      * <p/>Key for user restrictions.
62      * <p/>Type: Boolean
63      * @see #setUserRestrictions(Bundle)
64      * @see #getUserRestrictions()
65      */
66     public static final String DISALLOW_CONFIG_WIFI = "no_config_wifi";
67 
68     /**
69      * Specifies if a user is disallowed from installing applications.
70      * The default value is <code>false</code>.
71      *
72      * <p/>Key for user restrictions.
73      * <p/>Type: Boolean
74      * @see #setUserRestrictions(Bundle)
75      * @see #getUserRestrictions()
76      */
77     public static final String DISALLOW_INSTALL_APPS = "no_install_apps";
78 
79     /**
80      * Specifies if a user is disallowed from uninstalling applications.
81      * The default value is <code>false</code>.
82      *
83      * <p/>Key for user restrictions.
84      * <p/>Type: Boolean
85      * @see #setUserRestrictions(Bundle)
86      * @see #getUserRestrictions()
87      */
88     public static final String DISALLOW_UNINSTALL_APPS = "no_uninstall_apps";
89 
90     /**
91      * Specifies if a user is disallowed from turning on location sharing.
92      * The default value is <code>false</code>.
93      * <p/>In a managed profile, location sharing always reflects the primary user's setting, but
94      * can be overridden and forced off by setting this restriction to true in the managed profile.
95      *
96      * <p/>Key for user restrictions.
97      * <p/>Type: Boolean
98      * @see #setUserRestrictions(Bundle)
99      * @see #getUserRestrictions()
100      */
101     public static final String DISALLOW_SHARE_LOCATION = "no_share_location";
102 
103     /**
104      * Specifies if a user is disallowed from enabling the
105      * "Unknown Sources" setting, that allows installation of apps from unknown sources.
106      * The default value is <code>false</code>.
107      *
108      * <p/>Key for user restrictions.
109      * <p/>Type: Boolean
110      * @see #setUserRestrictions(Bundle)
111      * @see #getUserRestrictions()
112      */
113     public static final String DISALLOW_INSTALL_UNKNOWN_SOURCES = "no_install_unknown_sources";
114 
115     /**
116      * Specifies if a user is disallowed from configuring bluetooth.
117      * The default value is <code>false</code>.
118      * <p/>This restriction has no effect in a managed profile.
119      *
120      * <p/>Key for user restrictions.
121      * <p/>Type: Boolean
122      * @see #setUserRestrictions(Bundle)
123      * @see #getUserRestrictions()
124      */
125     public static final String DISALLOW_CONFIG_BLUETOOTH = "no_config_bluetooth";
126 
127     /**
128      * Specifies if a user is disallowed from transferring files over
129      * USB. This can only be set by device owners and profile owners on the primary user.
130      * The default value is <code>false</code>.
131      *
132      * <p/>Key for user restrictions.
133      * <p/>Type: Boolean
134      * @see #setUserRestrictions(Bundle)
135      * @see #getUserRestrictions()
136      */
137     public static final String DISALLOW_USB_FILE_TRANSFER = "no_usb_file_transfer";
138 
139     /**
140      * Specifies if a user is disallowed from configuring user
141      * credentials. The default value is <code>false</code>.
142      *
143      * <p/>Key for user restrictions.
144      * <p/>Type: Boolean
145      * @see #setUserRestrictions(Bundle)
146      * @see #getUserRestrictions()
147      */
148     public static final String DISALLOW_CONFIG_CREDENTIALS = "no_config_credentials";
149 
150     /**
151      * When set on the primary user this specifies if the user can remove other users.
152      * When set on a secondary user, this specifies if the user can remove itself.
153      * This restriction has no effect on managed profiles.
154      * The default value is <code>false</code>.
155      *
156      * <p/>Key for user restrictions.
157      * <p/>Type: Boolean
158      * @see #setUserRestrictions(Bundle)
159      * @see #getUserRestrictions()
160      */
161     public static final String DISALLOW_REMOVE_USER = "no_remove_user";
162 
163     /**
164      * Specifies if a user is disallowed from enabling or
165      * accessing debugging features. The default value is <code>false</code>.
166      *
167      * <p/>Key for user restrictions.
168      * <p/>Type: Boolean
169      * @see #setUserRestrictions(Bundle)
170      * @see #getUserRestrictions()
171      */
172     public static final String DISALLOW_DEBUGGING_FEATURES = "no_debugging_features";
173 
174     /**
175      * Specifies if a user is disallowed from configuring VPN.
176      * The default value is <code>false</code>.
177      * This restriction has no effect in a managed profile.
178      *
179      * <p/>Key for user restrictions.
180      * <p/>Type: Boolean
181      * @see #setUserRestrictions(Bundle)
182      * @see #getUserRestrictions()
183      */
184     public static final String DISALLOW_CONFIG_VPN = "no_config_vpn";
185 
186     /**
187      * Specifies if a user is disallowed from configuring Tethering
188      * & portable hotspots. This can only be set by device owners and profile owners on the
189      * primary user. The default value is <code>false</code>.
190      *
191      * <p/>Key for user restrictions.
192      * <p/>Type: Boolean
193      * @see #setUserRestrictions(Bundle)
194      * @see #getUserRestrictions()
195      */
196     public static final String DISALLOW_CONFIG_TETHERING = "no_config_tethering";
197 
198     /**
199      * Specifies if a user is disallowed from factory resetting
200      * from Settings. This can only be set by device owners and profile owners on the primary user.
201      * The default value is <code>false</code>.
202      * <p/>This restriction has no effect on secondary users and managed profiles since only the
203      * primary user can factory reset the device.
204      *
205      * <p/>Key for user restrictions.
206      * <p/>Type: Boolean
207      * @see #setUserRestrictions(Bundle)
208      * @see #getUserRestrictions()
209      */
210     public static final String DISALLOW_FACTORY_RESET = "no_factory_reset";
211 
212     /**
213      * Specifies if a user is disallowed from adding new users and
214      * profiles. This can only be set by device owners and profile owners on the primary user.
215      * The default value is <code>false</code>.
216      * <p/>This restriction has no effect on secondary users and managed profiles since only the
217      * primary user can add other users.
218      *
219      * <p/>Key for user restrictions.
220      * <p/>Type: Boolean
221      * @see #setUserRestrictions(Bundle)
222      * @see #getUserRestrictions()
223      */
224     public static final String DISALLOW_ADD_USER = "no_add_user";
225 
226     /**
227      * Specifies if a user is disallowed from disabling application
228      * verification. The default value is <code>false</code>.
229      *
230      * <p/>Key for user restrictions.
231      * <p/>Type: Boolean
232      * @see #setUserRestrictions(Bundle)
233      * @see #getUserRestrictions()
234      */
235     public static final String ENSURE_VERIFY_APPS = "ensure_verify_apps";
236 
237     /**
238      * Specifies if a user is disallowed from configuring cell
239      * broadcasts. This can only be set by device owners and profile owners on the primary user.
240      * The default value is <code>false</code>.
241      * <p/>This restriction has no effect on secondary users and managed profiles since only the
242      * primary user can configure cell broadcasts.
243      *
244      * <p/>Key for user restrictions.
245      * <p/>Type: Boolean
246      * @see #setUserRestrictions(Bundle)
247      * @see #getUserRestrictions()
248      */
249     public static final String DISALLOW_CONFIG_CELL_BROADCASTS = "no_config_cell_broadcasts";
250 
251     /**
252      * Specifies if a user is disallowed from configuring mobile
253      * networks. This can only be set by device owners and profile owners on the primary user.
254      * The default value is <code>false</code>.
255      * <p/>This restriction has no effect on secondary users and managed profiles since only the
256      * primary user can configure mobile networks.
257      *
258      * <p/>Key for user restrictions.
259      * <p/>Type: Boolean
260      * @see #setUserRestrictions(Bundle)
261      * @see #getUserRestrictions()
262      */
263     public static final String DISALLOW_CONFIG_MOBILE_NETWORKS = "no_config_mobile_networks";
264 
265     /**
266      * Specifies if a user is disallowed from modifying
267      * applications in Settings or launchers. The following actions will not be allowed when this
268      * restriction is enabled:
269      * <li>uninstalling apps</li>
270      * <li>disabling apps</li>
271      * <li>clearing app caches</li>
272      * <li>clearing app data</li>
273      * <li>force stopping apps</li>
274      * <li>clearing app defaults</li>
275      * <p>
276      * The default value is <code>false</code>.
277      *
278      * <p/>Key for user restrictions.
279      * <p/>Type: Boolean
280      * @see #setUserRestrictions(Bundle)
281      * @see #getUserRestrictions()
282      */
283     public static final String DISALLOW_APPS_CONTROL = "no_control_apps";
284 
285     /**
286      * Specifies if a user is disallowed from mounting
287      * physical external media. This can only be set by device owners and profile owners on the
288      * primary user. The default value is <code>false</code>.
289      *
290      * <p/>Key for user restrictions.
291      * <p/>Type: Boolean
292      * @see #setUserRestrictions(Bundle)
293      * @see #getUserRestrictions()
294      */
295     public static final String DISALLOW_MOUNT_PHYSICAL_MEDIA = "no_physical_media";
296 
297     /**
298      * Specifies if a user is disallowed from adjusting microphone
299      * volume. If set, the microphone will be muted. This can only be set by device owners
300      * and profile owners on the primary user. The default value is <code>false</code>.
301      *
302      * <p/>Key for user restrictions.
303      * <p/>Type: Boolean
304      * @see #setUserRestrictions(Bundle)
305      * @see #getUserRestrictions()
306      */
307     public static final String DISALLOW_UNMUTE_MICROPHONE = "no_unmute_microphone";
308 
309     /**
310      * Specifies if a user is disallowed from adjusting the master
311      * volume. If set, the master volume will be muted. This can only be set by device owners
312      * and profile owners on the primary user. The default value is <code>false</code>.
313      *
314      * <p/>Key for user restrictions.
315      * <p/>Type: Boolean
316      * @see #setUserRestrictions(Bundle)
317      * @see #getUserRestrictions()
318      */
319     public static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume";
320 
321     /**
322      * Specifies that the user is not allowed to make outgoing
323      * phone calls. Emergency calls are still permitted.
324      * The default value is <code>false</code>.
325      * <p/>This restriction has no effect on managed profiles since call intents are normally
326      * forwarded to the primary user.
327      *
328      * <p/>Key for user restrictions.
329      * <p/>Type: Boolean
330      * @see #setUserRestrictions(Bundle)
331      * @see #getUserRestrictions()
332      */
333     public static final String DISALLOW_OUTGOING_CALLS = "no_outgoing_calls";
334 
335     /**
336      * Specifies that the user is not allowed to send or receive
337      * SMS messages. The default value is <code>false</code>.
338      *
339      * <p/>Key for user restrictions.
340      * <p/>Type: Boolean
341      * @see #setUserRestrictions(Bundle)
342      * @see #getUserRestrictions()
343      */
344     public static final String DISALLOW_SMS = "no_sms";
345 
346     /**
347      * Specifies that windows besides app windows should not be
348      * created. This will block the creation of the following types of windows.
349      * <li>{@link LayoutParams#TYPE_TOAST}</li>
350      * <li>{@link LayoutParams#TYPE_PHONE}</li>
351      * <li>{@link LayoutParams#TYPE_PRIORITY_PHONE}</li>
352      * <li>{@link LayoutParams#TYPE_SYSTEM_ALERT}</li>
353      * <li>{@link LayoutParams#TYPE_SYSTEM_ERROR}</li>
354      * <li>{@link LayoutParams#TYPE_SYSTEM_OVERLAY}</li>
355      *
356      * <p>This can only be set by device owners and profile owners on the primary user.
357      * The default value is <code>false</code>.
358      *
359      * <p/>Key for user restrictions.
360      * <p/>Type: Boolean
361      * @see #setUserRestrictions(Bundle)
362      * @see #getUserRestrictions()
363      */
364     public static final String DISALLOW_CREATE_WINDOWS = "no_create_windows";
365 
366     /**
367      * Specifies if what is copied in the clipboard of this profile can
368      * be pasted in related profiles. Does not restrict if the clipboard of related profiles can be
369      * pasted in this profile.
370      * The default value is <code>false</code>.
371      *
372      * <p/>Key for user restrictions.
373      * <p/>Type: Boolean
374      * @see #setUserRestrictions(Bundle)
375      * @see #getUserRestrictions()
376      */
377     public static final String DISALLOW_CROSS_PROFILE_COPY_PASTE = "no_cross_profile_copy_paste";
378 
379     /**
380      * Specifies if the user is not allowed to use NFC to beam out data from apps.
381      * The default value is <code>false</code>.
382      *
383      * <p/>Key for user restrictions.
384      * <p/>Type: Boolean
385      * @see #setUserRestrictions(Bundle)
386      * @see #getUserRestrictions()
387      */
388     public static final String DISALLOW_OUTGOING_BEAM = "no_outgoing_beam";
389 
390     /**
391      * Application restriction key that is used to indicate the pending arrival
392      * of real restrictions for the app.
393      *
394      * <p>
395      * Applications that support restrictions should check for the presence of this key.
396      * A <code>true</code> value indicates that restrictions may be applied in the near
397      * future but are not available yet. It is the responsibility of any
398      * management application that sets this flag to update it when the final
399      * restrictions are enforced.
400      *
401      * <p/>Key for application restrictions.
402      * <p/>Type: Boolean
403      * @see android.app.admin.DevicePolicyManager#setApplicationRestrictions(
404      *      android.content.ComponentName, String, Bundle)
405      * @see android.app.admin.DevicePolicyManager#getApplicationRestrictions(
406      *      android.content.ComponentName, String)
407      */
408     public static final String KEY_RESTRICTIONS_PENDING = "restrictions_pending";
409 
410     /** @hide */
411     public static final int PIN_VERIFICATION_FAILED_INCORRECT = -3;
412     /** @hide */
413     public static final int PIN_VERIFICATION_FAILED_NOT_SET = -2;
414     /** @hide */
415     public static final int PIN_VERIFICATION_SUCCESS = -1;
416 
417     private static UserManager sInstance = null;
418 
419     /** @hide */
get(Context context)420     public synchronized static UserManager get(Context context) {
421         if (sInstance == null) {
422             sInstance = (UserManager) context.getSystemService(Context.USER_SERVICE);
423         }
424         return sInstance;
425     }
426 
427     /** @hide */
UserManager(Context context, IUserManager service)428     public UserManager(Context context, IUserManager service) {
429         mService = service;
430         mContext = context;
431     }
432 
433     /**
434      * Returns whether the system supports multiple users.
435      * @return true if multiple users can be created by user, false if it is a single user device.
436      * @hide
437      */
supportsMultipleUsers()438     public static boolean supportsMultipleUsers() {
439         return getMaxSupportedUsers() > 1
440                 && SystemProperties.getBoolean("fw.show_multiuserui",
441                 Resources.getSystem().getBoolean(R.bool.config_enableMultiUserUI));
442     }
443 
444     /**
445      * Returns the user handle for the user that the calling process is running on.
446      *
447      * @return the user handle of the user making this call.
448      * @hide
449      */
getUserHandle()450     public int getUserHandle() {
451         return UserHandle.myUserId();
452     }
453 
454     /**
455      * Returns the user name of the user making this call.  This call is only
456      * available to applications on the system image; it requires the
457      * MANAGE_USERS permission.
458      * @return the user name
459      */
getUserName()460     public String getUserName() {
461         try {
462             return mService.getUserInfo(getUserHandle()).name;
463         } catch (RemoteException re) {
464             Log.w(TAG, "Could not get user name", re);
465             return "";
466         }
467     }
468 
469     /**
470      * Used to determine whether the user making this call is subject to
471      * teleportations.
472      *
473      * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
474      * now automatically identify goats using advanced goat recognition technology.</p>
475      *
476      * @return Returns true if the user making this call is a goat.
477      */
isUserAGoat()478     public boolean isUserAGoat() {
479         return mContext.getPackageManager()
480                 .isPackageAvailable("com.coffeestainstudios.goatsimulator");
481     }
482 
483     /**
484      * Used to check if the user making this call is linked to another user. Linked users may have
485      * a reduced number of available apps, app restrictions and account restrictions.
486      * @return whether the user making this call is a linked user
487      * @hide
488      */
isLinkedUser()489     public boolean isLinkedUser() {
490         try {
491             return mService.isRestricted();
492         } catch (RemoteException re) {
493             Log.w(TAG, "Could not check if user is limited ", re);
494             return false;
495         }
496     }
497 
498     /**
499      * Checks if the calling app is running as a guest user.
500      * @return whether the caller is a guest user.
501      * @hide
502      */
isGuestUser()503     public boolean isGuestUser() {
504         UserInfo user = getUserInfo(UserHandle.myUserId());
505         return user != null ? user.isGuest() : false;
506     }
507 
508     /**
509      * Checks if the calling app is running in a managed profile.
510      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
511      *
512      * @return whether the caller is in a managed profile.
513      * @hide
514      */
515     @SystemApi
isManagedProfile()516     public boolean isManagedProfile() {
517         UserInfo user = getUserInfo(UserHandle.myUserId());
518         return user != null ? user.isManagedProfile() : false;
519     }
520 
521     /**
522      * Return whether the given user is actively running.  This means that
523      * the user is in the "started" state, not "stopped" -- it is currently
524      * allowed to run code through scheduled alarms, receiving broadcasts,
525      * etc.  A started user may be either the current foreground user or a
526      * background user; the result here does not distinguish between the two.
527      * @param user The user to retrieve the running state for.
528      */
isUserRunning(UserHandle user)529     public boolean isUserRunning(UserHandle user) {
530         try {
531             return ActivityManagerNative.getDefault().isUserRunning(
532                     user.getIdentifier(), false);
533         } catch (RemoteException e) {
534             return false;
535         }
536     }
537 
538     /**
539      * Return whether the given user is actively running <em>or</em> stopping.
540      * This is like {@link #isUserRunning(UserHandle)}, but will also return
541      * true if the user had been running but is in the process of being stopped
542      * (but is not yet fully stopped, and still running some code).
543      * @param user The user to retrieve the running state for.
544      */
isUserRunningOrStopping(UserHandle user)545     public boolean isUserRunningOrStopping(UserHandle user) {
546         try {
547             return ActivityManagerNative.getDefault().isUserRunning(
548                     user.getIdentifier(), true);
549         } catch (RemoteException e) {
550             return false;
551         }
552     }
553 
554     /**
555      * Returns the UserInfo object describing a specific user.
556      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
557      * @param userHandle the user handle of the user whose information is being requested.
558      * @return the UserInfo object for a specific user.
559      * @hide
560      */
getUserInfo(int userHandle)561     public UserInfo getUserInfo(int userHandle) {
562         try {
563             return mService.getUserInfo(userHandle);
564         } catch (RemoteException re) {
565             Log.w(TAG, "Could not get user info", re);
566             return null;
567         }
568     }
569 
570     /**
571      * Returns the user-wide restrictions imposed on this user.
572      * @return a Bundle containing all the restrictions.
573      */
getUserRestrictions()574     public Bundle getUserRestrictions() {
575         return getUserRestrictions(Process.myUserHandle());
576     }
577 
578     /**
579      * Returns the user-wide restrictions imposed on the user specified by <code>userHandle</code>.
580      * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
581      * @return a Bundle containing all the restrictions.
582      */
getUserRestrictions(UserHandle userHandle)583     public Bundle getUserRestrictions(UserHandle userHandle) {
584         try {
585             return mService.getUserRestrictions(userHandle.getIdentifier());
586         } catch (RemoteException re) {
587             Log.w(TAG, "Could not get user restrictions", re);
588             return Bundle.EMPTY;
589         }
590     }
591 
592     /**
593      * Sets all the user-wide restrictions for this user.
594      * Requires the MANAGE_USERS permission.
595      * @param restrictions the Bundle containing all the restrictions.
596      * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
597      * android.content.ComponentName, String)} or
598      * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
599      * android.content.ComponentName, String)} instead.
600      */
601     @Deprecated
setUserRestrictions(Bundle restrictions)602     public void setUserRestrictions(Bundle restrictions) {
603         setUserRestrictions(restrictions, Process.myUserHandle());
604     }
605 
606     /**
607      * Sets all the user-wide restrictions for the specified user.
608      * Requires the MANAGE_USERS permission.
609      * @param restrictions the Bundle containing all the restrictions.
610      * @param userHandle the UserHandle of the user for whom to set the restrictions.
611      * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
612      * android.content.ComponentName, String)} or
613      * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
614      * android.content.ComponentName, String)} instead.
615      */
616     @Deprecated
setUserRestrictions(Bundle restrictions, UserHandle userHandle)617     public void setUserRestrictions(Bundle restrictions, UserHandle userHandle) {
618         try {
619             mService.setUserRestrictions(restrictions, userHandle.getIdentifier());
620         } catch (RemoteException re) {
621             Log.w(TAG, "Could not set user restrictions", re);
622         }
623     }
624 
625     /**
626      * Sets the value of a specific restriction.
627      * Requires the MANAGE_USERS permission.
628      * @param key the key of the restriction
629      * @param value the value for the restriction
630      * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
631      * android.content.ComponentName, String)} or
632      * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
633      * android.content.ComponentName, String)} instead.
634      */
635     @Deprecated
setUserRestriction(String key, boolean value)636     public void setUserRestriction(String key, boolean value) {
637         Bundle bundle = getUserRestrictions();
638         bundle.putBoolean(key, value);
639         setUserRestrictions(bundle);
640     }
641 
642     /**
643      * @hide
644      * Sets the value of a specific restriction on a specific user.
645      * Requires the MANAGE_USERS permission.
646      * @param key the key of the restriction
647      * @param value the value for the restriction
648      * @param userHandle the user whose restriction is to be changed.
649      * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
650      * android.content.ComponentName, String)} or
651      * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
652      * android.content.ComponentName, String)} instead.
653      */
654     @Deprecated
setUserRestriction(String key, boolean value, UserHandle userHandle)655     public void setUserRestriction(String key, boolean value, UserHandle userHandle) {
656         Bundle bundle = getUserRestrictions(userHandle);
657         bundle.putBoolean(key, value);
658         setUserRestrictions(bundle, userHandle);
659     }
660 
661     /**
662      * Returns whether the current user has been disallowed from performing certain actions
663      * or setting certain settings.
664      *
665      * @param restrictionKey The string key representing the restriction.
666      * @return {@code true} if the current user has the given restriction, {@code false} otherwise.
667      */
hasUserRestriction(String restrictionKey)668     public boolean hasUserRestriction(String restrictionKey) {
669         return hasUserRestriction(restrictionKey, Process.myUserHandle());
670     }
671 
672     /**
673      * @hide
674      * Returns whether the given user has been disallowed from performing certain actions
675      * or setting certain settings.
676      * @param restrictionKey the string key representing the restriction
677      * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
678      */
hasUserRestriction(String restrictionKey, UserHandle userHandle)679     public boolean hasUserRestriction(String restrictionKey, UserHandle userHandle) {
680         try {
681             return mService.hasUserRestriction(restrictionKey,
682                     userHandle.getIdentifier());
683         } catch (RemoteException re) {
684             Log.w(TAG, "Could not check user restrictions", re);
685             return false;
686         }
687     }
688 
689     /**
690      * Return the serial number for a user.  This is a device-unique
691      * number assigned to that user; if the user is deleted and then a new
692      * user created, the new users will not be given the same serial number.
693      * @param user The user whose serial number is to be retrieved.
694      * @return The serial number of the given user; returns -1 if the
695      * given UserHandle does not exist.
696      * @see #getUserForSerialNumber(long)
697      */
getSerialNumberForUser(UserHandle user)698     public long getSerialNumberForUser(UserHandle user) {
699         return getUserSerialNumber(user.getIdentifier());
700     }
701 
702     /**
703      * Return the user associated with a serial number previously
704      * returned by {@link #getSerialNumberForUser(UserHandle)}.
705      * @param serialNumber The serial number of the user that is being
706      * retrieved.
707      * @return Return the user associated with the serial number, or null
708      * if there is not one.
709      * @see #getSerialNumberForUser(UserHandle)
710      */
getUserForSerialNumber(long serialNumber)711     public UserHandle getUserForSerialNumber(long serialNumber) {
712         int ident = getUserHandle((int)serialNumber);
713         return ident >= 0 ? new UserHandle(ident) : null;
714     }
715 
716     /**
717      * Creates a user with the specified name and options.
718      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
719      *
720      * @param name the user's name
721      * @param flags flags that identify the type of user and other properties.
722      * @see UserInfo
723      *
724      * @return the UserInfo object for the created user, or null if the user could not be created.
725      * @hide
726      */
createUser(String name, int flags)727     public UserInfo createUser(String name, int flags) {
728         try {
729             return mService.createUser(name, flags);
730         } catch (RemoteException re) {
731             Log.w(TAG, "Could not create a user", re);
732             return null;
733         }
734     }
735 
736     /**
737      * Creates a guest user and configures it.
738      * @param context an application context
739      * @param name the name to set for the user
740      * @hide
741      */
createGuest(Context context, String name)742     public UserInfo createGuest(Context context, String name) {
743         UserInfo guest = createUser(name, UserInfo.FLAG_GUEST);
744         if (guest != null) {
745             Settings.Secure.putStringForUser(context.getContentResolver(),
746                     Settings.Secure.SKIP_FIRST_USE_HINTS, "1", guest.id);
747             try {
748                 Bundle guestRestrictions = mService.getDefaultGuestRestrictions();
749                 guestRestrictions.putBoolean(DISALLOW_SMS, true);
750                 guestRestrictions.putBoolean(DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
751                 mService.setUserRestrictions(guestRestrictions, guest.id);
752             } catch (RemoteException re) {
753                 Log.w(TAG, "Could not update guest restrictions");
754             }
755         }
756         return guest;
757     }
758 
759     /**
760      * Creates a secondary user with the specified name and options and configures it with default
761      * restrictions.
762      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
763      *
764      * @param name the user's name
765      * @param flags flags that identify the type of user and other properties.
766      * @see UserInfo
767      *
768      * @return the UserInfo object for the created user, or null if the user could not be created.
769      * @hide
770      */
createSecondaryUser(String name, int flags)771     public UserInfo createSecondaryUser(String name, int flags) {
772         try {
773             UserInfo user = mService.createUser(name, flags);
774             if (user == null) {
775                 return null;
776             }
777             Bundle userRestrictions = mService.getUserRestrictions(user.id);
778             addDefaultUserRestrictions(userRestrictions);
779             mService.setUserRestrictions(userRestrictions, user.id);
780             return user;
781         } catch (RemoteException re) {
782             Log.w(TAG, "Could not create a user", re);
783             return null;
784         }
785     }
786 
addDefaultUserRestrictions(Bundle restrictions)787     private static void addDefaultUserRestrictions(Bundle restrictions) {
788         restrictions.putBoolean(DISALLOW_OUTGOING_CALLS, true);
789         restrictions.putBoolean(DISALLOW_SMS, true);
790     }
791 
792     /**
793      * Creates a user with the specified name and options as a profile of another user.
794      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
795      *
796      * @param name the user's name
797      * @param flags flags that identify the type of user and other properties.
798      * @see UserInfo
799      * @param userHandle new user will be a profile of this use.
800      *
801      * @return the UserInfo object for the created user, or null if the user could not be created.
802      * @hide
803      */
createProfileForUser(String name, int flags, int userHandle)804     public UserInfo createProfileForUser(String name, int flags, int userHandle) {
805         try {
806             return mService.createProfileForUser(name, flags, userHandle);
807         } catch (RemoteException re) {
808             Log.w(TAG, "Could not create a user", re);
809             return null;
810         }
811     }
812 
813     /**
814      * @hide
815      * Marks the guest user for deletion to allow a new guest to be created before deleting
816      * the current user who is a guest.
817      * @param userHandle
818      * @return
819      */
markGuestForDeletion(int userHandle)820     public boolean markGuestForDeletion(int userHandle) {
821         try {
822             return mService.markGuestForDeletion(userHandle);
823         } catch (RemoteException re) {
824             Log.w(TAG, "Could not mark guest for deletion", re);
825             return false;
826         }
827     }
828 
829     /**
830      * Sets the user as enabled, if such an user exists.
831      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
832      * Note that the default is true, it's only that managed profiles might not be enabled.
833      *
834      * @param userHandle the id of the profile to enable
835      * @hide
836      */
setUserEnabled(int userHandle)837     public void setUserEnabled(int userHandle) {
838         try {
839             mService.setUserEnabled(userHandle);
840         } catch (RemoteException e) {
841             Log.w(TAG, "Could not enable the profile", e);
842         }
843     }
844 
845     /**
846      * Return the number of users currently created on the device.
847      */
getUserCount()848     public int getUserCount() {
849         List<UserInfo> users = getUsers();
850         return users != null ? users.size() : 1;
851     }
852 
853     /**
854      * Returns information for all users on this device.
855      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
856      * @return the list of users that were created.
857      * @hide
858      */
getUsers()859     public List<UserInfo> getUsers() {
860         try {
861             return mService.getUsers(false);
862         } catch (RemoteException re) {
863             Log.w(TAG, "Could not get user list", re);
864             return null;
865         }
866     }
867 
868     /**
869      * Checks whether it's possible to add more users. Caller must hold the MANAGE_USERS
870      * permission.
871      *
872      * @return true if more users can be added, false if limit has been reached.
873      * @hide
874      */
canAddMoreUsers()875     public boolean canAddMoreUsers() {
876         final List<UserInfo> users = getUsers(true);
877         final int totalUserCount = users.size();
878         int aliveUserCount = 0;
879         for (int i = 0; i < totalUserCount; i++) {
880             UserInfo user = users.get(i);
881             if (!user.isGuest()) {
882                 aliveUserCount++;
883             }
884         }
885         return aliveUserCount < getMaxSupportedUsers();
886     }
887 
888     /**
889      * Returns list of the profiles of userHandle including
890      * userHandle itself.
891      * Note that this returns both enabled and not enabled profiles. See
892      * {@link #getUserProfiles()} if you need only the enabled ones.
893      *
894      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
895      * @param userHandle profiles of this user will be returned.
896      * @return the list of profiles.
897      * @hide
898      */
getProfiles(int userHandle)899     public List<UserInfo> getProfiles(int userHandle) {
900         try {
901             return mService.getProfiles(userHandle, false /* enabledOnly */);
902         } catch (RemoteException re) {
903             Log.w(TAG, "Could not get user list", re);
904             return null;
905         }
906     }
907 
908     /**
909      * Returns a list of UserHandles for profiles associated with the user that the calling process
910      * is running on, including the user itself.
911      *
912      * @return A non-empty list of UserHandles associated with the calling user.
913      */
getUserProfiles()914     public List<UserHandle> getUserProfiles() {
915         ArrayList<UserHandle> profiles = new ArrayList<UserHandle>();
916         List<UserInfo> users = new ArrayList<UserInfo>();
917         try {
918             users = mService.getProfiles(UserHandle.myUserId(), true /* enabledOnly */);
919         } catch (RemoteException re) {
920             Log.w(TAG, "Could not get user list", re);
921             return null;
922         }
923         for (UserInfo info : users) {
924             UserHandle userHandle = new UserHandle(info.id);
925             profiles.add(userHandle);
926         }
927         return profiles;
928     }
929 
930     /**
931      * Returns the parent of the profile which this method is called from
932      * or null if called from a user that is not a profile.
933      *
934      * @hide
935      */
getProfileParent(int userHandle)936     public UserInfo getProfileParent(int userHandle) {
937         try {
938             return mService.getProfileParent(userHandle);
939         } catch (RemoteException re) {
940             Log.w(TAG, "Could not get profile parent", re);
941             return null;
942         }
943     }
944 
945     /**
946      * If the target user is a managed profile of the calling user or the caller
947      * is itself a managed profile, then this returns a badged copy of the given
948      * icon to be able to distinguish it from the original icon. For badging an
949      * arbitrary drawable use {@link #getBadgedDrawableForUser(
950      * android.graphics.drawable.Drawable, UserHandle, android.graphics.Rect, int)}.
951      * <p>
952      * If the original drawable is a BitmapDrawable and the backing bitmap is
953      * mutable as per {@link android.graphics.Bitmap#isMutable()}, the bading
954      * is performed in place and the original drawable is returned.
955      * </p>
956      *
957      * @param icon The icon to badge.
958      * @param user The target user.
959      * @return A drawable that combines the original icon and a badge as
960      *         determined by the system.
961      * @removed
962      */
getBadgedIconForUser(Drawable icon, UserHandle user)963     public Drawable getBadgedIconForUser(Drawable icon, UserHandle user) {
964         return mContext.getPackageManager().getUserBadgedIcon(icon, user);
965     }
966 
967     /**
968      * If the target user is a managed profile of the calling user or the caller
969      * is itself a managed profile, then this returns a badged copy of the given
970      * drawable allowing the user to distinguish it from the original drawable.
971      * The caller can specify the location in the bounds of the drawable to be
972      * badged where the badge should be applied as well as the density of the
973      * badge to be used.
974      * <p>
975      * If the original drawable is a BitmapDrawable and the backing bitmap is
976      * mutable as per {@link android.graphics.Bitmap#isMutable()}, the bading
977      * is performed in place and the original drawable is returned.
978      * </p>
979      *
980      * @param badgedDrawable The drawable to badge.
981      * @param user The target user.
982      * @param badgeLocation Where in the bounds of the badged drawable to place
983      *         the badge. If not provided, the badge is applied on top of the entire
984      *         drawable being badged.
985      * @param badgeDensity The optional desired density for the badge as per
986      *         {@link android.util.DisplayMetrics#densityDpi}. If not provided,
987      *         the density of the display is used.
988      * @return A drawable that combines the original drawable and a badge as
989      *         determined by the system.
990      * @removed
991      */
getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user, Rect badgeLocation, int badgeDensity)992     public Drawable getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user,
993             Rect badgeLocation, int badgeDensity) {
994         return mContext.getPackageManager().getUserBadgedDrawableForDensity(badgedDrawable, user,
995                 badgeLocation, badgeDensity);
996     }
997 
998     /**
999      * If the target user is a managed profile of the calling user or the caller
1000      * is itself a managed profile, then this returns a copy of the label with
1001      * badging for accessibility services like talkback. E.g. passing in "Email"
1002      * and it might return "Work Email" for Email in the work profile.
1003      *
1004      * @param label The label to change.
1005      * @param user The target user.
1006      * @return A label that combines the original label and a badge as
1007      *         determined by the system.
1008      * @removed
1009      */
getBadgedLabelForUser(CharSequence label, UserHandle user)1010     public CharSequence getBadgedLabelForUser(CharSequence label, UserHandle user) {
1011         return mContext.getPackageManager().getUserBadgedLabel(label, user);
1012     }
1013 
1014     /**
1015      * Returns information for all users on this device. Requires
1016      * {@link android.Manifest.permission#MANAGE_USERS} permission.
1017      *
1018      * @param excludeDying specify if the list should exclude users being
1019      *            removed.
1020      * @return the list of users that were created.
1021      * @hide
1022      */
getUsers(boolean excludeDying)1023     public List<UserInfo> getUsers(boolean excludeDying) {
1024         try {
1025             return mService.getUsers(excludeDying);
1026         } catch (RemoteException re) {
1027             Log.w(TAG, "Could not get user list", re);
1028             return null;
1029         }
1030     }
1031 
1032     /**
1033      * Removes a user and all associated data.
1034      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1035      * @param userHandle the integer handle of the user, where 0 is the primary user.
1036      * @hide
1037      */
removeUser(int userHandle)1038     public boolean removeUser(int userHandle) {
1039         try {
1040             return mService.removeUser(userHandle);
1041         } catch (RemoteException re) {
1042             Log.w(TAG, "Could not remove user ", re);
1043             return false;
1044         }
1045     }
1046 
1047     /**
1048      * Updates the user's name.
1049      * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1050      *
1051      * @param userHandle the user's integer handle
1052      * @param name the new name for the user
1053      * @hide
1054      */
setUserName(int userHandle, String name)1055     public void setUserName(int userHandle, String name) {
1056         try {
1057             mService.setUserName(userHandle, name);
1058         } catch (RemoteException re) {
1059             Log.w(TAG, "Could not set the user name ", re);
1060         }
1061     }
1062 
1063     /**
1064      * Sets the user's photo.
1065      * @param userHandle the user for whom to change the photo.
1066      * @param icon the bitmap to set as the photo.
1067      * @hide
1068      */
setUserIcon(int userHandle, Bitmap icon)1069     public void setUserIcon(int userHandle, Bitmap icon) {
1070         try {
1071             mService.setUserIcon(userHandle, icon);
1072         } catch (RemoteException re) {
1073             Log.w(TAG, "Could not set the user icon ", re);
1074         }
1075     }
1076 
1077     /**
1078      * Returns a file descriptor for the user's photo. PNG data can be read from this file.
1079      * @param userHandle the user whose photo we want to read.
1080      * @return a {@link Bitmap} of the user's photo, or null if there's no photo.
1081      * @see com.android.internal.util.UserIcons#getDefaultUserIcon for a default.
1082      * @hide
1083      */
getUserIcon(int userHandle)1084     public Bitmap getUserIcon(int userHandle) {
1085         try {
1086             return mService.getUserIcon(userHandle);
1087         } catch (RemoteException re) {
1088             Log.w(TAG, "Could not get the user icon ", re);
1089             return null;
1090         }
1091     }
1092 
1093     /**
1094      * Returns the maximum number of users that can be created on this device. A return value
1095      * of 1 means that it is a single user device.
1096      * @hide
1097      * @return a value greater than or equal to 1
1098      */
getMaxSupportedUsers()1099     public static int getMaxSupportedUsers() {
1100         // Don't allow multiple users on certain builds
1101         if (android.os.Build.ID.startsWith("JVP")) return 1;
1102         // Svelte devices don't get multi-user.
1103         if (ActivityManager.isLowRamDeviceStatic()) return 1;
1104         return SystemProperties.getInt("fw.max_users",
1105                 Resources.getSystem().getInteger(R.integer.config_multiuserMaximumUsers));
1106     }
1107 
1108     /**
1109      * Returns true if the user switcher should be shown, this will be if there
1110      * are multiple users that aren't managed profiles.
1111      * @hide
1112      * @return true if user switcher should be shown.
1113      */
isUserSwitcherEnabled()1114     public boolean isUserSwitcherEnabled() {
1115         List<UserInfo> users = getUsers(true);
1116         if (users == null) {
1117            return false;
1118         }
1119         int switchableUserCount = 0;
1120         for (UserInfo user : users) {
1121             if (user.supportsSwitchTo()) {
1122                 ++switchableUserCount;
1123             }
1124         }
1125         final boolean guestEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1126                 Settings.Global.GUEST_USER_ENABLED, 0) == 1;
1127         return switchableUserCount > 1 || guestEnabled;
1128     }
1129 
1130     /**
1131      * Returns a serial number on this device for a given userHandle. User handles can be recycled
1132      * when deleting and creating users, but serial numbers are not reused until the device is wiped.
1133      * @param userHandle
1134      * @return a serial number associated with that user, or -1 if the userHandle is not valid.
1135      * @hide
1136      */
getUserSerialNumber(int userHandle)1137     public int getUserSerialNumber(int userHandle) {
1138         try {
1139             return mService.getUserSerialNumber(userHandle);
1140         } catch (RemoteException re) {
1141             Log.w(TAG, "Could not get serial number for user " + userHandle);
1142         }
1143         return -1;
1144     }
1145 
1146     /**
1147      * Returns a userHandle on this device for a given user serial number. User handles can be
1148      * recycled when deleting and creating users, but serial numbers are not reused until the device
1149      * is wiped.
1150      * @param userSerialNumber
1151      * @return the userHandle associated with that user serial number, or -1 if the serial number
1152      * is not valid.
1153      * @hide
1154      */
getUserHandle(int userSerialNumber)1155     public int getUserHandle(int userSerialNumber) {
1156         try {
1157             return mService.getUserHandle(userSerialNumber);
1158         } catch (RemoteException re) {
1159             Log.w(TAG, "Could not get userHandle for user " + userSerialNumber);
1160         }
1161         return -1;
1162     }
1163 
1164     /**
1165      * Returns a Bundle containing any saved application restrictions for this user, for the
1166      * given package name. Only an application with this package name can call this method.
1167      * @param packageName the package name of the calling application
1168      * @return a Bundle with the restrictions as key/value pairs, or null if there are no
1169      * saved restrictions. The values can be of type Boolean, String or String[], depending
1170      * on the restriction type, as defined by the application.
1171      */
getApplicationRestrictions(String packageName)1172     public Bundle getApplicationRestrictions(String packageName) {
1173         try {
1174             return mService.getApplicationRestrictions(packageName);
1175         } catch (RemoteException re) {
1176             Log.w(TAG, "Could not get application restrictions for package " + packageName);
1177         }
1178         return null;
1179     }
1180 
1181     /**
1182      * @hide
1183      */
getApplicationRestrictions(String packageName, UserHandle user)1184     public Bundle getApplicationRestrictions(String packageName, UserHandle user) {
1185         try {
1186             return mService.getApplicationRestrictionsForUser(packageName, user.getIdentifier());
1187         } catch (RemoteException re) {
1188             Log.w(TAG, "Could not get application restrictions for user " + user.getIdentifier());
1189         }
1190         return null;
1191     }
1192 
1193     /**
1194      * @hide
1195      */
setApplicationRestrictions(String packageName, Bundle restrictions, UserHandle user)1196     public void setApplicationRestrictions(String packageName, Bundle restrictions,
1197             UserHandle user) {
1198         try {
1199             mService.setApplicationRestrictions(packageName, restrictions, user.getIdentifier());
1200         } catch (RemoteException re) {
1201             Log.w(TAG, "Could not set application restrictions for user " + user.getIdentifier());
1202         }
1203     }
1204 
1205     /**
1206      * Sets a new challenge PIN for restrictions. This is only for use by pre-installed
1207      * apps and requires the MANAGE_USERS permission.
1208      * @param newPin the PIN to use for challenge dialogs.
1209      * @return Returns true if the challenge PIN was set successfully.
1210      */
setRestrictionsChallenge(String newPin)1211     public boolean setRestrictionsChallenge(String newPin) {
1212         try {
1213             return mService.setRestrictionsChallenge(newPin);
1214         } catch (RemoteException re) {
1215             Log.w(TAG, "Could not change restrictions pin");
1216         }
1217         return false;
1218     }
1219 
1220     /**
1221      * @hide
1222      * @param pin The PIN to verify, or null to get the number of milliseconds to wait for before
1223      * allowing the user to enter the PIN.
1224      * @return Returns a positive number (including zero) for how many milliseconds before
1225      * you can accept another PIN, when the input is null or the input doesn't match the saved PIN.
1226      * Returns {@link #PIN_VERIFICATION_SUCCESS} if the input matches the saved PIN. Returns
1227      * {@link #PIN_VERIFICATION_FAILED_NOT_SET} if there is no PIN set.
1228      */
checkRestrictionsChallenge(String pin)1229     public int checkRestrictionsChallenge(String pin) {
1230         try {
1231             return mService.checkRestrictionsChallenge(pin);
1232         } catch (RemoteException re) {
1233             Log.w(TAG, "Could not check restrictions pin");
1234         }
1235         return PIN_VERIFICATION_FAILED_INCORRECT;
1236     }
1237 
1238     /**
1239      * @hide
1240      * Checks whether the user has restrictions that are PIN-protected. An application that
1241      * participates in restrictions can check if the owner has requested a PIN challenge for
1242      * any restricted operations. If there is a PIN in effect, the application should launch
1243      * the PIN challenge activity {@link android.content.Intent#ACTION_RESTRICTIONS_CHALLENGE}.
1244      * @see android.content.Intent#ACTION_RESTRICTIONS_CHALLENGE
1245      * @return whether a restrictions PIN is in effect.
1246      */
hasRestrictionsChallenge()1247     public boolean hasRestrictionsChallenge() {
1248         try {
1249             return mService.hasRestrictionsChallenge();
1250         } catch (RemoteException re) {
1251             Log.w(TAG, "Could not change restrictions pin");
1252         }
1253         return false;
1254     }
1255 
1256     /** @hide */
removeRestrictions()1257     public void removeRestrictions() {
1258         try {
1259             mService.removeRestrictions();
1260         } catch (RemoteException re) {
1261             Log.w(TAG, "Could not change restrictions pin");
1262         }
1263     }
1264 
1265     /**
1266      * @hide
1267      * Set restrictions that should apply to any future guest user that's created.
1268      */
setDefaultGuestRestrictions(Bundle restrictions)1269     public void setDefaultGuestRestrictions(Bundle restrictions) {
1270         try {
1271             mService.setDefaultGuestRestrictions(restrictions);
1272         } catch (RemoteException re) {
1273             Log.w(TAG, "Could not set guest restrictions");
1274         }
1275     }
1276 
1277     /**
1278      * @hide
1279      * Gets the default guest restrictions.
1280      */
getDefaultGuestRestrictions()1281     public Bundle getDefaultGuestRestrictions() {
1282         try {
1283             return mService.getDefaultGuestRestrictions();
1284         } catch (RemoteException re) {
1285             Log.w(TAG, "Could not set guest restrictions");
1286         }
1287         return new Bundle();
1288     }
1289 }
1290