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