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