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