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