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