UserManager.java revision 29ce85bab94a2d0dc98d9075ae86c8a282367117
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.os;
17
18import android.annotation.SystemApi;
19import android.app.ActivityManager;
20import android.app.ActivityManagerNative;
21import android.content.Context;
22import android.content.pm.UserInfo;
23import android.content.res.Resources;
24import android.graphics.Bitmap;
25import android.graphics.Canvas;
26import android.graphics.Bitmap.Config;
27import android.graphics.Rect;
28import android.graphics.drawable.BitmapDrawable;
29import android.graphics.drawable.Drawable;
30import android.provider.Settings;
31import android.util.Log;
32import android.view.WindowManager.LayoutParams;
33
34import com.android.internal.R;
35
36import java.util.ArrayList;
37import java.util.List;
38
39/**
40 * Manages users and user details on a multi-user system.
41 */
42public class UserManager {
43
44    private static String TAG = "UserManager";
45    private final IUserManager mService;
46    private final Context mContext;
47
48    /**
49     * Key for user restrictions. Specifies if a user is disallowed from adding and removing
50     * accounts.
51     * The default value is <code>false</code>.
52     * <p/>
53     * Type: Boolean
54     * @see #setUserRestrictions(Bundle)
55     * @see #getUserRestrictions()
56     */
57    public static final String DISALLOW_MODIFY_ACCOUNTS = "no_modify_accounts";
58
59    /**
60     * Key for user restrictions. Specifies if a user is disallowed from changing Wi-Fi
61     * access points. 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. This can only be set by device owners. 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. The default value is <code>false</code>.
143     * <p/>
144     * Type: Boolean
145     * @see #setUserRestrictions(Bundle)
146     * @see #getUserRestrictions()
147     */
148    public static final String DISALLOW_REMOVE_USER = "no_remove_user";
149
150    /**
151     * Key for user restrictions. Specifies if a user is disallowed from enabling or
152     * accessing debugging features. The default value is <code>false</code>.
153     * <p/>
154     * Type: Boolean
155     * @see #setUserRestrictions(Bundle)
156     * @see #getUserRestrictions()
157     */
158    public static final String DISALLOW_DEBUGGING_FEATURES = "no_debugging_features";
159
160    /**
161     * Key for user restrictions. Specifies if a user is disallowed from configuring VPN.
162     * The default value is <code>false</code>.
163     * <p/>
164     * Type: Boolean
165     * @see #setUserRestrictions(Bundle)
166     * @see #getUserRestrictions()
167     */
168    public static final String DISALLOW_CONFIG_VPN = "no_config_vpn";
169
170    /**
171     * Key for user restrictions. Specifies if a user is disallowed from configuring Tethering
172     * & portable hotspots. This can only be set by device owners. The default value is
173     * <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. This can only be set by device owners. The default value is
184     * <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. This can only be set by device owners. 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. This can only be set by device owners. 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. This can only be set by device owners. 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. This can only be set by device owners. The default value is
253     * <code>false</code>.
254     * <p/>
255     * Type: Boolean
256     * @see #setUserRestrictions(Bundle)
257     * @see #getUserRestrictions()
258     */
259    public static final String DISALLOW_MOUNT_PHYSICAL_MEDIA = "no_physical_media";
260
261    /**
262     * Key for user restrictions. Specifies if a user is disallowed from adjusting microphone
263     * volume. If set, the microphone will be muted. This can only be set by device owners.
264     * The default value is <code>false</code>.
265     * <p/>
266     * Type: Boolean
267     * @see #setUserRestrictions(Bundle)
268     * @see #getUserRestrictions()
269     */
270    public static final String DISALLOW_UNMUTE_MICROPHONE = "no_unmute_microphone";
271
272    /**
273     * Key for user restrictions. Specifies if a user is disallowed from adjusting the master
274     * volume. If set, the master volume will be muted. This can only be set by device owners.
275     * The default value is <code>false</code>.
276     * <p/>
277     * Type: Boolean
278     * @see #setUserRestrictions(Bundle)
279     * @see #getUserRestrictions()
280     */
281    public static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume";
282
283    /**
284     * Key for user restrictions. Specifies that the user is not allowed to make outgoing
285     * phone calls. Emergency calls are still permitted.
286     * The default value is <code>false</code>.
287     * <p/>
288     * Type: Boolean
289     * @see #setUserRestrictions(Bundle)
290     * @see #getUserRestrictions()
291     */
292    public static final String DISALLOW_OUTGOING_CALLS = "no_outgoing_calls";
293
294    /**
295     * Key for user restrictions. Specifies that the user is not allowed to send or receive
296     * SMS messages. This can only be set by device owners. 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>This can only be set by device owners. 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     * Checks if the calling app is running in a managed profile.
429     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
430     *
431     * @return whether the caller is in a managed profile.
432     * @hide
433     */
434    @SystemApi
435    public boolean isManagedProfile() {
436        UserInfo user = getUserInfo(UserHandle.myUserId());
437        return user != null ? user.isManagedProfile() : false;
438    }
439
440    /**
441     * Return whether the given user is actively running.  This means that
442     * the user is in the "started" state, not "stopped" -- it is currently
443     * allowed to run code through scheduled alarms, receiving broadcasts,
444     * etc.  A started user may be either the current foreground user or a
445     * background user; the result here does not distinguish between the two.
446     * @param user The user to retrieve the running state for.
447     */
448    public boolean isUserRunning(UserHandle user) {
449        try {
450            return ActivityManagerNative.getDefault().isUserRunning(
451                    user.getIdentifier(), false);
452        } catch (RemoteException e) {
453            return false;
454        }
455    }
456
457    /**
458     * Return whether the given user is actively running <em>or</em> stopping.
459     * This is like {@link #isUserRunning(UserHandle)}, but will also return
460     * true if the user had been running but is in the process of being stopped
461     * (but is not yet fully stopped, and still running some code).
462     * @param user The user to retrieve the running state for.
463     */
464    public boolean isUserRunningOrStopping(UserHandle user) {
465        try {
466            return ActivityManagerNative.getDefault().isUserRunning(
467                    user.getIdentifier(), true);
468        } catch (RemoteException e) {
469            return false;
470        }
471    }
472
473    /**
474     * Returns the UserInfo object describing a specific user.
475     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
476     * @param userHandle the user handle of the user whose information is being requested.
477     * @return the UserInfo object for a specific user.
478     * @hide
479     */
480    public UserInfo getUserInfo(int userHandle) {
481        try {
482            return mService.getUserInfo(userHandle);
483        } catch (RemoteException re) {
484            Log.w(TAG, "Could not get user info", re);
485            return null;
486        }
487    }
488
489    /**
490     * Returns the user-wide restrictions imposed on this user.
491     * @return a Bundle containing all the restrictions.
492     */
493    public Bundle getUserRestrictions() {
494        return getUserRestrictions(Process.myUserHandle());
495    }
496
497    /**
498     * Returns the user-wide restrictions imposed on the user specified by <code>userHandle</code>.
499     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
500     * @return a Bundle containing all the restrictions.
501     */
502    public Bundle getUserRestrictions(UserHandle userHandle) {
503        try {
504            return mService.getUserRestrictions(userHandle.getIdentifier());
505        } catch (RemoteException re) {
506            Log.w(TAG, "Could not get user restrictions", re);
507            return Bundle.EMPTY;
508        }
509    }
510
511    /**
512     * Sets all the user-wide restrictions for this user.
513     * Requires the MANAGE_USERS permission.
514     * @param restrictions the Bundle containing all the restrictions.
515     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
516     * android.content.ComponentName, String)} or
517     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
518     * android.content.ComponentName, String)} instead.
519     */
520    @Deprecated
521    public void setUserRestrictions(Bundle restrictions) {
522        setUserRestrictions(restrictions, Process.myUserHandle());
523    }
524
525    /**
526     * Sets all the user-wide restrictions for the specified user.
527     * Requires the MANAGE_USERS permission.
528     * @param restrictions the Bundle containing all the restrictions.
529     * @param userHandle the UserHandle of the user for whom to set the restrictions.
530     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
531     * android.content.ComponentName, String)} or
532     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
533     * android.content.ComponentName, String)} instead.
534     */
535    @Deprecated
536    public void setUserRestrictions(Bundle restrictions, UserHandle userHandle) {
537        try {
538            mService.setUserRestrictions(restrictions, userHandle.getIdentifier());
539        } catch (RemoteException re) {
540            Log.w(TAG, "Could not set user restrictions", re);
541        }
542    }
543
544    /**
545     * Sets the value of a specific restriction.
546     * Requires the MANAGE_USERS permission.
547     * @param key the key of the restriction
548     * @param value the value for the restriction
549     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
550     * android.content.ComponentName, String)} or
551     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
552     * android.content.ComponentName, String)} instead.
553     */
554    @Deprecated
555    public void setUserRestriction(String key, boolean value) {
556        Bundle bundle = getUserRestrictions();
557        bundle.putBoolean(key, value);
558        setUserRestrictions(bundle);
559    }
560
561    /**
562     * @hide
563     * Sets the value of a specific restriction on a specific user.
564     * Requires the MANAGE_USERS permission.
565     * @param key the key of the restriction
566     * @param value the value for the restriction
567     * @param userHandle the user whose restriction is to be changed.
568     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
569     * android.content.ComponentName, String)} or
570     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
571     * android.content.ComponentName, String)} instead.
572     */
573    @Deprecated
574    public void setUserRestriction(String key, boolean value, UserHandle userHandle) {
575        Bundle bundle = getUserRestrictions(userHandle);
576        bundle.putBoolean(key, value);
577        setUserRestrictions(bundle, userHandle);
578    }
579
580    /**
581     * Returns whether the current user has been disallowed from performing certain actions
582     * or setting certain settings.
583     *
584     * @param restrictionKey The string key representing the restriction.
585     * @return {@code true} if the current user has the given restriction, {@code false} otherwise.
586     */
587    public boolean hasUserRestriction(String restrictionKey) {
588        return hasUserRestriction(restrictionKey, Process.myUserHandle());
589    }
590
591    /**
592     * @hide
593     * Returns whether the given user has been disallowed from performing certain actions
594     * or setting certain settings.
595     * @param restrictionKey the string key representing the restriction
596     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
597     */
598    public boolean hasUserRestriction(String restrictionKey, UserHandle userHandle) {
599        return getUserRestrictions(userHandle).getBoolean(restrictionKey, false);
600    }
601
602    /**
603     * Return the serial number for a user.  This is a device-unique
604     * number assigned to that user; if the user is deleted and then a new
605     * user created, the new users will not be given the same serial number.
606     * @param user The user whose serial number is to be retrieved.
607     * @return The serial number of the given user; returns -1 if the
608     * given UserHandle does not exist.
609     * @see #getUserForSerialNumber(long)
610     */
611    public long getSerialNumberForUser(UserHandle user) {
612        return getUserSerialNumber(user.getIdentifier());
613    }
614
615    /**
616     * Return the user associated with a serial number previously
617     * returned by {@link #getSerialNumberForUser(UserHandle)}.
618     * @param serialNumber The serial number of the user that is being
619     * retrieved.
620     * @return Return the user associated with the serial number, or null
621     * if there is not one.
622     * @see #getSerialNumberForUser(UserHandle)
623     */
624    public UserHandle getUserForSerialNumber(long serialNumber) {
625        int ident = getUserHandle((int)serialNumber);
626        return ident >= 0 ? new UserHandle(ident) : null;
627    }
628
629    /**
630     * Creates a user with the specified name and options.
631     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
632     *
633     * @param name the user's name
634     * @param flags flags that identify the type of user and other properties.
635     * @see UserInfo
636     *
637     * @return the UserInfo object for the created user, or null if the user could not be created.
638     * @hide
639     */
640    public UserInfo createUser(String name, int flags) {
641        try {
642            return mService.createUser(name, flags);
643        } catch (RemoteException re) {
644            Log.w(TAG, "Could not create a user", re);
645            return null;
646        }
647    }
648
649    /**
650     * Creates a guest user and configures it.
651     * @param context an application context
652     * @param name the name to set for the user
653     * @hide
654     */
655    public UserInfo createGuest(Context context, String name) {
656        UserInfo guest = createUser(name, UserInfo.FLAG_GUEST);
657        if (guest != null) {
658            Settings.Secure.putStringForUser(context.getContentResolver(),
659                    Settings.Secure.SKIP_FIRST_USE_HINTS, "1", guest.id);
660            try {
661                Bundle guestRestrictions = mService.getDefaultGuestRestrictions();
662                guestRestrictions.putBoolean(DISALLOW_SMS, true);
663                guestRestrictions.putBoolean(DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
664                mService.setUserRestrictions(guestRestrictions, guest.id);
665            } catch (RemoteException re) {
666                Log.w(TAG, "Could not update guest restrictions");
667            }
668        }
669        return guest;
670    }
671
672    /**
673     * Creates a user with the specified name and options as a profile of another user.
674     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
675     *
676     * @param name the user's name
677     * @param flags flags that identify the type of user and other properties.
678     * @see UserInfo
679     * @param userHandle new user will be a profile of this use.
680     *
681     * @return the UserInfo object for the created user, or null if the user could not be created.
682     * @hide
683     */
684    public UserInfo createProfileForUser(String name, int flags, int userHandle) {
685        try {
686            return mService.createProfileForUser(name, flags, userHandle);
687        } catch (RemoteException re) {
688            Log.w(TAG, "Could not create a user", re);
689            return null;
690        }
691    }
692
693    /**
694     * @hide
695     * Marks the guest user for deletion to allow a new guest to be created before deleting
696     * the current user who is a guest.
697     * @param userHandle
698     * @return
699     */
700    public boolean markGuestForDeletion(int userHandle) {
701        try {
702            return mService.markGuestForDeletion(userHandle);
703        } catch (RemoteException re) {
704            Log.w(TAG, "Could not mark guest for deletion", re);
705            return false;
706        }
707    }
708
709    /**
710     * Sets the user as enabled, if such an user exists.
711     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
712     * Note that the default is true, it's only that managed profiles might not be enabled.
713     *
714     * @param userHandle the id of the profile to enable
715     * @hide
716     */
717    public void setUserEnabled(int userHandle) {
718        try {
719            mService.setUserEnabled(userHandle);
720        } catch (RemoteException e) {
721            Log.w(TAG, "Could not enable the profile", e);
722        }
723    }
724
725    /**
726     * Return the number of users currently created on the device.
727     */
728    public int getUserCount() {
729        List<UserInfo> users = getUsers();
730        return users != null ? users.size() : 1;
731    }
732
733    /**
734     * Returns information for all users on this device.
735     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
736     * @return the list of users that were created.
737     * @hide
738     */
739    public List<UserInfo> getUsers() {
740        try {
741            return mService.getUsers(false);
742        } catch (RemoteException re) {
743            Log.w(TAG, "Could not get user list", re);
744            return null;
745        }
746    }
747
748    /**
749     * Checks whether it's possible to add more users. Caller must hold the MANAGE_USERS
750     * permission.
751     *
752     * @return true if more users can be added, false if limit has been reached.
753     * @hide
754     */
755    public boolean canAddMoreUsers() {
756        final List<UserInfo> users = getUsers(true);
757        final int totalUserCount = users.size();
758        int aliveUserCount = 0;
759        for (int i = 0; i < totalUserCount; i++) {
760            UserInfo user = users.get(i);
761            if (!user.isGuest()) {
762                aliveUserCount++;
763            }
764        }
765        return aliveUserCount < getMaxSupportedUsers();
766    }
767
768    /**
769     * Returns list of the profiles of userHandle including
770     * userHandle itself.
771     * Note that this returns both enabled and not enabled profiles. See
772     * {@link #getUserProfiles()} if you need only the enabled ones.
773     *
774     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
775     * @param userHandle profiles of this user will be returned.
776     * @return the list of profiles.
777     * @hide
778     */
779    public List<UserInfo> getProfiles(int userHandle) {
780        try {
781            return mService.getProfiles(userHandle, false /* enabledOnly */);
782        } catch (RemoteException re) {
783            Log.w(TAG, "Could not get user list", re);
784            return null;
785        }
786    }
787
788    /**
789     * Returns a list of UserHandles for profiles associated with the user that the calling process
790     * is running on, including the user itself.
791     *
792     * @return A non-empty list of UserHandles associated with the calling user.
793     */
794    public List<UserHandle> getUserProfiles() {
795        ArrayList<UserHandle> profiles = new ArrayList<UserHandle>();
796        List<UserInfo> users = new ArrayList<UserInfo>();
797        try {
798            users = mService.getProfiles(UserHandle.myUserId(), true /* enabledOnly */);
799        } catch (RemoteException re) {
800            Log.w(TAG, "Could not get user list", re);
801            return null;
802        }
803        for (UserInfo info : users) {
804            UserHandle userHandle = new UserHandle(info.id);
805            profiles.add(userHandle);
806        }
807        return profiles;
808    }
809
810    /**
811     * Returns the parent of the profile which this method is called from
812     * or null if called from a user that is not a profile.
813     *
814     * @hide
815     */
816    public UserInfo getProfileParent(int userHandle) {
817        try {
818            return mService.getProfileParent(userHandle);
819        } catch (RemoteException re) {
820            Log.w(TAG, "Could not get profile parent", re);
821            return null;
822        }
823    }
824
825    /**
826     * If the target user is a managed profile of the calling user or the caller
827     * is itself a managed profile, then this returns a badged copy of the given
828     * icon to be able to distinguish it from the original icon. For badging an
829     * arbitrary drawable use {@link #getBadgedDrawableForUser(
830     * android.graphics.drawable.Drawable, UserHandle, android.graphics.Rect, int)}.
831     * <p>
832     * If the original drawable is a BitmapDrawable and the backing bitmap is
833     * mutable as per {@link android.graphics.Bitmap#isMutable()}, the bading
834     * is performed in place and the original drawable is returned.
835     * </p>
836     *
837     * @param icon The icon to badge.
838     * @param user The target user.
839     * @return A drawable that combines the original icon and a badge as
840     *         determined by the system.
841     */
842    public Drawable getBadgedIconForUser(Drawable icon, UserHandle user) {
843        final int badgeResId = getBadgeResIdForUser(user.getIdentifier());
844        if (badgeResId == 0) {
845            return icon;
846        }
847        Drawable badgeIcon = mContext.getPackageManager()
848                .getDrawable("system", badgeResId, null);
849        return getBadgedDrawable(icon, badgeIcon, null, true);
850    }
851
852    /**
853     * If the target user is a managed profile of the calling user or the caller
854     * is itself a managed profile, then this returns a badged copy of the given
855     * icon to be able to distinguish it from the original icon.
856     * <p>
857     * If the original drawable is not a BitmapDrawable, then the original
858     * drawable is returned.
859     * </p>
860     *
861     * @param icon The icon to badge.
862     * @param user The target user.
863     * @return A drawable that combines the original icon and a badge as
864     *         determined by the system.
865     *
866     * @deprecation Use {@link #getBadgedIconForUser(
867     *     android.graphics.drawable.Drawable, UserHandle)}
868     *
869     * @hide
870     */
871    @Deprecated
872    public Drawable getBadgedDrawableForUser(Drawable icon, UserHandle user) {
873        int badgeResId = getBadgeResIdForUser(user.getIdentifier());
874        if (badgeResId == 0) {
875            return icon;
876        } else {
877            Drawable badgeIcon = mContext.getPackageManager()
878                    .getDrawable("system", badgeResId, null);
879            return getBadgedDrawable(icon, badgeIcon, null, false);
880        }
881    }
882
883    /**
884     * If the target user is a managed profile of the calling user or the caller
885     * is itself a managed profile, then this returns a badged copy of the given
886     * drawable allowing the user to distinguish it from the original drawable.
887     * The caller can specify the location in the bounds of the drawable to be
888     * badged where the badge should be applied as well as the density of the
889     * badge to be used.
890     * <p>
891     * If the original drawable is a BitmapDrawable and the backing bitmap is
892     * mutable as per {@link android.graphics.Bitmap#isMutable()}, the bading
893     * is performed in place and the original drawable is returned.
894     * </p>
895     *
896     * @param badgedDrawable The drawable to badge.
897     * @param user The target user.
898     * @param badgeLocation Where in the bounds of the badged drawable to place
899     *         the badge. If not provided, the badge is applied on top of the entire
900     *         drawable being badged.
901     * @param badgeDensity The optional desired density for the badge as per
902     *         {@link android.util.DisplayMetrics#densityDpi}. If not provided,
903     *         the density of the display is used.
904     * @return A drawable that combines the original drawable and a badge as
905     *         determined by the system.
906     */
907    public Drawable getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user,
908            Rect badgeLocation, int badgeDensity) {
909        Drawable badgeDrawable = getBadgeForUser(user, badgeDensity);
910        if (badgeDrawable == null) {
911            return badgedDrawable;
912        }
913        return getBadgedDrawable(badgedDrawable, badgeDrawable, badgeLocation, true);
914    }
915
916    /**
917     * If the target user is a managed profile of the calling user or the caller
918     * is itself a managed profile, then this returns a copy of the label with
919     * badging for accessibility services like talkback. E.g. passing in "Email"
920     * and it might return "Work Email" for Email in the work profile.
921     *
922     * @param label The label to change.
923     * @param user The target user.
924     * @return A label that combines the original label and a badge as
925     *         determined by the system.
926     */
927    public CharSequence getBadgedLabelForUser(CharSequence label, UserHandle user) {
928        UserInfo userInfo = getUserIfProfile(user.getIdentifier());
929        if (userInfo != null && userInfo.isManagedProfile()) {
930            return Resources.getSystem().getString(
931                    R.string.managed_profile_label_badge, label);
932        }
933        return label;
934    }
935
936    /**
937     * If the target user is a managed profile of the calling user or the caller
938     * is itself a managed profile, then this returns a drawable to use as a small
939     * icon to include in a view to distinguish it from the original icon.
940     *
941     * @param user The target user.
942     * @param density The optional desired density for the badge as per
943     *         {@link android.util.DisplayMetrics#densityDpi}. If not provided
944     *         the density of the current display is used.
945     * @return the drawable or null if no drawable is required.
946     * @hide
947     */
948    public Drawable getBadgeForUser(UserHandle user, int density) {
949        UserInfo userInfo = getUserIfProfile(user.getIdentifier());
950        if (userInfo != null && userInfo.isManagedProfile()) {
951            if (density <= 0) {
952                density = mContext.getResources().getDisplayMetrics().densityDpi;
953            }
954            return Resources.getSystem().getDrawableForDensity(
955                    com.android.internal.R.drawable.ic_corp_badge, density);
956        }
957        return null;
958    }
959
960    private int getBadgeResIdForUser(int userHandle) {
961        // Return the framework-provided badge.
962        UserInfo userInfo = getUserIfProfile(userHandle);
963        if (userInfo != null && userInfo.isManagedProfile()) {
964            return com.android.internal.R.drawable.ic_corp_icon_badge;
965        }
966        return 0;
967    }
968
969    /**
970     * @return UserInfo for userHandle if it exists and is a profile of the current
971     *         user or null.
972     */
973    private UserInfo getUserIfProfile(int userHandle) {
974        List<UserInfo> userProfiles = getProfiles(getUserHandle());
975        for (UserInfo user : userProfiles) {
976            if (user.id == userHandle) {
977                return user;
978            }
979        }
980        return null;
981    }
982
983    private Drawable getBadgedDrawable(Drawable badgedDrawable, Drawable badgeDrawable,
984            Rect badgeLocation, boolean tryBadgeInPlace) {
985        final int badgedWidth = badgedDrawable.getIntrinsicWidth();
986        final int badgedHeight = badgedDrawable.getIntrinsicHeight();
987        final boolean canBadgeInPlace = tryBadgeInPlace
988                && (badgedDrawable instanceof BitmapDrawable)
989                && ((BitmapDrawable) badgedDrawable).getBitmap().isMutable();
990
991        final Bitmap bitmap;
992        if (canBadgeInPlace) {
993            bitmap = ((BitmapDrawable) badgedDrawable).getBitmap();
994        } else {
995            bitmap = Bitmap.createBitmap(badgedWidth, badgedHeight, Config.ARGB_8888);
996        }
997        Canvas canvas = new Canvas(bitmap);
998
999        if (!canBadgeInPlace) {
1000            badgedDrawable.setBounds(0, 0, badgedWidth, badgedHeight);
1001            badgedDrawable.draw(canvas);
1002        }
1003
1004        if (badgeLocation != null) {
1005            if (badgeLocation.left < 0 || badgeLocation.top < 0
1006                    || badgeLocation.width() > badgedWidth || badgeLocation.height() > badgedHeight) {
1007                throw new IllegalArgumentException("Badge location " + badgeLocation
1008                        + " not in badged drawable bounds "
1009                        + new Rect(0, 0, badgedWidth, badgedHeight));
1010            }
1011            badgeDrawable.setBounds(0, 0, badgeLocation.width(), badgeLocation.height());
1012
1013            canvas.save();
1014            canvas.translate(badgeLocation.left, badgeLocation.top);
1015            badgeDrawable.draw(canvas);
1016            canvas.restore();
1017        } else {
1018            badgeDrawable.setBounds(0, 0, badgedWidth, badgedHeight);
1019            badgeDrawable.draw(canvas);
1020        }
1021
1022        if (!canBadgeInPlace) {
1023            BitmapDrawable mergedDrawable = new BitmapDrawable(mContext.getResources(), bitmap);
1024
1025            if (badgedDrawable instanceof BitmapDrawable) {
1026                BitmapDrawable bitmapDrawable = (BitmapDrawable) badgedDrawable;
1027                mergedDrawable.setTargetDensity(bitmapDrawable.getBitmap().getDensity());
1028            }
1029
1030            return mergedDrawable;
1031        }
1032
1033        return badgedDrawable;
1034    }
1035
1036    /**
1037     * Returns information for all users on this device. Requires
1038     * {@link android.Manifest.permission#MANAGE_USERS} permission.
1039     *
1040     * @param excludeDying specify if the list should exclude users being
1041     *            removed.
1042     * @return the list of users that were created.
1043     * @hide
1044     */
1045    public List<UserInfo> getUsers(boolean excludeDying) {
1046        try {
1047            return mService.getUsers(excludeDying);
1048        } catch (RemoteException re) {
1049            Log.w(TAG, "Could not get user list", re);
1050            return null;
1051        }
1052    }
1053
1054    /**
1055     * Removes a user and all associated data.
1056     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1057     * @param userHandle the integer handle of the user, where 0 is the primary user.
1058     * @hide
1059     */
1060    public boolean removeUser(int userHandle) {
1061        try {
1062            return mService.removeUser(userHandle);
1063        } catch (RemoteException re) {
1064            Log.w(TAG, "Could not remove user ", re);
1065            return false;
1066        }
1067    }
1068
1069    /**
1070     * Updates the user's name.
1071     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1072     *
1073     * @param userHandle the user's integer handle
1074     * @param name the new name for the user
1075     * @hide
1076     */
1077    public void setUserName(int userHandle, String name) {
1078        try {
1079            mService.setUserName(userHandle, name);
1080        } catch (RemoteException re) {
1081            Log.w(TAG, "Could not set the user name ", re);
1082        }
1083    }
1084
1085    /**
1086     * Sets the user's photo.
1087     * @param userHandle the user for whom to change the photo.
1088     * @param icon the bitmap to set as the photo.
1089     * @hide
1090     */
1091    public void setUserIcon(int userHandle, Bitmap icon) {
1092        try {
1093            mService.setUserIcon(userHandle, icon);
1094        } catch (RemoteException re) {
1095            Log.w(TAG, "Could not set the user icon ", re);
1096        }
1097    }
1098
1099    /**
1100     * Returns a file descriptor for the user's photo. PNG data can be read from this file.
1101     * @param userHandle the user whose photo we want to read.
1102     * @return a {@link Bitmap} of the user's photo, or null if there's no photo.
1103     * @hide
1104     */
1105    public Bitmap getUserIcon(int userHandle) {
1106        try {
1107            return mService.getUserIcon(userHandle);
1108        } catch (RemoteException re) {
1109            Log.w(TAG, "Could not get the user icon ", re);
1110            return null;
1111        }
1112    }
1113
1114    /**
1115     * Returns the maximum number of users that can be created on this device. A return value
1116     * of 1 means that it is a single user device.
1117     * @hide
1118     * @return a value greater than or equal to 1
1119     */
1120    public static int getMaxSupportedUsers() {
1121        // Don't allow multiple users on certain builds
1122        if (android.os.Build.ID.startsWith("JVP")) return 1;
1123        // Svelte devices don't get multi-user.
1124        if (ActivityManager.isLowRamDeviceStatic()) return 1;
1125        return SystemProperties.getInt("fw.max_users",
1126                Resources.getSystem().getInteger(R.integer.config_multiuserMaximumUsers));
1127    }
1128
1129    /**
1130     * Returns true if the user switcher should be shown, this will be if there
1131     * are multiple users that aren't managed profiles.
1132     * @hide
1133     * @return true if user switcher should be shown.
1134     */
1135    public boolean isUserSwitcherEnabled() {
1136        List<UserInfo> users = getUsers(true);
1137        if (users == null) {
1138           return false;
1139        }
1140        int switchableUserCount = 0;
1141        for (UserInfo user : users) {
1142            if (user.supportsSwitchTo()) {
1143                ++switchableUserCount;
1144            }
1145        }
1146        final boolean guestEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1147                Settings.Global.GUEST_USER_ENABLED, 0) == 1;
1148        return switchableUserCount > 1 || guestEnabled;
1149    }
1150
1151    /**
1152     * Returns a serial number on this device for a given userHandle. User handles can be recycled
1153     * when deleting and creating users, but serial numbers are not reused until the device is wiped.
1154     * @param userHandle
1155     * @return a serial number associated with that user, or -1 if the userHandle is not valid.
1156     * @hide
1157     */
1158    public int getUserSerialNumber(int userHandle) {
1159        try {
1160            return mService.getUserSerialNumber(userHandle);
1161        } catch (RemoteException re) {
1162            Log.w(TAG, "Could not get serial number for user " + userHandle);
1163        }
1164        return -1;
1165    }
1166
1167    /**
1168     * Returns a userHandle on this device for a given user serial number. User handles can be
1169     * recycled when deleting and creating users, but serial numbers are not reused until the device
1170     * is wiped.
1171     * @param userSerialNumber
1172     * @return the userHandle associated with that user serial number, or -1 if the serial number
1173     * is not valid.
1174     * @hide
1175     */
1176    public int getUserHandle(int userSerialNumber) {
1177        try {
1178            return mService.getUserHandle(userSerialNumber);
1179        } catch (RemoteException re) {
1180            Log.w(TAG, "Could not get userHandle for user " + userSerialNumber);
1181        }
1182        return -1;
1183    }
1184
1185    /**
1186     * Returns a Bundle containing any saved application restrictions for this user, for the
1187     * given package name. Only an application with this package name can call this method.
1188     * @param packageName the package name of the calling application
1189     * @return a Bundle with the restrictions as key/value pairs, or null if there are no
1190     * saved restrictions. The values can be of type Boolean, String or String[], depending
1191     * on the restriction type, as defined by the application.
1192     */
1193    public Bundle getApplicationRestrictions(String packageName) {
1194        try {
1195            return mService.getApplicationRestrictions(packageName);
1196        } catch (RemoteException re) {
1197            Log.w(TAG, "Could not get application restrictions for package " + packageName);
1198        }
1199        return null;
1200    }
1201
1202    /**
1203     * @hide
1204     */
1205    public Bundle getApplicationRestrictions(String packageName, UserHandle user) {
1206        try {
1207            return mService.getApplicationRestrictionsForUser(packageName, user.getIdentifier());
1208        } catch (RemoteException re) {
1209            Log.w(TAG, "Could not get application restrictions for user " + user.getIdentifier());
1210        }
1211        return null;
1212    }
1213
1214    /**
1215     * @hide
1216     */
1217    public void setApplicationRestrictions(String packageName, Bundle restrictions,
1218            UserHandle user) {
1219        try {
1220            mService.setApplicationRestrictions(packageName, restrictions, user.getIdentifier());
1221        } catch (RemoteException re) {
1222            Log.w(TAG, "Could not set application restrictions for user " + user.getIdentifier());
1223        }
1224    }
1225
1226    /**
1227     * Sets a new challenge PIN for restrictions. This is only for use by pre-installed
1228     * apps and requires the MANAGE_USERS permission.
1229     * @param newPin the PIN to use for challenge dialogs.
1230     * @return Returns true if the challenge PIN was set successfully.
1231     */
1232    public boolean setRestrictionsChallenge(String newPin) {
1233        try {
1234            return mService.setRestrictionsChallenge(newPin);
1235        } catch (RemoteException re) {
1236            Log.w(TAG, "Could not change restrictions pin");
1237        }
1238        return false;
1239    }
1240
1241    /**
1242     * @hide
1243     * @param pin The PIN to verify, or null to get the number of milliseconds to wait for before
1244     * allowing the user to enter the PIN.
1245     * @return Returns a positive number (including zero) for how many milliseconds before
1246     * you can accept another PIN, when the input is null or the input doesn't match the saved PIN.
1247     * Returns {@link #PIN_VERIFICATION_SUCCESS} if the input matches the saved PIN. Returns
1248     * {@link #PIN_VERIFICATION_FAILED_NOT_SET} if there is no PIN set.
1249     */
1250    public int checkRestrictionsChallenge(String pin) {
1251        try {
1252            return mService.checkRestrictionsChallenge(pin);
1253        } catch (RemoteException re) {
1254            Log.w(TAG, "Could not check restrictions pin");
1255        }
1256        return PIN_VERIFICATION_FAILED_INCORRECT;
1257    }
1258
1259    /**
1260     * @hide
1261     * Checks whether the user has restrictions that are PIN-protected. An application that
1262     * participates in restrictions can check if the owner has requested a PIN challenge for
1263     * any restricted operations. If there is a PIN in effect, the application should launch
1264     * the PIN challenge activity {@link android.content.Intent#ACTION_RESTRICTIONS_CHALLENGE}.
1265     * @see android.content.Intent#ACTION_RESTRICTIONS_CHALLENGE
1266     * @return whether a restrictions PIN is in effect.
1267     */
1268    public boolean hasRestrictionsChallenge() {
1269        try {
1270            return mService.hasRestrictionsChallenge();
1271        } catch (RemoteException re) {
1272            Log.w(TAG, "Could not change restrictions pin");
1273        }
1274        return false;
1275    }
1276
1277    /** @hide */
1278    public void removeRestrictions() {
1279        try {
1280            mService.removeRestrictions();
1281        } catch (RemoteException re) {
1282            Log.w(TAG, "Could not change restrictions pin");
1283        }
1284    }
1285
1286    /**
1287     * @hide
1288     * Set restrictions that should apply to any future guest user that's created.
1289     */
1290    public void setDefaultGuestRestrictions(Bundle restrictions) {
1291        try {
1292            mService.setDefaultGuestRestrictions(restrictions);
1293        } catch (RemoteException re) {
1294            Log.w(TAG, "Could not set guest restrictions");
1295        }
1296    }
1297
1298    /**
1299     * @hide
1300     * Gets the default guest restrictions.
1301     */
1302    public Bundle getDefaultGuestRestrictions() {
1303        try {
1304            return mService.getDefaultGuestRestrictions();
1305        } catch (RemoteException re) {
1306            Log.w(TAG, "Could not set guest restrictions");
1307        }
1308        return new Bundle();
1309    }
1310}
1311