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