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