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