UserManager.java revision 0e62384ccbd00e9f78851929ca88b919679ee32e
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.Manifest;
19import android.accounts.AccountManager;
20import android.annotation.Nullable;
21import android.annotation.RequiresPermission;
22import android.annotation.SystemApi;
23import android.annotation.UserIdInt;
24import android.app.ActivityManager;
25import android.app.ActivityManagerNative;
26import android.app.admin.DevicePolicyManager;
27import android.content.ComponentName;
28import android.content.Context;
29import android.content.pm.UserInfo;
30import android.content.res.Resources;
31import android.graphics.Bitmap;
32import android.graphics.BitmapFactory;
33import android.graphics.Rect;
34import android.graphics.drawable.Drawable;
35import android.os.storage.StorageManager;
36import android.provider.Settings;
37import android.util.Log;
38import android.view.WindowManager.LayoutParams;
39
40import com.android.internal.R;
41
42import java.io.IOException;
43import java.util.ArrayList;
44import java.util.List;
45
46/**
47 * Manages users and user details on a multi-user system.
48 */
49public class UserManager {
50
51    private static String TAG = "UserManager";
52    private final IUserManager mService;
53    private final Context mContext;
54
55    /**
56     * Specifies if a user is disallowed from adding and removing accounts, unless they are
57     * {@link android.accounts.AccountManager#addAccountExplicitly programmatically} added by
58     * Authenticator.
59     * The default value is <code>false</code>.
60     *
61     * <p>From {@link android.os.Build.VERSION_CODES#N} a profile or device owner app can still
62     * use {@link android.accounts.AccountManager} APIs to add or remove accounts when account
63     * management is disallowed.
64     *
65     * <p/>Key for user restrictions.
66     * <p/>Type: Boolean
67     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
68     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
69     * @see #getUserRestrictions()
70     */
71    public static final String DISALLOW_MODIFY_ACCOUNTS = "no_modify_accounts";
72
73    /**
74     * Specifies if a user is disallowed from changing Wi-Fi
75     * access points. The default value is <code>false</code>.
76     * <p/>This restriction has no effect in a managed profile.
77     *
78     * <p/>Key for user restrictions.
79     * <p/>Type: Boolean
80     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
81     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
82     * @see #getUserRestrictions()
83     */
84    public static final String DISALLOW_CONFIG_WIFI = "no_config_wifi";
85
86    /**
87     * Specifies if a user is disallowed from installing applications.
88     * The default value is <code>false</code>.
89     *
90     * <p/>Key for user restrictions.
91     * <p/>Type: Boolean
92     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
93     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
94     * @see #getUserRestrictions()
95     */
96    public static final String DISALLOW_INSTALL_APPS = "no_install_apps";
97
98    /**
99     * Specifies if a user is disallowed from uninstalling applications.
100     * The default value is <code>false</code>.
101     *
102     * <p/>Key for user restrictions.
103     * <p/>Type: Boolean
104     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
105     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
106     * @see #getUserRestrictions()
107     */
108    public static final String DISALLOW_UNINSTALL_APPS = "no_uninstall_apps";
109
110    /**
111     * Specifies if a user is disallowed from turning on location sharing.
112     * The default value is <code>false</code>.
113     * <p/>In a managed profile, location sharing always reflects the primary user's setting, but
114     * can be overridden and forced off by setting this restriction to true in the managed profile.
115     *
116     * <p/>Key for user restrictions.
117     * <p/>Type: Boolean
118     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
119     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
120     * @see #getUserRestrictions()
121     */
122    public static final String DISALLOW_SHARE_LOCATION = "no_share_location";
123
124    /**
125     * Specifies if a user is disallowed from enabling the
126     * "Unknown Sources" setting, that allows installation of apps from unknown sources.
127     * The default value is <code>false</code>.
128     *
129     * <p/>Key for user restrictions.
130     * <p/>Type: Boolean
131     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
132     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
133     * @see #getUserRestrictions()
134     */
135    public static final String DISALLOW_INSTALL_UNKNOWN_SOURCES = "no_install_unknown_sources";
136
137    /**
138     * Specifies if a user is disallowed from configuring bluetooth.
139     * This does <em>not</em> restrict the user from turning bluetooth on or off.
140     * The default value is <code>false</code>.
141     * <p/>This restriction has no effect in a managed profile.
142     *
143     * <p/>Key for user restrictions.
144     * <p/>Type: Boolean
145     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
146     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
147     * @see #getUserRestrictions()
148     */
149    public static final String DISALLOW_CONFIG_BLUETOOTH = "no_config_bluetooth";
150
151    /**
152     * Specifies if a user is disallowed from transferring files over
153     * USB. This can only be set by device owners and profile owners on the primary user.
154     * The default value is <code>false</code>.
155     *
156     * <p/>Key for user restrictions.
157     * <p/>Type: Boolean
158     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
159     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
160     * @see #getUserRestrictions()
161     */
162    public static final String DISALLOW_USB_FILE_TRANSFER = "no_usb_file_transfer";
163
164    /**
165     * Specifies if a user is disallowed from configuring user
166     * credentials. The default value is <code>false</code>.
167     *
168     * <p/>Key for user restrictions.
169     * <p/>Type: Boolean
170     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
171     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
172     * @see #getUserRestrictions()
173     */
174    public static final String DISALLOW_CONFIG_CREDENTIALS = "no_config_credentials";
175
176    /**
177     * When set on the primary user this specifies if the user can remove other users.
178     * When set on a secondary user, this specifies if the user can remove itself.
179     * This restriction has no effect on managed profiles.
180     * The default value is <code>false</code>.
181     *
182     * <p/>Key for user restrictions.
183     * <p/>Type: Boolean
184     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
185     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
186     * @see #getUserRestrictions()
187     */
188    public static final String DISALLOW_REMOVE_USER = "no_remove_user";
189
190    /**
191     * Specifies if a user is disallowed from enabling or
192     * accessing debugging features. The default value is <code>false</code>.
193     *
194     * <p/>Key for user restrictions.
195     * <p/>Type: Boolean
196     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
197     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
198     * @see #getUserRestrictions()
199     */
200    public static final String DISALLOW_DEBUGGING_FEATURES = "no_debugging_features";
201
202    /**
203     * Specifies if a user is disallowed from configuring VPN.
204     * The default value is <code>false</code>.
205     * This restriction has an effect in a managed profile only from
206     * {@link android.os.Build.VERSION_CODES#M}
207     *
208     * <p/>Key for user restrictions.
209     * <p/>Type: Boolean
210     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
211     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
212     * @see #getUserRestrictions()
213     */
214    public static final String DISALLOW_CONFIG_VPN = "no_config_vpn";
215
216    /**
217     * Specifies if a user is disallowed from configuring Tethering
218     * & portable hotspots. This can only be set by device owners and profile owners on the
219     * primary user. The default value is <code>false</code>.
220     *
221     * <p/>Key for user restrictions.
222     * <p/>Type: Boolean
223     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
224     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
225     * @see #getUserRestrictions()
226     */
227    public static final String DISALLOW_CONFIG_TETHERING = "no_config_tethering";
228
229    /**
230     * Specifies if a user is disallowed from resetting network settings
231     * from Settings. This can only be set by device owners and profile owners on the primary user.
232     * The default value is <code>false</code>.
233     * <p/>This restriction has no effect on secondary users and managed profiles since only the
234     * primary user can reset the network settings of the device.
235     *
236     * <p/>Key for user restrictions.
237     * <p/>Type: Boolean
238     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
239     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
240     * @see #getUserRestrictions()
241     */
242    public static final String DISALLOW_NETWORK_RESET = "no_network_reset";
243
244    /**
245     * Specifies if a user is disallowed from factory resetting
246     * from Settings. This can only be set by device owners and profile owners on the primary user.
247     * The default value is <code>false</code>.
248     * <p/>This restriction has no effect on secondary users and managed profiles since only the
249     * primary user can factory reset the device.
250     *
251     * <p/>Key for user restrictions.
252     * <p/>Type: Boolean
253     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
254     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
255     * @see #getUserRestrictions()
256     */
257    public static final String DISALLOW_FACTORY_RESET = "no_factory_reset";
258
259    /**
260     * Specifies if a user is disallowed from adding new users and
261     * profiles. This can only be set by device owners and profile owners on the primary user.
262     * The default value is <code>false</code>.
263     * <p/>This restriction has no effect on secondary users and managed profiles since only the
264     * primary user can add other users.
265     *
266     * <p/>Key for user restrictions.
267     * <p/>Type: Boolean
268     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
269     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
270     * @see #getUserRestrictions()
271     */
272    public static final String DISALLOW_ADD_USER = "no_add_user";
273
274    /**
275     * Specifies if a user is disallowed from disabling application
276     * verification. The default value is <code>false</code>.
277     *
278     * <p/>Key for user restrictions.
279     * <p/>Type: Boolean
280     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
281     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
282     * @see #getUserRestrictions()
283     */
284    public static final String ENSURE_VERIFY_APPS = "ensure_verify_apps";
285
286    /**
287     * Specifies if a user is disallowed from configuring cell
288     * broadcasts. This can only be set by device owners and profile owners on the primary user.
289     * The default value is <code>false</code>.
290     * <p/>This restriction has no effect on secondary users and managed profiles since only the
291     * primary user can configure cell broadcasts.
292     *
293     * <p/>Key for user restrictions.
294     * <p/>Type: Boolean
295     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
296     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
297     * @see #getUserRestrictions()
298     */
299    public static final String DISALLOW_CONFIG_CELL_BROADCASTS = "no_config_cell_broadcasts";
300
301    /**
302     * Specifies if a user is disallowed from configuring mobile
303     * networks. This can only be set by device owners and profile owners on the primary user.
304     * The default value is <code>false</code>.
305     * <p/>This restriction has no effect on secondary users and managed profiles since only the
306     * primary user can configure mobile networks.
307     *
308     * <p/>Key for user restrictions.
309     * <p/>Type: Boolean
310     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
311     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
312     * @see #getUserRestrictions()
313     */
314    public static final String DISALLOW_CONFIG_MOBILE_NETWORKS = "no_config_mobile_networks";
315
316    /**
317     * Specifies if a user is disallowed from modifying
318     * applications in Settings or launchers. The following actions will not be allowed when this
319     * restriction is enabled:
320     * <li>uninstalling apps</li>
321     * <li>disabling apps</li>
322     * <li>clearing app caches</li>
323     * <li>clearing app data</li>
324     * <li>force stopping apps</li>
325     * <li>clearing app defaults</li>
326     * <p>
327     * The default value is <code>false</code>.
328     *
329     * <p/>Key for user restrictions.
330     * <p/>Type: Boolean
331     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
332     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
333     * @see #getUserRestrictions()
334     */
335    public static final String DISALLOW_APPS_CONTROL = "no_control_apps";
336
337    /**
338     * Specifies if a user is disallowed from mounting
339     * physical external media. This can only be set by device owners and profile owners on the
340     * primary user. The default value is <code>false</code>.
341     *
342     * <p/>Key for user restrictions.
343     * <p/>Type: Boolean
344     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
345     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
346     * @see #getUserRestrictions()
347     */
348    public static final String DISALLOW_MOUNT_PHYSICAL_MEDIA = "no_physical_media";
349
350    /**
351     * Specifies if a user is disallowed from adjusting microphone
352     * volume. If set, the microphone will be muted. This can only be set by device owners
353     * and profile owners on the primary user. The default value is <code>false</code>.
354     *
355     * <p/>Key for user restrictions.
356     * <p/>Type: Boolean
357     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
358     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
359     * @see #getUserRestrictions()
360     */
361    public static final String DISALLOW_UNMUTE_MICROPHONE = "no_unmute_microphone";
362
363    /**
364     * Specifies if a user is disallowed from adjusting the master
365     * volume. If set, the master volume will be muted. This can only be set by device owners
366     * and profile owners on the primary user. The default value is <code>false</code>.
367     *
368     * <p/>Key for user restrictions.
369     * <p/>Type: Boolean
370     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
371     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
372     * @see #getUserRestrictions()
373     */
374    public static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume";
375
376    /**
377     * Specifies that the user is not allowed to make outgoing
378     * phone calls. Emergency calls are still permitted.
379     * The default value is <code>false</code>.
380     * <p/>This restriction has no effect on managed profiles since call intents are normally
381     * forwarded to the primary user.
382     *
383     * <p/>Key for user restrictions.
384     * <p/>Type: Boolean
385     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
386     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
387     * @see #getUserRestrictions()
388     */
389    public static final String DISALLOW_OUTGOING_CALLS = "no_outgoing_calls";
390
391    /**
392     * Specifies that the user is not allowed to send or receive
393     * SMS messages. The default value is <code>false</code>.
394     *
395     * <p/>Key for user restrictions.
396     * <p/>Type: Boolean
397     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
398     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
399     * @see #getUserRestrictions()
400     */
401    public static final String DISALLOW_SMS = "no_sms";
402
403    /**
404     * Specifies if the user is not allowed to have fun. In some cases, the
405     * device owner may wish to prevent the user from experiencing amusement or
406     * joy while using the device. The default value is <code>false</code>.
407     *
408     * <p/>Key for user restrictions.
409     * <p/>Type: Boolean
410     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
411     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
412     * @see #getUserRestrictions()
413     */
414    public static final String DISALLOW_FUN = "no_fun";
415
416    /**
417     * Specifies that windows besides app windows should not be
418     * created. This will block the creation of the following types of windows.
419     * <li>{@link LayoutParams#TYPE_TOAST}</li>
420     * <li>{@link LayoutParams#TYPE_PHONE}</li>
421     * <li>{@link LayoutParams#TYPE_PRIORITY_PHONE}</li>
422     * <li>{@link LayoutParams#TYPE_SYSTEM_ALERT}</li>
423     * <li>{@link LayoutParams#TYPE_SYSTEM_ERROR}</li>
424     * <li>{@link LayoutParams#TYPE_SYSTEM_OVERLAY}</li>
425     *
426     * <p>This can only be set by device owners and profile owners on the primary user.
427     * The default value is <code>false</code>.
428     *
429     * <p/>Key for user restrictions.
430     * <p/>Type: Boolean
431     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
432     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
433     * @see #getUserRestrictions()
434     */
435    public static final String DISALLOW_CREATE_WINDOWS = "no_create_windows";
436
437    /**
438     * Specifies if what is copied in the clipboard of this profile can
439     * be pasted in related profiles. Does not restrict if the clipboard of related profiles can be
440     * pasted in this profile.
441     * The default value is <code>false</code>.
442     *
443     * <p/>Key for user restrictions.
444     * <p/>Type: Boolean
445     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
446     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
447     * @see #getUserRestrictions()
448     */
449    public static final String DISALLOW_CROSS_PROFILE_COPY_PASTE = "no_cross_profile_copy_paste";
450
451    /**
452     * Specifies if the user is not allowed to use NFC to beam out data from apps.
453     * The default value is <code>false</code>.
454     *
455     * <p/>Key for user restrictions.
456     * <p/>Type: Boolean
457     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
458     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
459     * @see #getUserRestrictions()
460     */
461    public static final String DISALLOW_OUTGOING_BEAM = "no_outgoing_beam";
462
463    /**
464     * Hidden user restriction to disallow access to wallpaper manager APIs. This user restriction
465     * is always set for managed profiles.
466     * @hide
467     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
468     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
469     * @see #getUserRestrictions()
470     */
471    public static final String DISALLOW_WALLPAPER = "no_wallpaper";
472
473    /**
474     * Specifies if the user is not allowed to reboot the device into safe boot mode.
475     * This can only be set by device owners and profile owners on the primary user.
476     * The default value is <code>false</code>.
477     *
478     * <p/>Key for user restrictions.
479     * <p/>Type: Boolean
480     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
481     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
482     * @see #getUserRestrictions()
483     */
484    public static final String DISALLOW_SAFE_BOOT = "no_safe_boot";
485
486    /**
487     * Specifies if a user is not allowed to record audio. This restriction is always enabled for
488     * background users. The default value is <code>false</code>.
489     *
490     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
491     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
492     * @see #getUserRestrictions()
493     * @hide
494     */
495    public static final String DISALLOW_RECORD_AUDIO = "no_record_audio";
496
497    /**
498     * Specifies if a user is not allowed to run in the background and should be stopped during
499     * user switch. The default value is <code>false</code>.
500     *
501     * <p>This restriction can be set by device owners and profile owners.
502     *
503     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
504     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
505     * @see #getUserRestrictions()
506     * @hide
507     */
508    public static final String DISALLOW_RUN_IN_BACKGROUND = "no_run_in_background";
509
510    /**
511     * Specifies if a user is not allowed to use the camera.
512     *
513     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
514     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
515     * @see #getUserRestrictions()
516     * @hide
517     */
518    public static final String DISALLOW_CAMERA = "no_camera";
519
520    /**
521     * Specifies if a user is not allowed to use cellular data when roaming. This can only be set by
522     * device owners. The default value is <code>false</code>.
523     *
524     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
525     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
526     * @see #getUserRestrictions()
527     */
528    public static final String DISALLOW_DATA_ROAMING = "no_data_roaming";
529
530    /**
531     * Allows apps in the parent profile to handle web links from the managed profile.
532     *
533     * This user restriction has an effect only in a managed profile.
534     * If set:
535     * Intent filters of activities in the parent profile with action
536     * {@link android.content.Intent#ACTION_VIEW},
537     * category {@link android.content.Intent#CATEGORY_BROWSABLE}, scheme http or https, and which
538     * define a host can handle intents from the managed profile.
539     * The default value is <code>false</code>.
540     *
541     * <p/>Key for user restrictions.
542     * <p/>Type: Boolean
543     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
544     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
545     * @see #getUserRestrictions()
546     */
547    public static final String ALLOW_PARENT_PROFILE_APP_LINKING
548            = "allow_parent_profile_app_linking";
549
550    /**
551     * Application restriction key that is used to indicate the pending arrival
552     * of real restrictions for the app.
553     *
554     * <p>
555     * Applications that support restrictions should check for the presence of this key.
556     * A <code>true</code> value indicates that restrictions may be applied in the near
557     * future but are not available yet. It is the responsibility of any
558     * management application that sets this flag to update it when the final
559     * restrictions are enforced.
560     *
561     * <p/>Key for application restrictions.
562     * <p/>Type: Boolean
563     * @see android.app.admin.DevicePolicyManager#setApplicationRestrictions(
564     *      android.content.ComponentName, String, Bundle)
565     * @see android.app.admin.DevicePolicyManager#getApplicationRestrictions(
566     *      android.content.ComponentName, String)
567     */
568    public static final String KEY_RESTRICTIONS_PENDING = "restrictions_pending";
569
570    /** @hide */
571    public static final int PIN_VERIFICATION_FAILED_INCORRECT = -3;
572    /** @hide */
573    public static final int PIN_VERIFICATION_FAILED_NOT_SET = -2;
574    /** @hide */
575    public static final int PIN_VERIFICATION_SUCCESS = -1;
576
577    /** @hide */
578    public static UserManager get(Context context) {
579        return (UserManager) context.getSystemService(Context.USER_SERVICE);
580    }
581
582    /** @hide */
583    public UserManager(Context context, IUserManager service) {
584        mService = service;
585        mContext = context;
586    }
587
588    /**
589     * Returns whether the system supports multiple users.
590     * @return true if multiple users can be created by user, false if it is a single user device.
591     * @hide
592     */
593    public static boolean supportsMultipleUsers() {
594        return getMaxSupportedUsers() > 1
595                && SystemProperties.getBoolean("fw.show_multiuserui",
596                Resources.getSystem().getBoolean(R.bool.config_enableMultiUserUI));
597    }
598
599    /**
600     * @hide
601     * @return Whether the device is running with split system user. It means the system user and
602     * primary user are two separate users. Previously system user and primary user are combined as
603     * a single owner user.  see @link {android.os.UserHandle#USER_OWNER}
604     */
605    public static boolean isSplitSystemUser() {
606        return SystemProperties.getBoolean("ro.fw.system_user_split", false);
607    }
608
609    /**
610     * Returns the user handle for the user that this process is running under.
611     *
612     * @return the user handle of this process.
613     * @hide
614     */
615    public @UserIdInt int getUserHandle() {
616        return UserHandle.myUserId();
617    }
618
619    /**
620     * Returns the user name of the user making this call.  This call is only
621     * available to applications on the system image; it requires the
622     * MANAGE_USERS permission.
623     * @return the user name
624     */
625    public String getUserName() {
626        try {
627            return mService.getUserInfo(getUserHandle()).name;
628        } catch (RemoteException re) {
629            Log.w(TAG, "Could not get user name", re);
630            return "";
631        }
632    }
633
634    /**
635     * Used to determine whether the user making this call is subject to
636     * teleportations.
637     *
638     * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
639     * now automatically identify goats using advanced goat recognition technology.</p>
640     *
641     * @return Returns true if the user making this call is a goat.
642     */
643    public boolean isUserAGoat() {
644        return mContext.getPackageManager()
645                .isPackageAvailable("com.coffeestainstudios.goatsimulator");
646    }
647
648    /**
649     * Used to check if this process is running under the primary user. The primary user
650     * is the first human user on a device.
651     *
652     * @return whether this process is running under the primary user.
653     * @hide
654     */
655    public boolean isPrimaryUser() {
656        UserInfo user = getUserInfo(UserHandle.myUserId());
657        return user != null ? user.isPrimary() : false;
658    }
659
660    /**
661     * Used to check if this process is running under the system user. The system user
662     * is the initial user that is implicitly created on first boot and hosts most of the
663     * system services.
664     *
665     * @return whether this process is running under the system user.
666     */
667    public boolean isSystemUser() {
668        return UserHandle.myUserId() == UserHandle.USER_SYSTEM;
669    }
670
671    /**
672     * @hide
673     * Returns whether the caller is running as an admin user. There can be more than one admin
674     * user.
675     */
676    public boolean isAdminUser() {
677        return isUserAdmin(UserHandle.myUserId());
678    }
679
680    /**
681     * @hide
682     * Returns whether the provided user is an admin user. There can be more than one admin
683     * user.
684     */
685    public boolean isUserAdmin(@UserIdInt int userId) {
686        UserInfo user = getUserInfo(userId);
687        return user != null && user.isAdmin();
688    }
689
690    /**
691     * Used to check if the user making this call is linked to another user. Linked users may have
692     * a reduced number of available apps, app restrictions and account restrictions.
693     * @return whether the user making this call is a linked user
694     * @hide
695     */
696    public boolean isLinkedUser() {
697        try {
698            return mService.isRestricted();
699        } catch (RemoteException re) {
700            Log.w(TAG, "Could not check if user is limited ", re);
701            return false;
702        }
703    }
704
705    /**
706     * Checks if specified user can have restricted profile.
707     * @hide
708     */
709    public boolean canHaveRestrictedProfile(@UserIdInt int userId) {
710        try {
711            return mService.canHaveRestrictedProfile(userId);
712        } catch (RemoteException re) {
713            Log.w(TAG, "Could not check if user can have restricted profile", re);
714            return false;
715        }
716    }
717
718    /**
719     * Checks if the calling app is running as a guest user.
720     * @return whether the caller is a guest user.
721     * @hide
722     */
723    public boolean isGuestUser() {
724        UserInfo user = getUserInfo(UserHandle.myUserId());
725        return user != null ? user.isGuest() : false;
726    }
727
728    /**
729     * Checks if the calling app is running in a managed profile.
730     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
731     *
732     * @return whether the caller is in a managed profile.
733     * @hide
734     */
735    @SystemApi
736    public boolean isManagedProfile() {
737        UserInfo user = getUserInfo(UserHandle.myUserId());
738        return user != null ? user.isManagedProfile() : false;
739    }
740
741    /**
742     * Checks if the calling app is running as an ephemeral user.
743     *
744     * @return whether the caller is an ephemeral user.
745     * @hide
746     */
747    public boolean isEphemeralUser() {
748        return isUserEphemeral(UserHandle.myUserId());
749    }
750
751    /**
752     * Returns whether the specified user is ephemeral.
753     * @hide
754     */
755    public boolean isUserEphemeral(@UserIdInt int userId) {
756        final UserInfo user = getUserInfo(userId);
757        return user != null && user.isEphemeral();
758    }
759
760    /**
761     * Return whether the given user is actively running.  This means that
762     * the user is in the "started" state, not "stopped" -- it is currently
763     * allowed to run code through scheduled alarms, receiving broadcasts,
764     * etc.  A started user may be either the current foreground user or a
765     * background user; the result here does not distinguish between the two.
766     * @param user The user to retrieve the running state for.
767     */
768    public boolean isUserRunning(UserHandle user) {
769        return isUserRunning(user.getIdentifier());
770    }
771
772    /** {@hide} */
773    public boolean isUserRunning(int userId) {
774        try {
775            return ActivityManagerNative.getDefault().isUserRunning(userId, 0);
776        } catch (RemoteException e) {
777            return false;
778        }
779    }
780
781    /**
782     * Return whether the given user is actively running <em>or</em> stopping.
783     * This is like {@link #isUserRunning(UserHandle)}, but will also return
784     * true if the user had been running but is in the process of being stopped
785     * (but is not yet fully stopped, and still running some code).
786     * @param user The user to retrieve the running state for.
787     */
788    public boolean isUserRunningOrStopping(UserHandle user) {
789        try {
790            // TODO: reconcile stopped vs stopping?
791            return ActivityManagerNative.getDefault().isUserRunning(
792                    user.getIdentifier(), ActivityManager.FLAG_OR_STOPPED);
793        } catch (RemoteException e) {
794            return false;
795        }
796    }
797
798    /**
799     * Return whether the calling user is running in a "locked" state. A user is
800     * unlocked only after they've entered their credentials (such as a lock
801     * pattern or PIN), and credential-encrypted private app data storage is
802     * available.
803     */
804    @Deprecated
805    public boolean isUserRunningAndLocked() {
806        return isUserRunningAndLocked(Process.myUserHandle());
807    }
808
809    /**
810     * Return whether the given user is running in a "locked" state. A user
811     * is unlocked only after they've entered their credentials (such as a lock
812     * pattern or PIN), and credential-encrypted private app data storage is
813     * available.
814     *
815     * @param user to retrieve the unlocked state for.
816     */
817    @Deprecated
818    public boolean isUserRunningAndLocked(UserHandle user) {
819        try {
820            return ActivityManagerNative.getDefault().isUserRunning(
821                    user.getIdentifier(), ActivityManager.FLAG_AND_LOCKED);
822        } catch (RemoteException e) {
823            return false;
824        }
825    }
826
827    /**
828     * Return whether the calling user is running in an "unlocked" state. A user
829     * is unlocked only after they've entered their credentials (such as a lock
830     * pattern or PIN), and credential-encrypted private app data storage is
831     * available.
832     */
833    @Deprecated
834    public boolean isUserRunningAndUnlocked() {
835        return isUserRunningAndUnlocked(Process.myUserHandle());
836    }
837
838    /**
839     * Return whether the given user is running in an "unlocked" state. A user
840     * is unlocked only after they've entered their credentials (such as a lock
841     * pattern or PIN), and credential-encrypted private app data storage is
842     * available.
843     *
844     * @param user to retrieve the unlocked state for.
845     */
846    @Deprecated
847    public boolean isUserRunningAndUnlocked(UserHandle user) {
848        try {
849            return ActivityManagerNative.getDefault().isUserRunning(
850                    user.getIdentifier(), ActivityManager.FLAG_AND_UNLOCKED);
851        } catch (RemoteException e) {
852            return false;
853        }
854    }
855
856    /**
857     * Return whether the calling user is running in an "unlocked" state. A user
858     * is unlocked only after they've entered their credentials (such as a lock
859     * pattern or PIN), and credential-encrypted private app data storage is
860     * available.
861     */
862    public boolean isUserUnlocked() {
863        return isUserUnlocked(Process.myUserHandle());
864    }
865
866    /**
867     * Return whether the given user is running in an "unlocked" state. A user
868     * is unlocked only after they've entered their credentials (such as a lock
869     * pattern or PIN), and credential-encrypted private app data storage is
870     * available.
871     *
872     * @param user to retrieve the unlocked state for.
873     */
874    public boolean isUserUnlocked(UserHandle user) {
875        return isUserUnlocked(user.getIdentifier());
876    }
877
878    /** {@hide} */
879    public boolean isUserUnlocked(@UserIdInt int userId) {
880        // TODO: eventually pivot this back to look at ActivityManager state,
881        // but there is race where we can start a non-encryption-aware launcher
882        // before that lifecycle has entered the running unlocked state.
883        return mContext.getSystemService(StorageManager.class).isUserKeyUnlocked(userId);
884    }
885
886    /**
887     * Returns the UserInfo object describing a specific user.
888     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
889     * @param userHandle the user handle of the user whose information is being requested.
890     * @return the UserInfo object for a specific user.
891     * @hide
892     */
893    public UserInfo getUserInfo(@UserIdInt int userHandle) {
894        try {
895            return mService.getUserInfo(userHandle);
896        } catch (RemoteException re) {
897            Log.w(TAG, "Could not get user info", re);
898            return null;
899        }
900    }
901
902    /**
903     * Returns the user-wide restrictions imposed on this user.
904     * @return a Bundle containing all the restrictions.
905     */
906    public Bundle getUserRestrictions() {
907        return getUserRestrictions(Process.myUserHandle());
908    }
909
910    /**
911     * Returns the user-wide restrictions imposed on the user specified by <code>userHandle</code>.
912     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
913     * @return a Bundle containing all the restrictions.
914     */
915    public Bundle getUserRestrictions(UserHandle userHandle) {
916        try {
917            return mService.getUserRestrictions(userHandle.getIdentifier());
918        } catch (RemoteException re) {
919            Log.w(TAG, "Could not get user restrictions", re);
920            return Bundle.EMPTY;
921        }
922    }
923
924     /**
925     * @hide
926     * Returns whether the given user has been disallowed from performing certain actions
927     * or setting certain settings through UserManager. This method disregards restrictions
928     * set by device policy.
929     * @param restrictionKey the string key representing the restriction
930     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
931     */
932    public boolean hasBaseUserRestriction(String restrictionKey, UserHandle userHandle) {
933        try {
934            return mService.hasBaseUserRestriction(restrictionKey, userHandle.getIdentifier());
935        } catch (RemoteException re) {
936            Log.w(TAG, "Could not get base user restrictions for user " +
937                    userHandle.getIdentifier(), re);
938            return false;
939        }
940    }
941
942    /**
943     * This will no longer work.  Device owners and profile owners should use
944     * {@link DevicePolicyManager#addUserRestriction(ComponentName, String)} instead.
945     */
946    // System apps should use UserManager.setUserRestriction() instead.
947    @Deprecated
948    public void setUserRestrictions(Bundle restrictions) {
949        throw new UnsupportedOperationException("This method is no longer supported");
950    }
951
952    /**
953     * This will no longer work.  Device owners and profile owners should use
954     * {@link DevicePolicyManager#addUserRestriction(ComponentName, String)} instead.
955     */
956    // System apps should use UserManager.setUserRestriction() instead.
957    @Deprecated
958    public void setUserRestrictions(Bundle restrictions, UserHandle userHandle) {
959        throw new UnsupportedOperationException("This method is no longer supported");
960    }
961
962    /**
963     * Sets the value of a specific restriction.
964     * Requires the MANAGE_USERS permission.
965     * @param key the key of the restriction
966     * @param value the value for the restriction
967     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
968     * android.content.ComponentName, String)} or
969     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
970     * android.content.ComponentName, String)} instead.
971     */
972    @Deprecated
973    public void setUserRestriction(String key, boolean value) {
974        setUserRestriction(key, value, Process.myUserHandle());
975    }
976
977    /**
978     * @hide
979     * Sets the value of a specific restriction on a specific user.
980     * Requires the MANAGE_USERS permission.
981     * @param key the key of the restriction
982     * @param value the value for the restriction
983     * @param userHandle the user whose restriction is to be changed.
984     * @deprecated use {@link android.app.admin.DevicePolicyManager#addUserRestriction(
985     * android.content.ComponentName, String)} or
986     * {@link android.app.admin.DevicePolicyManager#clearUserRestriction(
987     * android.content.ComponentName, String)} instead.
988     */
989    @Deprecated
990    public void setUserRestriction(String key, boolean value, UserHandle userHandle) {
991        try {
992            mService.setUserRestriction(key, value, userHandle.getIdentifier());
993        } catch (RemoteException re) {
994            Log.w(TAG, "Could not set user restriction", re);
995        }
996    }
997
998    /**
999     * Returns whether the current user has been disallowed from performing certain actions
1000     * or setting certain settings.
1001     *
1002     * @param restrictionKey The string key representing the restriction.
1003     * @return {@code true} if the current user has the given restriction, {@code false} otherwise.
1004     */
1005    public boolean hasUserRestriction(String restrictionKey) {
1006        return hasUserRestriction(restrictionKey, Process.myUserHandle());
1007    }
1008
1009    /**
1010     * @hide
1011     * Returns whether the given user has been disallowed from performing certain actions
1012     * or setting certain settings.
1013     * @param restrictionKey the string key representing the restriction
1014     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
1015     */
1016    public boolean hasUserRestriction(String restrictionKey, UserHandle userHandle) {
1017        try {
1018            return mService.hasUserRestriction(restrictionKey,
1019                    userHandle.getIdentifier());
1020        } catch (RemoteException re) {
1021            Log.w(TAG, "Could not check user restrictions", re);
1022            return false;
1023        }
1024    }
1025
1026    /**
1027     * Return the serial number for a user.  This is a device-unique
1028     * number assigned to that user; if the user is deleted and then a new
1029     * user created, the new users will not be given the same serial number.
1030     * @param user The user whose serial number is to be retrieved.
1031     * @return The serial number of the given user; returns -1 if the
1032     * given UserHandle does not exist.
1033     * @see #getUserForSerialNumber(long)
1034     */
1035    public long getSerialNumberForUser(UserHandle user) {
1036        return getUserSerialNumber(user.getIdentifier());
1037    }
1038
1039    /**
1040     * Return the user associated with a serial number previously
1041     * returned by {@link #getSerialNumberForUser(UserHandle)}.
1042     * @param serialNumber The serial number of the user that is being
1043     * retrieved.
1044     * @return Return the user associated with the serial number, or null
1045     * if there is not one.
1046     * @see #getSerialNumberForUser(UserHandle)
1047     */
1048    public UserHandle getUserForSerialNumber(long serialNumber) {
1049        int ident = getUserHandle((int) serialNumber);
1050        return ident >= 0 ? new UserHandle(ident) : null;
1051    }
1052
1053    /**
1054     * Creates a user with the specified name and options. For non-admin users, default user
1055     * restrictions are going to be applied.
1056     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1057     *
1058     * @param name the user's name
1059     * @param flags flags that identify the type of user and other properties.
1060     * @see UserInfo
1061     *
1062     * @return the UserInfo object for the created user, or null if the user could not be created.
1063     * @hide
1064     */
1065    public UserInfo createUser(String name, int flags) {
1066        UserInfo user = null;
1067        try {
1068            user = mService.createUser(name, flags);
1069            if (user != null && !user.isAdmin()) {
1070                mService.setUserRestriction(DISALLOW_SMS, true, user.id);
1071                mService.setUserRestriction(DISALLOW_OUTGOING_CALLS, true, user.id);
1072            }
1073        } catch (RemoteException re) {
1074            Log.w(TAG, "Could not create a user", re);
1075        }
1076        return user;
1077    }
1078
1079    /**
1080     * Creates a guest user and configures it.
1081     * @param context an application context
1082     * @param name the name to set for the user
1083     * @hide
1084     */
1085    public UserInfo createGuest(Context context, String name) {
1086        UserInfo guest = null;
1087        try {
1088            guest = mService.createUser(name, UserInfo.FLAG_GUEST);
1089            if (guest != null) {
1090                Settings.Secure.putStringForUser(context.getContentResolver(),
1091                        Settings.Secure.SKIP_FIRST_USE_HINTS, "1", guest.id);
1092            }
1093        } catch (RemoteException re) {
1094            Log.w(TAG, "Could not create a user", re);
1095        }
1096        return guest;
1097    }
1098
1099    /**
1100     * Creates a user with the specified name and options as a profile of another user.
1101     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1102     *
1103     * @param name the user's name
1104     * @param flags flags that identify the type of user and other properties.
1105     * @see UserInfo
1106     * @param userHandle new user will be a profile of this use.
1107     *
1108     * @return the UserInfo object for the created user, or null if the user could not be created.
1109     * @hide
1110     */
1111    public UserInfo createProfileForUser(String name, int flags, @UserIdInt int userHandle) {
1112        try {
1113            return mService.createProfileForUser(name, flags, userHandle);
1114        } catch (RemoteException re) {
1115            Log.w(TAG, "Could not create a user", re);
1116            return null;
1117        }
1118    }
1119
1120    /**
1121     * Creates a restricted profile with the specified name. This method also sets necessary
1122     * restrictions and adds shared accounts.
1123     *
1124     * @param name profile's name
1125     * @return UserInfo object for the created user, or null if the user could not be created.
1126     * @hide
1127     */
1128    public UserInfo createRestrictedProfile(String name) {
1129        try {
1130            UserHandle parentUserHandle = Process.myUserHandle();
1131            UserInfo user = mService.createRestrictedProfile(name,
1132                    parentUserHandle.getIdentifier());
1133            if (user != null) {
1134                AccountManager.get(mContext).addSharedAccountsFromParentUser(parentUserHandle,
1135                        UserHandle.of(user.id));
1136            }
1137            return user;
1138        } catch (RemoteException e) {
1139            Log.w(TAG, "Could not create a restricted profile", e);
1140        }
1141        return null;
1142    }
1143
1144    /**
1145     * @hide
1146     * Marks the guest user for deletion to allow a new guest to be created before deleting
1147     * the current user who is a guest.
1148     * @param userHandle
1149     * @return
1150     */
1151    public boolean markGuestForDeletion(@UserIdInt int userHandle) {
1152        try {
1153            return mService.markGuestForDeletion(userHandle);
1154        } catch (RemoteException re) {
1155            Log.w(TAG, "Could not mark guest for deletion", re);
1156            return false;
1157        }
1158    }
1159
1160    /**
1161     * Sets the user as enabled, if such an user exists.
1162     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1163     * Note that the default is true, it's only that managed profiles might not be enabled.
1164     *
1165     * @param userHandle the id of the profile to enable
1166     * @hide
1167     */
1168    public void setUserEnabled(@UserIdInt int userHandle) {
1169        try {
1170            mService.setUserEnabled(userHandle);
1171        } catch (RemoteException e) {
1172            Log.w(TAG, "Could not enable the profile", e);
1173        }
1174    }
1175
1176    /**
1177     * Return the number of users currently created on the device.
1178     */
1179    public int getUserCount() {
1180        List<UserInfo> users = getUsers();
1181        return users != null ? users.size() : 1;
1182    }
1183
1184    /**
1185     * Returns information for all users on this device.
1186     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1187     * @return the list of users that were created.
1188     * @hide
1189     */
1190    public List<UserInfo> getUsers() {
1191        try {
1192            return mService.getUsers(false);
1193        } catch (RemoteException re) {
1194            Log.w(TAG, "Could not get user list", re);
1195            return null;
1196        }
1197    }
1198
1199    /**
1200     * @return the user's account name, null if not found.
1201     * @hide
1202     */
1203    @RequiresPermission( allOf = {
1204            Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1205            Manifest.permission.MANAGE_USERS
1206    })
1207    public @Nullable String getUserAccount(@UserIdInt int userHandle) {
1208        try {
1209            return mService.getUserAccount(userHandle);
1210        } catch (RemoteException re) {
1211            Log.w(TAG, "Could not get user account", re);
1212            return null;
1213        }
1214    }
1215
1216    /**
1217     * Set account name for the given user.
1218     * @hide
1219     */
1220    @RequiresPermission( allOf = {
1221            Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1222            Manifest.permission.MANAGE_USERS
1223    })
1224    public void setUserAccount(@UserIdInt int userHandle, @Nullable String accountName) {
1225        try {
1226            mService.setUserAccount(userHandle, accountName);
1227        } catch (RemoteException re) {
1228            Log.w(TAG, "Could not set user account", re);
1229        }
1230    }
1231
1232    /**
1233     * Returns information for Primary user.
1234     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1235     *
1236     * @return the Primary user, null if not found.
1237     * @hide
1238     */
1239    public @Nullable UserInfo getPrimaryUser() {
1240        try {
1241            return mService.getPrimaryUser();
1242        } catch (RemoteException re) {
1243            Log.w(TAG, "Could not get Primary user", re);
1244            return null;
1245        }
1246    }
1247
1248    /**
1249     * Checks whether it's possible to add more users. Caller must hold the MANAGE_USERS
1250     * permission.
1251     *
1252     * @return true if more users can be added, false if limit has been reached.
1253     * @hide
1254     */
1255    public boolean canAddMoreUsers() {
1256        final List<UserInfo> users = getUsers(true);
1257        final int totalUserCount = users.size();
1258        int aliveUserCount = 0;
1259        for (int i = 0; i < totalUserCount; i++) {
1260            UserInfo user = users.get(i);
1261            if (!user.isGuest()) {
1262                aliveUserCount++;
1263            }
1264        }
1265        return aliveUserCount < getMaxSupportedUsers();
1266    }
1267
1268    /**
1269     * Checks whether it's possible to add more managed profiles. Caller must hold the MANAGE_USERS
1270     * permission.
1271     * if allowedToRemoveOne is true and if the user already has a managed profile, then return if
1272     * we could add a new managed profile to this user after removing the existing one.
1273     *
1274     * @return true if more managed profiles can be added, false if limit has been reached.
1275     * @hide
1276     */
1277    public boolean canAddMoreManagedProfiles(@UserIdInt int userId, boolean allowedToRemoveOne) {
1278        try {
1279            return mService.canAddMoreManagedProfiles(userId, allowedToRemoveOne);
1280        } catch (RemoteException re) {
1281            Log.w(TAG, "Could not check if we can add more managed profiles", re);
1282            return false;
1283        }
1284    }
1285
1286    /**
1287     * Returns list of the profiles of userHandle including
1288     * userHandle itself.
1289     * Note that this returns both enabled and not enabled profiles. See
1290     * {@link #getEnabledProfiles(int)} if you need only the enabled ones.
1291     *
1292     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1293     * @param userHandle profiles of this user will be returned.
1294     * @return the list of profiles.
1295     * @hide
1296     */
1297    public List<UserInfo> getProfiles(@UserIdInt int userHandle) {
1298        try {
1299            return mService.getProfiles(userHandle, false /* enabledOnly */);
1300        } catch (RemoteException re) {
1301            Log.w(TAG, "Could not get user list", re);
1302            return null;
1303        }
1304    }
1305
1306    /**
1307     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1308     * @param userId one of the two user ids to check.
1309     * @param otherUserId one of the two user ids to check.
1310     * @return true if the two user ids are in the same profile group.
1311     * @hide
1312     */
1313    public boolean isSameProfileGroup(@UserIdInt int userId, int otherUserId) {
1314        try {
1315            return mService.isSameProfileGroup(userId, otherUserId);
1316        } catch (RemoteException re) {
1317            Log.w(TAG, "Could not get user list", re);
1318            return false;
1319        }
1320    }
1321
1322    /**
1323     * Returns list of the profiles of userHandle including
1324     * userHandle itself.
1325     * Note that this returns only enabled.
1326     *
1327     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1328     * @param userHandle profiles of this user will be returned.
1329     * @return the list of profiles.
1330     * @hide
1331     */
1332    public List<UserInfo> getEnabledProfiles(@UserIdInt int userHandle) {
1333        try {
1334            return mService.getProfiles(userHandle, true /* enabledOnly */);
1335        } catch (RemoteException re) {
1336            Log.w(TAG, "Could not get user list", re);
1337            return null;
1338        }
1339    }
1340
1341    /**
1342     * Returns a list of UserHandles for profiles associated with the user that the calling process
1343     * is running on, including the user itself.
1344     *
1345     * @return A non-empty list of UserHandles associated with the calling user.
1346     */
1347    public List<UserHandle> getUserProfiles() {
1348        ArrayList<UserHandle> profiles = new ArrayList<UserHandle>();
1349        List<UserInfo> users;
1350        try {
1351            users = mService.getProfiles(UserHandle.myUserId(), true /* enabledOnly */);
1352        } catch (RemoteException re) {
1353            Log.w(TAG, "Could not get user list", re);
1354            return null;
1355        }
1356        for (UserInfo info : users) {
1357            UserHandle userHandle = new UserHandle(info.id);
1358            profiles.add(userHandle);
1359        }
1360        return profiles;
1361    }
1362
1363    /**
1364     * Returns the device credential owner id of the profile from
1365     * which this method is called, or userHandle if called from a user that
1366     * is not a profile.
1367     *
1368     * @hide
1369     */
1370    public int getCredentialOwnerProfile(@UserIdInt int userHandle) {
1371        try {
1372            return mService.getCredentialOwnerProfile(userHandle);
1373        } catch (RemoteException re) {
1374            Log.w(TAG, "Could not get credential owner", re);
1375            return -1;
1376        }
1377    }
1378
1379    /**
1380     * Returns the parent of the profile which this method is called from
1381     * or null if called from a user that is not a profile.
1382     *
1383     * @hide
1384     */
1385    public UserInfo getProfileParent(@UserIdInt int userHandle) {
1386        try {
1387            return mService.getProfileParent(userHandle);
1388        } catch (RemoteException re) {
1389            Log.w(TAG, "Could not get profile parent", re);
1390            return null;
1391        }
1392    }
1393
1394    /**
1395     * Set quiet mode of a managed profile.
1396     *
1397     * @param userHandle The user handle of the profile.
1398     * @param enableQuietMode Whether quiet mode should be enabled or disabled.
1399     * @hide
1400     */
1401    public void setQuietModeEnabled(@UserIdInt int userHandle, boolean enableQuietMode) {
1402        try {
1403            mService.setQuietModeEnabled(userHandle, enableQuietMode);
1404        } catch (RemoteException e) {
1405            Log.w(TAG, "Could not change the profile's quiet mode", e);
1406        }
1407    }
1408
1409    /**
1410     * Returns whether the given profile is in quiet mode or not.
1411     *
1412     * @param userHandle The user handle of the profile to be queried.
1413     * @return true if the profile is in quiet mode, false otherwise.
1414     */
1415    public boolean isQuietModeEnabled(UserHandle userHandle) {
1416        try {
1417            return mService.isQuietModeEnabled(userHandle.getIdentifier());
1418        } catch (RemoteException e) {
1419            Log.w(TAG, "Could not query the profile's quiet mode", e);
1420        }
1421        return false;
1422    }
1423
1424    /**
1425     * If the target user is a managed profile of the calling user or the caller
1426     * is itself a managed profile, then this returns a badged copy of the given
1427     * icon to be able to distinguish it from the original icon. For badging an
1428     * arbitrary drawable use {@link #getBadgedDrawableForUser(
1429     * android.graphics.drawable.Drawable, UserHandle, android.graphics.Rect, int)}.
1430     * <p>
1431     * If the original drawable is a BitmapDrawable and the backing bitmap is
1432     * mutable as per {@link android.graphics.Bitmap#isMutable()}, the bading
1433     * is performed in place and the original drawable is returned.
1434     * </p>
1435     *
1436     * @param icon The icon to badge.
1437     * @param user The target user.
1438     * @return A drawable that combines the original icon and a badge as
1439     *         determined by the system.
1440     * @removed
1441     */
1442    public Drawable getBadgedIconForUser(Drawable icon, UserHandle user) {
1443        return mContext.getPackageManager().getUserBadgedIcon(icon, user);
1444    }
1445
1446    /**
1447     * If the target user is a managed profile of the calling user or the caller
1448     * is itself a managed profile, then this returns a badged copy of the given
1449     * drawable allowing the user to distinguish it from the original drawable.
1450     * The caller can specify the location in the bounds of the drawable to be
1451     * badged where the badge should be applied as well as the density of the
1452     * badge to be used.
1453     * <p>
1454     * If the original drawable is a BitmapDrawable and the backing bitmap is
1455     * mutable as per {@link android.graphics.Bitmap#isMutable()}, the bading
1456     * is performed in place and the original drawable is returned.
1457     * </p>
1458     *
1459     * @param badgedDrawable The drawable to badge.
1460     * @param user The target user.
1461     * @param badgeLocation Where in the bounds of the badged drawable to place
1462     *         the badge. If not provided, the badge is applied on top of the entire
1463     *         drawable being badged.
1464     * @param badgeDensity The optional desired density for the badge as per
1465     *         {@link android.util.DisplayMetrics#densityDpi}. If not provided,
1466     *         the density of the display is used.
1467     * @return A drawable that combines the original drawable and a badge as
1468     *         determined by the system.
1469     * @removed
1470     */
1471    public Drawable getBadgedDrawableForUser(Drawable badgedDrawable, UserHandle user,
1472            Rect badgeLocation, int badgeDensity) {
1473        return mContext.getPackageManager().getUserBadgedDrawableForDensity(badgedDrawable, user,
1474                badgeLocation, badgeDensity);
1475    }
1476
1477    /**
1478     * If the target user is a managed profile of the calling user or the caller
1479     * is itself a managed profile, then this returns a copy of the label with
1480     * badging for accessibility services like talkback. E.g. passing in "Email"
1481     * and it might return "Work Email" for Email in the work profile.
1482     *
1483     * @param label The label to change.
1484     * @param user The target user.
1485     * @return A label that combines the original label and a badge as
1486     *         determined by the system.
1487     * @removed
1488     */
1489    public CharSequence getBadgedLabelForUser(CharSequence label, UserHandle user) {
1490        return mContext.getPackageManager().getUserBadgedLabel(label, user);
1491    }
1492
1493    /**
1494     * Returns information for all users on this device. Requires
1495     * {@link android.Manifest.permission#MANAGE_USERS} permission.
1496     *
1497     * @param excludeDying specify if the list should exclude users being
1498     *            removed.
1499     * @return the list of users that were created.
1500     * @hide
1501     */
1502    public List<UserInfo> getUsers(boolean excludeDying) {
1503        try {
1504            return mService.getUsers(excludeDying);
1505        } catch (RemoteException re) {
1506            Log.w(TAG, "Could not get user list", re);
1507            return null;
1508        }
1509    }
1510
1511    /**
1512     * Removes a user and all associated data.
1513     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1514     * @param userHandle the integer handle of the user, where 0 is the primary user.
1515     * @hide
1516     */
1517    public boolean removeUser(@UserIdInt int userHandle) {
1518        try {
1519            return mService.removeUser(userHandle);
1520        } catch (RemoteException re) {
1521            Log.w(TAG, "Could not remove user ", re);
1522            return false;
1523        }
1524    }
1525
1526    /**
1527     * Updates the user's name.
1528     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1529     *
1530     * @param userHandle the user's integer handle
1531     * @param name the new name for the user
1532     * @hide
1533     */
1534    public void setUserName(@UserIdInt int userHandle, String name) {
1535        try {
1536            mService.setUserName(userHandle, name);
1537        } catch (RemoteException re) {
1538            Log.w(TAG, "Could not set the user name ", re);
1539        }
1540    }
1541
1542    /**
1543     * Sets the user's photo.
1544     * @param userHandle the user for whom to change the photo.
1545     * @param icon the bitmap to set as the photo.
1546     * @hide
1547     */
1548    public void setUserIcon(@UserIdInt int userHandle, Bitmap icon) {
1549        try {
1550            mService.setUserIcon(userHandle, icon);
1551        } catch (RemoteException re) {
1552            Log.w(TAG, "Could not set the user icon ", re);
1553        }
1554    }
1555
1556    /**
1557     * Returns a file descriptor for the user's photo. PNG data can be read from this file.
1558     * @param userHandle the user whose photo we want to read.
1559     * @return a {@link Bitmap} of the user's photo, or null if there's no photo.
1560     * @see com.android.internal.util.UserIcons#getDefaultUserIcon for a default.
1561     * @hide
1562     */
1563    public Bitmap getUserIcon(@UserIdInt int userHandle) {
1564        try {
1565            ParcelFileDescriptor fd = mService.getUserIcon(userHandle);
1566            if (fd != null) {
1567                try {
1568                    return BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
1569                } finally {
1570                    try {
1571                        fd.close();
1572                    } catch (IOException e) {
1573                    }
1574                }
1575            }
1576        } catch (RemoteException re) {
1577            Log.w(TAG, "Could not get the user icon ", re);
1578        }
1579        return null;
1580    }
1581
1582    /**
1583     * Returns the maximum number of users that can be created on this device. A return value
1584     * of 1 means that it is a single user device.
1585     * @hide
1586     * @return a value greater than or equal to 1
1587     */
1588    public static int getMaxSupportedUsers() {
1589        // Don't allow multiple users on certain builds
1590        if (android.os.Build.ID.startsWith("JVP")) return 1;
1591        // Svelte devices don't get multi-user.
1592        if (ActivityManager.isLowRamDeviceStatic()) return 1;
1593        return SystemProperties.getInt("fw.max_users",
1594                Resources.getSystem().getInteger(R.integer.config_multiuserMaximumUsers));
1595    }
1596
1597    /**
1598     * Returns true if the user switcher should be shown, this will be if device supports multi-user
1599     * and there are at least 2 users available that are not managed profiles.
1600     * @hide
1601     * @return true if user switcher should be shown.
1602     */
1603    public boolean isUserSwitcherEnabled() {
1604        if (!supportsMultipleUsers()) {
1605            return false;
1606        }
1607        List<UserInfo> users = getUsers(true);
1608        if (users == null) {
1609           return false;
1610        }
1611        int switchableUserCount = 0;
1612        for (UserInfo user : users) {
1613            if (user.supportsSwitchToByUser()) {
1614                ++switchableUserCount;
1615            }
1616        }
1617        final boolean guestEnabled = !mContext.getSystemService(DevicePolicyManager.class)
1618                .getGuestUserDisabled(null);
1619        return switchableUserCount > 1 || guestEnabled;
1620    }
1621
1622    /**
1623     * Returns a serial number on this device for a given userHandle. User handles can be recycled
1624     * when deleting and creating users, but serial numbers are not reused until the device is wiped.
1625     * @param userHandle
1626     * @return a serial number associated with that user, or -1 if the userHandle is not valid.
1627     * @hide
1628     */
1629    public int getUserSerialNumber(@UserIdInt int userHandle) {
1630        try {
1631            return mService.getUserSerialNumber(userHandle);
1632        } catch (RemoteException re) {
1633            Log.w(TAG, "Could not get serial number for user " + userHandle);
1634        }
1635        return -1;
1636    }
1637
1638    /**
1639     * Returns a userHandle on this device for a given user serial number. User handles can be
1640     * recycled when deleting and creating users, but serial numbers are not reused until the device
1641     * is wiped.
1642     * @param userSerialNumber
1643     * @return the userHandle associated with that user serial number, or -1 if the serial number
1644     * is not valid.
1645     * @hide
1646     */
1647    public @UserIdInt int getUserHandle(int userSerialNumber) {
1648        try {
1649            return mService.getUserHandle(userSerialNumber);
1650        } catch (RemoteException re) {
1651            Log.w(TAG, "Could not get userHandle for user " + userSerialNumber);
1652        }
1653        return -1;
1654    }
1655
1656    /**
1657     * Returns a {@code Bundle} containing any saved application restrictions for this user, for the
1658     * given package name. Only an application with this package name can call this method.
1659     *
1660     * <p>The returned {@link Bundle} consists of key-value pairs, as defined by the application,
1661     * where the types of values may be:
1662     * <ul>
1663     * <li>{@code boolean}
1664     * <li>{@code int}
1665     * <li>{@code String} or {@code String[]}
1666     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
1667     * </ul>
1668     *
1669     * @param packageName the package name of the calling application
1670     * @return a {@code Bundle} with the restrictions for that package, or {@code null} if there
1671     * are no saved restrictions.
1672     *
1673     * @see #KEY_RESTRICTIONS_PENDING
1674     */
1675    public Bundle getApplicationRestrictions(String packageName) {
1676        try {
1677            return mService.getApplicationRestrictions(packageName);
1678        } catch (RemoteException re) {
1679            Log.w(TAG, "Could not get application restrictions for package " + packageName);
1680        }
1681        return null;
1682    }
1683
1684    /**
1685     * @hide
1686     */
1687    public Bundle getApplicationRestrictions(String packageName, UserHandle user) {
1688        try {
1689            return mService.getApplicationRestrictionsForUser(packageName, user.getIdentifier());
1690        } catch (RemoteException re) {
1691            Log.w(TAG, "Could not get application restrictions for user " + user.getIdentifier());
1692        }
1693        return null;
1694    }
1695
1696    /**
1697     * @hide
1698     */
1699    public void setApplicationRestrictions(String packageName, Bundle restrictions,
1700            UserHandle user) {
1701        try {
1702            mService.setApplicationRestrictions(packageName, restrictions, user.getIdentifier());
1703        } catch (RemoteException re) {
1704            Log.w(TAG, "Could not set application restrictions for user " + user.getIdentifier());
1705        }
1706    }
1707
1708    /**
1709     * Sets a new challenge PIN for restrictions. This is only for use by pre-installed
1710     * apps and requires the MANAGE_USERS permission.
1711     * @param newPin the PIN to use for challenge dialogs.
1712     * @return Returns true if the challenge PIN was set successfully.
1713     * @deprecated The restrictions PIN functionality is no longer provided by the system.
1714     * This method is preserved for backwards compatibility reasons and always returns false.
1715     */
1716    public boolean setRestrictionsChallenge(String newPin) {
1717        return false;
1718    }
1719
1720    /**
1721     * @hide
1722     * Set restrictions that should apply to any future guest user that's created.
1723     */
1724    public void setDefaultGuestRestrictions(Bundle restrictions) {
1725        try {
1726            mService.setDefaultGuestRestrictions(restrictions);
1727        } catch (RemoteException re) {
1728            Log.w(TAG, "Could not set guest restrictions");
1729        }
1730    }
1731
1732    /**
1733     * @hide
1734     * Gets the default guest restrictions.
1735     */
1736    public Bundle getDefaultGuestRestrictions() {
1737        try {
1738            return mService.getDefaultGuestRestrictions();
1739        } catch (RemoteException re) {
1740            Log.w(TAG, "Could not set guest restrictions");
1741        }
1742        return new Bundle();
1743    }
1744
1745    /**
1746     * Returns creation time of the user or of a managed profile associated with the calling user.
1747     * @param userHandle user handle of the user or a managed profile associated with the
1748     *                   calling user.
1749     * @return creation time in milliseconds since Epoch time.
1750     */
1751    public long getUserCreationTime(UserHandle userHandle) {
1752        try {
1753            return mService.getUserCreationTime(userHandle.getIdentifier());
1754        } catch (RemoteException re) {
1755            Log.w(TAG, "Could not get user creation time", re);
1756            return 0;
1757        }
1758    }
1759}
1760