DevicePolicyManager.java revision cb6fd80721253ffa9dcab5cf8c2f4e9b9cd17ccc
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     * @hide
2826     * @deprecated Do not use
2827     * @removed
2828     */
2829    @Deprecated
2830    @SystemApi
2831    public String getDeviceInitializerApp() {
2832        return null;
2833    }
2834
2835    /**
2836     * @hide
2837     * @deprecated Do not use
2838     * @removed
2839     */
2840    @Deprecated
2841    @SystemApi
2842    public ComponentName getDeviceInitializerComponent() {
2843        return null;
2844    }
2845
2846    /**
2847     * @hide
2848     * @deprecated Use #ACTION_SET_PROFILE_OWNER
2849     * Sets the given component as an active admin and registers the package as the profile
2850     * owner for this user. The package must already be installed and there shouldn't be
2851     * an existing profile owner registered for this user. Also, this method must be called
2852     * before the user setup has been completed.
2853     * <p>
2854     * This method can only be called by system apps that hold MANAGE_USERS permission and
2855     * MANAGE_DEVICE_ADMINS permission.
2856     * @param admin The component to register as an active admin and profile owner.
2857     * @param ownerName The user-visible name of the entity that is managing this user.
2858     * @return whether the admin was successfully registered as the profile owner.
2859     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
2860     *         the user has already been set up.
2861     */
2862    @SystemApi
2863    public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
2864            throws IllegalArgumentException {
2865        if (mService != null) {
2866            try {
2867                final int myUserId = myUserId();
2868                mService.setActiveAdmin(admin, false, myUserId);
2869                return mService.setProfileOwner(admin, ownerName, myUserId);
2870            } catch (RemoteException re) {
2871                Log.w(TAG, "Failed to set profile owner " + re);
2872                throw new IllegalArgumentException("Couldn't set profile owner.", re);
2873            }
2874        }
2875        return false;
2876    }
2877
2878    /**
2879     * @hide
2880     * Clears the active profile owner and removes all user restrictions. The caller must
2881     * be from the same package as the active profile owner for this user, otherwise a
2882     * SecurityException will be thrown.
2883     *
2884     * @param admin The component to remove as the profile owner.
2885     * @return
2886     */
2887    @SystemApi
2888    public void clearProfileOwner(@NonNull ComponentName admin) {
2889        if (mService != null) {
2890            try {
2891                mService.clearProfileOwner(admin);
2892            } catch (RemoteException re) {
2893                Log.w(TAG, "Failed to clear profile owner " + admin + re);
2894            }
2895        }
2896    }
2897
2898    /**
2899     * @hide
2900     * Checks whether the user was already setup.
2901     */
2902    public boolean hasUserSetupCompleted() {
2903        if (mService != null) {
2904            try {
2905                return mService.hasUserSetupCompleted();
2906            } catch (RemoteException re) {
2907                Log.w(TAG, "Failed to check whether user setup has completed");
2908            }
2909        }
2910        return true;
2911    }
2912
2913    /**
2914     * @hide
2915     * Sets the given component as the profile owner of the given user profile. The package must
2916     * already be installed. There must not already be a profile owner for this user.
2917     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
2918     * this method.
2919     * Calling this after the setup phase of the specified user has completed is allowed only if:
2920     * - the caller is SYSTEM_UID.
2921     * - or the caller is the shell uid, and there are no accounts on the specified user.
2922     * @param admin the component name to be registered as profile owner.
2923     * @param ownerName the human readable name of the organisation associated with this DPM.
2924     * @param userHandle the userId to set the profile owner for.
2925     * @return whether the component was successfully registered as the profile owner.
2926     * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
2927     * preconditions mentioned are not met.
2928     */
2929    public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
2930            int userHandle) throws IllegalArgumentException {
2931        if (mService != null) {
2932            try {
2933                if (ownerName == null) {
2934                    ownerName = "";
2935                }
2936                return mService.setProfileOwner(admin, ownerName, userHandle);
2937            } catch (RemoteException re) {
2938                Log.w(TAG, "Failed to set profile owner", re);
2939                throw new IllegalArgumentException("Couldn't set profile owner.", re);
2940            }
2941        }
2942        return false;
2943    }
2944
2945    /**
2946     * Sets the device owner information to be shown on the lock screen.
2947     *
2948     * <p>If the device owner information is {@code null} or empty then the device owner info is
2949     * cleared and the user owner info is shown on the lock screen if it is set.
2950     *
2951     * @param admin The name of the admin component to check.
2952     * @param info Device owner information which will be displayed instead of the user
2953     * owner info.
2954     * @return Whether the device owner information has been set.
2955     */
2956    public boolean setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, String info) {
2957        if (mService != null) {
2958            try {
2959                return mService.setDeviceOwnerLockScreenInfo(admin, info);
2960            } catch (RemoteException re) {
2961                Log.w(TAG, "Failed talking with device policy service", re);
2962            }
2963        }
2964        return false;
2965    }
2966
2967    /**
2968     * @return The device owner information. If it is not set returns {@code null}.
2969     */
2970    public String getDeviceOwnerLockScreenInfo() {
2971        if (mService != null) {
2972            try {
2973                return mService.getDeviceOwnerLockScreenInfo();
2974            } catch (RemoteException re) {
2975                Log.w(TAG, "Failed talking with device policy service", re);
2976            }
2977        }
2978        return null;
2979    }
2980
2981    /**
2982     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
2983     * be used. Only the profile owner can call this.
2984     *
2985     * @see #isProfileOwnerApp
2986     *
2987     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2988     */
2989    public void setProfileEnabled(@NonNull ComponentName admin) {
2990        if (mService != null) {
2991            try {
2992                mService.setProfileEnabled(admin);
2993            } catch (RemoteException e) {
2994                Log.w(TAG, "Failed talking with device policy service", e);
2995            }
2996        }
2997    }
2998
2999    /**
3000     * Sets the name of the profile. In the device owner case it sets the name of the user
3001     * which it is called from. Only a profile owner or device owner can call this. If this is
3002     * never called by the profile or device owner, the name will be set to default values.
3003     *
3004     * @see #isProfileOwnerApp
3005     * @see #isDeviceOwnerApp
3006     *
3007     * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
3008     * @param profileName The name of the profile.
3009     */
3010    public void setProfileName(@NonNull ComponentName admin, String profileName) {
3011        if (mService != null) {
3012            try {
3013                mService.setProfileName(admin, profileName);
3014            } catch (RemoteException e) {
3015                Log.w(TAG, "Failed talking with device policy service", e);
3016            }
3017        }
3018    }
3019
3020    /**
3021     * Used to determine if a particular package is registered as the profile owner for the
3022     * current user. A profile owner is a special device admin that has additional privileges
3023     * within the profile.
3024     *
3025     * @param packageName The package name of the app to compare with the registered profile owner.
3026     * @return Whether or not the package is registered as the profile owner.
3027     */
3028    public boolean isProfileOwnerApp(String packageName) {
3029        if (mService != null) {
3030            try {
3031                ComponentName profileOwner = mService.getProfileOwner(
3032                        Process.myUserHandle().getIdentifier());
3033                return profileOwner != null
3034                        && profileOwner.getPackageName().equals(packageName);
3035            } catch (RemoteException re) {
3036                Log.w(TAG, "Failed to check profile owner");
3037            }
3038        }
3039        return false;
3040    }
3041
3042    /**
3043     * @hide
3044     * @return the packageName of the owner of the given user profile or {@code null} if no profile
3045     * owner has been set for that user.
3046     * @throws IllegalArgumentException if the userId is invalid.
3047     */
3048    @SystemApi
3049    public ComponentName getProfileOwner() throws IllegalArgumentException {
3050        return getProfileOwnerAsUser(Process.myUserHandle().getIdentifier());
3051    }
3052
3053    /**
3054     * @see #getProfileOwner()
3055     * @hide
3056     */
3057    public ComponentName getProfileOwnerAsUser(final int userId) throws IllegalArgumentException {
3058        if (mService != null) {
3059            try {
3060                return mService.getProfileOwner(userId);
3061            } catch (RemoteException re) {
3062                Log.w(TAG, "Failed to get profile owner");
3063                throw new IllegalArgumentException(
3064                        "Requested profile owner for invalid userId", re);
3065            }
3066        }
3067        return null;
3068    }
3069
3070    /**
3071     * @hide
3072     * @return the human readable name of the organisation associated with this DPM or {@code null}
3073     *         if one is not set.
3074     * @throws IllegalArgumentException if the userId is invalid.
3075     */
3076    public String getProfileOwnerName() throws IllegalArgumentException {
3077        if (mService != null) {
3078            try {
3079                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
3080            } catch (RemoteException re) {
3081                Log.w(TAG, "Failed to get profile owner");
3082                throw new IllegalArgumentException(
3083                        "Requested profile owner for invalid userId", re);
3084            }
3085        }
3086        return null;
3087    }
3088
3089    /**
3090     * @hide
3091     * @param user The user for whom to fetch the profile owner name, if any.
3092     * @return the human readable name of the organisation associated with this profile owner or
3093     *         null if one is not set.
3094     * @throws IllegalArgumentException if the userId is invalid.
3095     */
3096    @SystemApi
3097    public String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
3098        if (mService != null) {
3099            try {
3100                return mService.getProfileOwnerName(userId);
3101            } catch (RemoteException re) {
3102                Log.w(TAG, "Failed to get profile owner");
3103                throw new IllegalArgumentException(
3104                        "Requested profile owner for invalid userId", re);
3105            }
3106        }
3107        return null;
3108    }
3109
3110    /**
3111     * Called by a profile owner or device owner to add a default intent handler activity for
3112     * intents that match a certain intent filter. This activity will remain the default intent
3113     * handler even if the set of potential event handlers for the intent filter changes and if
3114     * the intent preferences are reset.
3115     *
3116     * <p>The default disambiguation mechanism takes over if the activity is not installed
3117     * (anymore). When the activity is (re)installed, it is automatically reset as default
3118     * intent handler for the filter.
3119     *
3120     * <p>The calling device admin must be a profile owner or device owner. If it is not, a
3121     * security exception will be thrown.
3122     *
3123     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3124     * @param filter The IntentFilter for which a default handler is added.
3125     * @param activity The Activity that is added as default intent handler.
3126     */
3127    public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
3128            @NonNull ComponentName activity) {
3129        if (mService != null) {
3130            try {
3131                mService.addPersistentPreferredActivity(admin, filter, activity);
3132            } catch (RemoteException e) {
3133                Log.w(TAG, "Failed talking with device policy service", e);
3134            }
3135        }
3136    }
3137
3138    /**
3139     * Called by a profile owner or device owner to remove all persistent intent handler preferences
3140     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
3141     *
3142     * <p>The calling device admin must be a profile owner. If it is not, a security
3143     * exception will be thrown.
3144     *
3145     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3146     * @param packageName The name of the package for which preferences are removed.
3147     */
3148    public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
3149            String packageName) {
3150        if (mService != null) {
3151            try {
3152                mService.clearPackagePersistentPreferredActivities(admin, packageName);
3153            } catch (RemoteException e) {
3154                Log.w(TAG, "Failed talking with device policy service", e);
3155            }
3156        }
3157    }
3158
3159    /**
3160     * Called by a profile or device owner to set the application restrictions for a given target
3161     * application running in the profile.
3162     *
3163     * <p>The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
3164     * <ul>
3165     * <li>{@code boolean}
3166     * <li>{@code int}
3167     * <li>{@code String} or {@code String[]}
3168     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
3169     * </ul>
3170     *
3171     * <p>The application restrictions are only made visible to the target application and the
3172     * profile or device owner.
3173     *
3174     * <p>If the restrictions are not available yet, but may be applied in the near future,
3175     * the admin can notify the target application of that by adding
3176     * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
3177     *
3178     * <p>The calling device admin must be a profile or device owner; if it is not, a security
3179     * exception will be thrown.
3180     *
3181     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3182     * @param packageName The name of the package to update restricted settings for.
3183     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
3184     * set of active restrictions.
3185     *
3186     * @see UserManager#KEY_RESTRICTIONS_PENDING
3187     */
3188    public void setApplicationRestrictions(@NonNull ComponentName admin, String packageName,
3189            Bundle settings) {
3190        if (mService != null) {
3191            try {
3192                mService.setApplicationRestrictions(admin, packageName, settings);
3193            } catch (RemoteException e) {
3194                Log.w(TAG, "Failed talking with device policy service", e);
3195            }
3196        }
3197    }
3198
3199    /**
3200     * Sets a list of configuration features to enable for a TrustAgent component. This is meant
3201     * to be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all
3202     * trust agents but those enabled by this function call. If flag
3203     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
3204     *
3205     * <p>The calling device admin must have requested
3206     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call
3207     * this method; if not, a security exception will be thrown.
3208     *
3209     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3210     * @param target Component name of the agent to be enabled.
3211     * @param configuration TrustAgent-specific feature bundle. If null for any admin, agent
3212     * will be strictly disabled according to the state of the
3213     *  {@link #KEYGUARD_DISABLE_TRUST_AGENTS} flag.
3214     * <p>If {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is set and options is not null for all admins,
3215     * then it's up to the TrustAgent itself to aggregate the values from all device admins.
3216     * <p>Consult documentation for the specific TrustAgent to determine legal options parameters.
3217     */
3218    public void setTrustAgentConfiguration(@NonNull ComponentName admin,
3219            @NonNull ComponentName target, PersistableBundle configuration) {
3220        if (mService != null) {
3221            try {
3222                mService.setTrustAgentConfiguration(admin, target, configuration);
3223            } catch (RemoteException e) {
3224                Log.w(TAG, "Failed talking with device policy service", e);
3225            }
3226        }
3227    }
3228
3229    /**
3230     * Gets configuration for the given trust agent based on aggregating all calls to
3231     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
3232     * all device admins.
3233     *
3234     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
3235     * this function returns a list of configurations for all admins that declare
3236     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
3237     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
3238     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
3239     * for this {@param agent} or calls it with a null configuration, null is returned.
3240     * @param agent Which component to get enabled features for.
3241     * @return configuration for the given trust agent.
3242     */
3243    public List<PersistableBundle> getTrustAgentConfiguration(@Nullable ComponentName admin,
3244            @NonNull ComponentName agent) {
3245        return getTrustAgentConfiguration(admin, agent, myUserId());
3246    }
3247
3248    /** @hide per-user version */
3249    public List<PersistableBundle> getTrustAgentConfiguration(@Nullable ComponentName admin,
3250            @NonNull ComponentName agent, int userHandle) {
3251        if (mService != null) {
3252            try {
3253                return mService.getTrustAgentConfiguration(admin, agent, userHandle);
3254            } catch (RemoteException e) {
3255                Log.w(TAG, "Failed talking with device policy service", e);
3256            }
3257        }
3258        return new ArrayList<PersistableBundle>(); // empty list
3259    }
3260
3261    /**
3262     * Called by a profile owner of a managed profile to set whether caller-Id information from
3263     * the managed profile will be shown in the parent profile, for incoming calls.
3264     *
3265     * <p>The calling device admin must be a profile owner. If it is not, a
3266     * security exception will be thrown.
3267     *
3268     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3269     * @param disabled If true caller-Id information in the managed profile is not displayed.
3270     */
3271    public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
3272        if (mService != null) {
3273            try {
3274                mService.setCrossProfileCallerIdDisabled(admin, disabled);
3275            } catch (RemoteException e) {
3276                Log.w(TAG, "Failed talking with device policy service", e);
3277            }
3278        }
3279    }
3280
3281    /**
3282     * Called by a profile owner of a managed profile to determine whether or not caller-Id
3283     * information has been disabled.
3284     *
3285     * <p>The calling device admin must be a profile owner. If it is not, a
3286     * security exception will be thrown.
3287     *
3288     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3289     */
3290    public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
3291        if (mService != null) {
3292            try {
3293                return mService.getCrossProfileCallerIdDisabled(admin);
3294            } catch (RemoteException e) {
3295                Log.w(TAG, "Failed talking with device policy service", e);
3296            }
3297        }
3298        return false;
3299    }
3300
3301    /**
3302     * Determine whether or not caller-Id information has been disabled.
3303     *
3304     * @param userHandle The user for whom to check the caller-id permission
3305     * @hide
3306     */
3307    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
3308        if (mService != null) {
3309            try {
3310                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
3311            } catch (RemoteException e) {
3312                Log.w(TAG, "Failed talking with device policy service", e);
3313            }
3314        }
3315        return false;
3316    }
3317
3318    /**
3319     * Start Quick Contact on the managed profile for the current user, if the policy allows.
3320     * @hide
3321     */
3322    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
3323            Intent originalIntent) {
3324        if (mService != null) {
3325            try {
3326                mService.startManagedQuickContact(
3327                        actualLookupKey, actualContactId, originalIntent);
3328            } catch (RemoteException e) {
3329                Log.w(TAG, "Failed talking with device policy service", e);
3330            }
3331        }
3332    }
3333
3334    /**
3335     * Called by a profile owner of a managed profile to set whether bluetooth
3336     * devices can access enterprise contacts.
3337     * <p>
3338     * The calling device admin must be a profile owner. If it is not, a
3339     * security exception will be thrown.
3340     * <p>
3341     * This API works on managed profile only.
3342     *
3343     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3344     *            with.
3345     * @param disabled If true, bluetooth devices cannot access enterprise
3346     *            contacts.
3347     */
3348    public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
3349        if (mService != null) {
3350            try {
3351                mService.setBluetoothContactSharingDisabled(admin, disabled);
3352            } catch (RemoteException e) {
3353                Log.w(TAG, "Failed talking with device policy service", e);
3354            }
3355        }
3356    }
3357
3358    /**
3359     * Called by a profile owner of a managed profile to determine whether or
3360     * not Bluetooth devices cannot access enterprise contacts.
3361     * <p>
3362     * The calling device admin must be a profile owner. If it is not, a
3363     * security exception will be thrown.
3364     * <p>
3365     * This API works on managed profile only.
3366     *
3367     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3368     *            with.
3369     */
3370    public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
3371        if (mService != null) {
3372            try {
3373                return mService.getBluetoothContactSharingDisabled(admin);
3374            } catch (RemoteException e) {
3375                Log.w(TAG, "Failed talking with device policy service", e);
3376            }
3377        }
3378        return true;
3379    }
3380
3381    /**
3382     * Determine whether or not Bluetooth devices cannot access contacts.
3383     * <p>
3384     * This API works on managed profile UserHandle only.
3385     *
3386     * @param userHandle The user for whom to check the caller-id permission
3387     * @hide
3388     */
3389    public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
3390        if (mService != null) {
3391            try {
3392                return mService.getBluetoothContactSharingDisabledForUser(userHandle
3393                        .getIdentifier());
3394            } catch (RemoteException e) {
3395                Log.w(TAG, "Failed talking with device policy service", e);
3396            }
3397        }
3398        return true;
3399    }
3400
3401    /**
3402     * Called by the profile owner of a managed profile so that some intents sent in the managed
3403     * profile can also be resolved in the parent, or vice versa.
3404     * Only activity intents are supported.
3405     *
3406     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3407     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
3408     * other profile
3409     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
3410     * {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
3411     */
3412    public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
3413        if (mService != null) {
3414            try {
3415                mService.addCrossProfileIntentFilter(admin, filter, flags);
3416            } catch (RemoteException e) {
3417                Log.w(TAG, "Failed talking with device policy service", e);
3418            }
3419        }
3420    }
3421
3422    /**
3423     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
3424     * that go from the managed profile to the parent, or from the parent to the managed profile.
3425     * Only removes those that have been set by the profile owner.
3426     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3427     */
3428    public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
3429        if (mService != null) {
3430            try {
3431                mService.clearCrossProfileIntentFilters(admin);
3432            } catch (RemoteException e) {
3433                Log.w(TAG, "Failed talking with device policy service", e);
3434            }
3435        }
3436    }
3437
3438    /**
3439     * Called by a profile or device owner to set the permitted accessibility services. When
3440     * set by a device owner or profile owner the restriction applies to all profiles of the
3441     * user the device owner or profile owner is an admin for.
3442     *
3443     * By default the user can use any accessiblity service. When zero or more packages have
3444     * been added, accessiblity services that are not in the list and not part of the system
3445     * can not be enabled by the user.
3446     *
3447     * <p> Calling with a null value for the list disables the restriction so that all services
3448     * can be used, calling with an empty list only allows the builtin system's services.
3449     *
3450     * <p> System accesibility services are always available to the user the list can't modify
3451     * this.
3452     *
3453     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3454     * @param packageNames List of accessibility service package names.
3455     *
3456     * @return true if setting the restriction succeeded. It fail if there is
3457     * one or more non-system accessibility services enabled, that are not in the list.
3458     */
3459    public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
3460            List<String> packageNames) {
3461        if (mService != null) {
3462            try {
3463                return mService.setPermittedAccessibilityServices(admin, packageNames);
3464            } catch (RemoteException e) {
3465                Log.w(TAG, "Failed talking with device policy service", e);
3466            }
3467        }
3468        return false;
3469    }
3470
3471    /**
3472     * Returns the list of permitted accessibility services set by this device or profile owner.
3473     *
3474     * <p>An empty list means no accessibility services except system services are allowed.
3475     * Null means all accessibility services are allowed.
3476     *
3477     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3478     * @return List of accessiblity service package names.
3479     */
3480    public List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
3481        if (mService != null) {
3482            try {
3483                return mService.getPermittedAccessibilityServices(admin);
3484            } catch (RemoteException e) {
3485                Log.w(TAG, "Failed talking with device policy service", e);
3486            }
3487        }
3488        return null;
3489    }
3490
3491    /**
3492     * Returns the list of accessibility services permitted by the device or profiles
3493     * owners of this user.
3494     *
3495     * <p>Null means all accessibility services are allowed, if a non-null list is returned
3496     * it will contain the intersection of the permitted lists for any device or profile
3497     * owners that apply to this user. It will also include any system accessibility services.
3498     *
3499     * @param userId which user to check for.
3500     * @return List of accessiblity service package names.
3501     * @hide
3502     */
3503     @SystemApi
3504     public List<String> getPermittedAccessibilityServices(int userId) {
3505        if (mService != null) {
3506            try {
3507                return mService.getPermittedAccessibilityServicesForUser(userId);
3508            } catch (RemoteException e) {
3509                Log.w(TAG, "Failed talking with device policy service", e);
3510            }
3511        }
3512        return null;
3513     }
3514
3515    /**
3516     * Called by a profile or device owner to set the permitted input methods services. When
3517     * set by a device owner or profile owner the restriction applies to all profiles of the
3518     * user the device owner or profile owner is an admin for.
3519     *
3520     * By default the user can use any input method. When zero or more packages have
3521     * been added, input method that are not in the list and not part of the system
3522     * can not be enabled by the user.
3523     *
3524     * This method will fail if it is called for a admin that is not for the foreground user
3525     * or a profile of the foreground user.
3526     *
3527     * <p> Calling with a null value for the list disables the restriction so that all input methods
3528     * can be used, calling with an empty list disables all but the system's own input methods.
3529     *
3530     * <p> System input methods are always available to the user this method can't modify this.
3531     *
3532     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3533     * @param packageNames List of input method package names.
3534     * @return true if setting the restriction succeeded. It will fail if there are
3535     *     one or more non-system input methods currently enabled that are not in
3536     *     the packageNames list.
3537     */
3538    public boolean setPermittedInputMethods(@NonNull ComponentName admin, List<String> packageNames) {
3539        if (mService != null) {
3540            try {
3541                return mService.setPermittedInputMethods(admin, packageNames);
3542            } catch (RemoteException e) {
3543                Log.w(TAG, "Failed talking with device policy service", e);
3544            }
3545        }
3546        return false;
3547    }
3548
3549
3550    /**
3551     * Returns the list of permitted input methods set by this device or profile owner.
3552     *
3553     * <p>An empty list means no input methods except system input methods are allowed.
3554     * Null means all input methods are allowed.
3555     *
3556     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3557     * @return List of input method package names.
3558     */
3559    public List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
3560        if (mService != null) {
3561            try {
3562                return mService.getPermittedInputMethods(admin);
3563            } catch (RemoteException e) {
3564                Log.w(TAG, "Failed talking with device policy service", e);
3565            }
3566        }
3567        return null;
3568    }
3569
3570    /**
3571     * Returns the list of input methods permitted by the device or profiles
3572     * owners of the current user.
3573     *
3574     * <p>Null means all input methods are allowed, if a non-null list is returned
3575     * it will contain the intersection of the permitted lists for any device or profile
3576     * owners that apply to this user. It will also include any system input methods.
3577     *
3578     * @return List of input method package names.
3579     * @hide
3580     */
3581    @SystemApi
3582    public List<String> getPermittedInputMethodsForCurrentUser() {
3583        if (mService != null) {
3584            try {
3585                return mService.getPermittedInputMethodsForCurrentUser();
3586            } catch (RemoteException e) {
3587                Log.w(TAG, "Failed talking with device policy service", e);
3588            }
3589        }
3590        return null;
3591    }
3592
3593    /**
3594     * Called by a device owner to get the list of apps to keep around as APKs even if no user has
3595     * currently installed it.
3596     *
3597     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3598     *
3599     * @return List of package names to keep cached.
3600     * @hide
3601     */
3602    public List<String> getKeepUninstalledPackages(@NonNull ComponentName admin) {
3603        if (mService != null) {
3604            try {
3605                return mService.getKeepUninstalledPackages(admin);
3606            } catch (RemoteException e) {
3607                Log.w(TAG, "Failed talking with device policy service", e);
3608            }
3609        }
3610        return null;
3611    }
3612
3613    /**
3614     * Called by a device owner to set a list of apps to keep around as APKs even if no user has
3615     * currently installed it.
3616     *
3617     * <p>Please note that setting this policy does not imply that specified apps will be
3618     * automatically pre-cached.</p>
3619     *
3620     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3621     * @param packageNames List of package names to keep cached.
3622     * @hide
3623     */
3624    public void setKeepUninstalledPackages(@NonNull ComponentName admin,
3625            @NonNull List<String> packageNames) {
3626        if (mService != null) {
3627            try {
3628                mService.setKeepUninstalledPackages(admin, packageNames);
3629            } catch (RemoteException e) {
3630                Log.w(TAG, "Failed talking with device policy service", e);
3631            }
3632        }
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}.
3640     *
3641     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3642     * @param name the user's name
3643     * @see UserHandle
3644     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
3645     *         user could not be created.
3646     *
3647     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
3648     */
3649    @Deprecated
3650    public UserHandle createUser(@NonNull ComponentName admin, String name) {
3651        try {
3652            return mService.createUser(admin, name);
3653        } catch (RemoteException re) {
3654            Log.w(TAG, "Could not create a user", re);
3655        }
3656        return null;
3657    }
3658
3659    /**
3660     * Called by a device owner to create a user with the specified name. The UserHandle returned
3661     * by this method should not be persisted as user handles are recycled as users are removed and
3662     * created. If you need to persist an identifier for this user, use
3663     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
3664     * immediately.
3665     *
3666     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
3667     * as registered as an active admin on the new user.  The profile owner package will be
3668     * installed on the new user if it already is installed on the device.
3669     *
3670     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
3671     * profileOwnerComponent when onEnable is called.
3672     *
3673     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3674     * @param name the user's name
3675     * @param ownerName the human readable name of the organisation associated with this DPM.
3676     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
3677     *      the user.
3678     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
3679     *      on the new user.
3680     * @see UserHandle
3681     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
3682     *         user could not be created.
3683     *
3684     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
3685     */
3686    @Deprecated
3687    public UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
3688            String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
3689        try {
3690            return mService.createAndInitializeUser(admin, name, ownerName, profileOwnerComponent,
3691                    adminExtras);
3692        } catch (RemoteException re) {
3693            Log.w(TAG, "Could not create a user", re);
3694        }
3695        return null;
3696    }
3697
3698    /**
3699     * Called by a device owner to remove a user and all associated data. The primary user can
3700     * not be removed.
3701     *
3702     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3703     * @param userHandle the user to remove.
3704     * @return {@code true} if the user was removed, {@code false} otherwise.
3705     */
3706    public boolean removeUser(@NonNull ComponentName admin, UserHandle userHandle) {
3707        try {
3708            return mService.removeUser(admin, userHandle);
3709        } catch (RemoteException re) {
3710            Log.w(TAG, "Could not remove user ", re);
3711            return false;
3712        }
3713    }
3714
3715    /**
3716     * Called by a device owner to switch the specified user to the foreground.
3717     *
3718     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3719     * @param userHandle the user to switch to; null will switch to primary.
3720     * @return {@code true} if the switch was successful, {@code false} otherwise.
3721     *
3722     * @see Intent#ACTION_USER_FOREGROUND
3723     */
3724    public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
3725        try {
3726            return mService.switchUser(admin, userHandle);
3727        } catch (RemoteException re) {
3728            Log.w(TAG, "Could not switch user ", re);
3729            return false;
3730        }
3731    }
3732
3733    /**
3734     * Called by a profile or device owner to get the application restrictions for a given target
3735     * application running in the profile.
3736     *
3737     * <p>The calling device admin must be a profile or device owner; if it is not, a security
3738     * exception will be thrown.
3739     *
3740     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3741     * @param packageName The name of the package to fetch restricted settings of.
3742     * @return {@link Bundle} of settings corresponding to what was set last time
3743     * {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty {@link Bundle}
3744     * if no restrictions have been set.
3745     */
3746    public Bundle getApplicationRestrictions(@NonNull ComponentName admin, String packageName) {
3747        if (mService != null) {
3748            try {
3749                return mService.getApplicationRestrictions(admin, packageName);
3750            } catch (RemoteException e) {
3751                Log.w(TAG, "Failed talking with device policy service", e);
3752            }
3753        }
3754        return null;
3755    }
3756
3757    /**
3758     * Called by a profile or device owner to set a user restriction specified by the key.
3759     * <p>
3760     * The calling device admin must be a profile or device owner; if it is not,
3761     * a security exception will be thrown.
3762     *
3763     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3764     *            with.
3765     * @param key The key of the restriction. See the constants in
3766     *            {@link android.os.UserManager} for the list of keys.
3767     */
3768    public void addUserRestriction(@NonNull ComponentName admin, String key) {
3769        if (mService != null) {
3770            try {
3771                mService.setUserRestriction(admin, key, true);
3772            } catch (RemoteException e) {
3773                Log.w(TAG, "Failed talking with device policy service", e);
3774            }
3775        }
3776    }
3777
3778    /**
3779     * Called by a profile or device owner to clear a user restriction specified by the key.
3780     * <p>
3781     * The calling device admin must be a profile or device owner; if it is not,
3782     * a security exception will be thrown.
3783     *
3784     * @param admin Which {@link DeviceAdminReceiver} this request is associated
3785     *            with.
3786     * @param key The key of the restriction. See the constants in
3787     *            {@link android.os.UserManager} for the list of keys.
3788     */
3789    public void clearUserRestriction(@NonNull ComponentName admin, String key) {
3790        if (mService != null) {
3791            try {
3792                mService.setUserRestriction(admin, key, false);
3793            } catch (RemoteException e) {
3794                Log.w(TAG, "Failed talking with device policy service", e);
3795            }
3796        }
3797    }
3798
3799    /**
3800     * Called by a profile or device owner to get user restrictions set with
3801     * {@link #addUserRestriction(ComponentName, String)}.
3802     * <p>
3803     * The target user may have more restrictions set by the system or other device owner / profile
3804     * owner.  To get all the user restrictions currently set, use
3805     * {@link UserManager#getUserRestrictions()}.
3806     *
3807     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3808     */
3809    public Bundle getUserRestrictions(@NonNull ComponentName admin) {
3810        Bundle ret = null;
3811        if (mService != null) {
3812            try {
3813                ret = mService.getUserRestrictions(admin);
3814            } catch (RemoteException e) {
3815                Log.w(TAG, "Failed talking with device policy service", e);
3816            }
3817        }
3818        return ret == null ? new Bundle() : ret;
3819    }
3820
3821    /**
3822     * Called by profile or device owners to hide or unhide packages. When a package is hidden it
3823     * is unavailable for use, but the data and actual package file remain.
3824     *
3825     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3826     * @param packageName The name of the package to hide or unhide.
3827     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
3828     *                 unhidden.
3829     * @return boolean Whether the hidden setting of the package was successfully updated.
3830     */
3831    public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
3832            boolean hidden) {
3833        if (mService != null) {
3834            try {
3835                return mService.setApplicationHidden(admin, packageName, hidden);
3836            } catch (RemoteException e) {
3837                Log.w(TAG, "Failed talking with device policy service", e);
3838            }
3839        }
3840        return false;
3841    }
3842
3843    /**
3844     * Called by profile or device owners to determine if a package is hidden.
3845     *
3846     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3847     * @param packageName The name of the package to retrieve the hidden status of.
3848     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
3849     */
3850    public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
3851        if (mService != null) {
3852            try {
3853                return mService.isApplicationHidden(admin, packageName);
3854            } catch (RemoteException e) {
3855                Log.w(TAG, "Failed talking with device policy service", e);
3856            }
3857        }
3858        return false;
3859    }
3860
3861    /**
3862     * Called by profile or device owners to re-enable a system app that was disabled by default
3863     * when the user was initialized.
3864     *
3865     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3866     * @param packageName The package to be re-enabled in the current profile.
3867     */
3868    public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
3869        if (mService != null) {
3870            try {
3871                mService.enableSystemApp(admin, packageName);
3872            } catch (RemoteException e) {
3873                Log.w(TAG, "Failed to install package: " + packageName);
3874            }
3875        }
3876    }
3877
3878    /**
3879     * Called by profile or device owners to re-enable system apps by intent that were disabled
3880     * by default when the user was initialized.
3881     *
3882     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3883     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
3884     *               intent will be re-enabled in the current profile.
3885     * @return int The number of activities that matched the intent and were installed.
3886     */
3887    public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
3888        if (mService != null) {
3889            try {
3890                return mService.enableSystemAppWithIntent(admin, intent);
3891            } catch (RemoteException e) {
3892                Log.w(TAG, "Failed to install packages matching filter: " + intent);
3893            }
3894        }
3895        return 0;
3896    }
3897
3898    /**
3899     * Called by a device owner or profile owner to disable account management for a specific type
3900     * of account.
3901     *
3902     * <p>The calling device admin must be a device owner or profile owner. If it is not, a
3903     * security exception will be thrown.
3904     *
3905     * <p>When account management is disabled for an account type, adding or removing an account
3906     * of that type will not be possible.
3907     *
3908     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3909     * @param accountType For which account management is disabled or enabled.
3910     * @param disabled The boolean indicating that account management will be disabled (true) or
3911     * enabled (false).
3912     */
3913    public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
3914            boolean disabled) {
3915        if (mService != null) {
3916            try {
3917                mService.setAccountManagementDisabled(admin, accountType, disabled);
3918            } catch (RemoteException e) {
3919                Log.w(TAG, "Failed talking with device policy service", e);
3920            }
3921        }
3922    }
3923
3924    /**
3925     * Gets the array of accounts for which account management is disabled by the profile owner.
3926     *
3927     * <p> Account management can be disabled/enabled by calling
3928     * {@link #setAccountManagementDisabled}.
3929     *
3930     * @return a list of account types for which account management has been disabled.
3931     *
3932     * @see #setAccountManagementDisabled
3933     */
3934    public String[] getAccountTypesWithManagementDisabled() {
3935        return getAccountTypesWithManagementDisabledAsUser(myUserId());
3936    }
3937
3938    /**
3939     * @see #getAccountTypesWithManagementDisabled()
3940     * @hide
3941     */
3942    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
3943        if (mService != null) {
3944            try {
3945                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
3946            } catch (RemoteException e) {
3947                Log.w(TAG, "Failed talking with device policy service", e);
3948            }
3949        }
3950
3951        return null;
3952    }
3953
3954    /**
3955     * Sets which packages may enter lock task mode.
3956     *
3957     * <p>Any packages that shares uid with an allowed package will also be allowed
3958     * to activate lock task.
3959     *
3960     * From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
3961     * package list results in locked tasks belonging to those packages to be finished.
3962     *
3963     * This function can only be called by the device owner.
3964     * @param packages The list of packages allowed to enter lock task mode
3965     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3966     *
3967     * @see Activity#startLockTask()
3968     * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
3969     * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
3970     * @see UserManager#DISALLOW_CREATE_WINDOWS
3971     */
3972    public void setLockTaskPackages(@NonNull ComponentName admin, String[] packages)
3973            throws SecurityException {
3974        if (mService != null) {
3975            try {
3976                mService.setLockTaskPackages(admin, packages);
3977            } catch (RemoteException e) {
3978                Log.w(TAG, "Failed talking with device policy service", e);
3979            }
3980        }
3981    }
3982
3983    /**
3984     * This function returns the list of packages allowed to start the lock task mode.
3985     *
3986     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3987     * @hide
3988     */
3989    public String[] getLockTaskPackages(@NonNull ComponentName admin) {
3990        if (mService != null) {
3991            try {
3992                return mService.getLockTaskPackages(admin);
3993            } catch (RemoteException e) {
3994                Log.w(TAG, "Failed talking with device policy service", e);
3995            }
3996        }
3997        return null;
3998    }
3999
4000    /**
4001     * This function lets the caller know whether the given component is allowed to start the
4002     * lock task mode.
4003     * @param pkg The package to check
4004     */
4005    public boolean isLockTaskPermitted(String pkg) {
4006        if (mService != null) {
4007            try {
4008                return mService.isLockTaskPermitted(pkg);
4009            } catch (RemoteException e) {
4010                Log.w(TAG, "Failed talking with device policy service", e);
4011            }
4012        }
4013        return false;
4014    }
4015
4016    /**
4017     * Called by device owners to update {@link Settings.Global} settings. Validation that the value
4018     * of the setting is in the correct form for the setting type should be performed by the caller.
4019     * <p>The settings that can be updated with this method are:
4020     * <ul>
4021     * <li>{@link Settings.Global#ADB_ENABLED}</li>
4022     * <li>{@link Settings.Global#AUTO_TIME}</li>
4023     * <li>{@link Settings.Global#AUTO_TIME_ZONE}</li>
4024     * <li>{@link Settings.Global#DATA_ROAMING}</li>
4025     * <li>{@link Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
4026     * <li>{@link Settings.Global#WIFI_SLEEP_POLICY}</li>
4027     * <li>{@link Settings.Global#STAY_ON_WHILE_PLUGGED_IN}
4028     *   This setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards
4029     *   and can only be set if {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
4030     * <li>{@link Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li>
4031     *   This setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.
4032     *   </li>
4033     * </ul>
4034     * <p>Changing the following settings has no effect as of
4035     * {@link android.os.Build.VERSION_CODES#M}:
4036     * <ul>
4037     * <li>{@link Settings.Global#BLUETOOTH_ON}.
4038     *   Use {@link android.bluetooth.BluetoothAdapter#enable()} and
4039     *   {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
4040     * <li>{@link Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
4041     * <li>{@link Settings.Global#MODE_RINGER}.
4042     *   Use {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
4043     * <li>{@link Settings.Global#NETWORK_PREFERENCE}</li>
4044     * <li>{@link Settings.Global#WIFI_ON}.
4045     *   Use {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
4046     * </ul>
4047     *
4048     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4049     * @param setting The name of the setting to update.
4050     * @param value The value to update the setting to.
4051     */
4052    public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
4053        if (mService != null) {
4054            try {
4055                mService.setGlobalSetting(admin, setting, value);
4056            } catch (RemoteException e) {
4057                Log.w(TAG, "Failed talking with device policy service", e);
4058            }
4059        }
4060    }
4061
4062    /**
4063     * Called by profile or device owners to update {@link Settings.Secure} settings. Validation
4064     * that the value of the setting is in the correct form for the setting type should be performed
4065     * by the caller.
4066     * <p>The settings that can be updated by a profile or device owner with this method are:
4067     * <ul>
4068     * <li>{@link Settings.Secure#DEFAULT_INPUT_METHOD}</li>
4069     * <li>{@link Settings.Secure#INSTALL_NON_MARKET_APPS}</li>
4070     * <li>{@link Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
4071     * </ul>
4072     * <p>A device owner can additionally update the following settings:
4073     * <ul>
4074     * <li>{@link Settings.Secure#LOCATION_MODE}</li>
4075     * </ul>
4076     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4077     * @param setting The name of the setting to update.
4078     * @param value The value to update the setting to.
4079     */
4080    public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
4081        if (mService != null) {
4082            try {
4083                mService.setSecureSetting(admin, setting, value);
4084            } catch (RemoteException e) {
4085                Log.w(TAG, "Failed talking with device policy service", e);
4086            }
4087        }
4088    }
4089
4090    /**
4091     * Designates a specific service component as the provider for
4092     * making permission requests of a local or remote administrator of the user.
4093     * <p/>
4094     * Only a profile owner can designate the restrictions provider.
4095     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4096     * @param provider The component name of the service that implements
4097     * {@link RestrictionsReceiver}. If this param is null,
4098     * it removes the restrictions provider previously assigned.
4099     */
4100    public void setRestrictionsProvider(@NonNull ComponentName admin,
4101            @Nullable ComponentName provider) {
4102        if (mService != null) {
4103            try {
4104                mService.setRestrictionsProvider(admin, provider);
4105            } catch (RemoteException re) {
4106                Log.w(TAG, "Failed to set permission provider on device policy service");
4107            }
4108        }
4109    }
4110
4111    /**
4112     * Called by profile or device owners to set the master volume mute on or off.
4113     *
4114     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4115     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
4116     */
4117    public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
4118        if (mService != null) {
4119            try {
4120                mService.setMasterVolumeMuted(admin, on);
4121            } catch (RemoteException re) {
4122                Log.w(TAG, "Failed to setMasterMute on device policy service");
4123            }
4124        }
4125    }
4126
4127    /**
4128     * Called by profile or device owners to check whether the master volume mute is on or off.
4129     *
4130     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4131     * @return {@code true} if master volume is muted, {@code false} if it's not.
4132     */
4133    public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
4134        if (mService != null) {
4135            try {
4136                return mService.isMasterVolumeMuted(admin);
4137            } catch (RemoteException re) {
4138                Log.w(TAG, "Failed to get isMasterMute on device policy service");
4139            }
4140        }
4141        return false;
4142    }
4143
4144    /**
4145     * Called by profile or device owners to change whether a user can uninstall
4146     * a package.
4147     *
4148     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4149     * @param packageName package to change.
4150     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
4151     */
4152    public void setUninstallBlocked(@NonNull ComponentName admin, String packageName,
4153            boolean uninstallBlocked) {
4154        if (mService != null) {
4155            try {
4156                mService.setUninstallBlocked(admin, packageName, uninstallBlocked);
4157            } catch (RemoteException re) {
4158                Log.w(TAG, "Failed to call block uninstall on device policy service");
4159            }
4160        }
4161    }
4162
4163    /**
4164     * Check whether the current user has been blocked by device policy from uninstalling a package.
4165     * Requires the caller to be the profile owner if checking a specific admin's policy.
4166     * <p>
4167     * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
4168     * behavior of this API is changed such that passing {@code null} as the {@code admin}
4169     * parameter will return if any admin has blocked the uninstallation. Before L MR1, passing
4170     * {@code null} will cause a NullPointerException to be raised.
4171     *
4172     * @param admin The name of the admin component whose blocking policy will be checked, or
4173     *              {@code null} to check whether any admin has blocked the uninstallation.
4174     * @param packageName package to check.
4175     * @return true if uninstallation is blocked.
4176     */
4177    public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
4178        if (mService != null) {
4179            try {
4180                return mService.isUninstallBlocked(admin, packageName);
4181            } catch (RemoteException re) {
4182                Log.w(TAG, "Failed to call block uninstall on device policy service");
4183            }
4184        }
4185        return false;
4186    }
4187
4188    /**
4189     * Called by the profile owner of a managed profile to enable widget providers from a
4190     * given package to be available in the parent profile. As a result the user will be able to
4191     * add widgets from the white-listed package running under the profile to a widget
4192     * host which runs under the parent profile, for example the home screen. Note that
4193     * a package may have zero or more provider components, where each component
4194     * provides a different widget type.
4195     * <p>
4196     * <strong>Note:</strong> By default no widget provider package is white-listed.
4197     *
4198     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4199     * @param packageName The package from which widget providers are white-listed.
4200     * @return Whether the package was added.
4201     *
4202     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
4203     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
4204     */
4205    public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
4206        if (mService != null) {
4207            try {
4208                return mService.addCrossProfileWidgetProvider(admin, packageName);
4209            } catch (RemoteException re) {
4210                Log.w(TAG, "Error calling addCrossProfileWidgetProvider", re);
4211            }
4212        }
4213        return false;
4214    }
4215
4216    /**
4217     * Called by the profile owner of a managed profile to disable widget providers from a given
4218     * package to be available in the parent profile. For this method to take effect the
4219     * package should have been added via {@link #addCrossProfileWidgetProvider(
4220     * android.content.ComponentName, String)}.
4221     * <p>
4222     * <strong>Note:</strong> By default no widget provider package is white-listed.
4223     *
4224     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4225     * @param packageName The package from which widget providers are no longer
4226     *     white-listed.
4227     * @return Whether the package was removed.
4228     *
4229     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
4230     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
4231     */
4232    public boolean removeCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
4233        if (mService != null) {
4234            try {
4235                return mService.removeCrossProfileWidgetProvider(admin, packageName);
4236            } catch (RemoteException re) {
4237                Log.w(TAG, "Error calling removeCrossProfileWidgetProvider", re);
4238            }
4239        }
4240        return false;
4241    }
4242
4243    /**
4244     * Called by the profile owner of a managed profile to query providers from which packages are
4245     * available in the parent profile.
4246     *
4247     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4248     * @return The white-listed package list.
4249     *
4250     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
4251     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
4252     */
4253    public List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
4254        if (mService != null) {
4255            try {
4256                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
4257                if (providers != null) {
4258                    return providers;
4259                }
4260            } catch (RemoteException re) {
4261                Log.w(TAG, "Error calling getCrossProfileWidgetProviders", re);
4262            }
4263        }
4264        return Collections.emptyList();
4265    }
4266
4267    /**
4268     * Called by profile or device owners to set the current user's photo.
4269     *
4270     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4271     * @param icon the bitmap to set as the photo.
4272     */
4273    public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
4274        try {
4275            mService.setUserIcon(admin, icon);
4276        } catch (RemoteException re) {
4277            Log.w(TAG, "Could not set the user icon ", re);
4278        }
4279    }
4280
4281    /**
4282     * Called by device owners to set a local system update policy. When a new policy is set,
4283     * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
4284     *
4285     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
4286     *              components in the device owner package can set system update policies and the
4287     *              most recent policy takes
4288     * effect.
4289     * @param policy the new policy, or {@code null} to clear the current policy.
4290     * @see SystemUpdatePolicy
4291     */
4292    public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
4293        if (mService != null) {
4294            try {
4295                mService.setSystemUpdatePolicy(admin, policy);
4296            } catch (RemoteException re) {
4297                Log.w(TAG, "Error calling setSystemUpdatePolicy", re);
4298            }
4299        }
4300    }
4301
4302    /**
4303     * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
4304     *
4305     * @return The current policy object, or {@code null} if no policy is set.
4306     */
4307    public SystemUpdatePolicy getSystemUpdatePolicy() {
4308        if (mService != null) {
4309            try {
4310                return mService.getSystemUpdatePolicy();
4311            } catch (RemoteException re) {
4312                Log.w(TAG, "Error calling getSystemUpdatePolicy", re);
4313            }
4314        }
4315        return null;
4316    }
4317
4318    /**
4319     * Called by a device owner to disable the keyguard altogether.
4320     *
4321     * <p>Setting the keyguard to disabled has the same effect as choosing "None" as the screen
4322     * lock type. However, this call has no effect if a password, pin or pattern is currently set.
4323     * If a password, pin or pattern is set after the keyguard was disabled, the keyguard stops
4324     * being disabled.
4325     *
4326     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4327     * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
4328     *
4329     * @return {@code false} if attempting to disable the keyguard while a lock password was in
4330     * place. {@code true} otherwise.
4331     */
4332    public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
4333        try {
4334            return mService.setKeyguardDisabled(admin, disabled);
4335        } catch (RemoteException re) {
4336            Log.w(TAG, "Failed talking with device policy service", re);
4337            return false;
4338        }
4339    }
4340
4341    /**
4342     * Called by device owner to disable the status bar. Disabling the status bar blocks
4343     * notifications, quick settings and other screen overlays that allow escaping from
4344     * a single use device.
4345     *
4346     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4347     * @param disabled {@code true} disables the status bar, {@code false} reenables it.
4348     *
4349     * @return {@code false} if attempting to disable the status bar failed.
4350     * {@code true} otherwise.
4351     */
4352    public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
4353        try {
4354            return mService.setStatusBarDisabled(admin, disabled);
4355        } catch (RemoteException re) {
4356            Log.w(TAG, "Failed talking with device policy service", re);
4357            return false;
4358        }
4359    }
4360
4361    /**
4362     * Callable by the system update service to notify device owners about pending updates.
4363     * The caller must hold {@link android.Manifest.permission#NOTIFY_PENDING_SYSTEM_UPDATE}
4364     * permission.
4365     *
4366     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()} indicating
4367     *        when the current pending update was first available. -1 if no update is available.
4368     * @hide
4369     */
4370    @SystemApi
4371    public void notifyPendingSystemUpdate(long updateReceivedTime) {
4372        if (mService != null) {
4373            try {
4374                mService.notifyPendingSystemUpdate(updateReceivedTime);
4375            } catch (RemoteException re) {
4376                Log.w(TAG, "Could not notify device owner about pending system update", re);
4377            }
4378        }
4379    }
4380
4381    /**
4382     * Called by profile or device owners to set the default response for future runtime permission
4383     * requests by applications. The policy can allow for normal operation which prompts the
4384     * user to grant a permission, or can allow automatic granting or denying of runtime
4385     * permission requests by an application. This also applies to new permissions declared by app
4386     * updates. When a permission is denied or granted this way, the effect is equivalent to setting
4387     * the permission grant state via {@link #setPermissionGrantState}.
4388     *
4389     * <p/>As this policy only acts on runtime permission requests, it only applies to applications
4390     * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
4391     *
4392     * @param admin Which profile or device owner this request is associated with.
4393     * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
4394     * {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
4395     *
4396     * @see #setPermissionGrantState
4397     */
4398    public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
4399        try {
4400            mService.setPermissionPolicy(admin, policy);
4401        } catch (RemoteException re) {
4402            Log.w(TAG, "Failed talking with device policy service", re);
4403        }
4404    }
4405
4406    /**
4407     * Returns the current runtime permission policy set by the device or profile owner. The
4408     * default is {@link #PERMISSION_POLICY_PROMPT}.
4409     * @param admin Which profile or device owner this request is associated with.
4410     * @return the current policy for future permission requests.
4411     */
4412    public int getPermissionPolicy(ComponentName admin) {
4413        try {
4414            return mService.getPermissionPolicy(admin);
4415        } catch (RemoteException re) {
4416            return PERMISSION_POLICY_PROMPT;
4417        }
4418    }
4419
4420    /**
4421     * Sets the grant state of a runtime permission for a specific application. The state
4422     * can be {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it
4423     * through the UI, {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission
4424     * is denied and the user cannot manage it through the UI, and {@link
4425     * #PERMISSION_GRANT_STATE_GRANTED granted} in which the permission is granted and the
4426     * user cannot manage it through the UI. This might affect all permissions in a
4427     * group that the runtime permission belongs to. This method can only be called
4428     * by a profile or device owner.
4429     *
4430     * <p/>Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not
4431     * revoke the permission. It retains the previous grant, if any.
4432     *
4433     * <p/>Permissions can be granted or revoked only for applications built with a
4434     * {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
4435     *
4436     * @param admin Which profile or device owner this request is associated with.
4437     * @param packageName The application to grant or revoke a permission to.
4438     * @param permission The permission to grant or revoke.
4439     * @param grantState The permission grant state which is one of {@link
4440     *         #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
4441     *         {@link #PERMISSION_GRANT_STATE_GRANTED},
4442     * @return whether the permission was successfully granted or revoked.
4443     *
4444     * @see #PERMISSION_GRANT_STATE_DENIED
4445     * @see #PERMISSION_GRANT_STATE_DEFAULT
4446     * @see #PERMISSION_GRANT_STATE_GRANTED
4447     */
4448    public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName,
4449            String permission, int grantState) {
4450        try {
4451            return mService.setPermissionGrantState(admin, packageName, permission, grantState);
4452        } catch (RemoteException re) {
4453            Log.w(TAG, "Failed talking with device policy service", re);
4454            return false;
4455        }
4456    }
4457
4458    /**
4459     * Returns the current grant state of a runtime permission for a specific application.
4460     *
4461     * @param admin Which profile or device owner this request is associated with.
4462     * @param packageName The application to check the grant state for.
4463     * @param permission The permission to check for.
4464     * @return the current grant state specified by device policy. If the profile or device owner
4465     * has not set a grant state, the return value is {@link #PERMISSION_GRANT_STATE_DEFAULT}.
4466     * This does not indicate whether or not the permission is currently granted for the package.
4467     *
4468     * <p/>If a grant state was set by the profile or device owner, then the return value will
4469     * be one of {@link #PERMISSION_GRANT_STATE_DENIED} or {@link #PERMISSION_GRANT_STATE_GRANTED},
4470     * which indicates if the permission is currently denied or granted.
4471     *
4472     * @see #setPermissionGrantState(ComponentName, String, String, int)
4473     * @see PackageManager#checkPermission(String, String)
4474     */
4475    public int getPermissionGrantState(@NonNull ComponentName admin, String packageName,
4476            String permission) {
4477        try {
4478            return mService.getPermissionGrantState(admin, packageName, permission);
4479        } catch (RemoteException re) {
4480            Log.w(TAG, "Failed talking with device policy service", re);
4481            return PERMISSION_GRANT_STATE_DEFAULT;
4482        }
4483    }
4484
4485    /**
4486     * Returns if provisioning a managed profile or device is possible or not.
4487     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
4488     * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
4489     * Note that even if this method returns true, there is a slight possibility that the
4490     * provisioning will not be allowed when it is actually initiated because some event has
4491     * happened in between.
4492     * @return if provisioning a managed profile or device is possible or not.
4493     * @throws IllegalArgumentException if the supplied action is not valid.
4494     */
4495    public boolean isProvisioningAllowed(String action) {
4496        try {
4497            return mService.isProvisioningAllowed(action);
4498        } catch (RemoteException re) {
4499            Log.w(TAG, "Failed talking with device policy service", re);
4500            return false;
4501        }
4502    }
4503}
4504