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