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