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