DevicePolicyManager.java revision bc0ce990435fe02a356b3e43272f692709f633ed
1/*
2 * Copyright (C) 2010 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 */
16
17package android.app.admin;
18
19import android.annotation.IntDef;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.annotation.SdkConstant;
23import android.annotation.SdkConstant.SdkConstantType;
24import android.annotation.SystemApi;
25import android.app.Activity;
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.ActivityInfo;
31import android.content.pm.PackageManager;
32import android.content.pm.ResolveInfo;
33import android.graphics.Bitmap;
34import android.net.ProxyInfo;
35import android.net.Uri;
36import android.os.Bundle;
37import android.os.PersistableBundle;
38import android.os.Process;
39import android.os.RemoteCallback;
40import android.os.RemoteException;
41import android.os.ServiceManager;
42import android.os.UserHandle;
43import android.os.UserManager;
44import android.provider.ContactsContract.Directory;
45import android.provider.Settings;
46import android.security.Credentials;
47import android.service.restrictions.RestrictionsReceiver;
48import android.util.Log;
49
50import com.android.internal.annotations.VisibleForTesting;
51import com.android.org.conscrypt.TrustedCertificateStore;
52
53import org.xmlpull.v1.XmlPullParserException;
54
55import java.io.ByteArrayInputStream;
56import java.io.IOException;
57import java.lang.annotation.Retention;
58import java.lang.annotation.RetentionPolicy;
59import java.net.InetSocketAddress;
60import java.net.Proxy;
61import java.security.KeyFactory;
62import java.security.NoSuchAlgorithmException;
63import java.security.PrivateKey;
64import java.security.cert.Certificate;
65import java.security.cert.CertificateException;
66import java.security.cert.CertificateFactory;
67import java.security.cert.X509Certificate;
68import java.security.spec.InvalidKeySpecException;
69import java.security.spec.PKCS8EncodedKeySpec;
70import java.util.ArrayList;
71import java.util.Collections;
72import java.util.List;
73import java.util.Set;
74
75/**
76 * Public interface for managing policies enforced on a device. Most clients of this class must be
77 * registered with the system as a
78 * <a href="{@docRoot}guide/topics/admin/device-admin.html">device administrator</a>. Additionally,
79 * a device administrator may be registered as either a profile or device owner. A given method is
80 * accessible to all device administrators unless the documentation for that method specifies that
81 * it is restricted to either device or profile owners.
82 *
83 * <div class="special reference">
84 * <h3>Developer Guides</h3>
85 * <p>For more information about managing policies for device administration, read the
86 * <a href="{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a>
87 * developer guide.
88 * </div>
89 */
90public class DevicePolicyManager {
91    private static String TAG = "DevicePolicyManager";
92
93    private final Context mContext;
94    private final IDevicePolicyManager mService;
95    private final boolean mParentInstance;
96
97    private static final String REMOTE_EXCEPTION_MESSAGE =
98            "Failed to talk with device policy manager service";
99
100    private DevicePolicyManager(Context context, boolean parentInstance) {
101        this(context,
102                IDevicePolicyManager.Stub.asInterface(
103                        ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)),
104                parentInstance);
105    }
106
107    /** @hide */
108    @VisibleForTesting
109    protected DevicePolicyManager(
110            Context context, IDevicePolicyManager service, boolean parentInstance) {
111        mContext = context;
112        mService = service;
113        mParentInstance = parentInstance;
114    }
115
116    /** @hide */
117    public static DevicePolicyManager create(Context context) {
118        DevicePolicyManager me = new DevicePolicyManager(context, false);
119        return me.mService != null ? me : null;
120    }
121
122    /** @hide test will override it. */
123    @VisibleForTesting
124    protected int myUserId() {
125        return UserHandle.myUserId();
126    }
127
128    /**
129     * Activity action: Starts the provisioning flow which sets up a managed profile.
130     *
131     * <p>A managed profile allows data separation for example for the usage of a
132     * device as a personal and corporate device. The user which provisioning is started from and
133     * the managed profile share a launcher.
134     *
135     * <p>This intent will typically be sent by a mobile device management application (MDM).
136     * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
137     * control over the profile.
138     *
139     * <p>It is possible to check if provisioning is allowed or not by querying the method
140     * {@link #isProvisioningAllowed(String)}.
141     *
142     * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
143     * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
144     * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
145     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
146     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
147     *
148     * <p> The intent may also contain the following extras:
149     * <ul>
150     * <li> {@link #EXTRA_PROVISIONING_LOGO_URI}, optional </li>
151     * <li> {@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional </li>
152     * </ul>
153     *
154     * <p> When managed provisioning has completed, broadcasts are sent to the application specified
155     * in the provisioning intent. The
156     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
157     * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
158     * the primary profile.
159     *
160     * <p> If provisioning fails, the managedProfile is removed so the device returns to its
161     * previous state.
162     *
163     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
164     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
165     * the provisioning flow was successful, although this doesn't guarantee the full flow will
166     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
167     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
168     */
169    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
170    public static final String ACTION_PROVISION_MANAGED_PROFILE
171        = "android.app.action.PROVISION_MANAGED_PROFILE";
172
173    /**
174     * @hide
175     * Activity action: Starts the provisioning flow which sets up a managed user.
176     *
177     * <p>This intent will typically be sent by a mobile device management application (MDM).
178     * Provisioning configures the user as managed user and sets the MDM as the profile
179     * owner who has full control over the user. Provisioning can only happen before user setup has
180     * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
181     * allowed.
182     *
183     * <p>This intent should contain the extra
184     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}.
185     *
186     * <p> If provisioning fails, the device returns to its previous state.
187     *
188     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
189     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
190     * the provisioning flow was successful, although this doesn't guarantee the full flow will
191     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
192     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
193     */
194    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
195    public static final String ACTION_PROVISION_MANAGED_USER
196        = "android.app.action.PROVISION_MANAGED_USER";
197
198    /**
199     * Activity action: Starts the provisioning flow which sets up a managed device.
200     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
201     *
202     * <p> During device owner provisioning a device admin app is set as the owner of the device.
203     * A device owner has full control over the device. The device owner can not be modified by the
204     * user.
205     *
206     * <p> A typical use case would be a device that is owned by a company, but used by either an
207     * employee or client.
208     *
209     * <p> An intent with this action can be sent only on an unprovisioned device.
210     * It is possible to check if provisioning is allowed or not by querying the method
211     * {@link #isProvisioningAllowed(String)}.
212     *
213     * <p>The intent contains the following extras:
214     * <ul>
215     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
216     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
217     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
218     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
219     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
220     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
221     * </ul>
222     *
223     * <p> When device owner provisioning has completed, an intent of the type
224     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
225     * device owner.
226     *
227     * <p> If provisioning fails, the device is factory reset.
228     *
229     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
230     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
231     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
232     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
233     */
234    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
235    public static final String ACTION_PROVISION_MANAGED_DEVICE
236        = "android.app.action.PROVISION_MANAGED_DEVICE";
237
238    /**
239     * Activity action: Starts the provisioning flow which sets up a managed device.
240     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
241     *
242     * <p>NOTE: This is only supported on split system user devices, and puts the device into a
243     * management state that is distinct from that reached by
244     * {@link #ACTION_PROVISION_MANAGED_DEVICE} - specifically the device owner runs on the system
245     * user, and only has control over device-wide policies, not individual users and their data.
246     * The primary benefit is that multiple non-system users are supported when provisioning using
247     * this form of device management.
248     *
249     * <p> During device owner provisioning a device admin app is set as the owner of the device.
250     * A device owner has full control over the device. The device owner can not be modified by the
251     * user.
252     *
253     * <p> A typical use case would be a device that is owned by a company, but used by either an
254     * employee or client.
255     *
256     * <p> An intent with this action can be sent only on an unprovisioned device.
257     * It is possible to check if provisioning is allowed or not by querying the method
258     * {@link #isProvisioningAllowed(String)}.
259     *
260     * <p>The intent contains the following extras:
261     * <ul>
262     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
263     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
264     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
265     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
266     * </ul>
267     *
268     * <p> When device owner provisioning has completed, an intent of the type
269     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
270     * device owner.
271     *
272     * <p> If provisioning fails, the device is factory reset.
273     *
274     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
275     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
276     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
277     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
278     *
279     * @hide
280     */
281    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
282    public static final String ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE
283        = "android.app.action.PROVISION_MANAGED_SHAREABLE_DEVICE";
284
285    /**
286     * Activity action: Finalizes management provisioning, should be used after user-setup
287     * has been completed and {@link #getUserProvisioningState()} returns one of:
288     * <ul>
289     * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
290     * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
291     * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
292     * </ul>
293     *
294     * @hide
295     */
296    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
297    public static final String ACTION_PROVISION_FINALIZATION
298            = "android.app.action.PROVISION_FINALIZATION";
299
300    /**
301     * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
302     * allows a mobile device management application or NFC programmer application which starts
303     * managed provisioning to pass data to the management application instance after provisioning.
304     * <p>
305     * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
306     * sends the intent to pass data to itself on the newly created profile.
307     * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
308     * instance of the app on the primary user.
309     * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
310     * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
311     * message should contain a stringified {@link java.util.Properties} instance, whose string
312     * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
313     * management application after provisioning.
314     *
315     * <p>
316     * In both cases the application receives the data in
317     * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
318     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
319     * during the managed provisioning.
320     */
321    public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
322            "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
323
324    /**
325     * A String extra holding the package name of the mobile device management application that
326     * will be set as the profile owner or device owner.
327     *
328     * <p>If an application starts provisioning directly via an intent with action
329     * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
330     * application that started provisioning. The package will be set as profile owner in that case.
331     *
332     * <p>This package is set as device owner when device owner provisioning is started by an NFC
333     * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
334     *
335     * <p> When this extra is set, the application must have exactly one device admin receiver.
336     * This receiver will be set as the profile or device owner and active admin.
337
338     * @see DeviceAdminReceiver
339     * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
340     * supported, but only if there is only one device admin receiver in the package that requires
341     * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
342     */
343    @Deprecated
344    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
345        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
346
347    /**
348     * A ComponentName extra indicating the device admin receiver of the mobile device management
349     * application that will be set as the profile owner or device owner and active admin.
350     *
351     * <p>If an application starts provisioning directly via an intent with action
352     * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
353     * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
354     * component has to match the package name of the application that started provisioning.
355     *
356     * <p>This component is set as device owner and active admin when device owner provisioning is
357     * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
358     * message containing an NFC record with MIME type
359     * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name should be
360     * flattened to a string, via {@link ComponentName#flattenToShortString()}.
361     *
362     * @see DeviceAdminReceiver
363     */
364    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
365        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
366
367    /**
368     * An {@link android.accounts.Account} extra holding the account to migrate during managed
369     * profile provisioning. If the account supplied is present in the primary user, it will be
370     * copied, along with its credentials to the managed profile and removed from the primary user.
371     *
372     * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}.
373     */
374
375    public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
376        = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
377
378    /**
379     * A String extra that, holds the email address of the account which a managed profile is
380     * created for. Used with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
381     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}.
382     *
383     * <p> This extra is part of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}.
384     *
385     * <p> If the {@link #ACTION_PROVISION_MANAGED_PROFILE} intent that starts managed provisioning
386     * contains this extra, it is forwarded in the
387     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} intent to the mobile
388     * device management application that was set as the profile owner during provisioning.
389     * It is usually used to avoid that the user has to enter their email address twice.
390     */
391    public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
392        = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
393
394    /**
395     * A integer extra indicating the predominant color to show during the provisioning.
396     * Refer to {@link android.graphics.Color} for how the color is represented.
397     *
398     * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
399     * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
400     */
401    public static final String EXTRA_PROVISIONING_MAIN_COLOR =
402             "android.app.extra.PROVISIONING_MAIN_COLOR";
403
404    /**
405     * A Boolean extra that can be used by the mobile device management application to skip the
406     * disabling of system apps during provisioning when set to {@code true}.
407     *
408     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
409     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
410     */
411    public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
412            "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
413
414    /**
415     * A String extra holding the time zone {@link android.app.AlarmManager} that the device
416     * will be set to.
417     *
418     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
419     * provisioning via an NFC bump.
420     */
421    public static final String EXTRA_PROVISIONING_TIME_ZONE
422        = "android.app.extra.PROVISIONING_TIME_ZONE";
423
424    /**
425     * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
426     * {@link android.app.AlarmManager}.
427     *
428     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
429     * provisioning via an NFC bump.
430     */
431    public static final String EXTRA_PROVISIONING_LOCAL_TIME
432        = "android.app.extra.PROVISIONING_LOCAL_TIME";
433
434    /**
435     * A String extra holding the {@link java.util.Locale} that the device will be set to.
436     * Format: xx_yy, where xx is the language code, and yy the country code.
437     *
438     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
439     * provisioning via an NFC bump.
440     */
441    public static final String EXTRA_PROVISIONING_LOCALE
442        = "android.app.extra.PROVISIONING_LOCALE";
443
444    /**
445     * A String extra holding the ssid of the wifi network that should be used during nfc device
446     * owner provisioning for downloading the mobile device management application.
447     *
448     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
449     * provisioning via an NFC bump.
450     */
451    public static final String EXTRA_PROVISIONING_WIFI_SSID
452        = "android.app.extra.PROVISIONING_WIFI_SSID";
453
454    /**
455     * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
456     * is hidden or not.
457     *
458     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
459     * provisioning via an NFC bump.
460     */
461    public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
462        = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
463
464    /**
465     * A String extra indicating the security type of the wifi network in
466     * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA} or
467     * {@code WEP}.
468     *
469     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
470     * provisioning via an NFC bump.
471     */
472    public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
473        = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
474
475    /**
476     * A String extra holding the password of the wifi network in
477     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
478     *
479     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
480     * provisioning via an NFC bump.
481     */
482    public static final String EXTRA_PROVISIONING_WIFI_PASSWORD
483        = "android.app.extra.PROVISIONING_WIFI_PASSWORD";
484
485    /**
486     * A String extra holding the proxy host for the wifi network in
487     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
488     *
489     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
490     * provisioning via an NFC bump.
491     */
492    public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
493        = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
494
495    /**
496     * An int extra holding the proxy port for the wifi network in
497     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
498     *
499     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
500     * provisioning via an NFC bump.
501     */
502    public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
503        = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
504
505    /**
506     * A String extra holding the proxy bypass for the wifi network in
507     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
508     *
509     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
510     * provisioning via an NFC bump.
511     */
512    public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
513        = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
514
515    /**
516     * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
517     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
518     *
519     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
520     * provisioning via an NFC bump.
521     */
522    public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
523        = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
524
525    /**
526     * A String extra holding a url that specifies the download location of the device admin
527     * package. When not provided it is assumed that the device admin package is already installed.
528     *
529     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
530     * provisioning via an NFC bump.
531     */
532    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
533        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
534
535    /**
536     * An int extra holding a minimum required version code for the device admin package. If the
537     * device admin is already installed on the device, it will only be re-downloaded from
538     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
539     * installed package is less than this version code.
540     *
541     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
542     * provisioning via an NFC bump.
543     */
544    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
545        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
546
547    /**
548     * A String extra holding a http cookie header which should be used in the http request to the
549     * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
550     *
551     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
552     * provisioning via an NFC bump.
553     */
554    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
555        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
556
557    /**
558     * A String extra holding the URL-safe base64 encoded SHA-256 or SHA-1 hash (see notes below) of
559     * the file at download location specified in
560     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
561     *
562     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} should be
563     * present. The provided checksum should match the checksum of the file at the download
564     * location. If the checksum doesn't match an error will be shown to the user and the user will
565     * be asked to factory reset the device.
566     *
567     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
568     * provisioning via an NFC bump.
569     *
570     * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
571     * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
572     * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
573     * addition to SHA-1. Support for SHA-1 is likely to be removed in future OS releases.
574     */
575    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
576        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
577
578    /**
579     * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
580     * android package archive at the download location specified in {@link
581     * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
582     *
583     * <p>The signatures of an android package archive can be obtained using
584     * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
585     * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
586     *
587     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} should be
588     * present. The provided checksum should match the checksum of any signature of the file at
589     * the download location. If the checksum does not match an error will be shown to the user and
590     * the user will be asked to factory reset the device.
591     *
592     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
593     * provisioning via an NFC bump.
594     */
595    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
596        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
597
598    /**
599     * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
600     * has completed successfully.
601     *
602     * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
603     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
604     *
605     * <p>This intent will contain the extra {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} which
606     * corresponds to the account requested to be migrated at provisioning time, if any.
607     */
608    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
609    public static final String ACTION_MANAGED_PROFILE_PROVISIONED
610        = "android.app.action.MANAGED_PROFILE_PROVISIONED";
611
612    /**
613     * A boolean extra indicating whether device encryption can be skipped as part of Device Owner
614     * provisioning.
615     *
616     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
617     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
618     */
619    public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
620             "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
621
622    /**
623     * A {@link Uri} extra pointing to a logo image. This image will be shown during the
624     * provisioning. If this extra is not passed, a default image will be shown.
625     * <h5>The following URI schemes are accepted:</h5>
626     * <ul>
627     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
628     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
629     * </ul>
630     *
631     * <p> It is the responsability of the caller to provide an image with a reasonable
632     * pixed density for the device.
633     *
634     * <p> If a content: URI is passed, the intent should have the flag
635     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
636     * {@link android.content.ClipData} of the intent too.
637     *
638     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
639     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
640     */
641    public static final String EXTRA_PROVISIONING_LOGO_URI =
642            "android.app.extra.PROVISIONING_LOGO_URI";
643
644    /**
645     * A boolean extra indicating if user setup should be skipped, for when provisioning is started
646     * during setup-wizard.
647     *
648     * <p>If unspecified, defaults to {@code true} to match the behavior in
649     * {@link android.os.Build.VERSION_CODES#M} and earlier.
650     *
651     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or
652     * {@link #ACTION_PROVISION_MANAGED_USER}.
653     *
654     * @hide
655     */
656    public static final String EXTRA_PROVISIONING_SKIP_USER_SETUP =
657            "android.app.extra.PROVISIONING_SKIP_USER_SETUP";
658
659    /**
660     * This MIME type is used for starting the Device Owner provisioning.
661     *
662     * <p>During device owner provisioning a device admin app is set as the owner of the device.
663     * A device owner has full control over the device. The device owner can not be modified by the
664     * user and the only way of resetting the device is if the device owner app calls a factory
665     * reset.
666     *
667     * <p> A typical use case would be a device that is owned by a company, but used by either an
668     * employee or client.
669     *
670     * <p> The NFC message should be send to an unprovisioned device.
671     *
672     * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
673     * contains the following properties:
674     * <ul>
675     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
676     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
677     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
678     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
679     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
680     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
681     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
682     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
683     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
684     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
685     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
686     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
687     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
688     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
689     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
690     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from
691     * {@link android.os.Build.VERSION_CODES#M} </li></ul>
692     *
693     * <p>
694     * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
695     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
696     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
697     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
698     */
699    public static final String MIME_TYPE_PROVISIONING_NFC
700        = "application/com.android.managedprovisioning";
701
702    /**
703     * Activity action: ask the user to add a new device administrator to the system.
704     * The desired policy is the ComponentName of the policy in the
705     * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
706     * bring the user through adding the device administrator to the system (or
707     * allowing them to reject it).
708     *
709     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
710     * field to provide the user with additional explanation (in addition
711     * to your component's description) about what is being added.
712     *
713     * <p>If your administrator is already active, this will ordinarily return immediately (without
714     * user intervention).  However, if your administrator has been updated and is requesting
715     * additional uses-policy flags, the user will be presented with the new list.  New policies
716     * will not be available to the updated administrator until the user has accepted the new list.
717     */
718    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
719    public static final String ACTION_ADD_DEVICE_ADMIN
720            = "android.app.action.ADD_DEVICE_ADMIN";
721
722    /**
723     * @hide
724     * Activity action: ask the user to add a new device administrator as the profile owner
725     * for this user. Only system apps can launch this intent.
726     *
727     * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
728     * extra field. This will invoke a UI to bring the user through adding the profile owner admin
729     * to remotely control restrictions on the user.
730     *
731     * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
732     * result of whether or not the user approved the action. If approved, the result will
733     * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
734     * as a profile owner.
735     *
736     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
737     * field to provide the user with additional explanation (in addition
738     * to your component's description) about what is being added.
739     *
740     * <p>If there is already a profile owner active or the caller is not a system app, the
741     * operation will return a failure result.
742     */
743    @SystemApi
744    public static final String ACTION_SET_PROFILE_OWNER
745            = "android.app.action.SET_PROFILE_OWNER";
746
747    /**
748     * @hide
749     * Name of the profile owner admin that controls the user.
750     */
751    @SystemApi
752    public static final String EXTRA_PROFILE_OWNER_NAME
753            = "android.app.extra.PROFILE_OWNER_NAME";
754
755    /**
756     * Broadcast action: send when any policy admin changes a policy.
757     * This is generally used to find out when a new policy is in effect.
758     *
759     * @hide
760     */
761    public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
762            = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
763
764    /**
765     * Broadcast action: sent when the device owner is set or changed.
766     *
767     * This broadcast is sent only to the primary user.
768     * @see #ACTION_PROVISION_MANAGED_DEVICE
769     */
770    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
771    public static final String ACTION_DEVICE_OWNER_CHANGED
772            = "android.app.action.DEVICE_OWNER_CHANGED";
773
774    /**
775     * The ComponentName of the administrator component.
776     *
777     * @see #ACTION_ADD_DEVICE_ADMIN
778     */
779    public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
780
781    /**
782     * An optional CharSequence providing additional explanation for why the
783     * admin is being added.
784     *
785     * @see #ACTION_ADD_DEVICE_ADMIN
786     */
787    public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
788
789    /**
790     * Activity action: have the user enter a new password. This activity should
791     * be launched after using {@link #setPasswordQuality(ComponentName, int)},
792     * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
793     * enter a new password that meets the current requirements. You can use
794     * {@link #isActivePasswordSufficient()} to determine whether you need to
795     * have the user select a new password in order to meet the current
796     * constraints. Upon being resumed from this activity, you can check the new
797     * password characteristics to see if they are sufficient.
798     *
799     * If the intent is launched from within a managed profile with a profile
800     * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
801     * this will trigger entering a new password for the parent of the profile.
802     * For all other cases it will trigger entering a new password for the user
803     * or profile it is launched from.
804     */
805    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
806    public static final String ACTION_SET_NEW_PASSWORD
807            = "android.app.action.SET_NEW_PASSWORD";
808
809    /**
810     * Activity action: have the user enter a new password for the parent profile.
811     * If the intent is launched from within a managed profile, this will trigger
812     * entering a new password for the parent of the profile. In all other cases
813     * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
814     */
815    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
816    public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
817            = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
818
819    /**
820     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
821     * the parent profile to access intents sent from the managed profile.
822     * That is, when an app in the managed profile calls
823     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
824     * matching activity in the parent profile.
825     */
826    public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
827
828    /**
829     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
830     * the managed profile to access intents sent from the parent profile.
831     * That is, when an app in the parent profile calls
832     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
833     * matching activity in the managed profile.
834     */
835    public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
836
837    /**
838     * Broadcast action: notify that a new local system update policy has been set by the device
839     * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
840     */
841    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
842    public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
843            = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
844
845    /**
846     * Permission policy to prompt user for new permission requests for runtime permissions.
847     * Already granted or denied permissions are not affected by this.
848     */
849    public static final int PERMISSION_POLICY_PROMPT = 0;
850
851    /**
852     * Permission policy to always grant new permission requests for runtime permissions.
853     * Already granted or denied permissions are not affected by this.
854     */
855    public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
856
857    /**
858     * Permission policy to always deny new permission requests for runtime permissions.
859     * Already granted or denied permissions are not affected by this.
860     */
861    public static final int PERMISSION_POLICY_AUTO_DENY = 2;
862
863    /**
864     * Runtime permission state: The user can manage the permission
865     * through the UI.
866     */
867    public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
868
869    /**
870     * Runtime permission state: The permission is granted to the app
871     * and the user cannot manage the permission through the UI.
872     */
873    public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
874
875    /**
876     * Runtime permission state: The permission is denied to the app
877     * and the user cannot manage the permission through the UI.
878     */
879    public static final int PERMISSION_GRANT_STATE_DENIED = 2;
880
881    /**
882     * No management for current user in-effect. This is the default.
883     * @hide
884     */
885    public static final int STATE_USER_UNMANAGED = 0;
886
887    /**
888     * Management partially setup, user setup needs to be completed.
889     * @hide
890     */
891    public static final int STATE_USER_SETUP_INCOMPLETE = 1;
892
893    /**
894     * Management partially setup, user setup completed.
895     * @hide
896     */
897    public static final int STATE_USER_SETUP_COMPLETE = 2;
898
899    /**
900     * Management setup and active on current user.
901     * @hide
902     */
903    public static final int STATE_USER_SETUP_FINALIZED = 3;
904
905    /**
906     * Management partially setup on a managed profile.
907     * @hide
908     */
909    public static final int STATE_USER_PROFILE_COMPLETE = 4;
910
911    /**
912     * @hide
913     */
914    @IntDef({STATE_USER_UNMANAGED, STATE_USER_SETUP_INCOMPLETE, STATE_USER_SETUP_COMPLETE,
915            STATE_USER_SETUP_FINALIZED, STATE_USER_PROFILE_COMPLETE})
916    @Retention(RetentionPolicy.SOURCE)
917    public @interface UserProvisioningState {}
918
919    /**
920     * Return true if the given administrator component is currently
921     * active (enabled) in the system.
922     */
923    public boolean isAdminActive(@NonNull ComponentName admin) {
924        return isAdminActiveAsUser(admin, myUserId());
925    }
926
927    /**
928     * @see #isAdminActive(ComponentName)
929     * @hide
930     */
931    public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
932        if (mService != null) {
933            try {
934                return mService.isAdminActive(admin, userId);
935            } catch (RemoteException e) {
936                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
937            }
938        }
939        return false;
940    }
941    /**
942     * Return true if the given administrator component is currently being removed
943     * for the user.
944     * @hide
945     */
946    public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
947        if (mService != null) {
948            try {
949                return mService.isRemovingAdmin(admin, userId);
950            } catch (RemoteException e) {
951                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
952            }
953        }
954        return false;
955    }
956
957
958    /**
959     * Return a list of all currently active device administrators' component
960     * names.  If there are no administrators {@code null} may be
961     * returned.
962     */
963    public List<ComponentName> getActiveAdmins() {
964        return getActiveAdminsAsUser(myUserId());
965    }
966
967    /**
968     * @see #getActiveAdmins()
969     * @hide
970     */
971    public List<ComponentName> getActiveAdminsAsUser(int userId) {
972        if (mService != null) {
973            try {
974                return mService.getActiveAdmins(userId);
975            } catch (RemoteException e) {
976                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
977            }
978        }
979        return null;
980    }
981
982    /**
983     * Used by package administration code to determine if a package can be stopped
984     * or uninstalled.
985     * @hide
986     */
987    public boolean packageHasActiveAdmins(String packageName) {
988        if (mService != null) {
989            try {
990                return mService.packageHasActiveAdmins(packageName, myUserId());
991            } catch (RemoteException e) {
992                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
993            }
994        }
995        return false;
996    }
997
998    /**
999     * Remove a current administration component.  This can only be called
1000     * by the application that owns the administration component; if you
1001     * try to remove someone else's component, a security exception will be
1002     * thrown.
1003     */
1004    public void removeActiveAdmin(@NonNull ComponentName admin) {
1005        if (mService != null) {
1006            try {
1007                mService.removeActiveAdmin(admin, myUserId());
1008            } catch (RemoteException e) {
1009                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1010            }
1011        }
1012    }
1013
1014    /**
1015     * Returns true if an administrator has been granted a particular device policy.  This can
1016     * be used to check whether the administrator was activated under an earlier set of policies,
1017     * but requires additional policies after an upgrade.
1018     *
1019     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  Must be
1020     * an active administrator, or an exception will be thrown.
1021     * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
1022     */
1023    public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
1024        if (mService != null) {
1025            try {
1026                return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
1027            } catch (RemoteException e) {
1028                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1029            }
1030        }
1031        return false;
1032    }
1033
1034    /**
1035     * Returns true if the Profile Challenge is available to use for the given profile user.
1036     *
1037     * @hide
1038     */
1039    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
1040        if (mService != null) {
1041            try {
1042                return mService.isSeparateProfileChallengeAllowed(userHandle);
1043            } catch (RemoteException e) {
1044                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1045            }
1046        }
1047        return false;
1048    }
1049
1050    /**
1051     * Constant for {@link #setPasswordQuality}: the policy has no requirements
1052     * for the password.  Note that quality constants are ordered so that higher
1053     * values are more restrictive.
1054     */
1055    public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
1056
1057    /**
1058     * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
1059     * recognition technology.  This implies technologies that can recognize the identity of
1060     * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
1061     * Note that quality constants are ordered so that higher values are more restrictive.
1062     */
1063    public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
1064
1065    /**
1066     * Constant for {@link #setPasswordQuality}: the policy requires some kind
1067     * of password or pattern, but doesn't care what it is. Note that quality constants
1068     * are ordered so that higher values are more restrictive.
1069     */
1070    public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
1071
1072    /**
1073     * Constant for {@link #setPasswordQuality}: the user must have entered a
1074     * password containing at least numeric characters.  Note that quality
1075     * constants are ordered so that higher values are more restrictive.
1076     */
1077    public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
1078
1079    /**
1080     * Constant for {@link #setPasswordQuality}: the user must have entered a
1081     * password containing at least numeric characters with no repeating (4444)
1082     * or ordered (1234, 4321, 2468) sequences.  Note that quality
1083     * constants are ordered so that higher values are more restrictive.
1084     */
1085    public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
1086
1087    /**
1088     * Constant for {@link #setPasswordQuality}: the user must have entered a
1089     * password containing at least alphabetic (or other symbol) characters.
1090     * Note that quality constants are ordered so that higher values are more
1091     * restrictive.
1092     */
1093    public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
1094
1095    /**
1096     * Constant for {@link #setPasswordQuality}: the user must have entered a
1097     * password containing at least <em>both></em> numeric <em>and</em>
1098     * alphabetic (or other symbol) characters.  Note that quality constants are
1099     * ordered so that higher values are more restrictive.
1100     */
1101    public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
1102
1103    /**
1104     * Constant for {@link #setPasswordQuality}: the user must have entered a
1105     * password containing at least a letter, a numerical digit and a special
1106     * symbol, by default. With this password quality, passwords can be
1107     * restricted to contain various sets of characters, like at least an
1108     * uppercase letter, etc. These are specified using various methods,
1109     * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
1110     * that quality constants are ordered so that higher values are more
1111     * restrictive.
1112     */
1113    public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
1114
1115    /**
1116     * Constant for {@link #setPasswordQuality}: the user is not allowed to
1117     * modify password. In case this password quality is set, the password is
1118     * managed by a profile owner. The profile owner can set any password,
1119     * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
1120     * that quality constants are ordered so that higher values are more
1121     * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
1122     * the highest.
1123     * @hide
1124     */
1125    public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
1126
1127    /**
1128     * Called by an application that is administering the device to set the
1129     * password restrictions it is imposing.  After setting this, the user
1130     * will not be able to enter a new password that is not at least as
1131     * restrictive as what has been set.  Note that the current password
1132     * will remain until the user has set a new one, so the change does not
1133     * take place immediately.  To prompt the user for a new password, use
1134     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value.
1135     *
1136     * <p>Quality constants are ordered so that higher values are more restrictive;
1137     * thus the highest requested quality constant (between the policy set here,
1138     * the user's preference, and any other considerations) is the one that
1139     * is in effect.
1140     *
1141     * <p>The calling device admin must have requested
1142     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1143     * this method; if it has not, a security exception will be thrown.
1144     *
1145     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1146     * @param quality The new desired quality.  One of
1147     * {@link #PASSWORD_QUALITY_UNSPECIFIED}, {@link #PASSWORD_QUALITY_SOMETHING},
1148     * {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX},
1149     * {@link #PASSWORD_QUALITY_ALPHABETIC}, {@link #PASSWORD_QUALITY_ALPHANUMERIC}
1150     * or {@link #PASSWORD_QUALITY_COMPLEX}.
1151     */
1152    public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
1153        if (mService != null) {
1154            try {
1155                mService.setPasswordQuality(admin, quality, mParentInstance);
1156            } catch (RemoteException e) {
1157                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1158            }
1159        }
1160    }
1161
1162    /**
1163     * Retrieve the current minimum password quality for all admins of this user
1164     * and its profiles or a particular one.
1165     * @param admin The name of the admin component to check, or {@code null} to aggregate
1166     * all admins.
1167     */
1168    public int getPasswordQuality(@Nullable ComponentName admin) {
1169        return getPasswordQuality(admin, myUserId());
1170    }
1171
1172    /** @hide per-user version */
1173    public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
1174        if (mService != null) {
1175            try {
1176                return mService.getPasswordQuality(admin, userHandle, mParentInstance);
1177            } catch (RemoteException e) {
1178                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1179            }
1180        }
1181        return PASSWORD_QUALITY_UNSPECIFIED;
1182    }
1183
1184    /**
1185     * Called by an application that is administering the device to set the
1186     * minimum allowed password length.  After setting this, the user
1187     * will not be able to enter a new password that is not at least as
1188     * restrictive as what has been set.  Note that the current password
1189     * will remain until the user has set a new one, so the change does not
1190     * take place immediately.  To prompt the user for a new password, use
1191     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value.  This
1192     * constraint is only imposed if the administrator has also requested either
1193     * {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX},
1194     * {@link #PASSWORD_QUALITY_ALPHABETIC}, {@link #PASSWORD_QUALITY_ALPHANUMERIC},
1195     * or {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}.
1196     *
1197     * <p>The calling device admin must have requested
1198     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1199     * this method; if it has not, a security exception will be thrown.
1200     *
1201     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1202     * @param length The new desired minimum password length.  A value of 0
1203     * means there is no restriction.
1204     */
1205    public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
1206        if (mService != null) {
1207            try {
1208                mService.setPasswordMinimumLength(admin, length, mParentInstance);
1209            } catch (RemoteException e) {
1210                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1211            }
1212        }
1213    }
1214
1215    /**
1216     * Retrieve the current minimum password length for all admins of this
1217     * user and its profiles or a particular one.
1218     * @param admin The name of the admin component to check, or {@code null} to aggregate
1219     * all admins.
1220     */
1221    public int getPasswordMinimumLength(@Nullable ComponentName admin) {
1222        return getPasswordMinimumLength(admin, myUserId());
1223    }
1224
1225    /** @hide per-user version */
1226    public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
1227        if (mService != null) {
1228            try {
1229                return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
1230            } catch (RemoteException e) {
1231                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1232            }
1233        }
1234        return 0;
1235    }
1236
1237    /**
1238     * Called by an application that is administering the device to set the
1239     * minimum number of upper case letters required in the password. After
1240     * setting this, the user will not be able to enter a new password that is
1241     * not at least as restrictive as what has been set. Note that the current
1242     * password will remain until the user has set a new one, so the change does
1243     * not take place immediately. To prompt the user for a new password, use
1244     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1245     * constraint is only imposed if the administrator has also requested
1246     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1247     * default value is 0.
1248     * <p>
1249     * The calling device admin must have requested
1250     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1251     * this method; if it has not, a security exception will be thrown.
1252     *
1253     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1254     *            with.
1255     * @param length The new desired minimum number of upper case letters
1256     *            required in the password. A value of 0 means there is no
1257     *            restriction.
1258     */
1259    public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
1260        if (mService != null) {
1261            try {
1262                mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
1263            } catch (RemoteException e) {
1264                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1265            }
1266        }
1267    }
1268
1269    /**
1270     * Retrieve the current number of upper case letters required in the
1271     * password for all admins of this user and its profiles or a particular one.
1272     * This is the same value as set by
1273     * {#link {@link #setPasswordMinimumUpperCase(ComponentName, int)}
1274     * and only applies when the password quality is
1275     * {@link #PASSWORD_QUALITY_COMPLEX}.
1276     *
1277     * @param admin The name of the admin component to check, or {@code null} to
1278     *            aggregate all admins.
1279     * @return The minimum number of upper case letters required in the
1280     *         password.
1281     */
1282    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
1283        return getPasswordMinimumUpperCase(admin, myUserId());
1284    }
1285
1286    /** @hide per-user version */
1287    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
1288        if (mService != null) {
1289            try {
1290                return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
1291            } catch (RemoteException e) {
1292                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1293            }
1294        }
1295        return 0;
1296    }
1297
1298    /**
1299     * Called by an application that is administering the device to set the
1300     * minimum number of lower case letters required in the password. After
1301     * setting this, the user will not be able to enter a new password that is
1302     * not at least as restrictive as what has been set. Note that the current
1303     * password will remain until the user has set a new one, so the change does
1304     * not take place immediately. To prompt the user for a new password, use
1305     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1306     * constraint is only imposed if the administrator has also requested
1307     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1308     * default value is 0.
1309     * <p>
1310     * The calling device admin must have requested
1311     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1312     * this method; if it has not, a security exception will be thrown.
1313     *
1314     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1315     *            with.
1316     * @param length The new desired minimum number of lower case letters
1317     *            required in the password. A value of 0 means there is no
1318     *            restriction.
1319     */
1320    public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
1321        if (mService != null) {
1322            try {
1323                mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
1324            } catch (RemoteException e) {
1325                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1326            }
1327        }
1328    }
1329
1330    /**
1331     * Retrieve the current number of lower case letters required in the
1332     * password for all admins of this user and its profiles or a particular one.
1333     * This is the same value as set by
1334     * {#link {@link #setPasswordMinimumLowerCase(ComponentName, int)}
1335     * and only applies when the password quality is
1336     * {@link #PASSWORD_QUALITY_COMPLEX}.
1337     *
1338     * @param admin The name of the admin component to check, or {@code null} to
1339     *            aggregate all admins.
1340     * @return The minimum number of lower case letters required in the
1341     *         password.
1342     */
1343    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
1344        return getPasswordMinimumLowerCase(admin, myUserId());
1345    }
1346
1347    /** @hide per-user version */
1348    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
1349        if (mService != null) {
1350            try {
1351                return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
1352            } catch (RemoteException e) {
1353                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1354            }
1355        }
1356        return 0;
1357    }
1358
1359    /**
1360     * Called by an application that is administering the device to set the
1361     * minimum number of letters required in the password. After setting this,
1362     * the user will not be able to enter a new password that is not at least as
1363     * restrictive as what has been set. Note that the current password will
1364     * remain until the user has set a new one, so the change does not take
1365     * place immediately. To prompt the user for a new password, use
1366     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1367     * constraint is only imposed if the administrator has also requested
1368     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1369     * default value is 1.
1370     * <p>
1371     * The calling device admin must have requested
1372     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1373     * this method; if it has not, a security exception will be thrown.
1374     *
1375     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1376     *            with.
1377     * @param length The new desired minimum number of letters required in the
1378     *            password. A value of 0 means there is no restriction.
1379     */
1380    public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
1381        if (mService != null) {
1382            try {
1383                mService.setPasswordMinimumLetters(admin, length, mParentInstance);
1384            } catch (RemoteException e) {
1385                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1386            }
1387        }
1388    }
1389
1390    /**
1391     * Retrieve the current number of letters required in the password for all
1392     * admins or a particular one. This is the same value as
1393     * set by {#link {@link #setPasswordMinimumLetters(ComponentName, int)}
1394     * and only applies when the password quality is
1395     * {@link #PASSWORD_QUALITY_COMPLEX}.
1396     *
1397     * @param admin The name of the admin component to check, or {@code null} to
1398     *            aggregate all admins.
1399     * @return The minimum number of letters required in the password.
1400     */
1401    public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
1402        return getPasswordMinimumLetters(admin, myUserId());
1403    }
1404
1405    /** @hide per-user version */
1406    public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
1407        if (mService != null) {
1408            try {
1409                return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
1410            } catch (RemoteException e) {
1411                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1412            }
1413        }
1414        return 0;
1415    }
1416
1417    /**
1418     * Called by an application that is administering the device to set the
1419     * minimum number of numerical digits required in the password. After
1420     * setting this, the user will not be able to enter a new password that is
1421     * not at least as restrictive as what has been set. Note that the current
1422     * password will remain until the user has set a new one, so the change does
1423     * not take place immediately. To prompt the user for a new password, use
1424     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1425     * constraint is only imposed if the administrator has also requested
1426     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1427     * default value is 1.
1428     * <p>
1429     * The calling device admin must have requested
1430     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1431     * this method; if it has not, a security exception will be thrown.
1432     *
1433     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1434     *            with.
1435     * @param length The new desired minimum number of numerical digits required
1436     *            in the password. A value of 0 means there is no restriction.
1437     */
1438    public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
1439        if (mService != null) {
1440            try {
1441                mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
1442            } catch (RemoteException e) {
1443                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1444            }
1445        }
1446    }
1447
1448    /**
1449     * Retrieve the current number of numerical digits required in the password
1450     * for all admins of this user and its profiles or a particular one.
1451     * This is the same value as set by
1452     * {#link {@link #setPasswordMinimumNumeric(ComponentName, int)}
1453     * and only applies when the password quality is
1454     * {@link #PASSWORD_QUALITY_COMPLEX}.
1455     *
1456     * @param admin The name of the admin component to check, or {@code null} to
1457     *            aggregate all admins.
1458     * @return The minimum number of numerical digits required in the password.
1459     */
1460    public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
1461        return getPasswordMinimumNumeric(admin, myUserId());
1462    }
1463
1464    /** @hide per-user version */
1465    public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
1466        if (mService != null) {
1467            try {
1468                return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
1469            } catch (RemoteException e) {
1470                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1471            }
1472        }
1473        return 0;
1474    }
1475
1476    /**
1477     * Called by an application that is administering the device to set the
1478     * minimum number of symbols required in the password. After setting this,
1479     * the user will not be able to enter a new password that is not at least as
1480     * restrictive as what has been set. Note that the current password will
1481     * remain until the user has set a new one, so the change does not take
1482     * place immediately. To prompt the user for a new password, use
1483     * {@link #ACTION_SET_NEW_PASSWORD} after setting this value. This
1484     * constraint is only imposed if the administrator has also requested
1485     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The
1486     * default value is 1.
1487     * <p>
1488     * The calling device admin must have requested
1489     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1490     * this method; if it has not, a security exception will be thrown.
1491     *
1492     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1493     *            with.
1494     * @param length The new desired minimum number of symbols required in the
1495     *            password. A value of 0 means there is no restriction.
1496     */
1497    public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
1498        if (mService != null) {
1499            try {
1500                mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
1501            } catch (RemoteException e) {
1502                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1503            }
1504        }
1505    }
1506
1507    /**
1508     * Retrieve the current number of symbols required in the password for all
1509     * admins or a particular one. This is the same value as
1510     * set by {#link {@link #setPasswordMinimumSymbols(ComponentName, int)}
1511     * and only applies when the password quality is
1512     * {@link #PASSWORD_QUALITY_COMPLEX}.
1513     *
1514     * @param admin The name of the admin component to check, or {@code null} to
1515     *            aggregate all admins.
1516     * @return The minimum number of symbols required in the password.
1517     */
1518    public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
1519        return getPasswordMinimumSymbols(admin, myUserId());
1520    }
1521
1522    /** @hide per-user version */
1523    public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
1524        if (mService != null) {
1525            try {
1526                return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
1527            } catch (RemoteException e) {
1528                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1529            }
1530        }
1531        return 0;
1532    }
1533
1534    /**
1535     * Called by an application that is administering the device to set the
1536     * minimum number of non-letter characters (numerical digits or symbols)
1537     * required in the password. After setting this, the user will not be able
1538     * to enter a new password that is not at least as restrictive as what has
1539     * been set. Note that the current password will remain until the user has
1540     * set a new one, so the change does not take place immediately. To prompt
1541     * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} after
1542     * setting this value. This constraint is only imposed if the administrator
1543     * has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
1544     * {@link #setPasswordQuality}. The default value is 0.
1545     * <p>
1546     * The calling device admin must have requested
1547     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1548     * this method; if it has not, a security exception will be thrown.
1549     *
1550     * @param admin Which {@link DeviceAdminReceiver} this request is associated
1551     *            with.
1552     * @param length The new desired minimum number of letters required in the
1553     *            password. A value of 0 means there is no restriction.
1554     */
1555    public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
1556        if (mService != null) {
1557            try {
1558                mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
1559            } catch (RemoteException e) {
1560                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1561            }
1562        }
1563    }
1564
1565    /**
1566     * Retrieve the current number of non-letter characters required in the
1567     * password for all admins of this user and its profiles or a particular one.
1568     * This is the same value as set by
1569     * {#link {@link #setPasswordMinimumNonLetter(ComponentName, int)}
1570     * and only applies when the password quality is
1571     * {@link #PASSWORD_QUALITY_COMPLEX}.
1572     *
1573     * @param admin The name of the admin component to check, or {@code null} to
1574     *            aggregate all admins.
1575     * @return The minimum number of letters required in the password.
1576     */
1577    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
1578        return getPasswordMinimumNonLetter(admin, myUserId());
1579    }
1580
1581    /** @hide per-user version */
1582    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
1583        if (mService != null) {
1584            try {
1585                return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
1586            } catch (RemoteException e) {
1587                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1588            }
1589        }
1590        return 0;
1591    }
1592
1593  /**
1594   * Called by an application that is administering the device to set the length
1595   * of the password history. After setting this, the user will not be able to
1596   * enter a new password that is the same as any password in the history. Note
1597   * that the current password will remain until the user has set a new one, so
1598   * the change does not take place immediately. To prompt the user for a new
1599   * password, use {@link #ACTION_SET_NEW_PASSWORD} after setting this value.
1600   * This constraint is only imposed if the administrator has also requested
1601   * either {@link #PASSWORD_QUALITY_NUMERIC}, {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}
1602   * {@link #PASSWORD_QUALITY_ALPHABETIC}, or {@link #PASSWORD_QUALITY_ALPHANUMERIC}
1603   * with {@link #setPasswordQuality}.
1604   *
1605   * <p>
1606   * The calling device admin must have requested
1607   * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this
1608   * method; if it has not, a security exception will be thrown.
1609   *
1610   * @param admin Which {@link DeviceAdminReceiver} this request is associated
1611   *        with.
1612   * @param length The new desired length of password history. A value of 0
1613   *        means there is no restriction.
1614   */
1615    public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
1616        if (mService != null) {
1617            try {
1618                mService.setPasswordHistoryLength(admin, length, mParentInstance);
1619            } catch (RemoteException e) {
1620                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1621            }
1622        }
1623    }
1624
1625    /**
1626     * Called by a device admin to set the password expiration timeout. Calling this method
1627     * will restart the countdown for password expiration for the given admin, as will changing
1628     * the device password (for all admins).
1629     *
1630     * <p>The provided timeout is the time delta in ms and will be added to the current time.
1631     * For example, to have the password expire 5 days from now, timeout would be
1632     * 5 * 86400 * 1000 = 432000000 ms for timeout.
1633     *
1634     * <p>To disable password expiration, a value of 0 may be used for timeout.
1635     *
1636     * <p>The calling device admin must have requested
1637     * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this
1638     * method; if it has not, a security exception will be thrown.
1639     *
1640     * <p> Note that setting the password will automatically reset the expiration time for all
1641     * active admins. Active admins do not need to explicitly call this method in that case.
1642     *
1643     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1644     * @param timeout The limit (in ms) that a password can remain in effect. A value of 0
1645     *        means there is no restriction (unlimited).
1646     */
1647    public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
1648        if (mService != null) {
1649            try {
1650                mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
1651            } catch (RemoteException e) {
1652                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1653            }
1654        }
1655    }
1656
1657    /**
1658     * Get the password expiration timeout for the given admin. The expiration timeout is the
1659     * recurring expiration timeout provided in the call to
1660     * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
1661     * aggregate of all policy administrators if {@code admin} is null.
1662     *
1663     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
1664     * @return The timeout for the given admin or the minimum of all timeouts
1665     */
1666    public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
1667        if (mService != null) {
1668            try {
1669                return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
1670            } catch (RemoteException e) {
1671                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1672            }
1673        }
1674        return 0;
1675    }
1676
1677    /**
1678     * Get the current password expiration time for the given admin or an aggregate of
1679     * all admins of this user and its profiles if admin is null. If the password is
1680     * expired, this will return the time since the password expired as a negative number.
1681     * If admin is null, then a composite of all expiration timeouts is returned
1682     * - which will be the minimum of all timeouts.
1683     *
1684     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
1685     * @return The password expiration time, in ms.
1686     */
1687    public long getPasswordExpiration(@Nullable ComponentName admin) {
1688        if (mService != null) {
1689            try {
1690                return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
1691            } catch (RemoteException e) {
1692                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1693            }
1694        }
1695        return 0;
1696    }
1697
1698    /**
1699     * Retrieve the current password history length for all admins of this
1700     * user and its profiles or a particular one.
1701     * @param admin The name of the admin component to check, or {@code null} to aggregate
1702     * all admins.
1703     * @return The length of the password history
1704     */
1705    public int getPasswordHistoryLength(@Nullable ComponentName admin) {
1706        return getPasswordHistoryLength(admin, myUserId());
1707    }
1708
1709    /** @hide per-user version */
1710    public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
1711        if (mService != null) {
1712            try {
1713                return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
1714            } catch (RemoteException e) {
1715                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1716            }
1717        }
1718        return 0;
1719    }
1720
1721    /**
1722     * Return the maximum password length that the device supports for a
1723     * particular password quality.
1724     * @param quality The quality being interrogated.
1725     * @return Returns the maximum length that the user can enter.
1726     */
1727    public int getPasswordMaximumLength(int quality) {
1728        // Kind-of arbitrary.
1729        return 16;
1730    }
1731
1732    /**
1733     * Determine whether the current password the user has set is sufficient
1734     * to meet the policy requirements (quality, minimum length) that have been
1735     * requested by the admins of this user and its profiles that don't have a separate challenge.
1736     *
1737     * <p>The calling device admin must have requested
1738     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call
1739     * this method; if it has not, a security exception will be thrown.
1740     *
1741     * @return Returns true if the password meets the current requirements, else false.
1742     */
1743    public boolean isActivePasswordSufficient() {
1744        if (mService != null) {
1745            try {
1746                return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
1747            } catch (RemoteException e) {
1748                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1749            }
1750        }
1751        return false;
1752    }
1753
1754    /**
1755     * Determine whether the current profile password the user has set is sufficient
1756     * to meet the policy requirements (quality, minimum length) that have been
1757     * requested by the admins of the parent user and its profiles.
1758     *
1759     * @param userHandle the userId of the profile to check the password for.
1760     * @return Returns true if the password would meet the current requirements, else false.
1761     * @hide
1762     */
1763    public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
1764        if (mService != null) {
1765            try {
1766                return mService.isProfileActivePasswordSufficientForParent(userHandle);
1767            } catch (RemoteException e) {
1768                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1769            }
1770        }
1771        return false;
1772    }
1773
1774    /**
1775     * Retrieve the number of times the user has failed at entering a
1776     * password since that last successful password entry.
1777     *
1778     * <p>The calling device admin must have requested
1779     * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call
1780     * this method; if it has not, a security exception will be thrown.
1781     */
1782    public int getCurrentFailedPasswordAttempts() {
1783        if (mService != null) {
1784            try {
1785                return mService.getCurrentFailedPasswordAttempts(myUserId(), mParentInstance);
1786            } catch (RemoteException e) {
1787                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1788            }
1789        }
1790        return -1;
1791    }
1792
1793    /**
1794     * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
1795     *
1796     * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
1797     * @hide
1798     */
1799    public boolean getDoNotAskCredentialsOnBoot() {
1800        if (mService != null) {
1801            try {
1802                return mService.getDoNotAskCredentialsOnBoot();
1803            } catch (RemoteException e) {
1804                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1805            }
1806        }
1807        return false;
1808    }
1809
1810    /**
1811     * Setting this to a value greater than zero enables a built-in policy
1812     * that will perform a device wipe after too many incorrect
1813     * device-unlock passwords have been entered.  This built-in policy combines
1814     * watching for failed passwords and wiping the device, and requires
1815     * that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
1816     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
1817     *
1818     * <p>To implement any other policy (e.g. wiping data for a particular
1819     * application only, erasing or revoking credentials, or reporting the
1820     * failure to a server), you should implement
1821     * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)}
1822     * instead.  Do not use this API, because if the maximum count is reached,
1823     * the device will be wiped immediately, and your callback will not be invoked.
1824     *
1825     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1826     * @param num The number of failed password attempts at which point the
1827     * device will wipe its data.
1828     */
1829    public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
1830        if (mService != null) {
1831            try {
1832                mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
1833            } catch (RemoteException e) {
1834                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1835            }
1836        }
1837    }
1838
1839    /**
1840     * Retrieve the current maximum number of login attempts that are allowed
1841     * before the device wipes itself, for all admins of this user and its profiles
1842     * or a particular one.
1843     * @param admin The name of the admin component to check, or {@code null} to aggregate
1844     * all admins.
1845     */
1846    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
1847        return getMaximumFailedPasswordsForWipe(admin, myUserId());
1848    }
1849
1850    /** @hide per-user version */
1851    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
1852        if (mService != null) {
1853            try {
1854                return mService.getMaximumFailedPasswordsForWipe(
1855                        admin, userHandle, mParentInstance);
1856            } catch (RemoteException e) {
1857                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1858            }
1859        }
1860        return 0;
1861    }
1862
1863    /**
1864     * Returns the profile with the smallest maximum failed passwords for wipe,
1865     * for the given user. So for primary user, it might return the primary or
1866     * a managed profile. For a secondary user, it would be the same as the
1867     * user passed in.
1868     * @hide Used only by Keyguard
1869     */
1870    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
1871        if (mService != null) {
1872            try {
1873                return mService.getProfileWithMinimumFailedPasswordsForWipe(
1874                        userHandle, mParentInstance);
1875            } catch (RemoteException e) {
1876                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1877            }
1878        }
1879        return UserHandle.USER_NULL;
1880    }
1881
1882    /**
1883     * Flag for {@link #resetPassword}: don't allow other admins to change
1884     * the password again until the user has entered it.
1885     */
1886    public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
1887
1888    /**
1889     * Flag for {@link #resetPassword}: don't ask for user credentials on device boot.
1890     * If the flag is set, the device can be booted without asking for user password.
1891     * The absence of this flag does not change the current boot requirements. This flag
1892     * can be set by the device owner only. If the app is not the device owner, the flag
1893     * is ignored. Once the flag is set, it cannot be reverted back without resetting the
1894     * device to factory defaults.
1895     */
1896    public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
1897
1898    /**
1899     * Force a new device unlock password (the password needed to access the
1900     * entire device, not for individual accounts) on the user.  This takes
1901     * effect immediately.
1902     *
1903     * <p>Calling this from a managed profile that shares the password with the owner profile
1904     * will throw a security exception.
1905     *
1906     * <p><em>Note: This API has been limited as of {@link android.os.Build.VERSION_CODES#N} for
1907     * device admins that are not device owner and not profile owner.
1908     * The password can now only be changed if there is currently no password set.  Device owner
1909     * and profile owner can still do this.</em>
1910     *
1911     * <p>The given password must be sufficient for the
1912     * current password quality and length constraints as returned by
1913     * {@link #getPasswordQuality(ComponentName)} and
1914     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet
1915     * these constraints, then it will be rejected and false returned.  Note
1916     * that the password may be a stronger quality (containing alphanumeric
1917     * characters when the requested quality is only numeric), in which case
1918     * the currently active quality will be increased to match.
1919     *
1920     * <p>Calling with a null or empty password will clear any existing PIN,
1921     * pattern or password if the current password constraints allow it. <em>Note: This will not
1922     * work in {@link android.os.Build.VERSION_CODES#N} and later for device admins that are not
1923     * device owner and not profile owner.  Once set, the password cannot be changed to null or
1924     * empty, except by device owner or profile owner.</em>
1925     *
1926     * <p>The calling device admin must have requested
1927     * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call
1928     * this method; if it has not, a security exception will be thrown.
1929     *
1930     * @param password The new password for the user. Null or empty clears the password.
1931     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
1932     *              {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
1933     * @return Returns true if the password was applied, or false if it is
1934     * not acceptable for the current constraints or if the user has not been decrypted yet.
1935     */
1936    public boolean resetPassword(String password, int flags) {
1937        if (mParentInstance) {
1938            throw new SecurityException("Reset password does not work across profiles.");
1939        }
1940        if (mService != null) {
1941            try {
1942                return mService.resetPassword(password, flags);
1943            } catch (RemoteException e) {
1944                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1945            }
1946        }
1947        return false;
1948    }
1949
1950    /**
1951     * Called by an application that is administering the device to set the
1952     * maximum time for user activity until the device will lock.  This limits
1953     * the length that the user can set.  It takes effect immediately.
1954     *
1955     * <p>The calling device admin must have requested
1956     * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} to be able to call
1957     * this method; if it has not, a security exception will be thrown.
1958     *
1959     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1960     * @param timeMs The new desired maximum time to lock in milliseconds.
1961     * A value of 0 means there is no restriction.
1962     */
1963    public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
1964        if (mService != null) {
1965            try {
1966                mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
1967            } catch (RemoteException e) {
1968                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1969            }
1970        }
1971    }
1972
1973    /**
1974     * Retrieve the current maximum time to unlock for all admins of this user
1975     * and its profiles or a particular one.
1976     * @param admin The name of the admin component to check, or {@code null} to aggregate
1977     * all admins.
1978     * @return time in milliseconds for the given admin or the minimum value (strictest) of
1979     * all admins if admin is null. Returns 0 if there are no restrictions.
1980     */
1981    public long getMaximumTimeToLock(@Nullable ComponentName admin) {
1982        return getMaximumTimeToLock(admin, myUserId());
1983    }
1984
1985    /** @hide per-user version */
1986    public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
1987        if (mService != null) {
1988            try {
1989                return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
1990            } catch (RemoteException e) {
1991                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
1992            }
1993        }
1994        return 0;
1995    }
1996
1997    /**
1998     * Make the device lock immediately, as if the lock screen timeout has
1999     * expired at the point of this call.
2000     *
2001     * <p>The calling device admin must have requested
2002     * {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} to be able to call
2003     * this method; if it has not, a security exception will be thrown.
2004     */
2005    public void lockNow() {
2006        if (mService != null) {
2007            try {
2008                mService.lockNow(mParentInstance);
2009            } catch (RemoteException e) {
2010                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2011            }
2012        }
2013    }
2014
2015    /**
2016     * Flag for {@link #wipeData(int)}: also erase the device's external
2017     * storage (such as SD cards).
2018     */
2019    public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
2020
2021    /**
2022     * Flag for {@link #wipeData(int)}: also erase the factory reset protection
2023     * data.
2024     *
2025     * <p>This flag may only be set by device owner admins; if it is set by
2026     * other admins a {@link SecurityException} will be thrown.
2027     */
2028    public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
2029
2030    /**
2031     * Ask the user data be wiped.  Wiping the primary user will cause the
2032     * device to reboot, erasing all user data while next booting up.
2033     *
2034     * <p>The calling device admin must have requested
2035     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to be able to call
2036     * this method; if it has not, a security exception will be thrown.
2037     *
2038     * @param flags Bit mask of additional options: currently supported flags
2039     * are {@link #WIPE_EXTERNAL_STORAGE} and
2040     * {@link #WIPE_RESET_PROTECTION_DATA}.
2041     */
2042    public void wipeData(int flags) {
2043        if (mService != null) {
2044            try {
2045                mService.wipeData(flags);
2046            } catch (RemoteException e) {
2047                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2048            }
2049        }
2050    }
2051
2052    /**
2053     * Called by an application that is administering the device to set the
2054     * global proxy and exclusion list.
2055     * <p>
2056     * The calling device admin must have requested
2057     * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
2058     * this method; if it has not, a security exception will be thrown.
2059     * Only the first device admin can set the proxy. If a second admin attempts
2060     * to set the proxy, the {@link ComponentName} of the admin originally setting the
2061     * proxy will be returned. If successful in setting the proxy, {@code null} will
2062     * be returned.
2063     * The method can be called repeatedly by the device admin alrady setting the
2064     * proxy to update the proxy and exclusion list.
2065     *
2066     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2067     * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
2068     *            Pass Proxy.NO_PROXY to reset the proxy.
2069     * @param exclusionList a list of domains to be excluded from the global proxy.
2070     * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
2071     *            of the device admin that sets the proxy.
2072     * @hide
2073     */
2074    public ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
2075            List<String> exclusionList ) {
2076        if (proxySpec == null) {
2077            throw new NullPointerException();
2078        }
2079        if (mService != null) {
2080            try {
2081                String hostSpec;
2082                String exclSpec;
2083                if (proxySpec.equals(Proxy.NO_PROXY)) {
2084                    hostSpec = null;
2085                    exclSpec = null;
2086                } else {
2087                    if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
2088                        throw new IllegalArgumentException();
2089                    }
2090                    InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
2091                    String hostName = sa.getHostName();
2092                    int port = sa.getPort();
2093                    StringBuilder hostBuilder = new StringBuilder();
2094                    hostSpec = hostBuilder.append(hostName)
2095                        .append(":").append(Integer.toString(port)).toString();
2096                    if (exclusionList == null) {
2097                        exclSpec = "";
2098                    } else {
2099                        StringBuilder listBuilder = new StringBuilder();
2100                        boolean firstDomain = true;
2101                        for (String exclDomain : exclusionList) {
2102                            if (!firstDomain) {
2103                                listBuilder = listBuilder.append(",");
2104                            } else {
2105                                firstDomain = false;
2106                            }
2107                            listBuilder = listBuilder.append(exclDomain.trim());
2108                        }
2109                        exclSpec = listBuilder.toString();
2110                    }
2111                    if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
2112                            != android.net.Proxy.PROXY_VALID)
2113                        throw new IllegalArgumentException();
2114                }
2115                return mService.setGlobalProxy(admin, hostSpec, exclSpec);
2116            } catch (RemoteException e) {
2117                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2118            }
2119        }
2120        return null;
2121    }
2122
2123    /**
2124     * Set a network-independent global HTTP proxy.  This is not normally what you want
2125     * for typical HTTP proxies - they are generally network dependent.  However if you're
2126     * doing something unusual like general internal filtering this may be useful.  On
2127     * a private network where the proxy is not accessible, you may break HTTP using this.
2128     *
2129     * <p>This method requires the caller to be the device owner.
2130     *
2131     * <p>This proxy is only a recommendation and it is possible that some apps will ignore it.
2132     * @see ProxyInfo
2133     *
2134     * @param admin Which {@link DeviceAdminReceiver} this request is associated
2135     *            with.
2136     * @param proxyInfo The a {@link ProxyInfo} object defining the new global
2137     *        HTTP proxy.  A {@code null} value will clear the global HTTP proxy.
2138     */
2139    public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
2140            proxyInfo) {
2141        if (mService != null) {
2142            try {
2143                mService.setRecommendedGlobalProxy(admin, proxyInfo);
2144            } catch (RemoteException e) {
2145                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2146            }
2147        }
2148    }
2149
2150    /**
2151     * Returns the component name setting the global proxy.
2152     * @return ComponentName object of the device admin that set the global proxy, or {@code null}
2153     *         if no admin has set the proxy.
2154     * @hide
2155     */
2156    public ComponentName getGlobalProxyAdmin() {
2157        if (mService != null) {
2158            try {
2159                return mService.getGlobalProxyAdmin(myUserId());
2160            } catch (RemoteException e) {
2161                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2162            }
2163        }
2164        return null;
2165    }
2166
2167    /**
2168     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
2169     * indicating that encryption is not supported.
2170     */
2171    public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
2172
2173    /**
2174     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
2175     * indicating that encryption is supported, but is not currently active.
2176     */
2177    public static final int ENCRYPTION_STATUS_INACTIVE = 1;
2178
2179    /**
2180     * Result code for {@link #getStorageEncryptionStatus}:
2181     * indicating that encryption is not currently active, but is currently
2182     * being activated.  This is only reported by devices that support
2183     * encryption of data and only when the storage is currently
2184     * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
2185     * to become encrypted will never return this value.
2186     */
2187    public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
2188
2189    /**
2190     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
2191     * indicating that encryption is active.
2192     */
2193    public static final int ENCRYPTION_STATUS_ACTIVE = 3;
2194
2195    /**
2196     * Result code for {@link #getStorageEncryptionStatus}:
2197     * indicating that encryption is active, but an encryption key has not
2198     * been set by the user.
2199     */
2200    public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
2201
2202    /**
2203     * Activity action: begin the process of encrypting data on the device.  This activity should
2204     * be launched after using {@link #setStorageEncryption} to request encryption be activated.
2205     * After resuming from this activity, use {@link #getStorageEncryption}
2206     * to check encryption status.  However, on some devices this activity may never return, as
2207     * it may trigger a reboot and in some cases a complete data wipe of the device.
2208     */
2209    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2210    public static final String ACTION_START_ENCRYPTION
2211            = "android.app.action.START_ENCRYPTION";
2212
2213    /**
2214     * Widgets are enabled in keyguard
2215     */
2216    public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
2217
2218    /**
2219     * Disable all keyguard widgets. Has no effect.
2220     */
2221    public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
2222
2223    /**
2224     * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
2225     */
2226    public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
2227
2228    /**
2229     * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
2230     */
2231    public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
2232
2233    /**
2234     * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
2235     */
2236    public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
2237
2238    /**
2239     * Ignore trust agent state on secure keyguard screens
2240     * (e.g. PIN/Pattern/Password).
2241     */
2242    public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
2243
2244    /**
2245     * Disable fingerprint sensor on keyguard secure screens (e.g. PIN/Pattern/Password).
2246     */
2247    public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
2248
2249    /**
2250     * Disable all current and future keyguard customizations.
2251     */
2252    public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
2253
2254    /**
2255     * Called by an application that is administering the device to
2256     * request that the storage system be encrypted.
2257     *
2258     * <p>When multiple device administrators attempt to control device
2259     * encryption, the most secure, supported setting will always be
2260     * used.  If any device administrator requests device encryption,
2261     * it will be enabled;  Conversely, if a device administrator
2262     * attempts to disable device encryption while another
2263     * device administrator has enabled it, the call to disable will
2264     * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
2265     *
2266     * <p>This policy controls encryption of the secure (application data) storage area.  Data
2267     * written to other storage areas may or may not be encrypted, and this policy does not require
2268     * or control the encryption of any other storage areas.
2269     * There is one exception:  If {@link android.os.Environment#isExternalStorageEmulated()} is
2270     * {@code true}, then the directory returned by
2271     * {@link android.os.Environment#getExternalStorageDirectory()} must be written to disk
2272     * within the encrypted storage area.
2273     *
2274     * <p>Important Note:  On some devices, it is possible to encrypt storage without requiring
2275     * the user to create a device PIN or Password.  In this case, the storage is encrypted, but
2276     * the encryption key may not be fully secured.  For maximum security, the administrator should
2277     * also require (and check for) a pattern, PIN, or password.
2278     *
2279     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2280     * @param encrypt true to request encryption, false to release any previous request
2281     * @return the new request status (for all active admins) - will be one of
2282     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, or
2283     * {@link #ENCRYPTION_STATUS_ACTIVE}.  This is the value of the requests;  Use
2284     * {@link #getStorageEncryptionStatus()} to query the actual device state.
2285     */
2286    public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
2287        if (mService != null) {
2288            try {
2289                return mService.setStorageEncryption(admin, encrypt);
2290            } catch (RemoteException e) {
2291                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2292            }
2293        }
2294        return ENCRYPTION_STATUS_UNSUPPORTED;
2295    }
2296
2297    /**
2298     * Called by an application that is administering the device to
2299     * determine the requested setting for secure storage.
2300     *
2301     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
2302     * this will return the requested encryption setting as an aggregate of all active
2303     * administrators.
2304     * @return true if the admin(s) are requesting encryption, false if not.
2305     */
2306    public boolean getStorageEncryption(@Nullable ComponentName admin) {
2307        if (mService != null) {
2308            try {
2309                return mService.getStorageEncryption(admin, myUserId());
2310            } catch (RemoteException e) {
2311                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2312            }
2313        }
2314        return false;
2315    }
2316
2317    /**
2318     * Called by an application that is administering the device to
2319     * determine the current encryption status of the device.
2320     *
2321     * Depending on the returned status code, the caller may proceed in different
2322     * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
2323     * storage system does not support encryption.  If the
2324     * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
2325     * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
2326     * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
2327     * storage system has enabled encryption but no password is set so further action
2328     * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING} or
2329     * {@link #ENCRYPTION_STATUS_ACTIVE}, no further action is required.
2330     *
2331     * @return current status of encryption. The value will be one of
2332     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
2333     * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
2334     * or {@link #ENCRYPTION_STATUS_ACTIVE}.
2335     */
2336    public int getStorageEncryptionStatus() {
2337        return getStorageEncryptionStatus(myUserId());
2338    }
2339
2340    /** @hide per-user version */
2341    public int getStorageEncryptionStatus(int userHandle) {
2342        if (mService != null) {
2343            try {
2344                return mService.getStorageEncryptionStatus(userHandle);
2345            } catch (RemoteException e) {
2346                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2347            }
2348        }
2349        return ENCRYPTION_STATUS_UNSUPPORTED;
2350    }
2351
2352    /**
2353     * Installs the given certificate as a user CA.
2354     *
2355     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2356     *              {@code null} if calling from a delegated certificate installer.
2357     * @param certBuffer encoded form of the certificate to install.
2358     *
2359     * @return false if the certBuffer cannot be parsed or installation is
2360     *         interrupted, true otherwise.
2361     */
2362    public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
2363        if (mService != null) {
2364            try {
2365                return mService.installCaCert(admin, certBuffer);
2366            } catch (RemoteException e) {
2367                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2368            }
2369        }
2370        return false;
2371    }
2372
2373    /**
2374     * Uninstalls the given certificate from trusted user CAs, if present.
2375     *
2376     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2377     *              {@code null} if calling from a delegated certificate installer.
2378     * @param certBuffer encoded form of the certificate to remove.
2379     */
2380    public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
2381        if (mService != null) {
2382            try {
2383                final String alias = getCaCertAlias(certBuffer);
2384                mService.uninstallCaCerts(admin, new String[] {alias});
2385            } catch (CertificateException e) {
2386                Log.w(TAG, "Unable to parse certificate", e);
2387            } catch (RemoteException e) {
2388                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2389            }
2390        }
2391    }
2392
2393    /**
2394     * Returns all CA certificates that are currently trusted, excluding system CA certificates.
2395     * If a user has installed any certificates by other means than device policy these will be
2396     * included too.
2397     *
2398     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2399     *              {@code null} if calling from a delegated certificate installer.
2400     * @return a List of byte[] arrays, each encoding one user CA certificate.
2401     */
2402    public List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
2403        List<byte[]> certs = new ArrayList<byte[]>();
2404        if (mService != null) {
2405            try {
2406                mService.enforceCanManageCaCerts(admin);
2407                final TrustedCertificateStore certStore = new TrustedCertificateStore();
2408                for (String alias : certStore.userAliases()) {
2409                    try {
2410                        certs.add(certStore.getCertificate(alias).getEncoded());
2411                    } catch (CertificateException ce) {
2412                        Log.w(TAG, "Could not encode certificate: " + alias, ce);
2413                    }
2414                }
2415            } catch (RemoteException re) {
2416                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
2417            }
2418        }
2419        return certs;
2420    }
2421
2422    /**
2423     * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
2424     * means other than device policy will also be removed, except for system CA certificates.
2425     *
2426     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2427     *              {@code null} if calling from a delegated certificate installer.
2428     */
2429    public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
2430        if (mService != null) {
2431            try {
2432                mService.uninstallCaCerts(admin, new TrustedCertificateStore().userAliases()
2433                        .toArray(new String[0]));
2434            } catch (RemoteException re) {
2435                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
2436            }
2437        }
2438    }
2439
2440    /**
2441     * Returns whether this certificate is installed as a trusted CA.
2442     *
2443     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2444     *              {@code null} if calling from a delegated certificate installer.
2445     * @param certBuffer encoded form of the certificate to look up.
2446     */
2447    public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
2448        if (mService != null) {
2449            try {
2450                mService.enforceCanManageCaCerts(admin);
2451                return getCaCertAlias(certBuffer) != null;
2452            } catch (RemoteException re) {
2453                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
2454            } catch (CertificateException ce) {
2455                Log.w(TAG, "Could not parse certificate", ce);
2456            }
2457        }
2458        return false;
2459    }
2460
2461    /**
2462     * Called by a device or profile owner to install a certificate and private key pair. The
2463     * keypair will be visible to all apps within the profile.
2464     *
2465     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2466     *            {@code null} if calling from a delegated certificate installer.
2467     * @param privKey The private key to install.
2468     * @param cert The certificate to install.
2469     * @param alias The private key alias under which to install the certificate. If a certificate
2470     * with that alias already exists, it will be overwritten.
2471     * @return {@code true} if the keys were installed, {@code false} otherwise.
2472     */
2473    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
2474            @NonNull Certificate cert, @NonNull String alias) {
2475        try {
2476            final byte[] pemCert = Credentials.convertToPem(cert);
2477            final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
2478                    .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
2479            return mService.installKeyPair(admin, pkcs8Key, pemCert, alias);
2480        } catch (RemoteException e) {
2481            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2482        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
2483            Log.w(TAG, "Failed to obtain private key material", e);
2484        } catch (CertificateException | IOException e) {
2485            Log.w(TAG, "Could not pem-encode certificate", e);
2486        }
2487        return false;
2488    }
2489
2490    /**
2491     * Called by a device or profile owner to remove all user credentials installed under a given
2492     * alias.
2493     *
2494     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2495     *            {@code null} if calling from a delegated certificate installer.
2496     * @param alias The private key alias under which the certificate is installed.
2497     * @return {@code true} if the keys were both removed, {@code false} otherwise.
2498     */
2499    public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
2500        try {
2501            return mService.removeKeyPair(admin, alias);
2502        } catch (RemoteException e) {
2503            Log.w(TAG, "Failed talking with device policy service", e);
2504        }
2505        return false;
2506    }
2507
2508    /**
2509     * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
2510     * doesn't exist.
2511     */
2512    private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
2513        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
2514        final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
2515                              new ByteArrayInputStream(certBuffer));
2516        return new TrustedCertificateStore().getCertificateAlias(cert);
2517    }
2518
2519    /**
2520     * Called by a profile owner or device owner to grant access to privileged certificate
2521     * manipulation APIs to a third-party certificate installer app. Granted APIs include
2522     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
2523     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
2524     * <p>
2525     * Delegated certificate installer is a per-user state. The delegated access is persistent until
2526     * it is later cleared by calling this method with a null value or uninstallling the certificate
2527     * installer.
2528     *
2529     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2530     * @param installerPackage The package name of the certificate installer which will be given
2531     * access. If {@code null} is given the current package will be cleared.
2532     */
2533    public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
2534            installerPackage) throws SecurityException {
2535        if (mService != null) {
2536            try {
2537                mService.setCertInstallerPackage(admin, installerPackage);
2538            } catch (RemoteException e) {
2539                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2540            }
2541        }
2542    }
2543
2544    /**
2545     * Called by a profile owner or device owner to retrieve the certificate installer for the
2546     * user. null if none is set.
2547     *
2548     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2549     * @return The package name of the current delegated certificate installer, or {@code null}
2550     * if none is set.
2551     */
2552    public String getCertInstallerPackage(@NonNull ComponentName admin) throws SecurityException {
2553        if (mService != null) {
2554            try {
2555                return mService.getCertInstallerPackage(admin);
2556            } catch (RemoteException e) {
2557                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2558            }
2559        }
2560        return null;
2561    }
2562
2563    /**
2564     * Called by a device or profile owner to configure an always-on VPN connection through a
2565     * specific application for the current user.
2566     * This connection is automatically granted and persisted after a reboot.
2567     *
2568     * <p>The designated package should declare a {@link android.net.VpnService} in its
2569     *    manifest guarded by {@link android.Manifest.permission#BIND_VPN_SERVICE},
2570     *    otherwise the call will fail.
2571     *
2572     * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
2573     *                   to remove an existing always-on VPN configuration.
2574     *
2575     * @return {@code true} if the package is set as always-on VPN controller;
2576     *         {@code false} otherwise.
2577     */
2578    public boolean setAlwaysOnVpnPackage(@NonNull ComponentName admin,
2579            @Nullable String vpnPackage) {
2580        if (mService != null) {
2581            try {
2582                return mService.setAlwaysOnVpnPackage(admin, vpnPackage);
2583            } catch (RemoteException e) {
2584                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2585            }
2586        }
2587        return false;
2588    }
2589
2590    /**
2591     * Called by a device or profile owner to read the name of the package administering an
2592     * always-on VPN connection for the current user.
2593     * If there is no such package, or the always-on VPN is provided by the system instead
2594     * of by an application, {@code null} will be returned.
2595     *
2596     * @return Package name of VPN controller responsible for always-on VPN,
2597     *         or {@code null} if none is set.
2598     */
2599    public String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
2600        if (mService != null) {
2601            try {
2602                return mService.getAlwaysOnVpnPackage(admin);
2603            } catch (RemoteException e) {
2604                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2605            }
2606        }
2607        return null;
2608    }
2609
2610    /**
2611     * Called by an application that is administering the device to disable all cameras
2612     * on the device, for this user. After setting this, no applications running as this user
2613     * will be able to access any cameras on the device.
2614     *
2615     * <p>If the caller is device owner, then the restriction will be applied to all users.
2616     *
2617     * <p>The calling device admin must have requested
2618     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call
2619     * this method; if it has not, a security exception will be thrown.
2620     *
2621     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2622     * @param disabled Whether or not the camera should be disabled.
2623     */
2624    public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
2625        if (mService != null) {
2626            try {
2627                mService.setCameraDisabled(admin, disabled);
2628            } catch (RemoteException e) {
2629                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2630            }
2631        }
2632    }
2633
2634    /**
2635     * Determine whether or not the device's cameras have been disabled for this user,
2636     * either by the calling admin, if specified, or all admins.
2637     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
2638     * have disabled the camera
2639     */
2640    public boolean getCameraDisabled(@Nullable ComponentName admin) {
2641        return getCameraDisabled(admin, myUserId());
2642    }
2643
2644    /** @hide per-user version */
2645    public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
2646        if (mService != null) {
2647            try {
2648                return mService.getCameraDisabled(admin, userHandle);
2649            } catch (RemoteException e) {
2650                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2651            }
2652        }
2653        return false;
2654    }
2655
2656    /**
2657     * Called by a device owner to request a bugreport.
2658     *
2659     * <p>There must be only one user on the device, managed by the device owner.
2660     * Otherwise a security exception will be thrown.
2661     *
2662     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2663     * @return {@code true} if the bugreport collection started successfully, or {@code false}
2664     * if it wasn't triggered because a previous bugreport operation is still active
2665     * (either the bugreport is still running or waiting for the user to share or decline)
2666     */
2667    public boolean requestBugreport(@NonNull ComponentName admin) {
2668        if (mService != null) {
2669            try {
2670                return mService.requestBugreport(admin);
2671            } catch (RemoteException e) {
2672                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2673            }
2674        }
2675        return false;
2676    }
2677
2678    /**
2679     * Determine whether or not creating a guest user has been disabled for the device
2680     *
2681     * @hide
2682     */
2683    public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
2684        // Currently guest users can always be created if multi-user is enabled
2685        // TODO introduce a policy for guest user creation
2686        return false;
2687    }
2688
2689    /**
2690     * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
2691     * screen capture also prevents the content from being shown on display devices that do not have
2692     * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
2693     * secure surfaces and secure displays.
2694     *
2695     * <p>The calling device admin must be a device or profile owner. If it is not, a
2696     * security exception will be thrown.
2697     *
2698     * <p>From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also
2699     * blocks assist requests for all activities of the relevant user.
2700     *
2701     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2702     * @param disabled Whether screen capture is disabled or not.
2703     */
2704    public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
2705        if (mService != null) {
2706            try {
2707                mService.setScreenCaptureDisabled(admin, disabled);
2708            } catch (RemoteException e) {
2709                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2710            }
2711        }
2712    }
2713
2714    /**
2715     * Determine whether or not screen capture has been disabled by the calling
2716     * admin, if specified, or all admins.
2717     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
2718     * have disabled screen capture.
2719     */
2720    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
2721        return getScreenCaptureDisabled(admin, myUserId());
2722    }
2723
2724    /** @hide per-user version */
2725    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
2726        if (mService != null) {
2727            try {
2728                return mService.getScreenCaptureDisabled(admin, userHandle);
2729            } catch (RemoteException e) {
2730                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2731            }
2732        }
2733        return false;
2734    }
2735
2736    /**
2737     * Called by a device owner to set whether auto time is required. If auto time is
2738     * required the user cannot set the date and time, but has to use network date and time.
2739     *
2740     * <p>Note: if auto time is required the user can still manually set the time zone.
2741     *
2742     * <p>The calling device admin must be a device owner. If it is not, a security exception will
2743     * be thrown.
2744     *
2745     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2746     * @param required Whether auto time is set required or not.
2747     */
2748    public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
2749        if (mService != null) {
2750            try {
2751                mService.setAutoTimeRequired(admin, required);
2752            } catch (RemoteException e) {
2753                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2754            }
2755        }
2756    }
2757
2758    /**
2759     * @return true if auto time is required.
2760     */
2761    public boolean getAutoTimeRequired() {
2762        if (mService != null) {
2763            try {
2764                return mService.getAutoTimeRequired();
2765            } catch (RemoteException e) {
2766                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2767            }
2768        }
2769        return false;
2770    }
2771
2772    /**
2773     * Called by a device owner to set whether all users created on the device should be ephemeral.
2774     *
2775     * <p>The system user is exempt from this policy - it is never ephemeral.
2776     *
2777     * <p>The calling device admin must be the device owner. If it is not, a security exception will
2778     * be thrown.
2779     *
2780     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2781     * @param forceEphemeralUsers If true, all the existing users will be deleted and all
2782     *         subsequently created users will be ephemeral.
2783     * @hide
2784     */
2785    public void setForceEphemeralUsers(
2786            @NonNull ComponentName admin, boolean forceEphemeralUsers) {
2787        if (mService != null) {
2788            try {
2789                mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
2790            } catch (RemoteException e) {
2791                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2792            }
2793        }
2794    }
2795
2796    /**
2797     * @return true if all users are created ephemeral.
2798     * @hide
2799     */
2800    public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
2801        if (mService != null) {
2802            try {
2803                return mService.getForceEphemeralUsers(admin);
2804            } catch (RemoteException e) {
2805                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2806            }
2807        }
2808        return false;
2809    }
2810
2811    /**
2812     * Called by an application that is administering the device to disable keyguard customizations,
2813     * such as widgets. After setting this, keyguard features will be disabled according to the
2814     * provided feature list.
2815     *
2816     * <p>The calling device admin must have requested
2817     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call
2818     * this method; if it has not, a security exception will be thrown.
2819     *
2820     * <p>Calling this from a managed profile before version
2821     * {@link android.os.Build.VERSION_CODES#M} will throw a security exception.
2822     *
2823     * <p>From version {@link android.os.Build.VERSION_CODES#M} a profile owner can set:
2824     * <ul>
2825     * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT}
2826     *      these will affect the profile's parent user.
2827     * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} this will affect notifications
2828     * generated by applications in the managed profile.
2829     * </ul>
2830     * <p>Requests to disable other features on a managed profile will be ignored. The admin
2831     * can check which features have been disabled by calling
2832     * {@link #getKeyguardDisabledFeatures(ComponentName)}
2833     *
2834     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2835     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
2836     * {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
2837     * {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}, {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
2838     * {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
2839     * {@link #KEYGUARD_DISABLE_FEATURES_ALL}
2840     */
2841    public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
2842        if (mService != null) {
2843            try {
2844                mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
2845            } catch (RemoteException e) {
2846                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2847            }
2848        }
2849    }
2850
2851    /**
2852     * Determine whether or not features have been disabled in keyguard either by the calling
2853     * admin, if specified, or all admins.
2854     * @param admin The name of the admin component to check, or {@code null} to check whether any
2855     * admins have disabled features in keyguard.
2856     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
2857     * for a list.
2858     */
2859    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
2860        return getKeyguardDisabledFeatures(admin, myUserId());
2861    }
2862
2863    /** @hide per-user version */
2864    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
2865        if (mService != null) {
2866            try {
2867                return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
2868            } catch (RemoteException e) {
2869                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2870            }
2871        }
2872        return KEYGUARD_DISABLE_FEATURES_NONE;
2873    }
2874
2875    /**
2876     * @hide
2877     */
2878    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
2879            int userHandle) {
2880        if (mService != null) {
2881            try {
2882                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
2883            } catch (RemoteException e) {
2884                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2885            }
2886        }
2887    }
2888
2889    /**
2890     * @hide
2891     */
2892    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
2893        setActiveAdmin(policyReceiver, refreshing, myUserId());
2894    }
2895
2896    /**
2897     * Returns the DeviceAdminInfo as defined by the administrator's package info &amp; meta-data
2898     * @hide
2899     */
2900    public DeviceAdminInfo getAdminInfo(@NonNull ComponentName cn) {
2901        ActivityInfo ai;
2902        try {
2903            ai = mContext.getPackageManager().getReceiverInfo(cn,
2904                    PackageManager.GET_META_DATA);
2905        } catch (PackageManager.NameNotFoundException e) {
2906            Log.w(TAG, "Unable to retrieve device policy " + cn, e);
2907            return null;
2908        }
2909
2910        ResolveInfo ri = new ResolveInfo();
2911        ri.activityInfo = ai;
2912
2913        try {
2914            return new DeviceAdminInfo(mContext, ri);
2915        } catch (XmlPullParserException | IOException e) {
2916            Log.w(TAG, "Unable to parse device policy " + cn, e);
2917            return null;
2918        }
2919    }
2920
2921    /**
2922     * @hide
2923     */
2924    public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
2925        if (mService != null) {
2926            try {
2927                mService.getRemoveWarning(admin, result, myUserId());
2928            } catch (RemoteException e) {
2929                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2930            }
2931        }
2932    }
2933
2934    /**
2935     * @hide
2936     */
2937    public void setActivePasswordState(int quality, int length, int letters, int uppercase,
2938            int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
2939        if (mService != null) {
2940            try {
2941                mService.setActivePasswordState(quality, length, letters, uppercase, lowercase,
2942                        numbers, symbols, nonletter, userHandle);
2943            } catch (RemoteException e) {
2944                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2945            }
2946        }
2947    }
2948
2949    /**
2950     * @hide
2951     */
2952    public void reportFailedPasswordAttempt(int userHandle) {
2953        if (mService != null) {
2954            try {
2955                mService.reportFailedPasswordAttempt(userHandle);
2956            } catch (RemoteException e) {
2957                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2958            }
2959        }
2960    }
2961
2962    /**
2963     * @hide
2964     */
2965    public void reportSuccessfulPasswordAttempt(int userHandle) {
2966        if (mService != null) {
2967            try {
2968                mService.reportSuccessfulPasswordAttempt(userHandle);
2969            } catch (RemoteException e) {
2970                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2971            }
2972        }
2973    }
2974
2975    /**
2976     * Should be called when keyguard has been dismissed.
2977     * @hide
2978     */
2979    public void reportKeyguardDismissed() {
2980        if (mService != null) {
2981            try {
2982                mService.reportKeyguardDismissed();
2983            } catch (RemoteException e) {
2984                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2985            }
2986        }
2987    }
2988
2989    /**
2990     * Should be called when keyguard view has been shown to the user.
2991     * @hide
2992     */
2993    public void reportKeyguardSecured() {
2994        if (mService != null) {
2995            try {
2996                mService.reportKeyguardSecured();
2997            } catch (RemoteException e) {
2998                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
2999            }
3000        }
3001    }
3002
3003    /**
3004     * @hide
3005     * Sets the given package as the device owner.
3006     * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
3007     * @param who the component name to be registered as device owner.
3008     * @return whether the package was successfully registered as the device owner.
3009     * @throws IllegalArgumentException if the package name is null or invalid
3010     * @throws IllegalStateException If the preconditions mentioned are not met.
3011     */
3012    public boolean setDeviceOwner(ComponentName who) {
3013        return setDeviceOwner(who, null);
3014    }
3015
3016    /**
3017     * @hide
3018     */
3019    public boolean setDeviceOwner(ComponentName who, int userId)  {
3020        return setDeviceOwner(who, null, userId);
3021    }
3022
3023    /**
3024     * @hide
3025     */
3026    public boolean setDeviceOwner(ComponentName who, String ownerName) {
3027        return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
3028    }
3029
3030    /**
3031     * @hide
3032     * Sets the given package as the device owner. The package must already be installed. There
3033     * must not already be a device owner.
3034     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
3035     * this method.
3036     * Calling this after the setup phase of the primary user has completed is allowed only if
3037     * the caller is the shell uid, and there are no additional users and no accounts.
3038     * @param who the component name to be registered as device owner.
3039     * @param ownerName the human readable name of the institution that owns this device.
3040     * @param userId ID of the user on which the device owner runs.
3041     * @return whether the package was successfully registered as the device owner.
3042     * @throws IllegalArgumentException if the package name is null or invalid
3043     * @throws IllegalStateException If the preconditions mentioned are not met.
3044     */
3045    public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
3046            throws IllegalArgumentException, IllegalStateException {
3047        if (mService != null) {
3048            try {
3049                return mService.setDeviceOwner(who, ownerName, userId);
3050            } catch (RemoteException re) {
3051                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3052            }
3053        }
3054        return false;
3055    }
3056
3057    /**
3058     * Used to determine if a particular package has been registered as a Device Owner app.
3059     * A device owner app is a special device admin that cannot be deactivated by the user, once
3060     * activated as a device admin. It also cannot be uninstalled. To check whether a particular
3061     * package is currently registered as the device owner app, pass in the package name from
3062     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
3063     * admin apps that want to check whether they are also registered as the device owner app. The
3064     * exact mechanism by which a device admin app is registered as a device owner app is defined by
3065     * the setup process.
3066     * @param packageName the package name of the app, to compare with the registered device owner
3067     * app, if any.
3068     * @return whether or not the package is registered as the device owner app.
3069     */
3070    public boolean isDeviceOwnerApp(String packageName) {
3071        return isDeviceOwnerAppOnCallingUser(packageName);
3072    }
3073
3074    /**
3075     * @return true if a package is registered as device owner, only when it's running on the
3076     * calling user.
3077     *
3078     * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
3079     * @hide
3080     */
3081    public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
3082        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
3083    }
3084
3085    /**
3086     * @return true if a package is registered as device owner, even if it's running on a different
3087     * user.
3088     *
3089     * <p>Requires the MANAGE_USERS permission.
3090     *
3091     * @hide
3092     */
3093    public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
3094        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
3095    }
3096
3097    /**
3098     * @return device owner component name, only when it's running on the calling user.
3099     *
3100     * @hide
3101     */
3102    public ComponentName getDeviceOwnerComponentOnCallingUser() {
3103        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
3104    }
3105
3106    /**
3107     * @return device owner component name, even if it's running on a different user.
3108     *
3109     * <p>Requires the MANAGE_USERS permission.
3110     *
3111     * @hide
3112     */
3113    public ComponentName getDeviceOwnerComponentOnAnyUser() {
3114        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
3115    }
3116
3117    private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
3118        if (packageName == null) {
3119            return false;
3120        }
3121        final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
3122        if (deviceOwner == null) {
3123            return false;
3124        }
3125        return packageName.equals(deviceOwner.getPackageName());
3126    }
3127
3128    private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
3129        if (mService != null) {
3130            try {
3131                return mService.getDeviceOwnerComponent(callingUserOnly);
3132            } catch (RemoteException re) {
3133                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3134            }
3135        }
3136        return null;
3137    }
3138
3139    /**
3140     * @return ID of the user who runs device owner, or {@link UserHandle#USER_NULL} if there's
3141     * no device owner.
3142     *
3143     * <p>Requires the MANAGE_USERS permission.
3144     *
3145     * @hide
3146     */
3147    public int getDeviceOwnerUserId() {
3148        if (mService != null) {
3149            try {
3150                return mService.getDeviceOwnerUserId();
3151            } catch (RemoteException re) {
3152                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3153            }
3154        }
3155        return UserHandle.USER_NULL;
3156    }
3157
3158    /**
3159     * Clears the current device owner.  The caller must be the device owner.
3160     *
3161     * This function should be used cautiously as once it is called it cannot
3162     * be undone.  The device owner can only be set as a part of device setup
3163     * before setup completes.
3164     *
3165     * @param packageName The package name of the device owner.
3166     */
3167    public void clearDeviceOwnerApp(String packageName) {
3168        if (mService != null) {
3169            try {
3170                mService.clearDeviceOwner(packageName);
3171            } catch (RemoteException re) {
3172                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3173            }
3174        }
3175    }
3176
3177    /**
3178     * Returns the device owner package name, only if it's running on the calling user.
3179     *
3180     * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
3181     *
3182     * @hide
3183     */
3184    @SystemApi
3185    public String getDeviceOwner() {
3186        final ComponentName name = getDeviceOwnerComponentOnCallingUser();
3187        return name != null ? name.getPackageName() : null;
3188    }
3189
3190    /**
3191     * @return true if the device is managed by any device owner.
3192     *
3193     * <p>Requires the MANAGE_USERS permission.
3194     *
3195     * @hide
3196     */
3197    public boolean isDeviceManaged() {
3198        return getDeviceOwnerComponentOnAnyUser() != null;
3199    }
3200
3201    /**
3202     * Returns the device owner name.  Note this method *will* return the device owner
3203     * name when it's running on a different user.
3204     *
3205     * <p>Requires the MANAGE_USERS permission.
3206     *
3207     * @hide
3208     */
3209    @SystemApi
3210    public String getDeviceOwnerNameOnAnyUser() {
3211        if (mService != null) {
3212            try {
3213                return mService.getDeviceOwnerName();
3214            } catch (RemoteException re) {
3215                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3216            }
3217        }
3218        return null;
3219    }
3220
3221    /**
3222     * @hide
3223     * @deprecated Do not use
3224     * @removed
3225     */
3226    @Deprecated
3227    @SystemApi
3228    public String getDeviceInitializerApp() {
3229        return null;
3230    }
3231
3232    /**
3233     * @hide
3234     * @deprecated Do not use
3235     * @removed
3236     */
3237    @Deprecated
3238    @SystemApi
3239    public ComponentName getDeviceInitializerComponent() {
3240        return null;
3241    }
3242
3243    /**
3244     * @hide
3245     * @deprecated Use #ACTION_SET_PROFILE_OWNER
3246     * Sets the given component as an active admin and registers the package as the profile
3247     * owner for this user. The package must already be installed and there shouldn't be
3248     * an existing profile owner registered for this user. Also, this method must be called
3249     * before the user setup has been completed.
3250     * <p>
3251     * This method can only be called by system apps that hold MANAGE_USERS permission and
3252     * MANAGE_DEVICE_ADMINS permission.
3253     * @param admin The component to register as an active admin and profile owner.
3254     * @param ownerName The user-visible name of the entity that is managing this user.
3255     * @return whether the admin was successfully registered as the profile owner.
3256     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
3257     *         the user has already been set up.
3258     */
3259    @SystemApi
3260    public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
3261            throws IllegalArgumentException {
3262        if (mService != null) {
3263            try {
3264                final int myUserId = myUserId();
3265                mService.setActiveAdmin(admin, false, myUserId);
3266                return mService.setProfileOwner(admin, ownerName, myUserId);
3267            } catch (RemoteException re) {
3268                throw new IllegalArgumentException("Couldn't set profile owner.", re);
3269            }
3270        }
3271        return false;
3272    }
3273
3274    /**
3275     * Clears the active profile owner and removes all user restrictions. The caller must
3276     * be from the same package as the active profile owner for this user, otherwise a
3277     * SecurityException will be thrown.
3278     *
3279     * <p>This doesn't work for managed profile owners.
3280     *
3281     * @param admin The component to remove as the profile owner.
3282     */
3283    public void clearProfileOwner(@NonNull ComponentName admin) {
3284        if (mService != null) {
3285            try {
3286                mService.clearProfileOwner(admin);
3287            } catch (RemoteException re) {
3288                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3289            }
3290        }
3291    }
3292
3293    /**
3294     * @hide
3295     * Checks whether the user was already setup.
3296     */
3297    public boolean hasUserSetupCompleted() {
3298        if (mService != null) {
3299            try {
3300                return mService.hasUserSetupCompleted();
3301            } catch (RemoteException re) {
3302                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3303            }
3304        }
3305        return true;
3306    }
3307
3308    /**
3309     * @hide
3310     * Sets the given component as the profile owner of the given user profile. The package must
3311     * already be installed. There must not already be a profile owner for this user.
3312     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
3313     * this method.
3314     * Calling this after the setup phase of the specified user has completed is allowed only if:
3315     * - the caller is SYSTEM_UID.
3316     * - or the caller is the shell uid, and there are no accounts on the specified user.
3317     * @param admin the component name to be registered as profile owner.
3318     * @param ownerName the human readable name of the organisation associated with this DPM.
3319     * @param userHandle the userId to set the profile owner for.
3320     * @return whether the component was successfully registered as the profile owner.
3321     * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
3322     * preconditions mentioned are not met.
3323     */
3324    public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
3325            int userHandle) throws IllegalArgumentException {
3326        if (mService != null) {
3327            try {
3328                if (ownerName == null) {
3329                    ownerName = "";
3330                }
3331                return mService.setProfileOwner(admin, ownerName, userHandle);
3332            } catch (RemoteException re) {
3333                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3334                throw new IllegalArgumentException("Couldn't set profile owner.", re);
3335            }
3336        }
3337        return false;
3338    }
3339
3340    /**
3341     * Sets the device owner information to be shown on the lock screen.
3342     *
3343     * <p>If the device owner information is {@code null} or empty then the device owner info is
3344     * cleared and the user owner info is shown on the lock screen if it is set.
3345     * <p>If the device owner information contains only whitespaces then the message on the lock
3346     * screen will be blank and the user will not be allowed to change it.
3347     *
3348     * @param admin The name of the admin component to check.
3349     * @param info Device owner information which will be displayed instead of the user
3350     * owner info.
3351     * @return Whether the device owner information has been set.
3352     */
3353    public boolean setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, String info) {
3354        if (mService != null) {
3355            try {
3356                return mService.setDeviceOwnerLockScreenInfo(admin, info);
3357            } catch (RemoteException re) {
3358                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3359            }
3360        }
3361        return false;
3362    }
3363
3364    /**
3365     * @return The device owner information. If it is not set returns {@code null}.
3366     */
3367    public String getDeviceOwnerLockScreenInfo() {
3368        if (mService != null) {
3369            try {
3370                return mService.getDeviceOwnerLockScreenInfo();
3371            } catch (RemoteException re) {
3372                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3373            }
3374        }
3375        return null;
3376    }
3377
3378    /**
3379     * Called by device or profile owners for setting the package suspended for this user.
3380     * A suspended package will not be started by the package manager, its notifications will
3381     * be hidden and it will not show up in recents. The package must already be installed.
3382     *
3383     * @param admin The name of the admin component to check.
3384     * @param packageName The package name of the app to suspend or unsuspend.
3385     * @param suspended If set to {@code true} than the package will be suspended, if set to
3386     * {@code false} the package will be unsuspended.
3387     * @return boolean {@code true} if the operation was successfully performed, {@code false}
3388     * otherwise.
3389     */
3390    public boolean setPackageSuspended(@NonNull ComponentName admin, String packageName,
3391            boolean suspended) {
3392        if (mService != null) {
3393            try {
3394                return mService.setPackageSuspended(admin, packageName, suspended);
3395            } catch (RemoteException re) {
3396                Log.w(TAG, "Failed talking with device policy service", re);
3397            }
3398        }
3399        return false;
3400    }
3401
3402    /**
3403     * Called by device or profile owners to determine if a package is suspended.
3404     *
3405     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3406     * @param packageName The name of the package to retrieve the suspended status of.
3407     * @return boolean {@code true} if the package is suspended, {@code false} otherwise.
3408     */
3409    public boolean getPackageSuspended(@NonNull ComponentName admin, String packageName) {
3410        if (mService != null) {
3411            try {
3412                return mService.getPackageSuspended(admin, packageName);
3413            } catch (RemoteException e) {
3414                Log.w(TAG, "Failed talking with device policy service", e);
3415            }
3416        }
3417        return false;
3418    }
3419
3420    /**
3421     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
3422     * be used. Only the profile owner can call this.
3423     *
3424     * @see #isProfileOwnerApp
3425     *
3426     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3427     */
3428    public void setProfileEnabled(@NonNull ComponentName admin) {
3429        if (mService != null) {
3430            try {
3431                mService.setProfileEnabled(admin);
3432            } catch (RemoteException e) {
3433                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3434            }
3435        }
3436    }
3437
3438    /**
3439     * Sets the name of the profile. In the device owner case it sets the name of the user
3440     * which it is called from. Only a profile owner or device owner can call this. If this is
3441     * never called by the profile or device owner, the name will be set to default values.
3442     *
3443     * @see #isProfileOwnerApp
3444     * @see #isDeviceOwnerApp
3445     *
3446     * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
3447     * @param profileName The name of the profile.
3448     */
3449    public void setProfileName(@NonNull ComponentName admin, String profileName) {
3450        if (mService != null) {
3451            try {
3452                mService.setProfileName(admin, profileName);
3453            } catch (RemoteException e) {
3454                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3455            }
3456        }
3457    }
3458
3459    /**
3460     * Used to determine if a particular package is registered as the profile owner for the
3461     * user. A profile owner is a special device admin that has additional privileges
3462     * within the profile.
3463     *
3464     * @param packageName The package name of the app to compare with the registered profile owner.
3465     * @return Whether or not the package is registered as the profile owner.
3466     */
3467    public boolean isProfileOwnerApp(String packageName) {
3468        if (mService != null) {
3469            try {
3470                ComponentName profileOwner = mService.getProfileOwner(
3471                        Process.myUserHandle().getIdentifier());
3472                return profileOwner != null
3473                        && profileOwner.getPackageName().equals(packageName);
3474            } catch (RemoteException re) {
3475                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3476            }
3477        }
3478        return false;
3479    }
3480
3481    /**
3482     * @hide
3483     * @return the packageName of the owner of the given user profile or {@code null} if no profile
3484     * owner has been set for that user.
3485     * @throws IllegalArgumentException if the userId is invalid.
3486     */
3487    @SystemApi
3488    public ComponentName getProfileOwner() throws IllegalArgumentException {
3489        return getProfileOwnerAsUser(Process.myUserHandle().getIdentifier());
3490    }
3491
3492    /**
3493     * @see #getProfileOwner()
3494     * @hide
3495     */
3496    public ComponentName getProfileOwnerAsUser(final int userId) throws IllegalArgumentException {
3497        if (mService != null) {
3498            try {
3499                return mService.getProfileOwner(userId);
3500            } catch (RemoteException re) {
3501                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3502                throw new IllegalArgumentException(
3503                        "Requested profile owner for invalid userId", re);
3504            }
3505        }
3506        return null;
3507    }
3508
3509    /**
3510     * @hide
3511     * @return the human readable name of the organisation associated with this DPM or {@code null}
3512     *         if one is not set.
3513     * @throws IllegalArgumentException if the userId is invalid.
3514     */
3515    public String getProfileOwnerName() throws IllegalArgumentException {
3516        if (mService != null) {
3517            try {
3518                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
3519            } catch (RemoteException re) {
3520                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3521                throw new IllegalArgumentException(
3522                        "Requested profile owner for invalid userId", re);
3523            }
3524        }
3525        return null;
3526    }
3527
3528    /**
3529     * @hide
3530     * @param userId The user for whom to fetch the profile owner name, if any.
3531     * @return the human readable name of the organisation associated with this profile owner or
3532     *         null if one is not set.
3533     * @throws IllegalArgumentException if the userId is invalid.
3534     */
3535    @SystemApi
3536    public String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
3537        if (mService != null) {
3538            try {
3539                return mService.getProfileOwnerName(userId);
3540            } catch (RemoteException re) {
3541                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
3542                throw new IllegalArgumentException(
3543                        "Requested profile owner for invalid userId", re);
3544            }
3545        }
3546        return null;
3547    }
3548
3549    /**
3550     * Called by a profile owner or device owner to add a default intent handler activity for
3551     * intents that match a certain intent filter. This activity will remain the default intent
3552     * handler even if the set of potential event handlers for the intent filter changes and if
3553     * the intent preferences are reset.
3554     *
3555     * <p>The default disambiguation mechanism takes over if the activity is not installed
3556     * (anymore). When the activity is (re)installed, it is automatically reset as default
3557     * intent handler for the filter.
3558     *
3559     * <p>The calling device admin must be a profile owner or device owner. If it is not, a
3560     * security exception will be thrown.
3561     *
3562     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3563     * @param filter The IntentFilter for which a default handler is added.
3564     * @param activity The Activity that is added as default intent handler.
3565     */
3566    public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
3567            @NonNull ComponentName activity) {
3568        if (mService != null) {
3569            try {
3570                mService.addPersistentPreferredActivity(admin, filter, activity);
3571            } catch (RemoteException e) {
3572                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3573            }
3574        }
3575    }
3576
3577    /**
3578     * Called by a profile owner or device owner to remove all persistent intent handler preferences
3579     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
3580     *
3581     * <p>The calling device admin must be a profile owner. If it is not, a security
3582     * exception will be thrown.
3583     *
3584     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3585     * @param packageName The name of the package for which preferences are removed.
3586     */
3587    public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
3588            String packageName) {
3589        if (mService != null) {
3590            try {
3591                mService.clearPackagePersistentPreferredActivities(admin, packageName);
3592            } catch (RemoteException e) {
3593                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3594            }
3595        }
3596    }
3597
3598    /**
3599     * Called by a profile owner or device owner to grant permission to a package to manage
3600     * application restrictions for the calling user via {@link #setApplicationRestrictions} and
3601     * {@link #getApplicationRestrictions}.
3602     * <p>
3603     * This permission is persistent until it is later cleared by calling this method with a
3604     * {@code null} value or uninstalling the managing package.
3605     *
3606     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3607     * @param packageName The package name which will be given access to application restrictions
3608     * APIs. If {@code null} is given the current package will be cleared.
3609     */
3610    public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
3611            @Nullable String packageName) {
3612        if (mService != null) {
3613            try {
3614                mService.setApplicationRestrictionsManagingPackage(admin, packageName);
3615            } catch (RemoteException e) {
3616                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3617            }
3618        }
3619    }
3620
3621    /**
3622     * Called by a profile owner or device owner to retrieve the application restrictions managing
3623     * package for the current user, or {@code null} if none is set.
3624     *
3625     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3626     * @return The package name allowed to manage application restrictions on the current user, or
3627     * {@code null} if none is set.
3628     */
3629    public String getApplicationRestrictionsManagingPackage(@NonNull ComponentName admin) {
3630        if (mService != null) {
3631            try {
3632                return mService.getApplicationRestrictionsManagingPackage(admin);
3633            } catch (RemoteException e) {
3634                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3635            }
3636        }
3637        return null;
3638    }
3639
3640    /**
3641     * Returns {@code true} if the calling package has been granted permission via
3642     * {@link #setApplicationRestrictionsManagingPackage} to manage application
3643     * restrictions for the calling user.
3644     */
3645    public boolean isCallerApplicationRestrictionsManagingPackage() {
3646        if (mService != null) {
3647            try {
3648                return mService.isCallerApplicationRestrictionsManagingPackage();
3649            } catch (RemoteException e) {
3650                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3651            }
3652        }
3653        return false;
3654    }
3655
3656    /**
3657     * Sets the application restrictions for a given target application running in the calling user.
3658     *
3659     * <p>The caller must be a profile or device owner on that user, or the package allowed to
3660     * manage application restrictions via {@link #setApplicationRestrictionsManagingPackage};
3661     * otherwise a security exception will be thrown.
3662     *
3663     * <p>The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
3664     * <ul>
3665     * <li>{@code boolean}
3666     * <li>{@code int}
3667     * <li>{@code String} or {@code String[]}
3668     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
3669     * </ul>
3670     *
3671     * <p>If the restrictions are not available yet, but may be applied in the near future,
3672     * the caller can notify the target application of that by adding
3673     * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
3674     *
3675     * <p>The application restrictions are only made visible to the target application via
3676     * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or
3677     * device owner, and the application restrictions managing package via
3678     * {@link #getApplicationRestrictions}.
3679     *
3680     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3681     * {@code null} if called by the application restrictions managing package.
3682     * @param packageName The name of the package to update restricted settings for.
3683     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
3684     * set of active restrictions.
3685     *
3686     * @see #setApplicationRestrictionsManagingPackage
3687     * @see UserManager#KEY_RESTRICTIONS_PENDING
3688     */
3689    public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
3690            Bundle settings) {
3691        if (mService != null) {
3692            try {
3693                mService.setApplicationRestrictions(admin, packageName, settings);
3694            } catch (RemoteException e) {
3695                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3696            }
3697        }
3698    }
3699
3700    /**
3701     * Sets a list of configuration features to enable for a TrustAgent component. This is meant
3702     * to be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all
3703     * trust agents but those enabled by this function call. If flag
3704     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
3705     *
3706     * <p>The calling device admin must have requested
3707     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call
3708     * this method; if not, a security exception will be thrown.
3709     *
3710     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3711     * @param target Component name of the agent to be enabled.
3712     * @param configuration TrustAgent-specific feature bundle. If null for any admin, agent
3713     * will be strictly disabled according to the state of the
3714     *  {@link #KEYGUARD_DISABLE_TRUST_AGENTS} flag.
3715     * <p>If {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is set and options is not null for all admins,
3716     * then it's up to the TrustAgent itself to aggregate the values from all device admins.
3717     * <p>Consult documentation for the specific TrustAgent to determine legal options parameters.
3718     */
3719    public void setTrustAgentConfiguration(@NonNull ComponentName admin,
3720            @NonNull ComponentName target, PersistableBundle configuration) {
3721        if (mService != null) {
3722            try {
3723                mService.setTrustAgentConfiguration(admin, target, configuration);
3724            } catch (RemoteException e) {
3725                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3726            }
3727        }
3728    }
3729
3730    /**
3731     * Gets configuration for the given trust agent based on aggregating all calls to
3732     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
3733     * all device admins.
3734     *
3735     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
3736     * this function returns a list of configurations for all admins that declare
3737     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
3738     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
3739     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
3740     * for this {@param agent} or calls it with a null configuration, null is returned.
3741     * @param agent Which component to get enabled features for.
3742     * @return configuration for the given trust agent.
3743     */
3744    public List<PersistableBundle> getTrustAgentConfiguration(@Nullable ComponentName admin,
3745            @NonNull ComponentName agent) {
3746        return getTrustAgentConfiguration(admin, agent, myUserId());
3747    }
3748
3749    /** @hide per-user version */
3750    public List<PersistableBundle> getTrustAgentConfiguration(@Nullable ComponentName admin,
3751            @NonNull ComponentName agent, int userHandle) {
3752        if (mService != null) {
3753            try {
3754                return mService.getTrustAgentConfiguration(admin, agent, userHandle);
3755            } catch (RemoteException e) {
3756                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3757            }
3758        }
3759        return new ArrayList<PersistableBundle>(); // empty list
3760    }
3761
3762    /**
3763     * Called by a profile owner of a managed profile to set whether caller-Id information from
3764     * the managed profile will be shown in the parent profile, for incoming calls.
3765     *
3766     * <p>The calling device admin must be a profile owner. If it is not, a
3767     * security exception will be thrown.
3768     *
3769     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3770     * @param disabled If true caller-Id information in the managed profile is not displayed.
3771     */
3772    public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
3773        if (mService != null) {
3774            try {
3775                mService.setCrossProfileCallerIdDisabled(admin, disabled);
3776            } catch (RemoteException e) {
3777                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3778            }
3779        }
3780    }
3781
3782    /**
3783     * Called by a profile owner of a managed profile to determine whether or not caller-Id
3784     * information has been disabled.
3785     *
3786     * <p>The calling device admin must be a profile owner. If it is not, a
3787     * security exception will be thrown.
3788     *
3789     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3790     */
3791    public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
3792        if (mService != null) {
3793            try {
3794                return mService.getCrossProfileCallerIdDisabled(admin);
3795            } catch (RemoteException e) {
3796                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3797            }
3798        }
3799        return false;
3800    }
3801
3802    /**
3803     * Determine whether or not caller-Id information has been disabled.
3804     *
3805     * @param userHandle The user for whom to check the caller-id permission
3806     * @hide
3807     */
3808    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
3809        if (mService != null) {
3810            try {
3811                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
3812            } catch (RemoteException e) {
3813                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3814            }
3815        }
3816        return false;
3817    }
3818
3819    /**
3820     * Called by a profile owner of a managed profile to set whether contacts search from
3821     * the managed profile will be shown in the parent profile, for incoming calls.
3822     *
3823     * <p>The calling device admin must be a profile owner. If it is not, a
3824     * security exception will be thrown.
3825     *
3826     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3827     * @param disabled If true contacts search in the managed profile is not displayed.
3828     */
3829    public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
3830            boolean disabled) {
3831        if (mService != null) {
3832            try {
3833                mService.setCrossProfileContactsSearchDisabled(admin, disabled);
3834            } catch (RemoteException e) {
3835                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3836            }
3837        }
3838    }
3839
3840    /**
3841     * Called by a profile owner of a managed profile to determine whether or not contacts search
3842     * has been disabled.
3843     *
3844     * <p>The calling device admin must be a profile owner. If it is not, a
3845     * security exception will be thrown.
3846     *
3847     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3848     */
3849    public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
3850        if (mService != null) {
3851            try {
3852                return mService.getCrossProfileContactsSearchDisabled(admin);
3853            } catch (RemoteException e) {
3854                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3855            }
3856        }
3857        return false;
3858    }
3859
3860
3861    /**
3862     * Determine whether or not contacts search has been disabled.
3863     *
3864     * @param userHandle The user for whom to check the contacts search permission
3865     * @hide
3866     */
3867    public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
3868        if (mService != null) {
3869            try {
3870                return mService
3871                        .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
3872            } catch (RemoteException e) {
3873                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3874            }
3875        }
3876        return false;
3877    }
3878
3879    /**
3880     * Start Quick Contact on the managed profile for the user, if the policy allows.
3881     *
3882     * @hide
3883     */
3884    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
3885            boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
3886        if (mService != null) {
3887            try {
3888                mService.startManagedQuickContact(actualLookupKey, actualContactId,
3889                        isContactIdIgnored, directoryId, originalIntent);
3890            } catch (RemoteException e) {
3891                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3892            }
3893        }
3894    }
3895
3896    /**
3897     * Start Quick Contact on the managed profile for the user, if the policy allows.
3898     * @hide
3899     */
3900    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
3901            Intent originalIntent) {
3902        startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
3903                originalIntent);
3904    }
3905
3906    /**
3907     * Called by a profile owner of a managed profile to set whether bluetooth
3908     * devices can access enterprise contacts.
3909     * <p>
3910     * The calling device admin must be a profile owner. If it is not, a
3911     * security exception will be thrown.
3912     * <p>
3913     * This API works on managed profile only.
3914     *
3915     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3916     *            with.
3917     * @param disabled If true, bluetooth devices cannot access enterprise
3918     *            contacts.
3919     */
3920    public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
3921        if (mService != null) {
3922            try {
3923                mService.setBluetoothContactSharingDisabled(admin, disabled);
3924            } catch (RemoteException e) {
3925                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3926            }
3927        }
3928    }
3929
3930    /**
3931     * Called by a profile owner of a managed profile to determine whether or
3932     * not Bluetooth devices cannot access enterprise contacts.
3933     * <p>
3934     * The calling device admin must be a profile owner. If it is not, a
3935     * security exception will be thrown.
3936     * <p>
3937     * This API works on managed profile only.
3938     *
3939     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3940     *            with.
3941     */
3942    public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
3943        if (mService != null) {
3944            try {
3945                return mService.getBluetoothContactSharingDisabled(admin);
3946            } catch (RemoteException e) {
3947                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3948            }
3949        }
3950        return true;
3951    }
3952
3953    /**
3954     * Determine whether or not Bluetooth devices cannot access contacts.
3955     * <p>
3956     * This API works on managed profile UserHandle only.
3957     *
3958     * @param userHandle The user for whom to check the caller-id permission
3959     * @hide
3960     */
3961    public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
3962        if (mService != null) {
3963            try {
3964                return mService.getBluetoothContactSharingDisabledForUser(userHandle
3965                        .getIdentifier());
3966            } catch (RemoteException e) {
3967                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3968            }
3969        }
3970        return true;
3971    }
3972
3973    /**
3974     * Called by the profile owner of a managed profile so that some intents sent in the managed
3975     * profile can also be resolved in the parent, or vice versa.
3976     * Only activity intents are supported.
3977     *
3978     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3979     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
3980     * other profile
3981     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
3982     * {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
3983     */
3984    public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
3985        if (mService != null) {
3986            try {
3987                mService.addCrossProfileIntentFilter(admin, filter, flags);
3988            } catch (RemoteException e) {
3989                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
3990            }
3991        }
3992    }
3993
3994    /**
3995     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
3996     * that go from the managed profile to the parent, or from the parent to the managed profile.
3997     * Only removes those that have been set by the profile owner.
3998     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3999     */
4000    public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
4001        if (mService != null) {
4002            try {
4003                mService.clearCrossProfileIntentFilters(admin);
4004            } catch (RemoteException e) {
4005                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4006            }
4007        }
4008    }
4009
4010    /**
4011     * Called by a profile or device owner to set the permitted accessibility services. When
4012     * set by a device owner or profile owner the restriction applies to all profiles of the
4013     * user the device owner or profile owner is an admin for.
4014     *
4015     * By default the user can use any accessiblity service. When zero or more packages have
4016     * been added, accessiblity services that are not in the list and not part of the system
4017     * can not be enabled by the user.
4018     *
4019     * <p> Calling with a null value for the list disables the restriction so that all services
4020     * can be used, calling with an empty list only allows the builtin system's services.
4021     *
4022     * <p> System accesibility services are always available to the user the list can't modify
4023     * this.
4024     *
4025     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4026     * @param packageNames List of accessibility service package names.
4027     *
4028     * @return true if setting the restriction succeeded. It fail if there is
4029     * one or more non-system accessibility services enabled, that are not in the list.
4030     */
4031    public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
4032            List<String> packageNames) {
4033        if (mService != null) {
4034            try {
4035                return mService.setPermittedAccessibilityServices(admin, packageNames);
4036            } catch (RemoteException e) {
4037                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4038            }
4039        }
4040        return false;
4041    }
4042
4043    /**
4044     * Returns the list of permitted accessibility services set by this device or profile owner.
4045     *
4046     * <p>An empty list means no accessibility services except system services are allowed.
4047     * Null means all accessibility services are allowed.
4048     *
4049     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4050     * @return List of accessiblity service package names.
4051     */
4052    public List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
4053        if (mService != null) {
4054            try {
4055                return mService.getPermittedAccessibilityServices(admin);
4056            } catch (RemoteException e) {
4057                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4058            }
4059        }
4060        return null;
4061    }
4062
4063    /**
4064     * Returns the list of accessibility services permitted by the device or profiles
4065     * owners of this user.
4066     *
4067     * <p>Null means all accessibility services are allowed, if a non-null list is returned
4068     * it will contain the intersection of the permitted lists for any device or profile
4069     * owners that apply to this user. It will also include any system accessibility services.
4070     *
4071     * @param userId which user to check for.
4072     * @return List of accessiblity service package names.
4073     * @hide
4074     */
4075     @SystemApi
4076     public List<String> getPermittedAccessibilityServices(int userId) {
4077        if (mService != null) {
4078            try {
4079                return mService.getPermittedAccessibilityServicesForUser(userId);
4080            } catch (RemoteException e) {
4081                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4082            }
4083        }
4084        return null;
4085     }
4086
4087    /**
4088     * Called by a profile or device owner to set the permitted input methods services. When
4089     * set by a device owner or profile owner the restriction applies to all profiles of the
4090     * user the device owner or profile owner is an admin for.
4091     *
4092     * By default the user can use any input method. When zero or more packages have
4093     * been added, input method that are not in the list and not part of the system
4094     * can not be enabled by the user.
4095     *
4096     * This method will fail if it is called for a admin that is not for the foreground user
4097     * or a profile of the foreground user.
4098     *
4099     * <p> Calling with a null value for the list disables the restriction so that all input methods
4100     * can be used, calling with an empty list disables all but the system's own input methods.
4101     *
4102     * <p> System input methods are always available to the user this method can't modify this.
4103     *
4104     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4105     * @param packageNames List of input method package names.
4106     * @return true if setting the restriction succeeded. It will fail if there are
4107     *     one or more non-system input methods currently enabled that are not in
4108     *     the packageNames list.
4109     */
4110    public boolean setPermittedInputMethods(@NonNull ComponentName admin, List<String> packageNames) {
4111        if (mService != null) {
4112            try {
4113                return mService.setPermittedInputMethods(admin, packageNames);
4114            } catch (RemoteException e) {
4115                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4116            }
4117        }
4118        return false;
4119    }
4120
4121
4122    /**
4123     * Returns the list of permitted input methods set by this device or profile owner.
4124     *
4125     * <p>An empty list means no input methods except system input methods are allowed.
4126     * Null means all input methods are allowed.
4127     *
4128     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4129     * @return List of input method package names.
4130     */
4131    public List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
4132        if (mService != null) {
4133            try {
4134                return mService.getPermittedInputMethods(admin);
4135            } catch (RemoteException e) {
4136                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4137            }
4138        }
4139        return null;
4140    }
4141
4142    /**
4143     * Returns the list of input methods permitted by the device or profiles
4144     * owners of the current user.  (*Not* calling user, due to a limitation in InputMethodManager.)
4145     *
4146     * <p>Null means all input methods are allowed, if a non-null list is returned
4147     * it will contain the intersection of the permitted lists for any device or profile
4148     * owners that apply to this user. It will also include any system input methods.
4149     *
4150     * @return List of input method package names.
4151     * @hide
4152     */
4153    @SystemApi
4154    public List<String> getPermittedInputMethodsForCurrentUser() {
4155        if (mService != null) {
4156            try {
4157                return mService.getPermittedInputMethodsForCurrentUser();
4158            } catch (RemoteException e) {
4159                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4160            }
4161        }
4162        return null;
4163    }
4164
4165    /**
4166     * Called by a device owner to get the list of apps to keep around as APKs even if no user has
4167     * currently installed it.
4168     *
4169     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4170     *
4171     * @return List of package names to keep cached.
4172     * @hide
4173     */
4174    public List<String> getKeepUninstalledPackages(@NonNull ComponentName admin) {
4175        if (mService != null) {
4176            try {
4177                return mService.getKeepUninstalledPackages(admin);
4178            } catch (RemoteException e) {
4179                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4180            }
4181        }
4182        return null;
4183    }
4184
4185    /**
4186     * Called by a device owner to set a list of apps to keep around as APKs even if no user has
4187     * currently installed it.
4188     *
4189     * <p>Please note that setting this policy does not imply that specified apps will be
4190     * automatically pre-cached.</p>
4191     *
4192     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4193     * @param packageNames List of package names to keep cached.
4194     * @hide
4195     */
4196    public void setKeepUninstalledPackages(@NonNull ComponentName admin,
4197            @NonNull List<String> packageNames) {
4198        if (mService != null) {
4199            try {
4200                mService.setKeepUninstalledPackages(admin, packageNames);
4201            } catch (RemoteException e) {
4202                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4203            }
4204        }
4205    }
4206
4207    /**
4208     * Called by a device owner to create a user with the specified name. The UserHandle returned
4209     * by this method should not be persisted as user handles are recycled as users are removed and
4210     * created. If you need to persist an identifier for this user, use
4211     * {@link UserManager#getSerialNumberForUser}.
4212     *
4213     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4214     * @param name the user's name
4215     * @see UserHandle
4216     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
4217     *         user could not be created.
4218     *
4219     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
4220     */
4221    @Deprecated
4222    public UserHandle createUser(@NonNull ComponentName admin, String name) {
4223        try {
4224            return mService.createUser(admin, name);
4225        } catch (RemoteException re) {
4226            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4227        }
4228        return null;
4229    }
4230
4231    /**
4232     * Called by a device owner to create a user with the specified name. The UserHandle returned
4233     * by this method should not be persisted as user handles are recycled as users are removed and
4234     * created. If you need to persist an identifier for this user, use
4235     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
4236     * immediately.
4237     *
4238     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
4239     * as registered as an active admin on the new user.  The profile owner package will be
4240     * installed on the new user if it already is installed on the device.
4241     *
4242     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
4243     * profileOwnerComponent when onEnable is called.
4244     *
4245     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4246     * @param name the user's name
4247     * @param ownerName the human readable name of the organisation associated with this DPM.
4248     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
4249     *      the user.
4250     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
4251     *      on the new user.
4252     * @see UserHandle
4253     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
4254     *         user could not be created.
4255     *
4256     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
4257     */
4258    @Deprecated
4259    public UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
4260            String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
4261        try {
4262            return mService.createAndInitializeUser(admin, name, ownerName, profileOwnerComponent,
4263                    adminExtras);
4264        } catch (RemoteException re) {
4265            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4266        }
4267        return null;
4268    }
4269
4270    /**
4271      * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
4272      */
4273    public static final int SKIP_SETUP_WIZARD = 0x0001;
4274
4275    /**
4276     * Flag used by {@link #createAndManageUser} to specify that the user should be created
4277     * ephemeral.
4278     * @hide
4279     */
4280    public static final int MAKE_USER_EPHEMERAL = 0x0002;
4281
4282    /**
4283     * Called by a device owner to create a user with the specified name and a given component of
4284     * the calling package as profile owner. The UserHandle returned by this method should not be
4285     * persisted as user handles are recycled as users are removed and created. If you need to
4286     * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
4287     * user will not be started in the background.
4288     *
4289     * <p>admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also
4290     * a DeviceAdminReceiver in the same package as admin, and will become the profile owner and
4291     * will be registered as an active admin on the new user. The profile owner package will be
4292     * installed on the new user.
4293     *
4294     * <p>If the adminExtras are not null, they will be stored on the device until the user is
4295     * started for the first time. Then the extras will be passed to the admin when
4296     * onEnable is called.
4297     *
4298     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4299     * @param name The user's name.
4300     * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
4301     *      same package as admin, otherwise no user is created and an IllegalArgumentException is
4302     *      thrown.
4303     * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
4304     *      user.
4305     * @param flags {@link #SKIP_SETUP_WIZARD} is supported.
4306     * @see UserHandle
4307     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
4308     *         user could not be created.
4309     */
4310    public UserHandle createAndManageUser(@NonNull ComponentName admin, @NonNull String name,
4311            @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
4312            int flags) {
4313        try {
4314            return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
4315        } catch (RemoteException re) {
4316            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4317        }
4318        return null;
4319    }
4320
4321    /**
4322     * Called by a device owner to remove a user and all associated data. The primary user can
4323     * not be removed.
4324     *
4325     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4326     * @param userHandle the user to remove.
4327     * @return {@code true} if the user was removed, {@code false} otherwise.
4328     */
4329    public boolean removeUser(@NonNull ComponentName admin, UserHandle userHandle) {
4330        try {
4331            return mService.removeUser(admin, userHandle);
4332        } catch (RemoteException re) {
4333            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4334            return false;
4335        }
4336    }
4337
4338    /**
4339     * Called by a device owner to switch the specified user to the foreground.
4340     *
4341     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4342     * @param userHandle the user to switch to; null will switch to primary.
4343     * @return {@code true} if the switch was successful, {@code false} otherwise.
4344     *
4345     * @see Intent#ACTION_USER_FOREGROUND
4346     */
4347    public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
4348        try {
4349            return mService.switchUser(admin, userHandle);
4350        } catch (RemoteException re) {
4351            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4352            return false;
4353        }
4354    }
4355
4356    /**
4357     * Retrieves the application restrictions for a given target application running in the calling
4358     * user.
4359     *
4360     * <p>The caller must be a profile or device owner on that user, or the package allowed to
4361     * manage application restrictions via {@link #setApplicationRestrictionsManagingPackage};
4362     * otherwise a security exception will be thrown.
4363     *
4364     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4365     * {@code null} if called by the application restrictions managing package.
4366     * @param packageName The name of the package to fetch restricted settings of.
4367     * @return {@link Bundle} of settings corresponding to what was set last time
4368     * {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty {@link Bundle}
4369     * if no restrictions have been set.
4370     *
4371     * @see {@link #setApplicationRestrictionsManagingPackage}
4372     */
4373    public Bundle getApplicationRestrictions(@Nullable ComponentName admin, String packageName) {
4374        if (mService != null) {
4375            try {
4376                return mService.getApplicationRestrictions(admin, packageName);
4377            } catch (RemoteException e) {
4378                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4379            }
4380        }
4381        return null;
4382    }
4383
4384    /**
4385     * Called by a profile or device owner to set a user restriction specified by the key.
4386     * <p>
4387     * The calling device admin must be a profile or device owner; if it is not,
4388     * a security exception will be thrown.
4389     *
4390     * @param admin Which {@link DeviceAdminReceiver} this request is associated
4391     *            with.
4392     * @param key The key of the restriction. See the constants in
4393     *            {@link android.os.UserManager} for the list of keys.
4394     */
4395    public void addUserRestriction(@NonNull ComponentName admin, String key) {
4396        if (mService != null) {
4397            try {
4398                mService.setUserRestriction(admin, key, true);
4399            } catch (RemoteException e) {
4400                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4401            }
4402        }
4403    }
4404
4405    /**
4406     * Called by a profile or device owner to clear a user restriction specified by the key.
4407     * <p>
4408     * The calling device admin must be a profile or device owner; if it is not,
4409     * a security exception will be thrown.
4410     *
4411     * @param admin Which {@link DeviceAdminReceiver} this request is associated
4412     *            with.
4413     * @param key The key of the restriction. See the constants in
4414     *            {@link android.os.UserManager} for the list of keys.
4415     */
4416    public void clearUserRestriction(@NonNull ComponentName admin, String key) {
4417        if (mService != null) {
4418            try {
4419                mService.setUserRestriction(admin, key, false);
4420            } catch (RemoteException e) {
4421                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4422            }
4423        }
4424    }
4425
4426    /**
4427     * Called by a profile or device owner to get user restrictions set with
4428     * {@link #addUserRestriction(ComponentName, String)}.
4429     * <p>
4430     * The target user may have more restrictions set by the system or other device owner / profile
4431     * owner.  To get all the user restrictions currently set, use
4432     * {@link UserManager#getUserRestrictions()}.
4433     *
4434     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4435     * @throws SecurityException if the {@code admin} is not an active admin.
4436     */
4437    public Bundle getUserRestrictions(@NonNull ComponentName admin) {
4438        return getUserRestrictions(admin, myUserId());
4439    }
4440
4441    /** @hide per-user version */
4442    public Bundle getUserRestrictions(@NonNull ComponentName admin, int userHandle) {
4443        Bundle ret = null;
4444        if (mService != null) {
4445            try {
4446                ret = mService.getUserRestrictions(admin, userHandle);
4447            } catch (RemoteException e) {
4448                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4449            }
4450        }
4451        return ret == null ? new Bundle() : ret;
4452    }
4453
4454    /**
4455     * Called by profile or device owners to hide or unhide packages. When a package is hidden it
4456     * is unavailable for use, but the data and actual package file remain.
4457     *
4458     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4459     * @param packageName The name of the package to hide or unhide.
4460     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
4461     *                 unhidden.
4462     * @return boolean Whether the hidden setting of the package was successfully updated.
4463     */
4464    public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
4465            boolean hidden) {
4466        if (mService != null) {
4467            try {
4468                return mService.setApplicationHidden(admin, packageName, hidden);
4469            } catch (RemoteException e) {
4470                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4471            }
4472        }
4473        return false;
4474    }
4475
4476    /**
4477     * Called by profile or device owners to determine if a package is hidden.
4478     *
4479     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4480     * @param packageName The name of the package to retrieve the hidden status of.
4481     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
4482     */
4483    public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
4484        if (mService != null) {
4485            try {
4486                return mService.isApplicationHidden(admin, packageName);
4487            } catch (RemoteException e) {
4488                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4489            }
4490        }
4491        return false;
4492    }
4493
4494    /**
4495     * Called by profile or device owners to re-enable a system app that was disabled by default
4496     * when the user was initialized.
4497     *
4498     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4499     * @param packageName The package to be re-enabled in the calling profile.
4500     */
4501    public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
4502        if (mService != null) {
4503            try {
4504                mService.enableSystemApp(admin, packageName);
4505            } catch (RemoteException e) {
4506                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4507            }
4508        }
4509    }
4510
4511    /**
4512     * Called by profile or device owners to re-enable system apps by intent that were disabled
4513     * by default when the user was initialized.
4514     *
4515     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4516     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
4517     *               intent will be re-enabled in the calling profile.
4518     * @return int The number of activities that matched the intent and were installed.
4519     */
4520    public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
4521        if (mService != null) {
4522            try {
4523                return mService.enableSystemAppWithIntent(admin, intent);
4524            } catch (RemoteException e) {
4525                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4526            }
4527        }
4528        return 0;
4529    }
4530
4531    /**
4532     * Called by a device owner or profile owner to disable account management for a specific type
4533     * of account.
4534     *
4535     * <p>The calling device admin must be a device owner or profile owner. If it is not, a
4536     * security exception will be thrown.
4537     *
4538     * <p>When account management is disabled for an account type, adding or removing an account
4539     * of that type will not be possible.
4540     *
4541     * <p>From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
4542     * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
4543     * management for a specific type is disabled.
4544     *
4545     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4546     * @param accountType For which account management is disabled or enabled.
4547     * @param disabled The boolean indicating that account management will be disabled (true) or
4548     * enabled (false).
4549     */
4550    public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
4551            boolean disabled) {
4552        if (mService != null) {
4553            try {
4554                mService.setAccountManagementDisabled(admin, accountType, disabled);
4555            } catch (RemoteException e) {
4556                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4557            }
4558        }
4559    }
4560
4561    /**
4562     * Gets the array of accounts for which account management is disabled by the profile owner.
4563     *
4564     * <p> Account management can be disabled/enabled by calling
4565     * {@link #setAccountManagementDisabled}.
4566     *
4567     * @return a list of account types for which account management has been disabled.
4568     *
4569     * @see #setAccountManagementDisabled
4570     */
4571    public String[] getAccountTypesWithManagementDisabled() {
4572        return getAccountTypesWithManagementDisabledAsUser(myUserId());
4573    }
4574
4575    /**
4576     * @see #getAccountTypesWithManagementDisabled()
4577     * @hide
4578     */
4579    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
4580        if (mService != null) {
4581            try {
4582                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
4583            } catch (RemoteException e) {
4584                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4585            }
4586        }
4587
4588        return null;
4589    }
4590
4591    /**
4592     * Sets which packages may enter lock task mode.
4593     *
4594     * <p>Any packages that shares uid with an allowed package will also be allowed
4595     * to activate lock task.
4596     *
4597     * From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
4598     * package list results in locked tasks belonging to those packages to be finished.
4599     *
4600     * This function can only be called by the device owner.
4601     * @param packages The list of packages allowed to enter lock task mode
4602     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4603     *
4604     * @see Activity#startLockTask()
4605     * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
4606     * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
4607     * @see UserManager#DISALLOW_CREATE_WINDOWS
4608     */
4609    public void setLockTaskPackages(@NonNull ComponentName admin, String[] packages)
4610            throws SecurityException {
4611        if (mService != null) {
4612            try {
4613                mService.setLockTaskPackages(admin, packages);
4614            } catch (RemoteException e) {
4615                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4616            }
4617        }
4618    }
4619
4620    /**
4621     * This function returns the list of packages allowed to start the lock task mode.
4622     *
4623     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4624     * @hide
4625     */
4626    public String[] getLockTaskPackages(@NonNull ComponentName admin) {
4627        if (mService != null) {
4628            try {
4629                return mService.getLockTaskPackages(admin);
4630            } catch (RemoteException e) {
4631                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4632            }
4633        }
4634        return null;
4635    }
4636
4637    /**
4638     * This function lets the caller know whether the given component is allowed to start the
4639     * lock task mode.
4640     * @param pkg The package to check
4641     */
4642    public boolean isLockTaskPermitted(String pkg) {
4643        if (mService != null) {
4644            try {
4645                return mService.isLockTaskPermitted(pkg);
4646            } catch (RemoteException e) {
4647                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4648            }
4649        }
4650        return false;
4651    }
4652
4653    /**
4654     * Called by device owners to update {@link Settings.Global} settings. Validation that the value
4655     * of the setting is in the correct form for the setting type should be performed by the caller.
4656     * <p>The settings that can be updated with this method are:
4657     * <ul>
4658     * <li>{@link Settings.Global#ADB_ENABLED}</li>
4659     * <li>{@link Settings.Global#AUTO_TIME}</li>
4660     * <li>{@link Settings.Global#AUTO_TIME_ZONE}</li>
4661     * <li>{@link Settings.Global#DATA_ROAMING}</li>
4662     * <li>{@link Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
4663     * <li>{@link Settings.Global#WIFI_SLEEP_POLICY}</li>
4664     * <li>{@link Settings.Global#STAY_ON_WHILE_PLUGGED_IN}
4665     *   This setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards
4666     *   and can only be set if {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
4667     * <li>{@link Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li>
4668     *   This setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.
4669     *   </li>
4670     * </ul>
4671     * <p>Changing the following settings has no effect as of
4672     * {@link android.os.Build.VERSION_CODES#M}:
4673     * <ul>
4674     * <li>{@link Settings.Global#BLUETOOTH_ON}.
4675     *   Use {@link android.bluetooth.BluetoothAdapter#enable()} and
4676     *   {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
4677     * <li>{@link Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
4678     * <li>{@link Settings.Global#MODE_RINGER}.
4679     *   Use {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
4680     * <li>{@link Settings.Global#NETWORK_PREFERENCE}</li>
4681     * <li>{@link Settings.Global#WIFI_ON}.
4682     *   Use {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
4683     * </ul>
4684     *
4685     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4686     * @param setting The name of the setting to update.
4687     * @param value The value to update the setting to.
4688     */
4689    public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
4690        if (mService != null) {
4691            try {
4692                mService.setGlobalSetting(admin, setting, value);
4693            } catch (RemoteException e) {
4694                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4695            }
4696        }
4697    }
4698
4699    /**
4700     * Called by profile or device owners to update {@link Settings.Secure} settings. Validation
4701     * that the value of the setting is in the correct form for the setting type should be performed
4702     * by the caller.
4703     * <p>The settings that can be updated by a profile or device owner with this method are:
4704     * <ul>
4705     * <li>{@link Settings.Secure#DEFAULT_INPUT_METHOD}</li>
4706     * <li>{@link Settings.Secure#INSTALL_NON_MARKET_APPS}</li>
4707     * <li>{@link Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
4708     * </ul>
4709     * <p>A device owner can additionally update the following settings:
4710     * <ul>
4711     * <li>{@link Settings.Secure#LOCATION_MODE}</li>
4712     * </ul>
4713     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4714     * @param setting The name of the setting to update.
4715     * @param value The value to update the setting to.
4716     */
4717    public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
4718        if (mService != null) {
4719            try {
4720                mService.setSecureSetting(admin, setting, value);
4721            } catch (RemoteException e) {
4722                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
4723            }
4724        }
4725    }
4726
4727    /**
4728     * Designates a specific service component as the provider for
4729     * making permission requests of a local or remote administrator of the user.
4730     * <p/>
4731     * Only a profile owner can designate the restrictions provider.
4732     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4733     * @param provider The component name of the service that implements
4734     * {@link RestrictionsReceiver}. If this param is null,
4735     * it removes the restrictions provider previously assigned.
4736     */
4737    public void setRestrictionsProvider(@NonNull ComponentName admin,
4738            @Nullable ComponentName provider) {
4739        if (mService != null) {
4740            try {
4741                mService.setRestrictionsProvider(admin, provider);
4742            } catch (RemoteException re) {
4743                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4744            }
4745        }
4746    }
4747
4748    /**
4749     * Called by profile or device owners to set the master volume mute on or off.
4750     *
4751     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4752     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
4753     */
4754    public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
4755        if (mService != null) {
4756            try {
4757                mService.setMasterVolumeMuted(admin, on);
4758            } catch (RemoteException re) {
4759                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4760            }
4761        }
4762    }
4763
4764    /**
4765     * Called by profile or device owners to check whether the master volume mute is on or off.
4766     *
4767     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4768     * @return {@code true} if master volume is muted, {@code false} if it's not.
4769     */
4770    public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
4771        if (mService != null) {
4772            try {
4773                return mService.isMasterVolumeMuted(admin);
4774            } catch (RemoteException re) {
4775                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4776            }
4777        }
4778        return false;
4779    }
4780
4781    /**
4782     * Called by profile or device owners to change whether a user can uninstall
4783     * a package.
4784     *
4785     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4786     * @param packageName package to change.
4787     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
4788     */
4789    public void setUninstallBlocked(@NonNull ComponentName admin, String packageName,
4790            boolean uninstallBlocked) {
4791        if (mService != null) {
4792            try {
4793                mService.setUninstallBlocked(admin, packageName, uninstallBlocked);
4794            } catch (RemoteException re) {
4795                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4796            }
4797        }
4798    }
4799
4800    /**
4801     * Check whether the user has been blocked by device policy from uninstalling a package.
4802     * Requires the caller to be the profile owner if checking a specific admin's policy.
4803     * <p>
4804     * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
4805     * behavior of this API is changed such that passing {@code null} as the {@code admin}
4806     * parameter will return if any admin has blocked the uninstallation. Before L MR1, passing
4807     * {@code null} will cause a NullPointerException to be raised.
4808     *
4809     * @param admin The name of the admin component whose blocking policy will be checked, or
4810     *              {@code null} to check whether any admin has blocked the uninstallation.
4811     * @param packageName package to check.
4812     * @return true if uninstallation is blocked.
4813     */
4814    public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
4815        if (mService != null) {
4816            try {
4817                return mService.isUninstallBlocked(admin, packageName);
4818            } catch (RemoteException re) {
4819                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4820            }
4821        }
4822        return false;
4823    }
4824
4825    /**
4826     * Called by the profile owner of a managed profile to enable widget providers from a
4827     * given package to be available in the parent profile. As a result the user will be able to
4828     * add widgets from the white-listed package running under the profile to a widget
4829     * host which runs under the parent profile, for example the home screen. Note that
4830     * a package may have zero or more provider components, where each component
4831     * provides a different widget type.
4832     * <p>
4833     * <strong>Note:</strong> By default no widget provider package is white-listed.
4834     *
4835     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4836     * @param packageName The package from which widget providers are white-listed.
4837     * @return Whether the package was added.
4838     *
4839     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
4840     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
4841     */
4842    public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
4843        if (mService != null) {
4844            try {
4845                return mService.addCrossProfileWidgetProvider(admin, packageName);
4846            } catch (RemoteException re) {
4847                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4848            }
4849        }
4850        return false;
4851    }
4852
4853    /**
4854     * Called by the profile owner of a managed profile to disable widget providers from a given
4855     * package to be available in the parent profile. For this method to take effect the
4856     * package should have been added via {@link #addCrossProfileWidgetProvider(
4857     * android.content.ComponentName, String)}.
4858     * <p>
4859     * <strong>Note:</strong> By default no widget provider package is white-listed.
4860     *
4861     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4862     * @param packageName The package from which widget providers are no longer
4863     *     white-listed.
4864     * @return Whether the package was removed.
4865     *
4866     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
4867     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
4868     */
4869    public boolean removeCrossProfileWidgetProvider(
4870            @NonNull ComponentName admin, String packageName) {
4871        if (mService != null) {
4872            try {
4873                return mService.removeCrossProfileWidgetProvider(admin, packageName);
4874            } catch (RemoteException re) {
4875                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4876            }
4877        }
4878        return false;
4879    }
4880
4881    /**
4882     * Called by the profile owner of a managed profile to query providers from which packages are
4883     * available in the parent profile.
4884     *
4885     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4886     * @return The white-listed package list.
4887     *
4888     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
4889     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
4890     */
4891    public List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
4892        if (mService != null) {
4893            try {
4894                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
4895                if (providers != null) {
4896                    return providers;
4897                }
4898            } catch (RemoteException re) {
4899                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4900            }
4901        }
4902        return Collections.emptyList();
4903    }
4904
4905    /**
4906     * Called by profile or device owners to set the user's photo.
4907     *
4908     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4909     * @param icon the bitmap to set as the photo.
4910     */
4911    public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
4912        try {
4913            mService.setUserIcon(admin, icon);
4914        } catch (RemoteException re) {
4915            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4916        }
4917    }
4918
4919    /**
4920     * Called by device owners to set a local system update policy. When a new policy is set,
4921     * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
4922     *
4923     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
4924     *              components in the device owner package can set system update policies and the
4925     *              most recent policy takes
4926     * effect.
4927     * @param policy the new policy, or {@code null} to clear the current policy.
4928     * @see SystemUpdatePolicy
4929     */
4930    public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
4931        if (mService != null) {
4932            try {
4933                mService.setSystemUpdatePolicy(admin, policy);
4934            } catch (RemoteException re) {
4935                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4936            }
4937        }
4938    }
4939
4940    /**
4941     * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
4942     *
4943     * @return The current policy object, or {@code null} if no policy is set.
4944     */
4945    public SystemUpdatePolicy getSystemUpdatePolicy() {
4946        if (mService != null) {
4947            try {
4948                return mService.getSystemUpdatePolicy();
4949            } catch (RemoteException re) {
4950                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4951            }
4952        }
4953        return null;
4954    }
4955
4956    /**
4957     * Called by a device owner to disable the keyguard altogether.
4958     *
4959     * <p>Setting the keyguard to disabled has the same effect as choosing "None" as the screen
4960     * lock type. However, this call has no effect if a password, pin or pattern is currently set.
4961     * If a password, pin or pattern is set after the keyguard was disabled, the keyguard stops
4962     * being disabled.
4963     *
4964     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4965     * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
4966     *
4967     * @return {@code false} if attempting to disable the keyguard while a lock password was in
4968     * place. {@code true} otherwise.
4969     */
4970    public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
4971        try {
4972            return mService.setKeyguardDisabled(admin, disabled);
4973        } catch (RemoteException re) {
4974            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4975            return false;
4976        }
4977    }
4978
4979    /**
4980     * Called by device owner to disable the status bar. Disabling the status bar blocks
4981     * notifications, quick settings and other screen overlays that allow escaping from
4982     * a single use device.
4983     *
4984     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4985     * @param disabled {@code true} disables the status bar, {@code false} reenables it.
4986     *
4987     * @return {@code false} if attempting to disable the status bar failed.
4988     * {@code true} otherwise.
4989     */
4990    public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
4991        try {
4992            return mService.setStatusBarDisabled(admin, disabled);
4993        } catch (RemoteException re) {
4994            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
4995            return false;
4996        }
4997    }
4998
4999    /**
5000     * Callable by the system update service to notify device owners about pending updates.
5001     * The caller must hold {@link android.Manifest.permission#NOTIFY_PENDING_SYSTEM_UPDATE}
5002     * permission.
5003     *
5004     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()} indicating
5005     *        when the current pending update was first available. -1 if no update is available.
5006     * @hide
5007     */
5008    @SystemApi
5009    public void notifyPendingSystemUpdate(long updateReceivedTime) {
5010        if (mService != null) {
5011            try {
5012                mService.notifyPendingSystemUpdate(updateReceivedTime);
5013            } catch (RemoteException re) {
5014                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5015            }
5016        }
5017    }
5018
5019    /**
5020     * Called by profile or device owners to set the default response for future runtime permission
5021     * requests by applications. The policy can allow for normal operation which prompts the
5022     * user to grant a permission, or can allow automatic granting or denying of runtime
5023     * permission requests by an application. This also applies to new permissions declared by app
5024     * updates. When a permission is denied or granted this way, the effect is equivalent to setting
5025     * the permission grant state via {@link #setPermissionGrantState}.
5026     *
5027     * <p/>As this policy only acts on runtime permission requests, it only applies to applications
5028     * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
5029     *
5030     * @param admin Which profile or device owner this request is associated with.
5031     * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
5032     * {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
5033     *
5034     * @see #setPermissionGrantState
5035     */
5036    public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
5037        try {
5038            mService.setPermissionPolicy(admin, policy);
5039        } catch (RemoteException re) {
5040            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5041        }
5042    }
5043
5044    /**
5045     * Returns the current runtime permission policy set by the device or profile owner. The
5046     * default is {@link #PERMISSION_POLICY_PROMPT}.
5047     * @param admin Which profile or device owner this request is associated with.
5048     * @return the current policy for future permission requests.
5049     */
5050    public int getPermissionPolicy(ComponentName admin) {
5051        try {
5052            return mService.getPermissionPolicy(admin);
5053        } catch (RemoteException re) {
5054            return PERMISSION_POLICY_PROMPT;
5055        }
5056    }
5057
5058    /**
5059     * Sets the grant state of a runtime permission for a specific application. The state
5060     * can be {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it
5061     * through the UI, {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission
5062     * is denied and the user cannot manage it through the UI, and {@link
5063     * #PERMISSION_GRANT_STATE_GRANTED granted} in which the permission is granted and the
5064     * user cannot manage it through the UI. This might affect all permissions in a
5065     * group that the runtime permission belongs to. This method can only be called
5066     * by a profile or device owner.
5067     *
5068     * <p/>Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not
5069     * revoke the permission. It retains the previous grant, if any.
5070     *
5071     * <p/>Permissions can be granted or revoked only for applications built with a
5072     * {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
5073     *
5074     * @param admin Which profile or device owner this request is associated with.
5075     * @param packageName The application to grant or revoke a permission to.
5076     * @param permission The permission to grant or revoke.
5077     * @param grantState The permission grant state which is one of {@link
5078     *         #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
5079     *         {@link #PERMISSION_GRANT_STATE_GRANTED},
5080     * @return whether the permission was successfully granted or revoked.
5081     *
5082     * @see #PERMISSION_GRANT_STATE_DENIED
5083     * @see #PERMISSION_GRANT_STATE_DEFAULT
5084     * @see #PERMISSION_GRANT_STATE_GRANTED
5085     */
5086    public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName,
5087            String permission, int grantState) {
5088        try {
5089            return mService.setPermissionGrantState(admin, packageName, permission, grantState);
5090        } catch (RemoteException re) {
5091            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5092            return false;
5093        }
5094    }
5095
5096    /**
5097     * Returns the current grant state of a runtime permission for a specific application.
5098     *
5099     * @param admin Which profile or device owner this request is associated with.
5100     * @param packageName The application to check the grant state for.
5101     * @param permission The permission to check for.
5102     * @return the current grant state specified by device policy. If the profile or device owner
5103     * has not set a grant state, the return value is {@link #PERMISSION_GRANT_STATE_DEFAULT}.
5104     * This does not indicate whether or not the permission is currently granted for the package.
5105     *
5106     * <p/>If a grant state was set by the profile or device owner, then the return value will
5107     * be one of {@link #PERMISSION_GRANT_STATE_DENIED} or {@link #PERMISSION_GRANT_STATE_GRANTED},
5108     * which indicates if the permission is currently denied or granted.
5109     *
5110     * @see #setPermissionGrantState(ComponentName, String, String, int)
5111     * @see PackageManager#checkPermission(String, String)
5112     */
5113    public int getPermissionGrantState(@NonNull ComponentName admin, String packageName,
5114            String permission) {
5115        try {
5116            return mService.getPermissionGrantState(admin, packageName, permission);
5117        } catch (RemoteException re) {
5118            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5119            return PERMISSION_GRANT_STATE_DEFAULT;
5120        }
5121    }
5122
5123    /**
5124     * Returns if provisioning a managed profile or device is possible or not.
5125     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
5126     * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
5127     * Note that even if this method returns true, there is a slight possibility that the
5128     * provisioning will not be allowed when it is actually initiated because some event has
5129     * happened in between.
5130     * @return if provisioning a managed profile or device is possible or not.
5131     * @throws IllegalArgumentException if the supplied action is not valid.
5132     */
5133    public boolean isProvisioningAllowed(String action) {
5134        try {
5135            return mService.isProvisioningAllowed(action);
5136        } catch (RemoteException re) {
5137            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5138            return false;
5139        }
5140    }
5141
5142    /**
5143     * @hide
5144     * Return if this user is a managed profile of another user. An admin can become the profile
5145     * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
5146     * user with {@link #ACTION_PROVISION_MANAGED_USER}.
5147     * @param admin Which profile owner this request is associated with.
5148     * @return if this user is a managed profile of another user.
5149     */
5150    public boolean isManagedProfile(@NonNull ComponentName admin) {
5151        try {
5152            return mService.isManagedProfile(admin);
5153        } catch (RemoteException re) {
5154            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5155            return false;
5156        }
5157    }
5158
5159    /**
5160     * @hide
5161     * Return if this user is a system-only user. An admin can manage a device from a system only
5162     * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
5163     * @param admin Which device owner this request is associated with.
5164     * @return if this user is a system-only user.
5165     */
5166    public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
5167        try {
5168            return mService.isSystemOnlyUser(admin);
5169        } catch (RemoteException re) {
5170            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5171            return false;
5172        }
5173    }
5174
5175    /**
5176     * Called by device owner to get the MAC address of the Wi-Fi device.
5177     *
5178     * @return the MAC address of the Wi-Fi device, or null when the information is not
5179     * available. (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
5180     *
5181     * <p>The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
5182     */
5183    public String getWifiMacAddress() {
5184        try {
5185            return mService.getWifiMacAddress();
5186        } catch (RemoteException re) {
5187            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5188            return null;
5189        }
5190    }
5191
5192    /**
5193     * Called by device owner to reboot the device.
5194     */
5195    public void reboot(@NonNull ComponentName admin) {
5196        try {
5197            mService.reboot(admin);
5198        } catch (RemoteException re) {
5199            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5200        }
5201    }
5202
5203    /**
5204     * Called by a device admin to set the short support message. This will
5205     * be displayed to the user in settings screens where funtionality has
5206     * been disabled by the admin.
5207     *
5208     * The message should be limited to a short statement such as
5209     * "This setting is disabled by your administrator. Contact someone@example.com
5210     *  for support."
5211     * If the message is longer than 200 characters it may be truncated.
5212     *
5213     * @see #setLongSupportMessage
5214     *
5215     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5216     * @param message Short message to be displayed to the user in settings or null to
5217     *        clear the existing message.
5218     */
5219    public void setShortSupportMessage(@NonNull ComponentName admin,
5220            @Nullable String message) {
5221        if (mService != null) {
5222            try {
5223                mService.setShortSupportMessage(admin, message);
5224            } catch (RemoteException e) {
5225                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
5226            }
5227        }
5228    }
5229
5230    /**
5231     * Called by a device admin to get the short support message.
5232     *
5233     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5234     * @return The message set by {@link #setShortSupportMessage(ComponentName, String)}
5235     *         or null if no message has been set.
5236     */
5237    public String getShortSupportMessage(@NonNull ComponentName admin) {
5238        if (mService != null) {
5239            try {
5240                return mService.getShortSupportMessage(admin);
5241            } catch (RemoteException e) {
5242                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
5243            }
5244        }
5245        return null;
5246    }
5247
5248    /**
5249     * Called by a device admin to set the long support message. This will
5250     * be displayed to the user in the device administators settings screen.
5251     *
5252     * @see #setShortSupportMessage
5253     *
5254     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5255     * @param message Long message to be displayed to the user in settings or null to
5256     *        clear the existing message.
5257     */
5258    public void setLongSupportMessage(@NonNull ComponentName admin,
5259            @Nullable String message) {
5260        if (mService != null) {
5261            try {
5262                mService.setLongSupportMessage(admin, message);
5263            } catch (RemoteException e) {
5264                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
5265            }
5266        }
5267    }
5268
5269    /**
5270     * Called by a device admin to get the long support message.
5271     *
5272     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5273     * @return The message set by {@link #setLongSupportMessage(ComponentName, String)}
5274     *         or null if no message has been set.
5275     */
5276    public String getLongSupportMessage(@NonNull ComponentName admin) {
5277        if (mService != null) {
5278            try {
5279                return mService.getLongSupportMessage(admin);
5280            } catch (RemoteException e) {
5281                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
5282            }
5283        }
5284        return null;
5285    }
5286
5287    /**
5288     * Called by the system to get the short support message.
5289     *
5290     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5291     * @param userHandle user id the admin is running as.
5292     * @return The message set by {@link #setShortSupportMessage(ComponentName, String)}
5293     *
5294     * @hide
5295     */
5296    public String getShortSupportMessageForUser(@NonNull ComponentName admin, int userHandle) {
5297        if (mService != null) {
5298            try {
5299                return mService.getShortSupportMessageForUser(admin, userHandle);
5300            } catch (RemoteException e) {
5301                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
5302            }
5303        }
5304        return null;
5305    }
5306
5307
5308    /**
5309     * Called by the system to get the long support message.
5310     *
5311     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5312     * @param userHandle user id the admin is running as.
5313     * @return The message set by {@link #setLongSupportMessage(ComponentName, String)}
5314     *
5315     * @hide
5316     */
5317    public String getLongSupportMessageForUser(@NonNull ComponentName admin, int userHandle) {
5318        if (mService != null) {
5319            try {
5320                return mService.getLongSupportMessageForUser(admin, userHandle);
5321            } catch (RemoteException e) {
5322                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
5323            }
5324        }
5325        return null;
5326    }
5327
5328    /**
5329     * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
5330     * whose calls act on the parent profile.
5331     *
5332     * <p> Note only some methods will work on the parent Manager.
5333     *
5334     * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
5335     */
5336    public DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
5337        try {
5338            if (!mService.isManagedProfile(admin)) {
5339                throw new SecurityException("The current user does not have a parent profile.");
5340            }
5341            return new DevicePolicyManager(mContext, true);
5342        } catch (RemoteException re) {
5343            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5344            return null;
5345        }
5346    }
5347
5348    /**
5349     * Called by a profile owner of a managed profile to set the color used for customization.
5350     * This color is used as background color of the confirm credentials screen for that user.
5351     * The default color is {@link android.graphics.Color#GRAY}.
5352     *
5353     * <p>The confirm credentials screen can be created using
5354     * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
5355     *
5356     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5357     * @param color The 32bit representation of the color to be used.
5358     */
5359    public void setOrganizationColor(@NonNull ComponentName admin, int color) {
5360        try {
5361            mService.setOrganizationColor(admin, color);
5362        } catch (RemoteException re) {
5363            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5364        }
5365    }
5366
5367    /**
5368     * Called by a profile owner of a managed profile to retrieve the color used for customization.
5369     * This color is used as background color of the confirm credentials screen for that user.
5370     *
5371     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5372     * @return The 32bit representation of the color to be used.
5373     */
5374    public int getOrganizationColor(@NonNull ComponentName admin) {
5375        try {
5376            return mService.getOrganizationColor(admin);
5377        } catch (RemoteException re) {
5378            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5379            return 0;
5380        }
5381    }
5382
5383    /**
5384     * @hide
5385     * Retrieve the customization color for a given user.
5386     *
5387     * @param userHandle The user id of the user we're interested in.
5388     * @return The 32bit representation of the color to be used.
5389     */
5390    public int getOrganizationColorForUser(int userHandle) {
5391        try {
5392            return mService.getOrganizationColorForUser(userHandle);
5393        } catch (RemoteException re) {
5394            Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, re);
5395            return 0;
5396        }
5397    }
5398
5399    /**
5400     * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
5401     *         return {@link #STATE_USER_UNMANAGED}
5402     * @hide
5403     */
5404    @UserProvisioningState
5405    public int getUserProvisioningState() {
5406        if (mService != null) {
5407            try {
5408                return mService.getUserProvisioningState();
5409            } catch (RemoteException e) {
5410                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
5411            }
5412        }
5413        return STATE_USER_UNMANAGED;
5414    }
5415
5416    /**
5417     * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
5418     *
5419     * @param state to store
5420     * @param userHandle for user
5421     * @hide
5422     */
5423    public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
5424        if (mService != null) {
5425            try {
5426                mService.setUserProvisioningState(state, userHandle);
5427            } catch (RemoteException e) {
5428                Log.w(TAG, REMOTE_EXCEPTION_MESSAGE, e);
5429            }
5430        }
5431    }
5432
5433    /**
5434     * @hide
5435     * Indicates the entity that controls the device or profile owner. A user/profile is considered
5436     * affiliated if it is managed by the same entity as the device.
5437     *
5438     * <p> By definition, the user that the device owner runs on is always affiliated. Any other
5439     * user/profile is considered affiliated if the following conditions are both met:
5440     * <ul>
5441     * <li>The device owner and the user's/profile's profile owner have called this method,
5442     *   specifying a set of opaque affiliation ids each. If the sets specified by the device owner
5443     *   and a profile owner intersect, they must have come from the same source, which means that
5444     *   the device owner and profile owner are controlled by the same entity.</li>
5445     * <li>The device owner's and profile owner's package names are the same.</li>
5446     * </ul>
5447     *
5448     * @param admin Which profile or device owner this request is associated with.
5449     * @param ids A set of opaque affiliation ids.
5450     */
5451    public void setAffiliationIds(@NonNull ComponentName admin, Set<String> ids) {
5452        try {
5453            mService.setAffiliationIds(admin, new ArrayList<String>(ids));
5454        } catch (RemoteException e) {
5455            Log.w(TAG, "Failed talking with device policy service", e);
5456        }
5457    }
5458
5459    /**
5460     * @hide
5461     * Returns whether this user/profile is affiliated with the device. See
5462     * {@link #setAffiliationIds} for the definition of affiliation.
5463     *
5464     * @return whether this user/profile is affiliated with the device.
5465     */
5466    public boolean isAffiliatedUser() {
5467        try {
5468            return mService != null && mService.isAffiliatedUser();
5469        } catch (RemoteException e) {
5470            Log.w(TAG, "Failed talking with device policy service", e);
5471            return false;
5472        }
5473    }
5474}
5475