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