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