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