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