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