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