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