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