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