UserManager.java revision 681bf60ce2a3973d5982f9b7a405bcef5fb72f20
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 modifying
233     * applications in Settings or launchers. The following actions will not be allowed when this
234     * restriction is enabled:
235     * <li>uninstalling apps</li>
236     * <li>disabling apps</li>
237     * <li>clearing app caches</li>
238     * <li>clearing app data</li>
239     * <li>force stopping apps</li>
240     * <li>clearing app defaults</li>
241     * <p>
242     * The default value is <code>false</code>.
243     * <p>
244     * Type: Boolean
245     * @see #setUserRestrictions(Bundle)
246     * @see #getUserRestrictions()
247     */
248    public static final String DISALLOW_APPS_CONTROL = "no_control_apps";
249
250    /**
251     * Key for user restrictions. Specifies if a user is disallowed from mounting
252     * physical external media. The default value is <code>false</code>.
253     * <p/>
254     * Type: Boolean
255     * @see #setUserRestrictions(Bundle)
256     * @see #getUserRestrictions()
257     */
258    public static final String DISALLOW_MOUNT_PHYSICAL_MEDIA = "no_physical_media";
259
260    /**
261     * Key for user restrictions. Specifies if a user is disallowed from adjusting microphone
262     * volume.
263     * The default value is <code>false</code>.
264     * <p/>
265     * Type: Boolean
266     * @see #setUserRestrictions(Bundle)
267     * @see #getUserRestrictions()
268     */
269    public static final String DISALLOW_UNMUTE_MICROPHONE = "no_unmute_microphone";
270
271    /**
272     * Key for user restrictions. Specifies if a user is disallowed from adjusting the master
273     * volume.
274     * The default value is <code>false</code>.
275     * <p/>
276     * Type: Boolean
277     * @see #setUserRestrictions(Bundle)
278     * @see #getUserRestrictions()
279     */
280    public static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume";
281
282    /**
283     * Key for user restrictions. Specifies that the user is not allowed to make outgoing
284     * phone calls. Emergency calls are still permitted.
285     * The default value is <code>false</code>.
286     * <p/>
287     * Type: Boolean
288     * @see #setUserRestrictions(Bundle)
289     * @see #getUserRestrictions()
290     */
291    public static final String DISALLOW_OUTGOING_CALLS = "no_outgoing_calls";
292
293    /**
294     * Key for user restrictions. Specifies that the user is not allowed to send or receive
295     * SMS messages.
296     * The default value is <code>false</code>.
297     * <p/>
298     * Type: Boolean
299     * @see #setUserRestrictions(Bundle)
300     * @see #getUserRestrictions()
301     */
302    public static final String DISALLOW_SMS = "no_sms";
303
304    /**
305     * Key for user restrictions. Specifies that windows besides app windows should not be
306     * created. This will block the creation of the following types of windows.
307     * <li>{@link LayoutParams#TYPE_TOAST}</li>
308     * <li>{@link LayoutParams#TYPE_PHONE}</li>
309     * <li>{@link LayoutParams#TYPE_PRIORITY_PHONE}</li>
310     * <li>{@link LayoutParams#TYPE_SYSTEM_ALERT}</li>
311     * <li>{@link LayoutParams#TYPE_SYSTEM_ERROR}</li>
312     * <li>{@link LayoutParams#TYPE_SYSTEM_OVERLAY}</li>
313     *
314     * <p>The default value is <code>false</code>.
315     * <p/>
316     * Type: Boolean
317     * @see #setUserRestrictions(Bundle)
318     * @see #getUserRestrictions()
319     */
320    public static final String DISALLOW_CREATE_WINDOWS = "no_create_windows";
321
322    /**
323     * Key for user restrictions. Specifies if what is copied in the clipboard of this profile can
324     * be pasted in related profiles. Does not restrict if the clipboard of related profiles can be
325     * pasted in this profile.
326     * The default value is <code>false</code>.
327     * <p/>
328     * Type: Boolean
329     * @see #setUserRestrictions(Bundle)
330     * @see #getUserRestrictions()
331     */
332    public static final String DISALLOW_CROSS_PROFILE_COPY_PASTE = "no_cross_profile_copy_paste";
333
334    /** @hide */
335    public static final int PIN_VERIFICATION_FAILED_INCORRECT = -3;
336    /** @hide */
337    public static final int PIN_VERIFICATION_FAILED_NOT_SET = -2;
338    /** @hide */
339    public static final int PIN_VERIFICATION_SUCCESS = -1;
340
341    private static UserManager sInstance = null;
342
343    /** @hide */
344    public synchronized static UserManager get(Context context) {
345        if (sInstance == null) {
346            sInstance = (UserManager) context.getSystemService(Context.USER_SERVICE);
347        }
348        return sInstance;
349    }
350
351    /** @hide */
352    public UserManager(Context context, IUserManager service) {
353        mService = service;
354        mContext = context;
355    }
356
357    /**
358     * Returns whether the system supports multiple users.
359     * @return true if multiple users can be created by user, false if it is a single user device.
360     * @hide
361     */
362    public static boolean supportsMultipleUsers() {
363        return getMaxSupportedUsers() > 1
364                && SystemProperties.getBoolean("fw.show_multiuserui",
365                Resources.getSystem().getBoolean(R.bool.config_enableMultiUserUI));
366    }
367
368    /**
369     * Returns the user handle for the user that the calling process is running on.
370     *
371     * @return the user handle of the user making this call.
372     * @hide
373     */
374    public int getUserHandle() {
375        return UserHandle.myUserId();
376    }
377
378    /**
379     * Returns the user name of the user making this call.  This call is only
380     * available to applications on the system image; it requires the
381     * MANAGE_USERS permission.
382     * @return the user name
383     */
384    public String getUserName() {
385        try {
386            return mService.getUserInfo(getUserHandle()).name;
387        } catch (RemoteException re) {
388            Log.w(TAG, "Could not get user name", re);
389            return "";
390        }
391    }
392
393   /**
394     * Used to determine whether the user making this call is subject to
395     * teleportations.
396     * @return whether the user making this call is a goat
397     */
398    public boolean isUserAGoat() {
399        return false;
400    }
401
402    /**
403     * Used to check if the user making this call is linked to another user. Linked users may have
404     * a reduced number of available apps, app restrictions and account restrictions.
405     * @return whether the user making this call is a linked user
406     * @hide
407     */
408    public boolean isLinkedUser() {
409        try {
410            return mService.isRestricted();
411        } catch (RemoteException re) {
412            Log.w(TAG, "Could not check if user is limited ", re);
413            return false;
414        }
415    }
416
417    /**
418     * Checks if the calling app is running as a guest user.
419     * @return whether the caller is a guest user.
420     * @hide
421     */
422    public boolean isGuestUser() {
423        UserInfo user = getUserInfo(UserHandle.myUserId());
424        return user != null ? user.isGuest() : false;
425    }
426
427    /**
428     * Return whether the given user is actively running.  This means that
429     * the user is in the "started" state, not "stopped" -- it is currently
430     * allowed to run code through scheduled alarms, receiving broadcasts,
431     * etc.  A started user may be either the current foreground user or a
432     * background user; the result here does not distinguish between the two.
433     * @param user The user to retrieve the running state for.
434     */
435    public boolean isUserRunning(UserHandle user) {
436        try {
437            return ActivityManagerNative.getDefault().isUserRunning(
438                    user.getIdentifier(), false);
439        } catch (RemoteException e) {
440            return false;
441        }
442    }
443
444    /**
445     * Return whether the given user is actively running <em>or</em> stopping.
446     * This is like {@link #isUserRunning(UserHandle)}, but will also return
447     * true if the user had been running but is in the process of being stopped
448     * (but is not yet fully stopped, and still running some code).
449     * @param user The user to retrieve the running state for.
450     */
451    public boolean isUserRunningOrStopping(UserHandle user) {
452        try {
453            return ActivityManagerNative.getDefault().isUserRunning(
454                    user.getIdentifier(), true);
455        } catch (RemoteException e) {
456            return false;
457        }
458    }
459
460    /**
461     * Returns the UserInfo object describing a specific user.
462     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
463     * @param userHandle the user handle of the user whose information is being requested.
464     * @return the UserInfo object for a specific user.
465     * @hide
466     */
467    public UserInfo getUserInfo(int userHandle) {
468        try {
469            return mService.getUserInfo(userHandle);
470        } catch (RemoteException re) {
471            Log.w(TAG, "Could not get user info", re);
472            return null;
473        }
474    }
475
476    /**
477     * Returns the user-wide restrictions imposed on this user.
478     * @return a Bundle containing all the restrictions.
479     */
480    public Bundle getUserRestrictions() {
481        return getUserRestrictions(Process.myUserHandle());
482    }
483
484    /**
485     * Returns the user-wide restrictions imposed on the user specified by <code>userHandle</code>.
486     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
487     * @return a Bundle containing all the restrictions.
488     */
489    public Bundle getUserRestrictions(UserHandle userHandle) {
490        try {
491            return mService.getUserRestrictions(userHandle.getIdentifier());
492        } catch (RemoteException re) {
493            Log.w(TAG, "Could not get user restrictions", re);
494            return Bundle.EMPTY;
495        }
496    }
497
498    /**
499     * Sets all the user-wide restrictions for this user.
500     * Requires the MANAGE_USERS permission.
501     * @param restrictions the Bundle containing all the restrictions.
502     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
503     * android.content.ComponentName, String)} or
504     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
505     * android.content.ComponentName, String)} instead.
506     */
507    @Deprecated
508    public void setUserRestrictions(Bundle restrictions) {
509        setUserRestrictions(restrictions, Process.myUserHandle());
510    }
511
512    /**
513     * Sets all the user-wide restrictions for the specified user.
514     * Requires the MANAGE_USERS permission.
515     * @param restrictions the Bundle containing all the restrictions.
516     * @param userHandle the UserHandle of the user for whom to set the restrictions.
517     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
518     * android.content.ComponentName, String)} or
519     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
520     * android.content.ComponentName, String)} instead.
521     */
522    @Deprecated
523    public void setUserRestrictions(Bundle restrictions, UserHandle userHandle) {
524        try {
525            mService.setUserRestrictions(restrictions, userHandle.getIdentifier());
526        } catch (RemoteException re) {
527            Log.w(TAG, "Could not set user restrictions", re);
528        }
529    }
530
531    /**
532     * Sets the value of a specific restriction.
533     * Requires the MANAGE_USERS permission.
534     * @param key the key of the restriction
535     * @param value the value for the restriction
536     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
537     * android.content.ComponentName, String)} or
538     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
539     * android.content.ComponentName, String)} instead.
540     */
541    @Deprecated
542    public void setUserRestriction(String key, boolean value) {
543        Bundle bundle = getUserRestrictions();
544        bundle.putBoolean(key, value);
545        setUserRestrictions(bundle);
546    }
547
548    /**
549     * @hide
550     * Sets the value of a specific restriction on a specific user.
551     * Requires the MANAGE_USERS permission.
552     * @param key the key of the restriction
553     * @param value the value for the restriction
554     * @param userHandle the user whose restriction is to be changed.
555     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
556     * android.content.ComponentName, String)} or
557     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
558     * android.content.ComponentName, String)} instead.
559     */
560    @Deprecated
561    public void setUserRestriction(String key, boolean value, UserHandle userHandle) {
562        Bundle bundle = getUserRestrictions(userHandle);
563        bundle.putBoolean(key, value);
564        setUserRestrictions(bundle, userHandle);
565    }
566
567    /**
568     * Returns whether the current user has been disallowed from performing certain actions
569     * or setting certain settings.
570     *
571     * @param restrictionKey The string key representing the restriction.
572     * @return {@code true} if the current user has the given restriction, {@code false} otherwise.
573     */
574    public boolean hasUserRestriction(String restrictionKey) {
575        return hasUserRestriction(restrictionKey, Process.myUserHandle());
576    }
577
578    /**
579     * @hide
580     * Returns whether the given user has been disallowed from performing certain actions
581     * or setting certain settings.
582     * @param restrictionKey the string key representing the restriction
583     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
584     */
585    public boolean hasUserRestriction(String restrictionKey, UserHandle userHandle) {
586        return getUserRestrictions(userHandle).getBoolean(restrictionKey, false);
587    }
588
589    /**
590     * Return the serial number for a user.  This is a device-unique
591     * number assigned to that user; if the user is deleted and then a new
592     * user created, the new users will not be given the same serial number.
593     * @param user The user whose serial number is to be retrieved.
594     * @return The serial number of the given user; returns -1 if the
595     * given UserHandle does not exist.
596     * @see #getUserForSerialNumber(long)
597     */
598    public long getSerialNumberForUser(UserHandle user) {
599        return getUserSerialNumber(user.getIdentifier());
600    }
601
602    /**
603     * Return the user associated with a serial number previously
604     * returned by {@link #getSerialNumberForUser(UserHandle)}.
605     * @param serialNumber The serial number of the user that is being
606     * retrieved.
607     * @return Return the user associated with the serial number, or null
608     * if there is not one.
609     * @see #getSerialNumberForUser(UserHandle)
610     */
611    public UserHandle getUserForSerialNumber(long serialNumber) {
612        int ident = getUserHandle((int)serialNumber);
613        return ident >= 0 ? new UserHandle(ident) : null;
614    }
615
616    /**
617     * Creates a user with the specified name and options.
618     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
619     *
620     * @param name the user's name
621     * @param flags flags that identify the type of user and other properties.
622     * @see UserInfo
623     *
624     * @return the UserInfo object for the created user, or null if the user could not be created.
625     * @hide
626     */
627    public UserInfo createUser(String name, int flags) {
628        try {
629            return mService.createUser(name, flags);
630        } catch (RemoteException re) {
631            Log.w(TAG, "Could not create a user", re);
632            return null;
633        }
634    }
635
636    /**
637     * Creates a guest user and configures it.
638     * @param context an application context
639     * @param name the name to set for the user
640     * @hide
641     */
642    public UserInfo createGuest(Context context, String name) {
643        UserInfo guest = createUser(name, UserInfo.FLAG_GUEST);
644        if (guest != null) {
645            Settings.Secure.putStringForUser(context.getContentResolver(),
646                    Settings.Secure.SKIP_FIRST_USE_HINTS, "1", guest.id);
647            try {
648                Bundle guestRestrictions = mService.getDefaultGuestRestrictions();
649                guestRestrictions.putBoolean(DISALLOW_SMS, true);
650                mService.setUserRestrictions(guestRestrictions, guest.id);
651            } catch (RemoteException re) {
652                Log.w(TAG, "Could not update guest restrictions");
653            }
654        }
655        return guest;
656    }
657
658    /**
659     * Creates a user with the specified name and options as a profile of another user.
660     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
661     *
662     * @param name the user's name
663     * @param flags flags that identify the type of user and other properties.
664     * @see UserInfo
665     * @param userHandle new user will be a profile of this use.
666     *
667     * @return the UserInfo object for the created user, or null if the user could not be created.
668     * @hide
669     */
670    public UserInfo createProfileForUser(String name, int flags, int userHandle) {
671        try {
672            return mService.createProfileForUser(name, flags, userHandle);
673        } catch (RemoteException re) {
674            Log.w(TAG, "Could not create a user", re);
675            return null;
676        }
677    }
678
679    /**
680     * Sets the user as enabled, if such an user exists.
681     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
682     * Note that the default is true, it's only that managed profiles might not be enabled.
683     *
684     * @param userHandle the id of the profile to enable
685     * @hide
686     */
687    public void setUserEnabled(int userHandle) {
688        try {
689            mService.setUserEnabled(userHandle);
690        } catch (RemoteException e) {
691            Log.w(TAG, "Could not enable the profile", e);
692        }
693    }
694
695    /**
696     * Return the number of users currently created on the device.
697     */
698    public int getUserCount() {
699        List<UserInfo> users = getUsers();
700        return users != null ? users.size() : 1;
701    }
702
703    /**
704     * Returns information for all users on this device.
705     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
706     * @return the list of users that were created.
707     * @hide
708     */
709    public List<UserInfo> getUsers() {
710        try {
711            return mService.getUsers(false);
712        } catch (RemoteException re) {
713            Log.w(TAG, "Could not get user list", re);
714            return null;
715        }
716    }
717
718    /**
719     * Checks whether it's possible to add more users. Caller must hold the MANAGE_USERS
720     * permission.
721     *
722     * @return true if more users can be added, false if limit has been reached.
723     * @hide
724     */
725    public boolean canAddMoreUsers() {
726        final List<UserInfo> users = getUsers(true);
727        final int totalUserCount = users.size();
728        int aliveUserCount = 0;
729        for (int i = 0; i < totalUserCount; i++) {
730            UserInfo user = users.get(i);
731            if (!user.isGuest()) {
732                aliveUserCount++;
733            }
734        }
735        return aliveUserCount < getMaxSupportedUsers();
736    }
737
738    /**
739     * Returns list of the profiles of userHandle including
740     * userHandle itself.
741     * Note that this returns both enabled and not enabled profiles. See
742     * {@link #getUserProfiles()} if you need only the enabled ones.
743     *
744     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
745     * @param userHandle profiles of this user will be returned.
746     * @return the list of profiles.
747     * @hide
748     */
749    public List<UserInfo> getProfiles(int userHandle) {
750        try {
751            return mService.getProfiles(userHandle, false /* enabledOnly */);
752        } catch (RemoteException re) {
753            Log.w(TAG, "Could not get user list", re);
754            return null;
755        }
756    }
757
758    /**
759     * Returns a list of UserHandles for profiles associated with the user that the calling process
760     * is running on, including the user itself.
761     *
762     * @return A non-empty list of UserHandles associated with the calling user.
763     */
764    public List<UserHandle> getUserProfiles() {
765        ArrayList<UserHandle> profiles = new ArrayList<UserHandle>();
766        List<UserInfo> users = new ArrayList<UserInfo>();
767        try {
768            users = mService.getProfiles(UserHandle.myUserId(), true /* enabledOnly */);
769        } catch (RemoteException re) {
770            Log.w(TAG, "Could not get user list", re);
771            return null;
772        }
773        for (UserInfo info : users) {
774            UserHandle userHandle = new UserHandle(info.id);
775            profiles.add(userHandle);
776        }
777        return profiles;
778    }
779
780    /**
781     * Returns the parent of the profile which this method is called from
782     * or null if called from a user that is not a profile.
783     *
784     * @hide
785     */
786    public UserInfo getProfileParent(int userHandle) {
787        try {
788            return mService.getProfileParent(userHandle);
789        } catch (RemoteException re) {
790            Log.w(TAG, "Could not get profile parent", re);
791            return null;
792        }
793    }
794
795    /**
796     * If the target user is a managed profile of the calling user or the caller
797     * is itself a managed profile, then this returns a badged copy of the given
798     * icon to be able to distinguish it from the original icon. For badging an
799     * arbitrary drawable use {@link #getBadgedDrawableForUser(
800     * android.graphics.drawable.Drawable, UserHandle, android.graphics.Rect, int)}.
801     * <p>
802     * If the original drawable is a BitmapDrawable and the backing bitmap is
803     * mutable as per {@link android.graphics.Bitmap#isMutable()}, the bading
804     * is performed in place and the original drawable is returned.
805     * </p>
806     *
807     * @param icon The icon to badge.
808     * @param user The target user.
809     * @return A drawable that combines the original icon and a badge as
810     *         determined by the system.
811     */
812    public Drawable getBadgedIconForUser(Drawable icon, UserHandle user) {
813        final int badgeResId = getBadgeResIdForUser(user.getIdentifier());
814        if (badgeResId == 0) {
815            return icon;
816        }
817        Drawable badgeIcon = mContext.getPackageManager()
818                .getDrawable("system", badgeResId, null);
819        return getBadgedDrawable(icon, badgeIcon, null, true);
820    }
821
822    /**
823     * If the target user is a managed profile of the calling user or the caller
824     * is itself a managed profile, then this returns a badged copy of the given
825     * icon to be able to distinguish it from the original icon.
826     * <p>
827     * If the original drawable is not a BitmapDrawable, then the original
828     * drawable is returned.
829     * </p>
830     *
831     * @param icon The icon to badge.
832     * @param user The target user.
833     * @return A drawable that combines the original icon and a badge as
834     *         determined by the system.
835     *
836     * @deprecation Use {@link #getBadgedIconForUser(
837     *     android.graphics.drawable.Drawable, UserHandle)}
838     *
839     * @hide
840     */
841    @Deprecated
842    public Drawable getBadgedDrawableForUser(Drawable icon, UserHandle user) {
843        int badgeResId = getBadgeResIdForUser(user.getIdentifier());
844        if (badgeResId == 0) {
845            return icon;
846        } else {
847            Drawable badgeIcon = mContext.getPackageManager()
848                    .getDrawable("system", badgeResId, null);
849            return getBadgedDrawable(icon, badgeIcon, null, false);
850        }
851    }
852
853    /**
854     * If the target user is a managed profile of the calling user or the caller
855     * is itself a managed profile, then this returns a badged copy of the given
856     * drawable allowing the user to distinguish it from the original drawable.
857     * The caller can specify the location in the bounds of the drawable to be
858     * badged where the badge should be applied as well as the density of the
859     * badge to be used.
860     * <p>
861     * If the original drawable is a BitmapDrawable and the backing bitmap is
862     * mutable as per {@link android.graphics.Bitmap#isMutable()}, the bading
863     * is performed in place and the original drawable is returned.
864     * </p>
865     *
866     * @param badgedDrawable The drawable to badge.
867     * @param user The target user.
868     * @param badgeLocation Where in the bounds of the badged drawable to place
869     *         the badge. If not provided, the badge is applied on top of the entire
870     *         drawable being badged.
871     * @param badgeDensity The optional desired density for the badge as per
872     *         {@link android.util.DisplayMetrics#densityDpi}. If not provided,
873     *         the density of the display is used.
874     * @return A drawable that combines the original drawable and a badge as
875     *         determined by the system.
876     */
877    public Drawable getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user,
878            Rect badgeLocation, int badgeDensity) {
879        Drawable badgeDrawable = getBadgeForUser(user, badgeDensity);
880        if (badgeDrawable == null) {
881            return badgedDrawable;
882        }
883        return getBadgedDrawable(badgedDrawable, badgeDrawable, badgeLocation, true);
884    }
885
886    /**
887     * If the target user is a managed profile of the calling user or the caller
888     * is itself a managed profile, then this returns a copy of the label with
889     * badging for accessibility services like talkback. E.g. passing in "Email"
890     * and it might return "Work Email" for Email in the work profile.
891     *
892     * @param label The label to change.
893     * @param user The target user.
894     * @return A label that combines the original label and a badge as
895     *         determined by the system.
896     */
897    public CharSequence getBadgedLabelForUser(CharSequence label, UserHandle user) {
898        UserInfo userInfo = getUserIfProfile(user.getIdentifier());
899        if (userInfo != null && userInfo.isManagedProfile()) {
900            return Resources.getSystem().getString(
901                    R.string.managed_profile_label_badge, label);
902        }
903        return label;
904    }
905
906    /**
907     * If the target user is a managed profile of the calling user or the caller
908     * is itself a managed profile, then this returns a drawable to use as a small
909     * icon to include in a view to distinguish it from the original icon.
910     *
911     * @param user The target user.
912     * @param density The optional desired density for the badge as per
913     *         {@link android.util.DisplayMetrics#densityDpi}. If not provided
914     *         the density of the current display is used.
915     * @return the drawable or null if no drawable is required.
916     * @hide
917     */
918    public Drawable getBadgeForUser(UserHandle user, int density) {
919        UserInfo userInfo = getUserIfProfile(user.getIdentifier());
920        if (userInfo != null && userInfo.isManagedProfile()) {
921            if (density <= 0) {
922                density = mContext.getResources().getDisplayMetrics().densityDpi;
923            }
924            return Resources.getSystem().getDrawableForDensity(
925                    com.android.internal.R.drawable.ic_corp_badge, density);
926        }
927        return null;
928    }
929
930    private int getBadgeResIdForUser(int userHandle) {
931        // Return the framework-provided badge.
932        UserInfo userInfo = getUserIfProfile(userHandle);
933        if (userInfo != null && userInfo.isManagedProfile()) {
934            return com.android.internal.R.drawable.ic_corp_icon_badge;
935        }
936        return 0;
937    }
938
939    /**
940     * @return UserInfo for userHandle if it exists and is a profile of the current
941     *         user or null.
942     */
943    private UserInfo getUserIfProfile(int userHandle) {
944        List<UserInfo> userProfiles = getProfiles(getUserHandle());
945        for (UserInfo user : userProfiles) {
946            if (user.id == userHandle) {
947                return user;
948            }
949        }
950        return null;
951    }
952
953    private Drawable getBadgedDrawable(Drawable badgedDrawable, Drawable badgeDrawable,
954            Rect badgeLocation, boolean tryBadgeInPlace) {
955        final int badgedWidth = badgedDrawable.getIntrinsicWidth();
956        final int badgedHeight = badgedDrawable.getIntrinsicHeight();
957        final boolean canBadgeInPlace = tryBadgeInPlace
958                && (badgedDrawable instanceof BitmapDrawable)
959                && ((BitmapDrawable) badgedDrawable).getBitmap().isMutable();
960
961        final Bitmap bitmap;
962        if (canBadgeInPlace) {
963            bitmap = ((BitmapDrawable) badgedDrawable).getBitmap();
964        } else {
965            bitmap = Bitmap.createBitmap(badgedWidth, badgedHeight, Config.ARGB_8888);
966        }
967        Canvas canvas = new Canvas(bitmap);
968
969        if (!canBadgeInPlace) {
970            badgedDrawable.setBounds(0, 0, badgedWidth, badgedHeight);
971            badgedDrawable.draw(canvas);
972        }
973
974        if (badgeLocation != null) {
975            if (badgeLocation.left < 0 || badgeLocation.top < 0
976                    || badgeLocation.width() > badgedWidth || badgeLocation.height() > badgedHeight) {
977                throw new IllegalArgumentException("Badge location " + badgeLocation
978                        + " not in badged drawable bounds "
979                        + new Rect(0, 0, badgedWidth, badgedHeight));
980            }
981            badgeDrawable.setBounds(0, 0, badgeLocation.width(), badgeLocation.height());
982
983            canvas.save();
984            canvas.translate(badgeLocation.left, badgeLocation.top);
985            badgeDrawable.draw(canvas);
986            canvas.restore();
987        } else {
988            badgeDrawable.setBounds(0, 0, badgedWidth, badgedHeight);
989            badgeDrawable.draw(canvas);
990        }
991
992        if (!canBadgeInPlace) {
993            BitmapDrawable mergedDrawable = new BitmapDrawable(mContext.getResources(), bitmap);
994
995            if (badgedDrawable instanceof BitmapDrawable) {
996                BitmapDrawable bitmapDrawable = (BitmapDrawable) badgedDrawable;
997                mergedDrawable.setTargetDensity(bitmapDrawable.getBitmap().getDensity());
998            }
999
1000            return mergedDrawable;
1001        }
1002
1003        return badgedDrawable;
1004    }
1005
1006    /**
1007     * Returns information for all users on this device. Requires
1008     * {@link android.Manifest.permission#MANAGE_USERS} permission.
1009     *
1010     * @param excludeDying specify if the list should exclude users being
1011     *            removed.
1012     * @return the list of users that were created.
1013     * @hide
1014     */
1015    public List<UserInfo> getUsers(boolean excludeDying) {
1016        try {
1017            return mService.getUsers(excludeDying);
1018        } catch (RemoteException re) {
1019            Log.w(TAG, "Could not get user list", re);
1020            return null;
1021        }
1022    }
1023
1024    /**
1025     * Removes a user and all associated data.
1026     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1027     * @param userHandle the integer handle of the user, where 0 is the primary user.
1028     * @hide
1029     */
1030    public boolean removeUser(int userHandle) {
1031        try {
1032            return mService.removeUser(userHandle);
1033        } catch (RemoteException re) {
1034            Log.w(TAG, "Could not remove user ", re);
1035            return false;
1036        }
1037    }
1038
1039    /**
1040     * Updates the user's name.
1041     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1042     *
1043     * @param userHandle the user's integer handle
1044     * @param name the new name for the user
1045     * @hide
1046     */
1047    public void setUserName(int userHandle, String name) {
1048        try {
1049            mService.setUserName(userHandle, name);
1050        } catch (RemoteException re) {
1051            Log.w(TAG, "Could not set the user name ", re);
1052        }
1053    }
1054
1055    /**
1056     * Sets the user's photo.
1057     * @param userHandle the user for whom to change the photo.
1058     * @param icon the bitmap to set as the photo.
1059     * @hide
1060     */
1061    public void setUserIcon(int userHandle, Bitmap icon) {
1062        try {
1063            mService.setUserIcon(userHandle, icon);
1064        } catch (RemoteException re) {
1065            Log.w(TAG, "Could not set the user icon ", re);
1066        }
1067    }
1068
1069    /**
1070     * Returns a file descriptor for the user's photo. PNG data can be read from this file.
1071     * @param userHandle the user whose photo we want to read.
1072     * @return a {@link Bitmap} of the user's photo, or null if there's no photo.
1073     * @hide
1074     */
1075    public Bitmap getUserIcon(int userHandle) {
1076        try {
1077            return mService.getUserIcon(userHandle);
1078        } catch (RemoteException re) {
1079            Log.w(TAG, "Could not get the user icon ", re);
1080            return null;
1081        }
1082    }
1083
1084    /**
1085     * Returns the maximum number of users that can be created on this device. A return value
1086     * of 1 means that it is a single user device.
1087     * @hide
1088     * @return a value greater than or equal to 1
1089     */
1090    public static int getMaxSupportedUsers() {
1091        // Don't allow multiple users on certain builds
1092        if (android.os.Build.ID.startsWith("JVP")) return 1;
1093        // Svelte devices don't get multi-user.
1094        if (ActivityManager.isLowRamDeviceStatic()) return 1;
1095        return SystemProperties.getInt("fw.max_users",
1096                Resources.getSystem().getInteger(R.integer.config_multiuserMaximumUsers));
1097    }
1098
1099    /**
1100     * Returns true if the user switcher should be shown, this will be if there
1101     * are multiple users that aren't managed profiles.
1102     * @hide
1103     * @return true if user switcher should be shown.
1104     */
1105    public boolean isUserSwitcherEnabled() {
1106        List<UserInfo> users = getUsers(true);
1107        if (users == null) {
1108           return false;
1109        }
1110        int switchableUserCount = 0;
1111        for (UserInfo user : users) {
1112            if (user.supportsSwitchTo()) {
1113                ++switchableUserCount;
1114            }
1115        }
1116        final boolean guestEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1117                Settings.Global.GUEST_USER_ENABLED, 0) == 1;
1118        return switchableUserCount > 1 || guestEnabled;
1119    }
1120
1121    /**
1122     * Returns a serial number on this device for a given userHandle. User handles can be recycled
1123     * when deleting and creating users, but serial numbers are not reused until the device is wiped.
1124     * @param userHandle
1125     * @return a serial number associated with that user, or -1 if the userHandle is not valid.
1126     * @hide
1127     */
1128    public int getUserSerialNumber(int userHandle) {
1129        try {
1130            return mService.getUserSerialNumber(userHandle);
1131        } catch (RemoteException re) {
1132            Log.w(TAG, "Could not get serial number for user " + userHandle);
1133        }
1134        return -1;
1135    }
1136
1137    /**
1138     * Returns a userHandle on this device for a given user serial number. User handles can be
1139     * recycled when deleting and creating users, but serial numbers are not reused until the device
1140     * is wiped.
1141     * @param userSerialNumber
1142     * @return the userHandle associated with that user serial number, or -1 if the serial number
1143     * is not valid.
1144     * @hide
1145     */
1146    public int getUserHandle(int userSerialNumber) {
1147        try {
1148            return mService.getUserHandle(userSerialNumber);
1149        } catch (RemoteException re) {
1150            Log.w(TAG, "Could not get userHandle for user " + userSerialNumber);
1151        }
1152        return -1;
1153    }
1154
1155    /**
1156     * Returns a Bundle containing any saved application restrictions for this user, for the
1157     * given package name. Only an application with this package name can call this method.
1158     * @param packageName the package name of the calling application
1159     * @return a Bundle with the restrictions as key/value pairs, or null if there are no
1160     * saved restrictions. The values can be of type Boolean, String or String[], depending
1161     * on the restriction type, as defined by the application.
1162     */
1163    public Bundle getApplicationRestrictions(String packageName) {
1164        try {
1165            return mService.getApplicationRestrictions(packageName);
1166        } catch (RemoteException re) {
1167            Log.w(TAG, "Could not get application restrictions for package " + packageName);
1168        }
1169        return null;
1170    }
1171
1172    /**
1173     * @hide
1174     */
1175    public Bundle getApplicationRestrictions(String packageName, UserHandle user) {
1176        try {
1177            return mService.getApplicationRestrictionsForUser(packageName, user.getIdentifier());
1178        } catch (RemoteException re) {
1179            Log.w(TAG, "Could not get application restrictions for user " + user.getIdentifier());
1180        }
1181        return null;
1182    }
1183
1184    /**
1185     * @hide
1186     */
1187    public void setApplicationRestrictions(String packageName, Bundle restrictions,
1188            UserHandle user) {
1189        try {
1190            mService.setApplicationRestrictions(packageName, restrictions, user.getIdentifier());
1191        } catch (RemoteException re) {
1192            Log.w(TAG, "Could not set application restrictions for user " + user.getIdentifier());
1193        }
1194    }
1195
1196    /**
1197     * Sets a new challenge PIN for restrictions. This is only for use by pre-installed
1198     * apps and requires the MANAGE_USERS permission.
1199     * @param newPin the PIN to use for challenge dialogs.
1200     * @return Returns true if the challenge PIN was set successfully.
1201     */
1202    public boolean setRestrictionsChallenge(String newPin) {
1203        try {
1204            return mService.setRestrictionsChallenge(newPin);
1205        } catch (RemoteException re) {
1206            Log.w(TAG, "Could not change restrictions pin");
1207        }
1208        return false;
1209    }
1210
1211    /**
1212     * @hide
1213     * @param pin The PIN to verify, or null to get the number of milliseconds to wait for before
1214     * allowing the user to enter the PIN.
1215     * @return Returns a positive number (including zero) for how many milliseconds before
1216     * you can accept another PIN, when the input is null or the input doesn't match the saved PIN.
1217     * Returns {@link #PIN_VERIFICATION_SUCCESS} if the input matches the saved PIN. Returns
1218     * {@link #PIN_VERIFICATION_FAILED_NOT_SET} if there is no PIN set.
1219     */
1220    public int checkRestrictionsChallenge(String pin) {
1221        try {
1222            return mService.checkRestrictionsChallenge(pin);
1223        } catch (RemoteException re) {
1224            Log.w(TAG, "Could not check restrictions pin");
1225        }
1226        return PIN_VERIFICATION_FAILED_INCORRECT;
1227    }
1228
1229    /**
1230     * @hide
1231     * Checks whether the user has restrictions that are PIN-protected. An application that
1232     * participates in restrictions can check if the owner has requested a PIN challenge for
1233     * any restricted operations. If there is a PIN in effect, the application should launch
1234     * the PIN challenge activity {@link android.content.Intent#ACTION_RESTRICTIONS_CHALLENGE}.
1235     * @see android.content.Intent#ACTION_RESTRICTIONS_CHALLENGE
1236     * @return whether a restrictions PIN is in effect.
1237     */
1238    public boolean hasRestrictionsChallenge() {
1239        try {
1240            return mService.hasRestrictionsChallenge();
1241        } catch (RemoteException re) {
1242            Log.w(TAG, "Could not change restrictions pin");
1243        }
1244        return false;
1245    }
1246
1247    /** @hide */
1248    public void removeRestrictions() {
1249        try {
1250            mService.removeRestrictions();
1251        } catch (RemoteException re) {
1252            Log.w(TAG, "Could not change restrictions pin");
1253        }
1254    }
1255
1256    /**
1257     * @hide
1258     * Set restrictions that should apply to any future guest user that's created.
1259     */
1260    public void setDefaultGuestRestrictions(Bundle restrictions) {
1261        try {
1262            mService.setDefaultGuestRestrictions(restrictions);
1263        } catch (RemoteException re) {
1264            Log.w(TAG, "Could not set guest restrictions");
1265        }
1266    }
1267
1268    /**
1269     * @hide
1270     * Gets the default guest restrictions.
1271     */
1272    public Bundle getDefaultGuestRestrictions() {
1273        try {
1274            return mService.getDefaultGuestRestrictions();
1275        } catch (RemoteException re) {
1276            Log.w(TAG, "Could not set guest restrictions");
1277        }
1278        return new Bundle();
1279    }
1280}
1281