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