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