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