DevicePolicyManager.java revision d55b73145204dce6593dcdb6923ce51f6f6851d7
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.ColorInt;
20import android.annotation.IntDef;
21import android.annotation.NonNull;
22import android.annotation.Nullable;
23import android.annotation.RequiresPermission;
24import android.annotation.SdkConstant;
25import android.annotation.SdkConstant.SdkConstantType;
26import android.annotation.SystemApi;
27import android.annotation.TestApi;
28import android.annotation.UserIdInt;
29import android.annotation.WorkerThread;
30import android.app.Activity;
31import android.app.admin.PasswordMetrics;
32import android.app.IServiceConnection;
33import android.app.admin.SecurityLog.SecurityEvent;
34import android.content.ComponentName;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.ServiceConnection;
39import android.content.pm.PackageManager;
40import android.content.pm.PackageManager.NameNotFoundException;
41import android.content.pm.ParceledListSlice;
42import android.content.pm.UserInfo;
43import android.graphics.Bitmap;
44import android.net.ProxyInfo;
45import android.net.Uri;
46import android.os.Bundle;
47import android.os.PersistableBundle;
48import android.os.Process;
49import android.os.RemoteCallback;
50import android.os.RemoteException;
51import android.os.UserHandle;
52import android.os.UserManager;
53import android.provider.ContactsContract.Directory;
54import android.provider.Settings;
55import android.security.Credentials;
56import android.service.restrictions.RestrictionsReceiver;
57import android.telephony.TelephonyManager;
58import android.util.Log;
59
60import com.android.internal.annotations.VisibleForTesting;
61import com.android.org.conscrypt.TrustedCertificateStore;
62
63import java.io.ByteArrayInputStream;
64import java.io.IOException;
65import java.lang.annotation.Retention;
66import java.lang.annotation.RetentionPolicy;
67import java.net.InetSocketAddress;
68import java.net.Proxy;
69import java.security.KeyFactory;
70import java.security.NoSuchAlgorithmException;
71import java.security.PrivateKey;
72import java.security.cert.Certificate;
73import java.security.cert.CertificateException;
74import java.security.cert.CertificateFactory;
75import java.security.cert.X509Certificate;
76import java.security.spec.InvalidKeySpecException;
77import java.security.spec.PKCS8EncodedKeySpec;
78import java.util.ArrayList;
79import java.util.Arrays;
80import java.util.Collections;
81import java.util.List;
82
83/**
84 * Public interface for managing policies enforced on a device. Most clients of this class must be
85 * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
86 * administrator</a>. Additionally, a device administrator may be registered as either a profile or
87 * device owner. A given method is accessible to all device administrators unless the documentation
88 * for that method specifies that it is restricted to either device or profile owners. Any
89 * application calling an api may only pass as an argument a device administrator component it
90 * owns. Otherwise, a {@link SecurityException} will be thrown.
91 * <div class="special reference">
92 * <h3>Developer Guides</h3>
93 * <p>
94 * For more information about managing policies for device administration, read the <a href=
95 * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
96 * guide. </div>
97 */
98public class DevicePolicyManager {
99    private static String TAG = "DevicePolicyManager";
100
101    private final Context mContext;
102    private final IDevicePolicyManager mService;
103    private final boolean mParentInstance;
104
105    /** @hide */
106    public DevicePolicyManager(Context context, IDevicePolicyManager service) {
107        this(context, service, false);
108    }
109
110    /** @hide */
111    @VisibleForTesting
112    protected DevicePolicyManager(Context context, IDevicePolicyManager service,
113            boolean parentInstance) {
114        mContext = context;
115        mService = service;
116        mParentInstance = parentInstance;
117    }
118
119    /** @hide test will override it. */
120    @VisibleForTesting
121    protected int myUserId() {
122        return UserHandle.myUserId();
123    }
124
125    /**
126     * Activity action: Starts the provisioning flow which sets up a managed profile.
127     *
128     * <p>A managed profile allows data separation for example for the usage of a
129     * device as a personal and corporate device. The user which provisioning is started from and
130     * the managed profile share a launcher.
131     *
132     * <p>This intent will typically be sent by a mobile device management application (MDM).
133     * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
134     * control over the profile.
135     *
136     * <p>It is possible to check if provisioning is allowed or not by querying the method
137     * {@link #isProvisioningAllowed(String)}.
138     *
139     * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
140     * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
141     * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
142     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
143     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
144     *
145     * <p>The intent may also contain the following extras:
146     * <ul>
147     * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
148     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
149     * {@link android.os.Build.VERSION_CODES#N}</li>
150     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
151     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
152     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
153     * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
154     * </ul>
155     *
156     * <p>When managed provisioning has completed, broadcasts are sent to the application specified
157     * in the provisioning intent. The
158     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
159     * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
160     * the primary profile.
161     *
162     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
163     * completed, along with the above broadcast, activity intent
164     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the application specified in
165     * the provisioning intent.
166     *
167     * <p>If provisioning fails, the managedProfile is removed so the device returns to its
168     * previous state.
169     *
170     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
171     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
172     * the provisioning flow was successful, although this doesn't guarantee the full flow will
173     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
174     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
175     */
176    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
177    public static final String ACTION_PROVISION_MANAGED_PROFILE
178        = "android.app.action.PROVISION_MANAGED_PROFILE";
179
180    /**
181     * Activity action: Starts the provisioning flow which sets up a managed user.
182     *
183     * <p>This intent will typically be sent by a mobile device management application (MDM).
184     * Provisioning configures the user as managed user and sets the MDM as the profile
185     * owner who has full control over the user. Provisioning can only happen before user setup has
186     * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
187     * allowed.
188     *
189     * <p>The intent contains the following extras:
190     * <ul>
191     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
192     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
193     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
194     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
195     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
196     * </ul>
197     *
198     * <p>If provisioning fails, the device returns to its previous state.
199     *
200     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
201     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
202     * the provisioning flow was successful, although this doesn't guarantee the full flow will
203     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
204     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
205     *
206     * @hide
207     */
208    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
209    public static final String ACTION_PROVISION_MANAGED_USER
210        = "android.app.action.PROVISION_MANAGED_USER";
211
212    /**
213     * Activity action: Starts the provisioning flow which sets up a managed device.
214     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
215     *
216     * <p> During device owner provisioning a device admin app is set as the owner of the device.
217     * A device owner has full control over the device. The device owner can not be modified by the
218     * user.
219     *
220     * <p> A typical use case would be a device that is owned by a company, but used by either an
221     * employee or client.
222     *
223     * <p> An intent with this action can be sent only on an unprovisioned device.
224     * It is possible to check if provisioning is allowed or not by querying the method
225     * {@link #isProvisioningAllowed(String)}.
226     *
227     * <p>The intent contains the following extras:
228     * <ul>
229     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
230     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
231     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
232     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
233     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
234     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
235     * </ul>
236     *
237     * <p>When device owner provisioning has completed, an intent of the type
238     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
239     * device owner.
240     *
241     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
242     * completed, along with the above broadcast, activity intent
243     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
244     *
245     * <p>If provisioning fails, the device is factory reset.
246     *
247     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
248     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
249     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
250     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
251     */
252    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
253    public static final String ACTION_PROVISION_MANAGED_DEVICE
254        = "android.app.action.PROVISION_MANAGED_DEVICE";
255
256    /**
257     * Activity action: Starts the provisioning flow which sets up a managed device.
258     *
259     * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
260     * the device. A device owner has full control over the device. The device owner can not be
261     * modified by the user and the only way of resetting the device is via factory reset.
262     *
263     * <p>A typical use case would be a device that is owned by a company, but used by either an
264     * employee or client.
265     *
266     * <p>The provisioning message should be sent to an unprovisioned device.
267     *
268     * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
269     * by a privileged app with the permission
270     * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
271     *
272     * <p>The provisioning intent contains the following properties:
273     * <ul>
274     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
275     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
276     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
277     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
278     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
279     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
280     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
281     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
282     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
283     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
284     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
285     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
286     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
287     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
288     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
289     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li></ul>
290     *
291     * @hide
292     */
293    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
294    @SystemApi
295    public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
296            "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
297
298    /**
299     * Activity action: Starts the provisioning flow which sets up a managed device.
300     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
301     *
302     * <p>NOTE: This is only supported on split system user devices, and puts the device into a
303     * management state that is distinct from that reached by
304     * {@link #ACTION_PROVISION_MANAGED_DEVICE} - specifically the device owner runs on the system
305     * user, and only has control over device-wide policies, not individual users and their data.
306     * The primary benefit is that multiple non-system users are supported when provisioning using
307     * this form of device management.
308     *
309     * <p>During device owner provisioning a device admin app is set as the owner of the device.
310     * A device owner has full control over the device. The device owner can not be modified by the
311     * user.
312     *
313     * <p>A typical use case would be a device that is owned by a company, but used by either an
314     * employee or client.
315     *
316     * <p>An intent with this action can be sent only on an unprovisioned device.
317     * It is possible to check if provisioning is allowed or not by querying the method
318     * {@link #isProvisioningAllowed(String)}.
319     *
320     * <p>The intent contains the following extras:
321     * <ul>
322     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
323     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
324     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
325     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
326     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
327     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
328     * </ul>
329     *
330     * <p>When device owner provisioning has completed, an intent of the type
331     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
332     * device owner.
333     *
334     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
335     * completed, along with the above broadcast, activity intent
336     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
337     *
338     * <p>If provisioning fails, the device is factory reset.
339     *
340     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
341     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
342     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
343     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
344     *
345     * @hide
346     */
347    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
348    public static final String ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE
349        = "android.app.action.PROVISION_MANAGED_SHAREABLE_DEVICE";
350
351    /**
352     * Activity action: Finalizes management provisioning, should be used after user-setup
353     * has been completed and {@link #getUserProvisioningState()} returns one of:
354     * <ul>
355     * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
356     * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
357     * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
358     * </ul>
359     *
360     * @hide
361     */
362    @SystemApi
363    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
364    public static final String ACTION_PROVISION_FINALIZATION
365            = "android.app.action.PROVISION_FINALIZATION";
366
367    /**
368     * Action: Bugreport sharing with device owner has been accepted by the user.
369     *
370     * @hide
371     */
372    public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
373            "com.android.server.action.BUGREPORT_SHARING_ACCEPTED";
374
375    /**
376     * Action: Bugreport sharing with device owner has been declined by the user.
377     *
378     * @hide
379     */
380    public static final String ACTION_BUGREPORT_SHARING_DECLINED =
381            "com.android.server.action.BUGREPORT_SHARING_DECLINED";
382
383    /**
384     * Action: Bugreport has been collected and is dispatched to {@link DevicePolicyManagerService}.
385     *
386     * @hide
387     */
388    public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
389            "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
390
391    /**
392     * Extra for shared bugreport's SHA-256 hash.
393     *
394     * @hide
395     */
396    public static final String EXTRA_REMOTE_BUGREPORT_HASH =
397            "android.intent.extra.REMOTE_BUGREPORT_HASH";
398
399    /**
400     * Extra for remote bugreport notification shown type.
401     *
402     * @hide
403     */
404    public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
405            "android.app.extra.bugreport_notification_type";
406
407    /**
408     * Notification type for a started remote bugreport flow.
409     *
410     * @hide
411     */
412    public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
413
414    /**
415     * Notification type for a bugreport that has already been accepted to be shared, but is still
416     * being taken.
417     *
418     * @hide
419     */
420    public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
421
422    /**
423     * Notification type for a bugreport that has been taken and can be shared or declined.
424     *
425     * @hide
426     */
427    public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
428
429    /**
430     * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
431     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
432     *
433     * @hide
434     */
435    public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
436
437    /**
438     * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
439     * allows a mobile device management application or NFC programmer application which starts
440     * managed provisioning to pass data to the management application instance after provisioning.
441     * <p>
442     * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
443     * sends the intent to pass data to itself on the newly created profile.
444     * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
445     * instance of the app on the primary user.
446     * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
447     * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
448     * message should contain a stringified {@link java.util.Properties} instance, whose string
449     * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
450     * management application after provisioning.
451     *
452     * <p>
453     * In both cases the application receives the data in
454     * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
455     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
456     * during the managed provisioning.
457     */
458    public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
459            "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
460
461    /**
462     * A String extra holding the package name of the mobile device management application that
463     * will be set as the profile owner or device owner.
464     *
465     * <p>If an application starts provisioning directly via an intent with action
466     * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
467     * application that started provisioning. The package will be set as profile owner in that case.
468     *
469     * <p>This package is set as device owner when device owner provisioning is started by an NFC
470     * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
471     *
472     * <p> When this extra is set, the application must have exactly one device admin receiver.
473     * This receiver will be set as the profile or device owner and active admin.
474     *
475     * @see DeviceAdminReceiver
476     * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
477     * supported, but only if there is only one device admin receiver in the package that requires
478     * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
479     */
480    @Deprecated
481    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
482        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
483
484    /**
485     * A ComponentName extra indicating the device admin receiver of the mobile device management
486     * application that will be set as the profile owner or device owner and active admin.
487     *
488     * <p>If an application starts provisioning directly via an intent with action
489     * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
490     * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
491     * component has to match the package name of the application that started provisioning.
492     *
493     * <p>This component is set as device owner and active admin when device owner provisioning is
494     * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
495     * message containing an NFC record with MIME type
496     * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
497     * flattened to a string, via {@link ComponentName#flattenToShortString()}.
498     *
499     * @see DeviceAdminReceiver
500     */
501    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
502        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
503
504    /**
505     * An {@link android.accounts.Account} extra holding the account to migrate during managed
506     * profile provisioning. If the account supplied is present in the primary user, it will be
507     * copied, along with its credentials to the managed profile and removed from the primary user.
508     *
509     * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}.
510     */
511
512    public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
513        = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
514
515    /**
516     * A String extra that, holds the email address of the account which a managed profile is
517     * created for. Used with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
518     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}.
519     *
520     * <p> This extra is part of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}.
521     *
522     * <p> If the {@link #ACTION_PROVISION_MANAGED_PROFILE} intent that starts managed provisioning
523     * contains this extra, it is forwarded in the
524     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} intent to the mobile
525     * device management application that was set as the profile owner during provisioning.
526     * It is usually used to avoid that the user has to enter their email address twice.
527     */
528    public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
529        = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
530
531    /**
532     * A integer extra indicating the predominant color to show during the provisioning.
533     * Refer to {@link android.graphics.Color} for how the color is represented.
534     *
535     * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
536     * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
537     */
538    public static final String EXTRA_PROVISIONING_MAIN_COLOR =
539             "android.app.extra.PROVISIONING_MAIN_COLOR";
540
541    /**
542     * A Boolean extra that can be used by the mobile device management application to skip the
543     * disabling of system apps during provisioning when set to {@code true}.
544     *
545     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
546     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
547     */
548    public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
549            "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
550
551    /**
552     * A String extra holding the time zone {@link android.app.AlarmManager} that the device
553     * will be set to.
554     *
555     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
556     * provisioning via an NFC bump.
557     */
558    public static final String EXTRA_PROVISIONING_TIME_ZONE
559        = "android.app.extra.PROVISIONING_TIME_ZONE";
560
561    /**
562     * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
563     * {@link android.app.AlarmManager}.
564     *
565     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
566     * provisioning via an NFC bump.
567     */
568    public static final String EXTRA_PROVISIONING_LOCAL_TIME
569        = "android.app.extra.PROVISIONING_LOCAL_TIME";
570
571    /**
572     * A String extra holding the {@link java.util.Locale} that the device will be set to.
573     * Format: xx_yy, where xx is the language code, and yy the country code.
574     *
575     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
576     * provisioning via an NFC bump.
577     */
578    public static final String EXTRA_PROVISIONING_LOCALE
579        = "android.app.extra.PROVISIONING_LOCALE";
580
581    /**
582     * A String extra holding the ssid of the wifi network that should be used during nfc device
583     * owner provisioning for downloading the mobile device management application.
584     *
585     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
586     * provisioning via an NFC bump.
587     */
588    public static final String EXTRA_PROVISIONING_WIFI_SSID
589        = "android.app.extra.PROVISIONING_WIFI_SSID";
590
591    /**
592     * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
593     * is hidden or not.
594     *
595     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
596     * provisioning via an NFC bump.
597     */
598    public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
599        = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
600
601    /**
602     * A String extra indicating the security type of the wifi network in
603     * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA} or
604     * {@code WEP}.
605     *
606     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
607     * provisioning via an NFC bump.
608     */
609    public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
610        = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
611
612    /**
613     * A String extra holding the password of the wifi network in
614     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
615     *
616     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
617     * provisioning via an NFC bump.
618     */
619    public static final String EXTRA_PROVISIONING_WIFI_PASSWORD
620        = "android.app.extra.PROVISIONING_WIFI_PASSWORD";
621
622    /**
623     * A String extra holding the proxy host for the wifi network in
624     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
625     *
626     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
627     * provisioning via an NFC bump.
628     */
629    public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
630        = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
631
632    /**
633     * An int extra holding the proxy port for the wifi network in
634     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
635     *
636     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
637     * provisioning via an NFC bump.
638     */
639    public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
640        = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
641
642    /**
643     * A String extra holding the proxy bypass for the wifi network in
644     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
645     *
646     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
647     * provisioning via an NFC bump.
648     */
649    public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
650        = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
651
652    /**
653     * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
654     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
655     *
656     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
657     * provisioning via an NFC bump.
658     */
659    public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
660        = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
661
662    /**
663     * A String extra holding a url that specifies the download location of the device admin
664     * package. When not provided it is assumed that the device admin package is already installed.
665     *
666     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
667     * provisioning via an NFC bump.
668     */
669    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
670        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
671
672    /**
673     * An int extra holding a minimum required version code for the device admin package. If the
674     * device admin is already installed on the device, it will only be re-downloaded from
675     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
676     * installed package is less than this version code.
677     *
678     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
679     * provisioning via an NFC bump.
680     */
681    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
682        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
683
684    /**
685     * A String extra holding a http cookie header which should be used in the http request to the
686     * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
687     *
688     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
689     * provisioning via an NFC bump.
690     */
691    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
692        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
693
694    /**
695     * A String extra holding the URL-safe base64 encoded SHA-256 or SHA-1 hash (see notes below) of
696     * the file at download location specified in
697     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
698     *
699     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
700     * present. The provided checksum must match the checksum of the file at the download
701     * location. If the checksum doesn't match an error will be shown to the user and the user will
702     * be asked to factory reset the device.
703     *
704     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
705     * provisioning via an NFC bump.
706     *
707     * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
708     * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
709     * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
710     * addition to SHA-1. Support for SHA-1 is likely to be removed in future OS releases.
711     */
712    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
713        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
714
715    /**
716     * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
717     * android package archive at the download location specified in {@link
718     * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
719     *
720     * <p>The signatures of an android package archive can be obtained using
721     * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
722     * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
723     *
724     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
725     * present. The provided checksum must match the checksum of any signature of the file at
726     * the download location. If the checksum does not match an error will be shown to the user and
727     * the user will be asked to factory reset the device.
728     *
729     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
730     * provisioning via an NFC bump.
731     */
732    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
733        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
734
735    /**
736     * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
737     * has completed successfully.
738     *
739     * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
740     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
741     *
742     * <p>This intent will contain the extra {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} which
743     * corresponds to the account requested to be migrated at provisioning time, if any.
744     */
745    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
746    public static final String ACTION_MANAGED_PROFILE_PROVISIONED
747        = "android.app.action.MANAGED_PROFILE_PROVISIONED";
748
749    /**
750     * Activity action: This activity action is sent to indicate that provisioning of a managed
751     * profile or managed device has completed successfully. It'll be sent at the same time as
752     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
753     * delivered faster as it's an activity intent.
754     *
755     * <p>The intent is only sent to the application on the profile that requested provisioning. In
756     * the device owner case the profile is the primary user.
757     *
758     * @see #ACTION_PROVISION_MANAGED_PROFILE
759     * @see #ACTION_PROVISION_MANAGED_DEVICE
760     */
761    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
762    public static final String ACTION_PROVISIONING_SUCCESSFUL =
763            "android.app.action.PROVISIONING_SUCCESSFUL";
764
765    /**
766     * A boolean extra indicating whether device encryption can be skipped as part of device owner
767     * or managed profile provisioning.
768     *
769     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
770     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
771     *
772     * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
773     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
774     */
775    public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
776             "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
777
778    /**
779     * A {@link Uri} extra pointing to a logo image. This image will be shown during the
780     * provisioning. If this extra is not passed, a default image will be shown.
781     * <h5>The following URI schemes are accepted:</h5>
782     * <ul>
783     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
784     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
785     * </ul>
786     *
787     * <p> It is the responsability of the caller to provide an image with a reasonable
788     * pixed density for the device.
789     *
790     * <p> If a content: URI is passed, the intent should have the flag
791     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
792     * {@link android.content.ClipData} of the intent too.
793     *
794     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
795     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
796     */
797    public static final String EXTRA_PROVISIONING_LOGO_URI =
798            "android.app.extra.PROVISIONING_LOGO_URI";
799
800    /**
801     * A boolean extra indicating if user setup should be skipped, for when provisioning is started
802     * during setup-wizard.
803     *
804     * <p>If unspecified, defaults to {@code true} to match the behavior in
805     * {@link android.os.Build.VERSION_CODES#M} and earlier.
806     *
807     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or
808     * {@link #ACTION_PROVISION_MANAGED_USER}.
809     *
810     * @hide
811     */
812    public static final String EXTRA_PROVISIONING_SKIP_USER_SETUP =
813            "android.app.extra.PROVISIONING_SKIP_USER_SETUP";
814
815    /**
816     * A boolean extra indicating if the user consent steps from the provisioning flow should be
817     * skipped. If unspecified, defaults to {@code false}.
818     *
819     * It can only be used by an existing device owner trying to create a managed profile via
820     * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
821     */
822    public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
823            "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
824
825    /**
826     * This MIME type is used for starting the device owner provisioning.
827     *
828     * <p>During device owner provisioning a device admin app is set as the owner of the device.
829     * A device owner has full control over the device. The device owner can not be modified by the
830     * user and the only way of resetting the device is if the device owner app calls a factory
831     * reset.
832     *
833     * <p> A typical use case would be a device that is owned by a company, but used by either an
834     * employee or client.
835     *
836     * <p> The NFC message must be sent to an unprovisioned device.
837     *
838     * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
839     * contains the following properties:
840     * <ul>
841     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
842     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
843     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
844     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
845     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
846     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
847     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
848     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
849     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
850     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
851     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
852     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
853     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
854     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
855     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
856     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from
857     * {@link android.os.Build.VERSION_CODES#M} </li></ul>
858     *
859     * <p>
860     * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
861     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
862     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
863     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
864     */
865    public static final String MIME_TYPE_PROVISIONING_NFC
866        = "application/com.android.managedprovisioning";
867
868    /**
869     * Activity action: ask the user to add a new device administrator to the system.
870     * The desired policy is the ComponentName of the policy in the
871     * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
872     * bring the user through adding the device administrator to the system (or
873     * allowing them to reject it).
874     *
875     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
876     * field to provide the user with additional explanation (in addition
877     * to your component's description) about what is being added.
878     *
879     * <p>If your administrator is already active, this will ordinarily return immediately (without
880     * user intervention).  However, if your administrator has been updated and is requesting
881     * additional uses-policy flags, the user will be presented with the new list.  New policies
882     * will not be available to the updated administrator until the user has accepted the new list.
883     */
884    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
885    public static final String ACTION_ADD_DEVICE_ADMIN
886            = "android.app.action.ADD_DEVICE_ADMIN";
887
888    /**
889     * @hide
890     * Activity action: ask the user to add a new device administrator as the profile owner
891     * for this user. Only system apps can launch this intent.
892     *
893     * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
894     * extra field. This will invoke a UI to bring the user through adding the profile owner admin
895     * to remotely control restrictions on the user.
896     *
897     * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
898     * result of whether or not the user approved the action. If approved, the result will
899     * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
900     * as a profile owner.
901     *
902     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
903     * field to provide the user with additional explanation (in addition
904     * to your component's description) about what is being added.
905     *
906     * <p>If there is already a profile owner active or the caller is not a system app, the
907     * operation will return a failure result.
908     */
909    @SystemApi
910    public static final String ACTION_SET_PROFILE_OWNER
911            = "android.app.action.SET_PROFILE_OWNER";
912
913    /**
914     * @hide
915     * Name of the profile owner admin that controls the user.
916     */
917    @SystemApi
918    public static final String EXTRA_PROFILE_OWNER_NAME
919            = "android.app.extra.PROFILE_OWNER_NAME";
920
921    /**
922     * Broadcast action: send when any policy admin changes a policy.
923     * This is generally used to find out when a new policy is in effect.
924     *
925     * @hide
926     */
927    public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
928            = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
929
930    /**
931     * Broadcast action: sent when the device owner is set, changed or cleared.
932     *
933     * This broadcast is sent only to the primary user.
934     * @see #ACTION_PROVISION_MANAGED_DEVICE
935     */
936    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
937    public static final String ACTION_DEVICE_OWNER_CHANGED
938            = "android.app.action.DEVICE_OWNER_CHANGED";
939
940    /**
941     * The ComponentName of the administrator component.
942     *
943     * @see #ACTION_ADD_DEVICE_ADMIN
944     */
945    public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
946
947    /**
948     * An optional CharSequence providing additional explanation for why the
949     * admin is being added.
950     *
951     * @see #ACTION_ADD_DEVICE_ADMIN
952     */
953    public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
954
955    /**
956     * Activity action: have the user enter a new password. This activity should
957     * be launched after using {@link #setPasswordQuality(ComponentName, int)},
958     * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
959     * enter a new password that meets the current requirements. You can use
960     * {@link #isActivePasswordSufficient()} to determine whether you need to
961     * have the user select a new password in order to meet the current
962     * constraints. Upon being resumed from this activity, you can check the new
963     * password characteristics to see if they are sufficient.
964     *
965     * If the intent is launched from within a managed profile with a profile
966     * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
967     * this will trigger entering a new password for the parent of the profile.
968     * For all other cases it will trigger entering a new password for the user
969     * or profile it is launched from.
970     *
971     * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
972     */
973    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
974    public static final String ACTION_SET_NEW_PASSWORD
975            = "android.app.action.SET_NEW_PASSWORD";
976
977    /**
978     * Activity action: have the user enter a new password for the parent profile.
979     * If the intent is launched from within a managed profile, this will trigger
980     * entering a new password for the parent of the profile. In all other cases
981     * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
982     */
983    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
984    public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
985            = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
986
987    /**
988     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
989     * the parent profile to access intents sent from the managed profile.
990     * That is, when an app in the managed profile calls
991     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
992     * matching activity in the parent profile.
993     */
994    public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
995
996    /**
997     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
998     * the managed profile to access intents sent from the parent profile.
999     * That is, when an app in the parent profile calls
1000     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1001     * matching activity in the managed profile.
1002     */
1003    public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1004
1005    /**
1006     * Broadcast action: notify that a new local system update policy has been set by the device
1007     * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1008     */
1009    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1010    public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1011            = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1012
1013    /**
1014     * Permission policy to prompt user for new permission requests for runtime permissions.
1015     * Already granted or denied permissions are not affected by this.
1016     */
1017    public static final int PERMISSION_POLICY_PROMPT = 0;
1018
1019    /**
1020     * Permission policy to always grant new permission requests for runtime permissions.
1021     * Already granted or denied permissions are not affected by this.
1022     */
1023    public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1024
1025    /**
1026     * Permission policy to always deny new permission requests for runtime permissions.
1027     * Already granted or denied permissions are not affected by this.
1028     */
1029    public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1030
1031    /**
1032     * Runtime permission state: The user can manage the permission
1033     * through the UI.
1034     */
1035    public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1036
1037    /**
1038     * Runtime permission state: The permission is granted to the app
1039     * and the user cannot manage the permission through the UI.
1040     */
1041    public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1042
1043    /**
1044     * Runtime permission state: The permission is denied to the app
1045     * and the user cannot manage the permission through the UI.
1046     */
1047    public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1048
1049    /**
1050     * No management for current user in-effect. This is the default.
1051     * @hide
1052     */
1053    @SystemApi
1054    public static final int STATE_USER_UNMANAGED = 0;
1055
1056    /**
1057     * Management partially setup, user setup needs to be completed.
1058     * @hide
1059     */
1060    @SystemApi
1061    public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1062
1063    /**
1064     * Management partially setup, user setup completed.
1065     * @hide
1066     */
1067    @SystemApi
1068    public static final int STATE_USER_SETUP_COMPLETE = 2;
1069
1070    /**
1071     * Management setup and active on current user.
1072     * @hide
1073     */
1074    @SystemApi
1075    public static final int STATE_USER_SETUP_FINALIZED = 3;
1076
1077    /**
1078     * Management partially setup on a managed profile.
1079     * @hide
1080     */
1081    @SystemApi
1082    public static final int STATE_USER_PROFILE_COMPLETE = 4;
1083
1084    /**
1085     * @hide
1086     */
1087    @IntDef({STATE_USER_UNMANAGED, STATE_USER_SETUP_INCOMPLETE, STATE_USER_SETUP_COMPLETE,
1088            STATE_USER_SETUP_FINALIZED, STATE_USER_PROFILE_COMPLETE})
1089    @Retention(RetentionPolicy.SOURCE)
1090    public @interface UserProvisioningState {}
1091
1092    /**
1093     * Return true if the given administrator component is currently active (enabled) in the system.
1094     *
1095     * @param admin The administrator component to check for.
1096     * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
1097     *         otherwise
1098     */
1099    public boolean isAdminActive(@NonNull ComponentName admin) {
1100        throwIfParentInstance("isAdminActive");
1101        return isAdminActiveAsUser(admin, myUserId());
1102    }
1103
1104    /**
1105     * @see #isAdminActive(ComponentName)
1106     * @hide
1107     */
1108    public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
1109        if (mService != null) {
1110            try {
1111                return mService.isAdminActive(admin, userId);
1112            } catch (RemoteException e) {
1113                throw e.rethrowFromSystemServer();
1114            }
1115        }
1116        return false;
1117    }
1118    /**
1119     * Return true if the given administrator component is currently being removed
1120     * for the user.
1121     * @hide
1122     */
1123    public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
1124        if (mService != null) {
1125            try {
1126                return mService.isRemovingAdmin(admin, userId);
1127            } catch (RemoteException e) {
1128                throw e.rethrowFromSystemServer();
1129            }
1130        }
1131        return false;
1132    }
1133
1134
1135    /**
1136     * Return a list of all currently active device administrators' component
1137     * names.  If there are no administrators {@code null} may be
1138     * returned.
1139     */
1140    public @Nullable List<ComponentName> getActiveAdmins() {
1141        throwIfParentInstance("getActiveAdmins");
1142        return getActiveAdminsAsUser(myUserId());
1143    }
1144
1145    /**
1146     * @see #getActiveAdmins()
1147     * @hide
1148     */
1149    public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
1150        if (mService != null) {
1151            try {
1152                return mService.getActiveAdmins(userId);
1153            } catch (RemoteException e) {
1154                throw e.rethrowFromSystemServer();
1155            }
1156        }
1157        return null;
1158    }
1159
1160    /**
1161     * Used by package administration code to determine if a package can be stopped
1162     * or uninstalled.
1163     * @hide
1164     */
1165    public boolean packageHasActiveAdmins(String packageName) {
1166        return packageHasActiveAdmins(packageName, myUserId());
1167    }
1168
1169    /**
1170     * Used by package administration code to determine if a package can be stopped
1171     * or uninstalled.
1172     * @hide
1173     */
1174    public boolean packageHasActiveAdmins(String packageName, int userId) {
1175        if (mService != null) {
1176            try {
1177                return mService.packageHasActiveAdmins(packageName, userId);
1178            } catch (RemoteException e) {
1179                throw e.rethrowFromSystemServer();
1180            }
1181        }
1182        return false;
1183    }
1184
1185    /**
1186     * Remove a current administration component.  This can only be called
1187     * by the application that owns the administration component; if you
1188     * try to remove someone else's component, a security exception will be
1189     * thrown.
1190     *
1191     * <p>Note that the operation is not synchronous and the admin might still be active (as
1192     * indicated by {@link #getActiveAdmins()}) by the time this method returns.
1193     *
1194     * @param admin The administration compononent to remove.
1195     * @throws SecurityException if the caller is not in the owner application of {@code admin}.
1196     */
1197    public void removeActiveAdmin(@NonNull ComponentName admin) {
1198        throwIfParentInstance("removeActiveAdmin");
1199        if (mService != null) {
1200            try {
1201                mService.removeActiveAdmin(admin, myUserId());
1202            } catch (RemoteException e) {
1203                throw e.rethrowFromSystemServer();
1204            }
1205        }
1206    }
1207
1208    /**
1209     * Returns true if an administrator has been granted a particular device policy. This can be
1210     * used to check whether the administrator was activated under an earlier set of policies, but
1211     * requires additional policies after an upgrade.
1212     *
1213     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
1214     *            active administrator, or an exception will be thrown.
1215     * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
1216     * @throws SecurityException if {@code admin} is not an active administrator.
1217     */
1218    public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
1219        throwIfParentInstance("hasGrantedPolicy");
1220        if (mService != null) {
1221            try {
1222                return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
1223            } catch (RemoteException e) {
1224                throw e.rethrowFromSystemServer();
1225            }
1226        }
1227        return false;
1228    }
1229
1230    /**
1231     * Returns true if the Profile Challenge is available to use for the given profile user.
1232     *
1233     * @hide
1234     */
1235    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
1236        if (mService != null) {
1237            try {
1238                return mService.isSeparateProfileChallengeAllowed(userHandle);
1239            } catch (RemoteException e) {
1240                throw e.rethrowFromSystemServer();
1241            }
1242        }
1243        return false;
1244    }
1245
1246    /**
1247     * Constant for {@link #setPasswordQuality}: the policy has no requirements
1248     * for the password.  Note that quality constants are ordered so that higher
1249     * values are more restrictive.
1250     */
1251    public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
1252
1253    /**
1254     * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
1255     * recognition technology.  This implies technologies that can recognize the identity of
1256     * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
1257     * Note that quality constants are ordered so that higher values are more restrictive.
1258     */
1259    public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
1260
1261    /**
1262     * Constant for {@link #setPasswordQuality}: the policy requires some kind
1263     * of password or pattern, but doesn't care what it is. Note that quality constants
1264     * are ordered so that higher values are more restrictive.
1265     */
1266    public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
1267
1268    /**
1269     * Constant for {@link #setPasswordQuality}: the user must have entered a
1270     * password containing at least numeric characters.  Note that quality
1271     * constants are ordered so that higher values are more restrictive.
1272     */
1273    public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
1274
1275    /**
1276     * Constant for {@link #setPasswordQuality}: the user must have entered a
1277     * password containing at least numeric characters with no repeating (4444)
1278     * or ordered (1234, 4321, 2468) sequences.  Note that quality
1279     * constants are ordered so that higher values are more restrictive.
1280     */
1281    public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
1282
1283    /**
1284     * Constant for {@link #setPasswordQuality}: the user must have entered a
1285     * password containing at least alphabetic (or other symbol) characters.
1286     * Note that quality constants are ordered so that higher values are more
1287     * restrictive.
1288     */
1289    public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
1290
1291    /**
1292     * Constant for {@link #setPasswordQuality}: the user must have entered a
1293     * password containing at least <em>both></em> numeric <em>and</em>
1294     * alphabetic (or other symbol) characters.  Note that quality constants are
1295     * ordered so that higher values are more restrictive.
1296     */
1297    public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
1298
1299    /**
1300     * Constant for {@link #setPasswordQuality}: the user must have entered a
1301     * password containing at least a letter, a numerical digit and a special
1302     * symbol, by default. With this password quality, passwords can be
1303     * restricted to contain various sets of characters, like at least an
1304     * uppercase letter, etc. These are specified using various methods,
1305     * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
1306     * that quality constants are ordered so that higher values are more
1307     * restrictive.
1308     */
1309    public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
1310
1311    /**
1312     * Constant for {@link #setPasswordQuality}: the user is not allowed to
1313     * modify password. In case this password quality is set, the password is
1314     * managed by a profile owner. The profile owner can set any password,
1315     * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
1316     * that quality constants are ordered so that higher values are more
1317     * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
1318     * the highest.
1319     * @hide
1320     */
1321    public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
1322
1323    /**
1324     * @hide
1325     *
1326     * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
1327     * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
1328     * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
1329     * used by authenticator to exempt their accounts from this:
1330     *
1331     * <ul>
1332     *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
1333     *     <p>In order to make an apk test-only, add android:testOnly="true" to the
1334     *     &lt;application&gt; tag in the manifest.
1335     *
1336     *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
1337     *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
1338     *     Some authenticators claim to have any features, so to detect it, we also check
1339     *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
1340     *     if any of the accounts have it.
1341     * </ul>
1342     */
1343    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
1344            "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
1345
1346    /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
1347    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
1348            "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
1349
1350    /**
1351     * Called by an application that is administering the device to set the password restrictions it
1352     * is imposing. After setting this, the user will not be able to enter a new password that is
1353     * not at least as restrictive as what has been set. Note that the current password will remain
1354     * until the user has set a new one, so the change does not take place immediately. To prompt
1355     * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
1356     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
1357     * <p>
1358     * Quality constants are ordered so that higher values are more restrictive; thus the highest
1359     * requested quality constant (between the policy set here, the user's preference, and any other
1360     * considerations) is the one that is in effect.
1361     * <p>
1362     * The calling device admin must have requested
1363     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1364     * not, a security exception will be thrown.
1365     * <p>
1366     * This method can be called on the {@link DevicePolicyManager} instance returned by
1367     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1368     * profile.
1369     *
1370     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1371     * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
1372     *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
1373     *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
1374     *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
1375     * @throws SecurityException if {@code admin} is not an active administrator or if {@code admin}
1376     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1377     */
1378    public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
1379        if (mService != null) {
1380            try {
1381                mService.setPasswordQuality(admin, quality, mParentInstance);
1382            } catch (RemoteException e) {
1383                throw e.rethrowFromSystemServer();
1384            }
1385        }
1386    }
1387
1388    /**
1389     * Retrieve the current minimum password quality for a particular admin or all admins that set
1390     * restrictions on this user and its participating profiles. Restrictions on profiles that have
1391     * a separate challenge are not taken into account.
1392     *
1393     * <p>This method can be called on the {@link DevicePolicyManager} instance
1394     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1395     * restrictions on the parent profile.
1396     *
1397     * @param admin The name of the admin component to check, or {@code null} to aggregate
1398     * all admins.
1399     */
1400    public int getPasswordQuality(@Nullable ComponentName admin) {
1401        return getPasswordQuality(admin, myUserId());
1402    }
1403
1404    /** @hide per-user version */
1405    public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
1406        if (mService != null) {
1407            try {
1408                return mService.getPasswordQuality(admin, userHandle, mParentInstance);
1409            } catch (RemoteException e) {
1410                throw e.rethrowFromSystemServer();
1411            }
1412        }
1413        return PASSWORD_QUALITY_UNSPECIFIED;
1414    }
1415
1416    /**
1417     * Called by an application that is administering the device to set the minimum allowed password
1418     * length. After setting this, the user will not be able to enter a new password that is not at
1419     * least as restrictive as what has been set. Note that the current password will remain until
1420     * the user has set a new one, so the change does not take place immediately. To prompt the user
1421     * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
1422     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
1423     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
1424     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
1425     * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
1426     * {@link #setPasswordQuality}.
1427     * <p>
1428     * The calling device admin must have requested
1429     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1430     * not, a security exception will be thrown.
1431     * <p>
1432     * This method can be called on the {@link DevicePolicyManager} instance returned by
1433     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1434     * profile.
1435     *
1436     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1437     * @param length The new desired minimum password length. A value of 0 means there is no
1438     *            restriction.
1439     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1440     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1441     */
1442    public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
1443        if (mService != null) {
1444            try {
1445                mService.setPasswordMinimumLength(admin, length, mParentInstance);
1446            } catch (RemoteException e) {
1447                throw e.rethrowFromSystemServer();
1448            }
1449        }
1450    }
1451
1452    /**
1453     * Retrieve the current minimum password length for a particular admin or all admins that set
1454     * restrictions on this user and its participating profiles. Restrictions on profiles that have
1455     * a separate challenge are not taken into account.
1456     *
1457     * <p>This method can be called on the {@link DevicePolicyManager} instance
1458     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1459     * restrictions on the parent profile.
1460     *
1461     * user and its profiles or a particular one.
1462     * @param admin The name of the admin component to check, or {@code null} to aggregate
1463     * all admins.
1464     */
1465    public int getPasswordMinimumLength(@Nullable ComponentName admin) {
1466        return getPasswordMinimumLength(admin, myUserId());
1467    }
1468
1469    /** @hide per-user version */
1470    public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
1471        if (mService != null) {
1472            try {
1473                return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
1474            } catch (RemoteException e) {
1475                throw e.rethrowFromSystemServer();
1476            }
1477        }
1478        return 0;
1479    }
1480
1481    /**
1482     * Called by an application that is administering the device to set the minimum number of upper
1483     * case letters required in the password. After setting this, the user will not be able to enter
1484     * a new password that is not at least as restrictive as what has been set. Note that the
1485     * current password will remain until the user has set a new one, so the change does not take
1486     * place immediately. To prompt the user for a new password, use
1487     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
1488     * setting this value. This constraint is only imposed if the administrator has also requested
1489     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
1490     * <p>
1491     * The calling device admin must have requested
1492     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1493     * not, a security exception will be thrown.
1494     * <p>
1495     * This method can be called on the {@link DevicePolicyManager} instance returned by
1496     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1497     * profile.
1498     *
1499     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1500     * @param length The new desired minimum number of upper case letters required in the password.
1501     *            A value of 0 means there is no restriction.
1502     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1503     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1504     */
1505    public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
1506        if (mService != null) {
1507            try {
1508                mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
1509            } catch (RemoteException e) {
1510                throw e.rethrowFromSystemServer();
1511            }
1512        }
1513    }
1514
1515    /**
1516     * Retrieve the current number of upper case letters required in the password
1517     * for a particular admin or all admins that set restrictions on this user and
1518     * its participating profiles. Restrictions on profiles that have a separate challenge
1519     * are not taken into account.
1520     * This is the same value as set by
1521     * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
1522     * and only applies when the password quality is
1523     * {@link #PASSWORD_QUALITY_COMPLEX}.
1524     *
1525     * <p>This method can be called on the {@link DevicePolicyManager} instance
1526     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1527     * restrictions on the parent profile.
1528     *
1529     * @param admin The name of the admin component to check, or {@code null} to
1530     *            aggregate all admins.
1531     * @return The minimum number of upper case letters required in the
1532     *         password.
1533     */
1534    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
1535        return getPasswordMinimumUpperCase(admin, myUserId());
1536    }
1537
1538    /** @hide per-user version */
1539    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
1540        if (mService != null) {
1541            try {
1542                return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
1543            } catch (RemoteException e) {
1544                throw e.rethrowFromSystemServer();
1545            }
1546        }
1547        return 0;
1548    }
1549
1550    /**
1551     * Called by an application that is administering the device to set the minimum number of lower
1552     * case letters required in the password. After setting this, the user will not be able to enter
1553     * a new password that is not at least as restrictive as what has been set. Note that the
1554     * current password will remain until the user has set a new one, so the change does not take
1555     * place immediately. To prompt the user for a new password, use
1556     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
1557     * setting this value. This constraint is only imposed if the administrator has also requested
1558     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
1559     * <p>
1560     * The calling device admin must have requested
1561     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1562     * not, a security exception will be thrown.
1563     * <p>
1564     * This method can be called on the {@link DevicePolicyManager} instance returned by
1565     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1566     * profile.
1567     *
1568     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1569     * @param length The new desired minimum number of lower case letters required in the password.
1570     *            A value of 0 means there is no restriction.
1571     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1572     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1573     */
1574    public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
1575        if (mService != null) {
1576            try {
1577                mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
1578            } catch (RemoteException e) {
1579                throw e.rethrowFromSystemServer();
1580            }
1581        }
1582    }
1583
1584    /**
1585     * Retrieve the current number of lower case letters required in the password
1586     * for a particular admin or all admins that set restrictions on this user
1587     * and its participating profiles. Restrictions on profiles that have
1588     * a separate challenge are not taken into account.
1589     * This is the same value as set by
1590     * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
1591     * and only applies when the password quality is
1592     * {@link #PASSWORD_QUALITY_COMPLEX}.
1593     *
1594     * <p>This method can be called on the {@link DevicePolicyManager} instance
1595     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1596     * restrictions on the parent profile.
1597     *
1598     * @param admin The name of the admin component to check, or {@code null} to
1599     *            aggregate all admins.
1600     * @return The minimum number of lower case letters required in the
1601     *         password.
1602     */
1603    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
1604        return getPasswordMinimumLowerCase(admin, myUserId());
1605    }
1606
1607    /** @hide per-user version */
1608    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
1609        if (mService != null) {
1610            try {
1611                return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
1612            } catch (RemoteException e) {
1613                throw e.rethrowFromSystemServer();
1614            }
1615        }
1616        return 0;
1617    }
1618
1619    /**
1620     * Called by an application that is administering the device to set the minimum number of
1621     * letters required in the password. After setting this, the user will not be able to enter a
1622     * new password that is not at least as restrictive as what has been set. Note that the current
1623     * password will remain until the user has set a new one, so the change does not take place
1624     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
1625     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
1626     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
1627     * {@link #setPasswordQuality}. The default value is 1.
1628     * <p>
1629     * The calling device admin must have requested
1630     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1631     * not, a security exception will be thrown.
1632     * <p>
1633     * This method can be called on the {@link DevicePolicyManager} instance returned by
1634     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1635     * profile.
1636     *
1637     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1638     * @param length The new desired minimum number of letters required in the password. A value of
1639     *            0 means there is no restriction.
1640     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1641     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1642     */
1643    public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
1644        if (mService != null) {
1645            try {
1646                mService.setPasswordMinimumLetters(admin, length, mParentInstance);
1647            } catch (RemoteException e) {
1648                throw e.rethrowFromSystemServer();
1649            }
1650        }
1651    }
1652
1653    /**
1654     * Retrieve the current number of letters required in the password
1655     * for a particular admin or all admins that set restrictions on this user
1656     * and its participating profiles. Restrictions on profiles that have
1657     * a separate challenge are not taken into account.
1658     * This is the same value as set by
1659     * {@link #setPasswordMinimumLetters(ComponentName, int)}
1660     * and only applies when the password quality is
1661     * {@link #PASSWORD_QUALITY_COMPLEX}.
1662     *
1663     * <p>This method can be called on the {@link DevicePolicyManager} instance
1664     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1665     * restrictions on the parent profile.
1666     *
1667     * @param admin The name of the admin component to check, or {@code null} to
1668     *            aggregate all admins.
1669     * @return The minimum number of letters required in the password.
1670     */
1671    public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
1672        return getPasswordMinimumLetters(admin, myUserId());
1673    }
1674
1675    /** @hide per-user version */
1676    public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
1677        if (mService != null) {
1678            try {
1679                return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
1680            } catch (RemoteException e) {
1681                throw e.rethrowFromSystemServer();
1682            }
1683        }
1684        return 0;
1685    }
1686
1687    /**
1688     * Called by an application that is administering the device to set the minimum number of
1689     * numerical digits required in the password. After setting this, the user will not be able to
1690     * enter a new password that is not at least as restrictive as what has been set. Note that the
1691     * current password will remain until the user has set a new one, so the change does not take
1692     * place immediately. To prompt the user for a new password, use
1693     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
1694     * setting this value. This constraint is only imposed if the administrator has also requested
1695     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 1.
1696     * <p>
1697     * The calling device admin must have requested
1698     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1699     * not, a security exception will be thrown.
1700     * <p>
1701     * This method can be called on the {@link DevicePolicyManager} instance returned by
1702     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1703     * profile.
1704     *
1705     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1706     * @param length The new desired minimum number of numerical digits required in the password. A
1707     *            value of 0 means there is no restriction.
1708     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1709     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1710     */
1711    public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
1712        if (mService != null) {
1713            try {
1714                mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
1715            } catch (RemoteException e) {
1716                throw e.rethrowFromSystemServer();
1717            }
1718        }
1719    }
1720
1721    /**
1722     * Retrieve the current number of numerical digits required in the password
1723     * for a particular admin or all admins that set restrictions on this user
1724     * and its participating profiles. Restrictions on profiles that have
1725     * a separate challenge are not taken into account.
1726     * This is the same value as set by
1727     * {@link #setPasswordMinimumNumeric(ComponentName, int)}
1728     * and only applies when the password quality is
1729     * {@link #PASSWORD_QUALITY_COMPLEX}.
1730     *
1731     * <p>This method can be called on the {@link DevicePolicyManager} instance
1732     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1733     * restrictions on the parent profile.
1734     *
1735     * @param admin The name of the admin component to check, or {@code null} to
1736     *            aggregate all admins.
1737     * @return The minimum number of numerical digits required in the password.
1738     */
1739    public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
1740        return getPasswordMinimumNumeric(admin, myUserId());
1741    }
1742
1743    /** @hide per-user version */
1744    public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
1745        if (mService != null) {
1746            try {
1747                return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
1748            } catch (RemoteException e) {
1749                throw e.rethrowFromSystemServer();
1750            }
1751        }
1752        return 0;
1753    }
1754
1755    /**
1756     * Called by an application that is administering the device to set the minimum number of
1757     * symbols required in the password. After setting this, the user will not be able to enter a
1758     * new password that is not at least as restrictive as what has been set. Note that the current
1759     * password will remain until the user has set a new one, so the change does not take place
1760     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
1761     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
1762     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
1763     * {@link #setPasswordQuality}. The default value is 1.
1764     * <p>
1765     * The calling device admin must have requested
1766     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1767     * not, a security exception will be thrown.
1768     * <p>
1769     * This method can be called on the {@link DevicePolicyManager} instance returned by
1770     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1771     * profile.
1772     *
1773     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1774     * @param length The new desired minimum number of symbols required in the password. A value of
1775     *            0 means there is no restriction.
1776     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1777     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1778     */
1779    public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
1780        if (mService != null) {
1781            try {
1782                mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
1783            } catch (RemoteException e) {
1784                throw e.rethrowFromSystemServer();
1785            }
1786        }
1787    }
1788
1789    /**
1790     * Retrieve the current number of symbols required in the password
1791     * for a particular admin or all admins that set restrictions on this user
1792     * and its participating profiles. Restrictions on profiles that have
1793     * a separate challenge are not taken into account. This is the same value as
1794     * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
1795     * and only applies when the password quality is
1796     * {@link #PASSWORD_QUALITY_COMPLEX}.
1797     *
1798     * <p>This method can be called on the {@link DevicePolicyManager} instance
1799     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1800     * restrictions on the parent profile.
1801     *
1802     * @param admin The name of the admin component to check, or {@code null} to
1803     *            aggregate all admins.
1804     * @return The minimum number of symbols required in the password.
1805     */
1806    public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
1807        return getPasswordMinimumSymbols(admin, myUserId());
1808    }
1809
1810    /** @hide per-user version */
1811    public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
1812        if (mService != null) {
1813            try {
1814                return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
1815            } catch (RemoteException e) {
1816                throw e.rethrowFromSystemServer();
1817            }
1818        }
1819        return 0;
1820    }
1821
1822    /**
1823     * Called by an application that is administering the device to set the minimum number of
1824     * non-letter characters (numerical digits or symbols) required in the password. After setting
1825     * this, the user will not be able to enter a new password that is not at least as restrictive
1826     * as what has been set. Note that the current password will remain until the user has set a new
1827     * one, so the change does not take place immediately. To prompt the user for a new password,
1828     * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
1829     * setting this value. This constraint is only imposed if the administrator has also requested
1830     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
1831     * <p>
1832     * The calling device admin must have requested
1833     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1834     * not, a security exception will be thrown.
1835     * <p>
1836     * This method can be called on the {@link DevicePolicyManager} instance returned by
1837     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1838     * profile.
1839     *
1840     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1841     * @param length The new desired minimum number of letters required in the password. A value of
1842     *            0 means there is no restriction.
1843     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1844     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1845     */
1846    public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
1847        if (mService != null) {
1848            try {
1849                mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
1850            } catch (RemoteException e) {
1851                throw e.rethrowFromSystemServer();
1852            }
1853        }
1854    }
1855
1856    /**
1857     * Retrieve the current number of non-letter characters required in the password
1858     * for a particular admin or all admins that set restrictions on this user
1859     * and its participating profiles. Restrictions on profiles that have
1860     * a separate challenge are not taken into account.
1861     * This is the same value as set by
1862     * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
1863     * and only applies when the password quality is
1864     * {@link #PASSWORD_QUALITY_COMPLEX}.
1865     *
1866     * <p>This method can be called on the {@link DevicePolicyManager} instance
1867     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1868     * restrictions on the parent profile.
1869     *
1870     * @param admin The name of the admin component to check, or {@code null} to
1871     *            aggregate all admins.
1872     * @return The minimum number of letters required in the password.
1873     */
1874    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
1875        return getPasswordMinimumNonLetter(admin, myUserId());
1876    }
1877
1878    /** @hide per-user version */
1879    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
1880        if (mService != null) {
1881            try {
1882                return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
1883            } catch (RemoteException e) {
1884                throw e.rethrowFromSystemServer();
1885            }
1886        }
1887        return 0;
1888    }
1889
1890    /**
1891     * Called by an application that is administering the device to set the length of the password
1892     * history. After setting this, the user will not be able to enter a new password that is the
1893     * same as any password in the history. Note that the current password will remain until the
1894     * user has set a new one, so the change does not take place immediately. To prompt the user for
1895     * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
1896     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
1897     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
1898     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX} {@link #PASSWORD_QUALITY_ALPHABETIC}, or
1899     * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
1900     * <p>
1901     * The calling device admin must have requested
1902     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
1903     * not, a security exception will be thrown.
1904     * <p>
1905     * This method can be called on the {@link DevicePolicyManager} instance returned by
1906     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1907     * profile.
1908     *
1909     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1910     * @param length The new desired length of password history. A value of 0 means there is no
1911     *            restriction.
1912     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1913     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
1914     */
1915    public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
1916        if (mService != null) {
1917            try {
1918                mService.setPasswordHistoryLength(admin, length, mParentInstance);
1919            } catch (RemoteException e) {
1920                throw e.rethrowFromSystemServer();
1921            }
1922        }
1923    }
1924
1925    /**
1926     * Called by a device admin to set the password expiration timeout. Calling this method will
1927     * restart the countdown for password expiration for the given admin, as will changing the
1928     * device password (for all admins).
1929     * <p>
1930     * The provided timeout is the time delta in ms and will be added to the current time. For
1931     * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
1932     * 432000000 ms for timeout.
1933     * <p>
1934     * To disable password expiration, a value of 0 may be used for timeout.
1935     * <p>
1936     * The calling device admin must have requested
1937     * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
1938     * not, a security exception will be thrown.
1939     * <p>
1940     * Note that setting the password will automatically reset the expiration time for all active
1941     * admins. Active admins do not need to explicitly call this method in that case.
1942     * <p>
1943     * This method can be called on the {@link DevicePolicyManager} instance returned by
1944     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
1945     * profile.
1946     *
1947     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
1948     * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
1949     *            there is no restriction (unlimited).
1950     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
1951     *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
1952     */
1953    public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
1954        if (mService != null) {
1955            try {
1956                mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
1957            } catch (RemoteException e) {
1958                throw e.rethrowFromSystemServer();
1959            }
1960        }
1961    }
1962
1963    /**
1964     * Get the password expiration timeout for the given admin. The expiration timeout is the
1965     * recurring expiration timeout provided in the call to
1966     * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
1967     * aggregate of all participating policy administrators if {@code admin} is null. Admins that
1968     * have set restrictions on profiles that have a separate challenge are not taken into account.
1969     *
1970     * <p>This method can be called on the {@link DevicePolicyManager} instance
1971     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1972     * restrictions on the parent profile.
1973     *
1974     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
1975     * @return The timeout for the given admin or the minimum of all timeouts
1976     */
1977    public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
1978        if (mService != null) {
1979            try {
1980                return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
1981            } catch (RemoteException e) {
1982                throw e.rethrowFromSystemServer();
1983            }
1984        }
1985        return 0;
1986    }
1987
1988    /**
1989     * Get the current password expiration time for a particular admin or all admins that set
1990     * restrictions on this user and its participating profiles. Restrictions on profiles that have
1991     * a separate challenge are not taken into account. If admin is {@code null}, then a composite
1992     * of all expiration times is returned - which will be the minimum of all of them.
1993     *
1994     * <p>This method can be called on the {@link DevicePolicyManager} instance
1995     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
1996     * the password expiration for the parent profile.
1997     *
1998     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
1999     * @return The password expiration time, in milliseconds since epoch.
2000     */
2001    public long getPasswordExpiration(@Nullable ComponentName admin) {
2002        if (mService != null) {
2003            try {
2004                return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
2005            } catch (RemoteException e) {
2006                throw e.rethrowFromSystemServer();
2007            }
2008        }
2009        return 0;
2010    }
2011
2012    /**
2013     * Retrieve the current password history length for a particular admin or all admins that
2014     * set restrictions on this user and its participating profiles. Restrictions on profiles that
2015     * have a separate challenge are not taken into account.
2016     *
2017     * <p>This method can be called on the {@link DevicePolicyManager} instance
2018     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2019     * restrictions on the parent profile.
2020     *
2021     * @param admin The name of the admin component to check, or {@code null} to aggregate
2022     * all admins.
2023     * @return The length of the password history
2024     */
2025    public int getPasswordHistoryLength(@Nullable ComponentName admin) {
2026        return getPasswordHistoryLength(admin, myUserId());
2027    }
2028
2029    /** @hide per-user version */
2030    public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
2031        if (mService != null) {
2032            try {
2033                return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
2034            } catch (RemoteException e) {
2035                throw e.rethrowFromSystemServer();
2036            }
2037        }
2038        return 0;
2039    }
2040
2041    /**
2042     * Return the maximum password length that the device supports for a
2043     * particular password quality.
2044     * @param quality The quality being interrogated.
2045     * @return Returns the maximum length that the user can enter.
2046     */
2047    public int getPasswordMaximumLength(int quality) {
2048        // Kind-of arbitrary.
2049        return 16;
2050    }
2051
2052    /**
2053     * Determine whether the current password the user has set is sufficient to meet the policy
2054     * requirements (e.g. quality, minimum length) that have been requested by the admins of this
2055     * user and its participating profiles. Restrictions on profiles that have a separate challenge
2056     * are not taken into account.
2057     * <p>
2058     * The calling device admin must have requested
2059     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2060     * not, a security exception will be thrown.
2061     * <p>
2062     * This method can be called on the {@link DevicePolicyManager} instance returned by
2063     * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
2064     * the parent profile is sufficient.
2065     *
2066     * @return Returns true if the password meets the current requirements, else false.
2067     * @throws SecurityException if the calling application does not own an active administrator
2068     *             that uses {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2069     */
2070    public boolean isActivePasswordSufficient() {
2071        if (mService != null) {
2072            try {
2073                return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
2074            } catch (RemoteException e) {
2075                throw e.rethrowFromSystemServer();
2076            }
2077        }
2078        return false;
2079    }
2080
2081    /**
2082     * Determine whether the current profile password the user has set is sufficient
2083     * to meet the policy requirements (e.g. quality, minimum length) that have been
2084     * requested by the admins of the parent user and its profiles.
2085     *
2086     * @param userHandle the userId of the profile to check the password for.
2087     * @return Returns true if the password would meet the current requirements, else false.
2088     * @throws SecurityException if {@code userHandle} is not a managed profile.
2089     * @hide
2090     */
2091    public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
2092        if (mService != null) {
2093            try {
2094                return mService.isProfileActivePasswordSufficientForParent(userHandle);
2095            } catch (RemoteException e) {
2096                throw e.rethrowFromSystemServer();
2097            }
2098        }
2099        return false;
2100    }
2101
2102    /**
2103     * Retrieve the number of times the user has failed at entering a password since that last
2104     * successful password entry.
2105     * <p>
2106     * This method can be called on the {@link DevicePolicyManager} instance returned by
2107     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
2108     * password attemts for the parent user.
2109     * <p>
2110     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2111     * to be able to call this method; if it has not, a security exception will be thrown.
2112     *
2113     * @return The number of times user has entered an incorrect password since the last correct
2114     *         password entry.
2115     * @throws SecurityException if the calling application does not own an active administrator
2116     *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2117     */
2118    public int getCurrentFailedPasswordAttempts() {
2119        return getCurrentFailedPasswordAttempts(myUserId());
2120    }
2121
2122    /**
2123     * Retrieve the number of times the given user has failed at entering a
2124     * password since that last successful password entry.
2125     *
2126     * <p>The calling device admin must have requested
2127     * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
2128     * not and it is not the system uid, a security exception will be thrown.
2129     *
2130     * @hide
2131     */
2132    public int getCurrentFailedPasswordAttempts(int userHandle) {
2133        if (mService != null) {
2134            try {
2135                return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
2136            } catch (RemoteException e) {
2137                throw e.rethrowFromSystemServer();
2138            }
2139        }
2140        return -1;
2141    }
2142
2143    /**
2144     * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
2145     *
2146     * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
2147     * @hide
2148     */
2149    public boolean getDoNotAskCredentialsOnBoot() {
2150        if (mService != null) {
2151            try {
2152                return mService.getDoNotAskCredentialsOnBoot();
2153            } catch (RemoteException e) {
2154                throw e.rethrowFromSystemServer();
2155            }
2156        }
2157        return false;
2158    }
2159
2160    /**
2161     * Setting this to a value greater than zero enables a built-in policy that will perform a
2162     * device or profile wipe after too many incorrect device-unlock passwords have been entered.
2163     * This built-in policy combines watching for failed passwords and wiping the device, and
2164     * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2165     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
2166     * <p>
2167     * To implement any other policy (e.g. wiping data for a particular application only, erasing or
2168     * revoking credentials, or reporting the failure to a server), you should implement
2169     * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
2170     * use this API, because if the maximum count is reached, the device or profile will be wiped
2171     * immediately, and your callback will not be invoked.
2172     * <p>
2173     * This method can be called on the {@link DevicePolicyManager} instance returned by
2174     * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
2175     * profile.
2176     *
2177     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2178     * @param num The number of failed password attempts at which point the device or profile will
2179     *            be wiped.
2180     * @throws SecurityException if {@code admin} is not an active administrator or does not use
2181     *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2182     *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
2183     */
2184    public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
2185        if (mService != null) {
2186            try {
2187                mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
2188            } catch (RemoteException e) {
2189                throw e.rethrowFromSystemServer();
2190            }
2191        }
2192    }
2193
2194    /**
2195     * Retrieve the current maximum number of login attempts that are allowed before the device
2196     * or profile is wiped, for a particular admin or all admins that set restrictions on this user
2197     * and its participating profiles. Restrictions on profiles that have a separate challenge are
2198     * not taken into account.
2199     *
2200     * <p>This method can be called on the {@link DevicePolicyManager} instance
2201     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2202     * the value for the parent profile.
2203     *
2204     * @param admin The name of the admin component to check, or {@code null} to aggregate
2205     * all admins.
2206     */
2207    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
2208        return getMaximumFailedPasswordsForWipe(admin, myUserId());
2209    }
2210
2211    /** @hide per-user version */
2212    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
2213        if (mService != null) {
2214            try {
2215                return mService.getMaximumFailedPasswordsForWipe(
2216                        admin, userHandle, mParentInstance);
2217            } catch (RemoteException e) {
2218                throw e.rethrowFromSystemServer();
2219            }
2220        }
2221        return 0;
2222    }
2223
2224    /**
2225     * Returns the profile with the smallest maximum failed passwords for wipe,
2226     * for the given user. So for primary user, it might return the primary or
2227     * a managed profile. For a secondary user, it would be the same as the
2228     * user passed in.
2229     * @hide Used only by Keyguard
2230     */
2231    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
2232        if (mService != null) {
2233            try {
2234                return mService.getProfileWithMinimumFailedPasswordsForWipe(
2235                        userHandle, mParentInstance);
2236            } catch (RemoteException e) {
2237                throw e.rethrowFromSystemServer();
2238            }
2239        }
2240        return UserHandle.USER_NULL;
2241    }
2242
2243    /**
2244     * Flag for {@link #resetPassword}: don't allow other admins to change
2245     * the password again until the user has entered it.
2246     */
2247    public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
2248
2249    /**
2250     * Flag for {@link #resetPassword}: don't ask for user credentials on device boot.
2251     * If the flag is set, the device can be booted without asking for user password.
2252     * The absence of this flag does not change the current boot requirements. This flag
2253     * can be set by the device owner only. If the app is not the device owner, the flag
2254     * is ignored. Once the flag is set, it cannot be reverted back without resetting the
2255     * device to factory defaults.
2256     */
2257    public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
2258
2259    /**
2260     * Force a new device unlock password (the password needed to access the entire device, not for
2261     * individual accounts) on the user. This takes effect immediately.
2262     * <p>
2263     * <em>Note: This API has been limited as of {@link android.os.Build.VERSION_CODES#N} for
2264     * device admins that are not device owner and not profile owner.
2265     * The password can now only be changed if there is currently no password set.  Device owner
2266     * and profile owner can still do this when user is unlocked and does not have a managed
2267     * profile.</em>
2268     * <p>
2269     * The given password must be sufficient for the current password quality and length constraints
2270     * as returned by {@link #getPasswordQuality(ComponentName)} and
2271     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
2272     * it will be rejected and false returned. Note that the password may be a stronger quality
2273     * (containing alphanumeric characters when the requested quality is only numeric), in which
2274     * case the currently active quality will be increased to match.
2275     * <p>
2276     * Calling with a null or empty password will clear any existing PIN, pattern or password if the
2277     * current password constraints allow it. <em>Note: This will not work in
2278     * {@link android.os.Build.VERSION_CODES#N} and later for managed profiles, or for device admins
2279     * that are not device owner or profile owner.  Once set, the password cannot be changed to null
2280     * or empty except by these admins.</em>
2281     * <p>
2282     * The calling device admin must have requested
2283     * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
2284     * not, a security exception will be thrown.
2285     *
2286     * @param password The new password for the user. Null or empty clears the password.
2287     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
2288     *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
2289     * @return Returns true if the password was applied, or false if it is not acceptable for the
2290     *         current constraints or if the user has not been decrypted yet.
2291     * @throws SecurityException if the calling application does not own an active administrator
2292     *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
2293     * @throws IllegalStateException if the calling user is locked or has a managed profile.
2294     * @throws IllegalArgumentException if the password does not meet system requirements.
2295     */
2296    public boolean resetPassword(String password, int flags) {
2297        throwIfParentInstance("resetPassword");
2298        if (mService != null) {
2299            try {
2300                return mService.resetPassword(password, flags);
2301            } catch (RemoteException e) {
2302                throw e.rethrowFromSystemServer();
2303            }
2304        }
2305        return false;
2306    }
2307
2308    /**
2309     * Called by an application that is administering the device to set the maximum time for user
2310     * activity until the device will lock. This limits the length that the user can set. It takes
2311     * effect immediately.
2312     * <p>
2313     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
2314     * to be able to call this method; if it has not, a security exception will be thrown.
2315     * <p>
2316     * This method can be called on the {@link DevicePolicyManager} instance returned by
2317     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2318     * profile.
2319     *
2320     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2321     * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
2322     *            is no restriction.
2323     * @throws SecurityException if {@code admin} is not an active administrator or it does not use
2324     *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
2325     */
2326    public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
2327        if (mService != null) {
2328            try {
2329                mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
2330            } catch (RemoteException e) {
2331                throw e.rethrowFromSystemServer();
2332            }
2333        }
2334    }
2335
2336    /**
2337     * Retrieve the current maximum time to unlock for a particular admin or all admins that set
2338     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2339     * a separate challenge are not taken into account.
2340     *
2341     * <p>This method can be called on the {@link DevicePolicyManager} instance
2342     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2343     * restrictions on the parent profile.
2344     *
2345     * @param admin The name of the admin component to check, or {@code null} to aggregate
2346     * all admins.
2347     * @return time in milliseconds for the given admin or the minimum value (strictest) of
2348     * all admins if admin is null. Returns 0 if there are no restrictions.
2349     */
2350    public long getMaximumTimeToLock(@Nullable ComponentName admin) {
2351        return getMaximumTimeToLock(admin, myUserId());
2352    }
2353
2354    /** @hide per-user version */
2355    public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
2356        if (mService != null) {
2357            try {
2358                return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
2359            } catch (RemoteException e) {
2360                throw e.rethrowFromSystemServer();
2361            }
2362        }
2363        return 0;
2364    }
2365
2366    /**
2367     * Returns maximum time to lock that applied by all profiles in this user. We do this because we
2368     * do not have a separate timeout to lock for work challenge only.
2369     *
2370     * @hide
2371     */
2372    public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
2373        if (mService != null) {
2374            try {
2375                return mService.getMaximumTimeToLockForUserAndProfiles(userHandle);
2376            } catch (RemoteException e) {
2377                throw e.rethrowFromSystemServer();
2378            }
2379        }
2380        return 0;
2381    }
2382
2383    /**
2384     * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
2385     * strong auth (e.g. fingerprint, trust agents) times out, i.e. the user has to use a strong
2386     * authentication method like password, pin or pattern.
2387     *
2388     * <p>This timeout is used internally to reset the timer to require strong auth again after
2389     * specified timeout each time it has been successfully used.
2390     *
2391     * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
2392     *
2393     * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
2394     *
2395     * <p>The calling device admin must be a device or profile owner. If it is not,
2396     * a {@link SecurityException} will be thrown.
2397     *
2398     * <p>The calling device admin can verify the value it has set by calling
2399     * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
2400     *
2401     * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
2402     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2403     * profile.
2404     *
2405     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2406     * @param timeoutMs The new timeout, after which the user will have to unlock with strong
2407     *         authentication method. A value of 0 means the admin is not participating in
2408     *         controlling the timeout.
2409     *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
2410     *         72 hours, respectively. Though discouraged, the admin may choose to require strong
2411     *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
2412     *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
2413     *
2414     * @throws SecurityException if {@code admin} is not a device or profile owner.
2415     */
2416    public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
2417            long timeoutMs) {
2418        if (mService != null) {
2419            try {
2420                mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
2421            } catch (RemoteException e) {
2422                throw e.rethrowFromSystemServer();
2423            }
2424        }
2425    }
2426
2427    /**
2428     * Determine for how long the user will be able to use secondary, non strong auth for
2429     * authentication, since last strong method authentication (password, pin or pattern) was used.
2430     * After the returned timeout the user is required to use strong authentication method.
2431     *
2432     * <p>This method can be called on the {@link DevicePolicyManager} instance
2433     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2434     * restrictions on the parent profile.
2435     *
2436     * @param admin The name of the admin component to check, or {@code null} to aggregate
2437     *         accross all participating admins.
2438     * @return The timeout or 0 if not configured for the provided admin.
2439     */
2440    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
2441        return getRequiredStrongAuthTimeout(admin, myUserId());
2442    }
2443
2444    /** @hide per-user version */
2445    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
2446        if (mService != null) {
2447            try {
2448                return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
2449            } catch (RemoteException e) {
2450                throw e.rethrowFromSystemServer();
2451            }
2452        }
2453        return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
2454    }
2455
2456    /**
2457     * Make the device lock immediately, as if the lock screen timeout has expired at the point of
2458     * this call.
2459     * <p>
2460     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
2461     * to be able to call this method; if it has not, a security exception will be thrown.
2462     * <p>
2463     * This method can be called on the {@link DevicePolicyManager} instance returned by
2464     * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
2465     *
2466     * @throws SecurityException if the calling application does not own an active administrator
2467     *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
2468     */
2469    public void lockNow() {
2470        if (mService != null) {
2471            try {
2472                mService.lockNow(mParentInstance);
2473            } catch (RemoteException e) {
2474                throw e.rethrowFromSystemServer();
2475            }
2476        }
2477    }
2478
2479    /**
2480     * Flag for {@link #wipeData(int)}: also erase the device's external
2481     * storage (such as SD cards).
2482     */
2483    public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
2484
2485    /**
2486     * Flag for {@link #wipeData(int)}: also erase the factory reset protection
2487     * data.
2488     *
2489     * <p>This flag may only be set by device owner admins; if it is set by
2490     * other admins a {@link SecurityException} will be thrown.
2491     */
2492    public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
2493
2494    /**
2495     * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
2496     * other users will remain unaffected. Calling from the primary user will cause the device to
2497     * reboot, erasing all device data - including all the secondary users and their data - while
2498     * booting up.
2499     * <p>
2500     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
2501     * be able to call this method; if it has not, a security exception will be thrown.
2502     *
2503     * @param flags Bit mask of additional options: currently supported flags are
2504     *            {@link #WIPE_EXTERNAL_STORAGE} and {@link #WIPE_RESET_PROTECTION_DATA}.
2505     * @throws SecurityException if the calling application does not own an active administrator
2506     *             that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
2507     */
2508    public void wipeData(int flags) {
2509        throwIfParentInstance("wipeData");
2510        if (mService != null) {
2511            try {
2512                mService.wipeData(flags);
2513            } catch (RemoteException e) {
2514                throw e.rethrowFromSystemServer();
2515            }
2516        }
2517    }
2518
2519    /**
2520     * Called by an application that is administering the device to set the
2521     * global proxy and exclusion list.
2522     * <p>
2523     * The calling device admin must have requested
2524     * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
2525     * this method; if it has not, a security exception will be thrown.
2526     * Only the first device admin can set the proxy. If a second admin attempts
2527     * to set the proxy, the {@link ComponentName} of the admin originally setting the
2528     * proxy will be returned. If successful in setting the proxy, {@code null} will
2529     * be returned.
2530     * The method can be called repeatedly by the device admin alrady setting the
2531     * proxy to update the proxy and exclusion list.
2532     *
2533     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2534     * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
2535     *            Pass Proxy.NO_PROXY to reset the proxy.
2536     * @param exclusionList a list of domains to be excluded from the global proxy.
2537     * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
2538     *            of the device admin that sets the proxy.
2539     * @hide
2540     */
2541    public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
2542            List<String> exclusionList ) {
2543        throwIfParentInstance("setGlobalProxy");
2544        if (proxySpec == null) {
2545            throw new NullPointerException();
2546        }
2547        if (mService != null) {
2548            try {
2549                String hostSpec;
2550                String exclSpec;
2551                if (proxySpec.equals(Proxy.NO_PROXY)) {
2552                    hostSpec = null;
2553                    exclSpec = null;
2554                } else {
2555                    if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
2556                        throw new IllegalArgumentException();
2557                    }
2558                    InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
2559                    String hostName = sa.getHostName();
2560                    int port = sa.getPort();
2561                    StringBuilder hostBuilder = new StringBuilder();
2562                    hostSpec = hostBuilder.append(hostName)
2563                        .append(":").append(Integer.toString(port)).toString();
2564                    if (exclusionList == null) {
2565                        exclSpec = "";
2566                    } else {
2567                        StringBuilder listBuilder = new StringBuilder();
2568                        boolean firstDomain = true;
2569                        for (String exclDomain : exclusionList) {
2570                            if (!firstDomain) {
2571                                listBuilder = listBuilder.append(",");
2572                            } else {
2573                                firstDomain = false;
2574                            }
2575                            listBuilder = listBuilder.append(exclDomain.trim());
2576                        }
2577                        exclSpec = listBuilder.toString();
2578                    }
2579                    if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
2580                            != android.net.Proxy.PROXY_VALID)
2581                        throw new IllegalArgumentException();
2582                }
2583                return mService.setGlobalProxy(admin, hostSpec, exclSpec);
2584            } catch (RemoteException e) {
2585                throw e.rethrowFromSystemServer();
2586            }
2587        }
2588        return null;
2589    }
2590
2591    /**
2592     * Set a network-independent global HTTP proxy. This is not normally what you want for typical
2593     * HTTP proxies - they are generally network dependent. However if you're doing something
2594     * unusual like general internal filtering this may be useful. On a private network where the
2595     * proxy is not accessible, you may break HTTP using this.
2596     * <p>
2597     * This method requires the caller to be the device owner.
2598     * <p>
2599     * This proxy is only a recommendation and it is possible that some apps will ignore it.
2600     *
2601     * @see ProxyInfo
2602     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2603     * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
2604     *            {@code null} value will clear the global HTTP proxy.
2605     * @throws SecurityException if {@code admin} is not the device owner.
2606     */
2607    public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
2608            proxyInfo) {
2609        throwIfParentInstance("setRecommendedGlobalProxy");
2610        if (mService != null) {
2611            try {
2612                mService.setRecommendedGlobalProxy(admin, proxyInfo);
2613            } catch (RemoteException e) {
2614                throw e.rethrowFromSystemServer();
2615            }
2616        }
2617    }
2618
2619    /**
2620     * Returns the component name setting the global proxy.
2621     * @return ComponentName object of the device admin that set the global proxy, or {@code null}
2622     *         if no admin has set the proxy.
2623     * @hide
2624     */
2625    public @Nullable ComponentName getGlobalProxyAdmin() {
2626        if (mService != null) {
2627            try {
2628                return mService.getGlobalProxyAdmin(myUserId());
2629            } catch (RemoteException e) {
2630                throw e.rethrowFromSystemServer();
2631            }
2632        }
2633        return null;
2634    }
2635
2636    /**
2637     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
2638     * indicating that encryption is not supported.
2639     */
2640    public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
2641
2642    /**
2643     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
2644     * indicating that encryption is supported, but is not currently active.
2645     */
2646    public static final int ENCRYPTION_STATUS_INACTIVE = 1;
2647
2648    /**
2649     * Result code for {@link #getStorageEncryptionStatus}:
2650     * indicating that encryption is not currently active, but is currently
2651     * being activated.  This is only reported by devices that support
2652     * encryption of data and only when the storage is currently
2653     * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
2654     * to become encrypted will never return this value.
2655     */
2656    public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
2657
2658    /**
2659     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
2660     * indicating that encryption is active.
2661     * <p>
2662     * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
2663     */
2664    public static final int ENCRYPTION_STATUS_ACTIVE = 3;
2665
2666    /**
2667     * Result code for {@link #getStorageEncryptionStatus}:
2668     * indicating that encryption is active, but an encryption key has not
2669     * been set by the user.
2670     */
2671    public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
2672
2673    /**
2674     * Result code for {@link #getStorageEncryptionStatus}:
2675     * indicating that encryption is active and the encryption key is tied to the user or profile.
2676     * <p>
2677     * This value is only returned to apps targeting API level 24 and above. For apps targeting
2678     * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
2679     * encryption key is specific to the user or profile.
2680     */
2681    public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
2682
2683    /**
2684     * Activity action: begin the process of encrypting data on the device.  This activity should
2685     * be launched after using {@link #setStorageEncryption} to request encryption be activated.
2686     * After resuming from this activity, use {@link #getStorageEncryption}
2687     * to check encryption status.  However, on some devices this activity may never return, as
2688     * it may trigger a reboot and in some cases a complete data wipe of the device.
2689     */
2690    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2691    public static final String ACTION_START_ENCRYPTION
2692            = "android.app.action.START_ENCRYPTION";
2693    /**
2694     * Widgets are enabled in keyguard
2695     */
2696    public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
2697
2698    /**
2699     * Disable all keyguard widgets. Has no effect.
2700     */
2701    public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
2702
2703    /**
2704     * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
2705     */
2706    public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
2707
2708    /**
2709     * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
2710     */
2711    public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
2712
2713    /**
2714     * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
2715     */
2716    public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
2717
2718    /**
2719     * Ignore trust agent state on secure keyguard screens
2720     * (e.g. PIN/Pattern/Password).
2721     */
2722    public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
2723
2724    /**
2725     * Disable fingerprint sensor on keyguard secure screens (e.g. PIN/Pattern/Password).
2726     */
2727    public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
2728
2729    /**
2730     * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
2731     */
2732    public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
2733
2734    /**
2735     * Disable all current and future keyguard customizations.
2736     */
2737    public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
2738
2739    /**
2740     * Called by an application that is administering the device to request that the storage system
2741     * be encrypted.
2742     * <p>
2743     * When multiple device administrators attempt to control device encryption, the most secure,
2744     * supported setting will always be used. If any device administrator requests device
2745     * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
2746     * device encryption while another device administrator has enabled it, the call to disable will
2747     * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
2748     * <p>
2749     * This policy controls encryption of the secure (application data) storage area. Data written
2750     * to other storage areas may or may not be encrypted, and this policy does not require or
2751     * control the encryption of any other storage areas. There is one exception: If
2752     * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
2753     * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
2754     * written to disk within the encrypted storage area.
2755     * <p>
2756     * Important Note: On some devices, it is possible to encrypt storage without requiring the user
2757     * to create a device PIN or Password. In this case, the storage is encrypted, but the
2758     * encryption key may not be fully secured. For maximum security, the administrator should also
2759     * require (and check for) a pattern, PIN, or password.
2760     *
2761     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2762     * @param encrypt true to request encryption, false to release any previous request
2763     * @return the new request status (for all active admins) - will be one of
2764     *         {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, or
2765     *         {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value of the requests; Use
2766     *         {@link #getStorageEncryptionStatus()} to query the actual device state.
2767     * @throws SecurityException if {@code admin} is not an active administrator or does not use
2768     *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
2769     */
2770    public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
2771        throwIfParentInstance("setStorageEncryption");
2772        if (mService != null) {
2773            try {
2774                return mService.setStorageEncryption(admin, encrypt);
2775            } catch (RemoteException e) {
2776                throw e.rethrowFromSystemServer();
2777            }
2778        }
2779        return ENCRYPTION_STATUS_UNSUPPORTED;
2780    }
2781
2782    /**
2783     * Called by an application that is administering the device to
2784     * determine the requested setting for secure storage.
2785     *
2786     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
2787     * this will return the requested encryption setting as an aggregate of all active
2788     * administrators.
2789     * @return true if the admin(s) are requesting encryption, false if not.
2790     */
2791    public boolean getStorageEncryption(@Nullable ComponentName admin) {
2792        throwIfParentInstance("getStorageEncryption");
2793        if (mService != null) {
2794            try {
2795                return mService.getStorageEncryption(admin, myUserId());
2796            } catch (RemoteException e) {
2797                throw e.rethrowFromSystemServer();
2798            }
2799        }
2800        return false;
2801    }
2802
2803    /**
2804     * Called by an application that is administering the device to
2805     * determine the current encryption status of the device.
2806     * <p>
2807     * Depending on the returned status code, the caller may proceed in different
2808     * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
2809     * storage system does not support encryption.  If the
2810     * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
2811     * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
2812     * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
2813     * storage system has enabled encryption but no password is set so further action
2814     * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
2815     * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
2816     * no further action is required.
2817     *
2818     * @return current status of encryption. The value will be one of
2819     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
2820     * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
2821     * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
2822     */
2823    public int getStorageEncryptionStatus() {
2824        throwIfParentInstance("getStorageEncryptionStatus");
2825        return getStorageEncryptionStatus(myUserId());
2826    }
2827
2828    /** @hide per-user version */
2829    public int getStorageEncryptionStatus(int userHandle) {
2830        if (mService != null) {
2831            try {
2832                return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
2833            } catch (RemoteException e) {
2834                throw e.rethrowFromSystemServer();
2835            }
2836        }
2837        return ENCRYPTION_STATUS_UNSUPPORTED;
2838    }
2839
2840    /**
2841     * Mark a CA certificate as approved by the device user. This means that they have been notified
2842     * of the installation, were made aware of the risks, viewed the certificate and still wanted to
2843     * keep the certificate on the device.
2844     *
2845     * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
2846     * this certificate.
2847     *
2848     * @hide
2849     */
2850    public boolean approveCaCert(String alias, int userHandle, boolean approval) {
2851        if (mService != null) {
2852            try {
2853                return mService.approveCaCert(alias, userHandle, approval);
2854            } catch (RemoteException e) {
2855                throw e.rethrowFromSystemServer();
2856            }
2857        }
2858        return false;
2859    }
2860
2861    /**
2862     * Check whether a CA certificate has been approved by the device user.
2863     *
2864     * @hide
2865     */
2866    public boolean isCaCertApproved(String alias, int userHandle) {
2867        if (mService != null) {
2868            try {
2869                return mService.isCaCertApproved(alias, userHandle);
2870            } catch (RemoteException e) {
2871                throw e.rethrowFromSystemServer();
2872            }
2873        }
2874        return false;
2875    }
2876
2877    /**
2878     * Installs the given certificate as a user CA.
2879     *
2880     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2881     *              {@code null} if calling from a delegated certificate installer.
2882     * @param certBuffer encoded form of the certificate to install.
2883     *
2884     * @return false if the certBuffer cannot be parsed or installation is
2885     *         interrupted, true otherwise.
2886     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
2887     *         owner.
2888     */
2889    public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
2890        throwIfParentInstance("installCaCert");
2891        if (mService != null) {
2892            try {
2893                return mService.installCaCert(admin, certBuffer);
2894            } catch (RemoteException e) {
2895                throw e.rethrowFromSystemServer();
2896            }
2897        }
2898        return false;
2899    }
2900
2901    /**
2902     * Uninstalls the given certificate from trusted user CAs, if present.
2903     *
2904     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2905     *              {@code null} if calling from a delegated certificate installer.
2906     * @param certBuffer encoded form of the certificate to remove.
2907     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
2908     *         owner.
2909     */
2910    public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
2911        throwIfParentInstance("uninstallCaCert");
2912        if (mService != null) {
2913            try {
2914                final String alias = getCaCertAlias(certBuffer);
2915                mService.uninstallCaCerts(admin, new String[] {alias});
2916            } catch (CertificateException e) {
2917                Log.w(TAG, "Unable to parse certificate", e);
2918            } catch (RemoteException e) {
2919                throw e.rethrowFromSystemServer();
2920            }
2921        }
2922    }
2923
2924    /**
2925     * Returns all CA certificates that are currently trusted, excluding system CA certificates.
2926     * If a user has installed any certificates by other means than device policy these will be
2927     * included too.
2928     *
2929     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2930     *              {@code null} if calling from a delegated certificate installer.
2931     * @return a List of byte[] arrays, each encoding one user CA certificate.
2932     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
2933     *         owner.
2934     */
2935    public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
2936        final List<byte[]> certs = new ArrayList<byte[]>();
2937        throwIfParentInstance("getInstalledCaCerts");
2938        if (mService != null) {
2939            try {
2940                mService.enforceCanManageCaCerts(admin);
2941                final TrustedCertificateStore certStore = new TrustedCertificateStore();
2942                for (String alias : certStore.userAliases()) {
2943                    try {
2944                        certs.add(certStore.getCertificate(alias).getEncoded());
2945                    } catch (CertificateException ce) {
2946                        Log.w(TAG, "Could not encode certificate: " + alias, ce);
2947                    }
2948                }
2949            } catch (RemoteException re) {
2950                throw re.rethrowFromSystemServer();
2951            }
2952        }
2953        return certs;
2954    }
2955
2956    /**
2957     * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
2958     * means other than device policy will also be removed, except for system CA certificates.
2959     *
2960     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2961     *              {@code null} if calling from a delegated certificate installer.
2962     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
2963     *         owner.
2964     */
2965    public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
2966        throwIfParentInstance("uninstallAllUserCaCerts");
2967        if (mService != null) {
2968            try {
2969                mService.uninstallCaCerts(admin, new TrustedCertificateStore().userAliases()
2970                        .toArray(new String[0]));
2971            } catch (RemoteException re) {
2972                throw re.rethrowFromSystemServer();
2973            }
2974        }
2975    }
2976
2977    /**
2978     * Returns whether this certificate is installed as a trusted CA.
2979     *
2980     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
2981     *              {@code null} if calling from a delegated certificate installer.
2982     * @param certBuffer encoded form of the certificate to look up.
2983     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
2984     *         owner.
2985     */
2986    public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
2987        throwIfParentInstance("hasCaCertInstalled");
2988        if (mService != null) {
2989            try {
2990                mService.enforceCanManageCaCerts(admin);
2991                return getCaCertAlias(certBuffer) != null;
2992            } catch (RemoteException re) {
2993                throw re.rethrowFromSystemServer();
2994            } catch (CertificateException ce) {
2995                Log.w(TAG, "Could not parse certificate", ce);
2996            }
2997        }
2998        return false;
2999    }
3000
3001    /**
3002     * Called by a device or profile owner, or delegated certificate installer, to install a
3003     * certificate and corresponding private key. All apps within the profile will be able to access
3004     * the certificate and use the private key, given direct user approval.
3005     *
3006     * <p>Access to the installed credentials will not be granted to the caller of this API without
3007     * direct user approval. This is for security - should a certificate installer become
3008     * compromised, certificates it had already installed will be protected.
3009     *
3010     * <p>If the installer must have access to the credentials, call
3011     * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
3012     *
3013     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3014     *            {@code null} if calling from a delegated certificate installer.
3015     * @param privKey The private key to install.
3016     * @param cert The certificate to install.
3017     * @param alias The private key alias under which to install the certificate. If a certificate
3018     * with that alias already exists, it will be overwritten.
3019     * @return {@code true} if the keys were installed, {@code false} otherwise.
3020     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3021     *         owner.
3022     */
3023    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
3024            @NonNull Certificate cert, @NonNull String alias) {
3025        return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
3026    }
3027
3028    /**
3029     * Called by a device or profile owner, or delegated certificate installer, to install a
3030     * certificate chain and corresponding private key for the leaf certificate. All apps within the
3031     * profile will be able to access the certificate chain and use the private key, given direct
3032     * user approval.
3033     *
3034     * <p>The caller of this API may grant itself access to the certificate and private key
3035     * immediately, without user approval. It is a best practice not to request this unless strictly
3036     * necessary since it opens up additional security vulnerabilities.
3037     *
3038     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3039     *        {@code null} if calling from a delegated certificate installer.
3040     * @param privKey The private key to install.
3041     * @param certs The certificate chain to install. The chain should start with the leaf
3042     *        certificate and include the chain of trust in order. This will be returned by
3043     *        {@link android.security.KeyChain#getCertificateChain}.
3044     * @param alias The private key alias under which to install the certificate. If a certificate
3045     *        with that alias already exists, it will be overwritten.
3046     * @param requestAccess {@code true} to request that the calling app be granted access to the
3047     *        credentials immediately. Otherwise, access to the credentials will be gated by user
3048     *        approval.
3049     * @return {@code true} if the keys were installed, {@code false} otherwise.
3050     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3051     *         owner.
3052     * @see android.security.KeyChain#getCertificateChain
3053     */
3054    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
3055            @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
3056        throwIfParentInstance("installKeyPair");
3057        try {
3058            final byte[] pemCert = Credentials.convertToPem(certs[0]);
3059            byte[] pemChain = null;
3060            if (certs.length > 1) {
3061                pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
3062            }
3063            final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
3064                    .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
3065            return mService.installKeyPair(admin, pkcs8Key, pemCert, pemChain, alias,
3066                    requestAccess);
3067        } catch (RemoteException e) {
3068            throw e.rethrowFromSystemServer();
3069        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
3070            Log.w(TAG, "Failed to obtain private key material", e);
3071        } catch (CertificateException | IOException e) {
3072            Log.w(TAG, "Could not pem-encode certificate", e);
3073        }
3074        return false;
3075    }
3076
3077    /**
3078     * Called by a device or profile owner, or delegated certificate installer, to remove a
3079     * certificate and private key pair installed under a given alias.
3080     *
3081     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3082     *        {@code null} if calling from a delegated certificate installer.
3083     * @param alias The private key alias under which the certificate is installed.
3084     * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
3085     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3086     *         owner.
3087     */
3088    public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
3089        throwIfParentInstance("removeKeyPair");
3090        try {
3091            return mService.removeKeyPair(admin, alias);
3092        } catch (RemoteException e) {
3093            throw e.rethrowFromSystemServer();
3094        }
3095    }
3096
3097    /**
3098     * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
3099     * doesn't exist.
3100     */
3101    private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
3102        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
3103        final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
3104                              new ByteArrayInputStream(certBuffer));
3105        return new TrustedCertificateStore().getCertificateAlias(cert);
3106    }
3107
3108    /**
3109     * Called by a profile owner or device owner to grant access to privileged certificate
3110     * manipulation APIs to a third-party certificate installer app. Granted APIs include
3111     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
3112     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
3113     * <p>
3114     * Delegated certificate installer is a per-user state. The delegated access is persistent until
3115     * it is later cleared by calling this method with a null value or uninstallling the certificate
3116     * installer.
3117     * <p>
3118     * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
3119     * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
3120     * supplied certificate installer package must be installed when calling this API, otherwise an
3121     * {@link IllegalArgumentException} will be thrown.
3122     *
3123     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3124     * @param installerPackage The package name of the certificate installer which will be given
3125     *            access. If {@code null} is given the current package will be cleared.
3126     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3127     */
3128    public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
3129            installerPackage) throws SecurityException {
3130        throwIfParentInstance("setCertInstallerPackage");
3131        if (mService != null) {
3132            try {
3133                mService.setCertInstallerPackage(admin, installerPackage);
3134            } catch (RemoteException e) {
3135                throw e.rethrowFromSystemServer();
3136            }
3137        }
3138    }
3139
3140    /**
3141     * Called by a profile owner or device owner to retrieve the certificate installer for the user.
3142     * null if none is set.
3143     *
3144     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3145     * @return The package name of the current delegated certificate installer, or {@code null} if
3146     *         none is set.
3147     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3148     */
3149    public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
3150            throws SecurityException {
3151        throwIfParentInstance("getCertInstallerPackage");
3152        if (mService != null) {
3153            try {
3154                return mService.getCertInstallerPackage(admin);
3155            } catch (RemoteException e) {
3156                throw e.rethrowFromSystemServer();
3157            }
3158        }
3159        return null;
3160    }
3161
3162    /**
3163     * Called by a device or profile owner to configure an always-on VPN connection through a
3164     * specific application for the current user.
3165     *
3166     * @deprecated this version only exists for compability with previous developer preview builds.
3167     *             TODO: delete once there are no longer any live references.
3168     * @hide
3169     */
3170    @Deprecated
3171    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage)
3172            throws NameNotFoundException, UnsupportedOperationException {
3173        setAlwaysOnVpnPackage(admin, vpnPackage, /* lockdownEnabled */ true);
3174    }
3175
3176    /**
3177     * Called by a device or profile owner to configure an always-on VPN connection through a
3178     * specific application for the current user. This connection is automatically granted and
3179     * persisted after a reboot.
3180     * <p>
3181     * The designated package should declare a {@link android.net.VpnService} in its manifest
3182     * guarded by {@link android.Manifest.permission#BIND_VPN_SERVICE}, otherwise the call will
3183     * fail.
3184     *
3185     * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
3186     *        remove an existing always-on VPN configuration.
3187     * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
3188     *        {@code false} otherwise. This carries the risk that any failure of the VPN provider
3189     *        could break networking for all apps. This has no effect when clearing.
3190     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3191     * @throws NameNotFoundException if {@code vpnPackage} is not installed.
3192     * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
3193     *         set as always-on, or if always-on VPN is not available.
3194     */
3195    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
3196            boolean lockdownEnabled)
3197            throws NameNotFoundException, UnsupportedOperationException {
3198        throwIfParentInstance("setAlwaysOnVpnPackage");
3199        if (mService != null) {
3200            try {
3201                if (!mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled)) {
3202                    throw new NameNotFoundException(vpnPackage);
3203                }
3204            } catch (RemoteException e) {
3205                throw e.rethrowFromSystemServer();
3206            }
3207        }
3208    }
3209
3210    /**
3211     * Called by a device or profile owner to read the name of the package administering an
3212     * always-on VPN connection for the current user. If there is no such package, or the always-on
3213     * VPN is provided by the system instead of by an application, {@code null} will be returned.
3214     *
3215     * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
3216     *         is set.
3217     * @throws SecurityException if {@code admin} is not a device or a profile owner.
3218     */
3219    public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
3220        throwIfParentInstance("getAlwaysOnVpnPackage");
3221        if (mService != null) {
3222            try {
3223                return mService.getAlwaysOnVpnPackage(admin);
3224            } catch (RemoteException e) {
3225                throw e.rethrowFromSystemServer();
3226            }
3227        }
3228        return null;
3229    }
3230
3231    /**
3232     * Called by an application that is administering the device to disable all cameras on the
3233     * device, for this user. After setting this, no applications running as this user will be able
3234     * to access any cameras on the device.
3235     * <p>
3236     * If the caller is device owner, then the restriction will be applied to all users.
3237     * <p>
3238     * The calling device admin must have requested
3239     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
3240     * not, a security exception will be thrown.
3241     *
3242     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3243     * @param disabled Whether or not the camera should be disabled.
3244     * @throws SecurityException if {@code admin} is not an active administrator or does not use
3245     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
3246     */
3247    public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
3248        throwIfParentInstance("setCameraDisabled");
3249        if (mService != null) {
3250            try {
3251                mService.setCameraDisabled(admin, disabled);
3252            } catch (RemoteException e) {
3253                throw e.rethrowFromSystemServer();
3254            }
3255        }
3256    }
3257
3258    /**
3259     * Determine whether or not the device's cameras have been disabled for this user,
3260     * either by the calling admin, if specified, or all admins.
3261     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
3262     * have disabled the camera
3263     */
3264    public boolean getCameraDisabled(@Nullable ComponentName admin) {
3265        throwIfParentInstance("getCameraDisabled");
3266        return getCameraDisabled(admin, myUserId());
3267    }
3268
3269    /** @hide per-user version */
3270    public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
3271        if (mService != null) {
3272            try {
3273                return mService.getCameraDisabled(admin, userHandle);
3274            } catch (RemoteException e) {
3275                throw e.rethrowFromSystemServer();
3276            }
3277        }
3278        return false;
3279    }
3280
3281    /**
3282     * Called by a device owner to request a bugreport.
3283     * <p>
3284     * There must be only one user on the device, managed by the device owner. Otherwise a
3285     * {@link SecurityException} will be thrown.
3286     *
3287     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3288     * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
3289     *         wasn't triggered because a previous bugreport operation is still active (either the
3290     *         bugreport is still running or waiting for the user to share or decline)
3291     * @throws SecurityException if {@code admin} is not a device owner, or if there are users other
3292     *             than the one managed by the device owner.
3293     */
3294    public boolean requestBugreport(@NonNull ComponentName admin) {
3295        throwIfParentInstance("requestBugreport");
3296        if (mService != null) {
3297            try {
3298                return mService.requestBugreport(admin);
3299            } catch (RemoteException e) {
3300                throw e.rethrowFromSystemServer();
3301            }
3302        }
3303        return false;
3304    }
3305
3306    /**
3307     * Determine whether or not creating a guest user has been disabled for the device
3308     *
3309     * @hide
3310     */
3311    public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
3312        // Currently guest users can always be created if multi-user is enabled
3313        // TODO introduce a policy for guest user creation
3314        return false;
3315    }
3316
3317    /**
3318     * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
3319     * screen capture also prevents the content from being shown on display devices that do not have
3320     * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
3321     * secure surfaces and secure displays.
3322     * <p>
3323     * The calling device admin must be a device or profile owner. If it is not, a security
3324     * exception will be thrown.
3325     * <p>
3326     * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
3327     * assist requests for all activities of the relevant user.
3328     *
3329     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3330     * @param disabled Whether screen capture is disabled or not.
3331     * @throws SecurityException if {@code admin} is not a device or profile owner.
3332     */
3333    public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
3334        throwIfParentInstance("setScreenCaptureDisabled");
3335        if (mService != null) {
3336            try {
3337                mService.setScreenCaptureDisabled(admin, disabled);
3338            } catch (RemoteException e) {
3339                throw e.rethrowFromSystemServer();
3340            }
3341        }
3342    }
3343
3344    /**
3345     * Determine whether or not screen capture has been disabled by the calling
3346     * admin, if specified, or all admins.
3347     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
3348     * have disabled screen capture.
3349     */
3350    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
3351        throwIfParentInstance("getScreenCaptureDisabled");
3352        return getScreenCaptureDisabled(admin, myUserId());
3353    }
3354
3355    /** @hide per-user version */
3356    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
3357        if (mService != null) {
3358            try {
3359                return mService.getScreenCaptureDisabled(admin, userHandle);
3360            } catch (RemoteException e) {
3361                throw e.rethrowFromSystemServer();
3362            }
3363        }
3364        return false;
3365    }
3366
3367    /**
3368     * Called by a device owner to set whether auto time is required. If auto time is required the
3369     * user cannot set the date and time, but has to use network date and time.
3370     * <p>
3371     * Note: if auto time is required the user can still manually set the time zone.
3372     * <p>
3373     * The calling device admin must be a device owner. If it is not, a security exception will be
3374     * thrown.
3375     *
3376     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3377     * @param required Whether auto time is set required or not.
3378     * @throws SecurityException if {@code admin} is not a device owner.
3379     */
3380    public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
3381        throwIfParentInstance("setAutoTimeRequired");
3382        if (mService != null) {
3383            try {
3384                mService.setAutoTimeRequired(admin, required);
3385            } catch (RemoteException e) {
3386                throw e.rethrowFromSystemServer();
3387            }
3388        }
3389    }
3390
3391    /**
3392     * @return true if auto time is required.
3393     */
3394    public boolean getAutoTimeRequired() {
3395        throwIfParentInstance("getAutoTimeRequired");
3396        if (mService != null) {
3397            try {
3398                return mService.getAutoTimeRequired();
3399            } catch (RemoteException e) {
3400                throw e.rethrowFromSystemServer();
3401            }
3402        }
3403        return false;
3404    }
3405
3406    /**
3407     * Called by a device owner to set whether all users created on the device should be ephemeral.
3408     * <p>
3409     * The system user is exempt from this policy - it is never ephemeral.
3410     * <p>
3411     * The calling device admin must be the device owner. If it is not, a security exception will be
3412     * thrown.
3413     *
3414     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3415     * @param forceEphemeralUsers If true, all the existing users will be deleted and all
3416     *            subsequently created users will be ephemeral.
3417     * @throws SecurityException if {@code admin} is not a device owner.
3418     * @hide
3419     */
3420    public void setForceEphemeralUsers(
3421            @NonNull ComponentName admin, boolean forceEphemeralUsers) {
3422        throwIfParentInstance("setForceEphemeralUsers");
3423        if (mService != null) {
3424            try {
3425                mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
3426            } catch (RemoteException e) {
3427                throw e.rethrowFromSystemServer();
3428            }
3429        }
3430    }
3431
3432    /**
3433     * @return true if all users are created ephemeral.
3434     * @throws SecurityException if {@code admin} is not a device owner.
3435     * @hide
3436     */
3437    public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
3438        throwIfParentInstance("getForceEphemeralUsers");
3439        if (mService != null) {
3440            try {
3441                return mService.getForceEphemeralUsers(admin);
3442            } catch (RemoteException e) {
3443                throw e.rethrowFromSystemServer();
3444            }
3445        }
3446        return false;
3447    }
3448
3449    /**
3450     * Called by an application that is administering the device to disable keyguard customizations,
3451     * such as widgets. After setting this, keyguard features will be disabled according to the
3452     * provided feature list.
3453     * <p>
3454     * The calling device admin must have requested
3455     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
3456     * if it has not, a security exception will be thrown.
3457     * <p>
3458     * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
3459     * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
3460     * profile owner of a managed profile can set:
3461     * <ul>
3462     * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
3463     * is no separate challenge set on the managed profile.
3464     * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT} which affects the managed profile challenge if
3465     * there is one, or the parent user otherwise.
3466     * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
3467     * by applications in the managed profile.
3468     * </ul>
3469     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and {@link #KEYGUARD_DISABLE_FINGERPRINT} can also be
3470     * set on the {@link DevicePolicyManager} instance returned by
3471     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3472     * profile.
3473     * <p>
3474     * Requests to disable other features on a managed profile will be ignored.
3475     * <p>
3476     * The admin can check which features have been disabled by calling
3477     * {@link #getKeyguardDisabledFeatures(ComponentName)}
3478     *
3479     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3480     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
3481     *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
3482     *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
3483     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
3484     *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
3485     *            {@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
3486     * @throws SecurityException if {@code admin} is not an active administrator or does not user
3487     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
3488     */
3489    public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
3490        if (mService != null) {
3491            try {
3492                mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
3493            } catch (RemoteException e) {
3494                throw e.rethrowFromSystemServer();
3495            }
3496        }
3497    }
3498
3499    /**
3500     * Determine whether or not features have been disabled in keyguard either by the calling
3501     * admin, if specified, or all admins that set restrictions on this user and its participating
3502     * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
3503     *
3504     * <p>This method can be called on the {@link DevicePolicyManager} instance
3505     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3506     * restrictions on the parent profile.
3507     *
3508     * @param admin The name of the admin component to check, or {@code null} to check whether any
3509     * admins have disabled features in keyguard.
3510     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
3511     * for a list.
3512     */
3513    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
3514        return getKeyguardDisabledFeatures(admin, myUserId());
3515    }
3516
3517    /** @hide per-user version */
3518    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
3519        if (mService != null) {
3520            try {
3521                return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
3522            } catch (RemoteException e) {
3523                throw e.rethrowFromSystemServer();
3524            }
3525        }
3526        return KEYGUARD_DISABLE_FEATURES_NONE;
3527    }
3528
3529    /**
3530     * @hide
3531     */
3532    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
3533            int userHandle) {
3534        if (mService != null) {
3535            try {
3536                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
3537            } catch (RemoteException e) {
3538                throw e.rethrowFromSystemServer();
3539            }
3540        }
3541    }
3542
3543    /**
3544     * @hide
3545     */
3546    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
3547        setActiveAdmin(policyReceiver, refreshing, myUserId());
3548    }
3549
3550    /**
3551     * @hide
3552     */
3553    public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
3554        if (mService != null) {
3555            try {
3556                mService.getRemoveWarning(admin, result, myUserId());
3557            } catch (RemoteException e) {
3558                throw e.rethrowFromSystemServer();
3559            }
3560        }
3561    }
3562
3563    /**
3564     * @hide
3565     */
3566    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
3567        if (mService != null) {
3568            try {
3569                mService.setActivePasswordState(metrics, userHandle);
3570            } catch (RemoteException e) {
3571                throw e.rethrowFromSystemServer();
3572            }
3573        }
3574    }
3575
3576    /**
3577     * @hide
3578     */
3579    public void reportFailedPasswordAttempt(int userHandle) {
3580        if (mService != null) {
3581            try {
3582                mService.reportFailedPasswordAttempt(userHandle);
3583            } catch (RemoteException e) {
3584                throw e.rethrowFromSystemServer();
3585            }
3586        }
3587    }
3588
3589    /**
3590     * @hide
3591     */
3592    public void reportSuccessfulPasswordAttempt(int userHandle) {
3593        if (mService != null) {
3594            try {
3595                mService.reportSuccessfulPasswordAttempt(userHandle);
3596            } catch (RemoteException e) {
3597                throw e.rethrowFromSystemServer();
3598            }
3599        }
3600    }
3601
3602    /**
3603     * @hide
3604     */
3605    public void reportFailedFingerprintAttempt(int userHandle) {
3606        if (mService != null) {
3607            try {
3608                mService.reportFailedFingerprintAttempt(userHandle);
3609            } catch (RemoteException e) {
3610                throw e.rethrowFromSystemServer();
3611            }
3612        }
3613    }
3614
3615    /**
3616     * @hide
3617     */
3618    public void reportSuccessfulFingerprintAttempt(int userHandle) {
3619        if (mService != null) {
3620            try {
3621                mService.reportSuccessfulFingerprintAttempt(userHandle);
3622            } catch (RemoteException e) {
3623                throw e.rethrowFromSystemServer();
3624            }
3625        }
3626    }
3627
3628    /**
3629     * Should be called when keyguard has been dismissed.
3630     * @hide
3631     */
3632    public void reportKeyguardDismissed(int userHandle) {
3633        if (mService != null) {
3634            try {
3635                mService.reportKeyguardDismissed(userHandle);
3636            } catch (RemoteException e) {
3637                throw e.rethrowFromSystemServer();
3638            }
3639        }
3640    }
3641
3642    /**
3643     * Should be called when keyguard view has been shown to the user.
3644     * @hide
3645     */
3646    public void reportKeyguardSecured(int userHandle) {
3647        if (mService != null) {
3648            try {
3649                mService.reportKeyguardSecured(userHandle);
3650            } catch (RemoteException e) {
3651                throw e.rethrowFromSystemServer();
3652            }
3653        }
3654    }
3655
3656    /**
3657     * @hide
3658     * Sets the given package as the device owner.
3659     * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
3660     * @param who the component name to be registered as device owner.
3661     * @return whether the package was successfully registered as the device owner.
3662     * @throws IllegalArgumentException if the package name is null or invalid
3663     * @throws IllegalStateException If the preconditions mentioned are not met.
3664     */
3665    public boolean setDeviceOwner(ComponentName who) {
3666        return setDeviceOwner(who, null);
3667    }
3668
3669    /**
3670     * @hide
3671     */
3672    public boolean setDeviceOwner(ComponentName who, int userId)  {
3673        return setDeviceOwner(who, null, userId);
3674    }
3675
3676    /**
3677     * @hide
3678     */
3679    public boolean setDeviceOwner(ComponentName who, String ownerName) {
3680        return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
3681    }
3682
3683    /**
3684     * @hide
3685     * Sets the given package as the device owner. The package must already be installed. There
3686     * must not already be a device owner.
3687     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
3688     * this method.
3689     * Calling this after the setup phase of the primary user has completed is allowed only if
3690     * the caller is the shell uid, and there are no additional users and no accounts.
3691     * @param who the component name to be registered as device owner.
3692     * @param ownerName the human readable name of the institution that owns this device.
3693     * @param userId ID of the user on which the device owner runs.
3694     * @return whether the package was successfully registered as the device owner.
3695     * @throws IllegalArgumentException if the package name is null or invalid
3696     * @throws IllegalStateException If the preconditions mentioned are not met.
3697     */
3698    public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
3699            throws IllegalArgumentException, IllegalStateException {
3700        if (mService != null) {
3701            try {
3702                return mService.setDeviceOwner(who, ownerName, userId);
3703            } catch (RemoteException re) {
3704                throw re.rethrowFromSystemServer();
3705            }
3706        }
3707        return false;
3708    }
3709
3710    /**
3711     * Used to determine if a particular package has been registered as a Device Owner app.
3712     * A device owner app is a special device admin that cannot be deactivated by the user, once
3713     * activated as a device admin. It also cannot be uninstalled. To check whether a particular
3714     * package is currently registered as the device owner app, pass in the package name from
3715     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
3716     * admin apps that want to check whether they are also registered as the device owner app. The
3717     * exact mechanism by which a device admin app is registered as a device owner app is defined by
3718     * the setup process.
3719     * @param packageName the package name of the app, to compare with the registered device owner
3720     * app, if any.
3721     * @return whether or not the package is registered as the device owner app.
3722     */
3723    public boolean isDeviceOwnerApp(String packageName) {
3724        throwIfParentInstance("isDeviceOwnerApp");
3725        return isDeviceOwnerAppOnCallingUser(packageName);
3726    }
3727
3728    /**
3729     * @return true if a package is registered as device owner, only when it's running on the
3730     * calling user.
3731     *
3732     * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
3733     * @hide
3734     */
3735    public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
3736        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
3737    }
3738
3739    /**
3740     * @return true if a package is registered as device owner, even if it's running on a different
3741     * user.
3742     *
3743     * <p>Requires the MANAGE_USERS permission.
3744     *
3745     * @hide
3746     */
3747    public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
3748        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
3749    }
3750
3751    /**
3752     * @return device owner component name, only when it's running on the calling user.
3753     *
3754     * @hide
3755     */
3756    public ComponentName getDeviceOwnerComponentOnCallingUser() {
3757        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
3758    }
3759
3760    /**
3761     * @return device owner component name, even if it's running on a different user.
3762     *
3763     * <p>Requires the MANAGE_USERS permission.
3764     *
3765     * @hide
3766     */
3767    public ComponentName getDeviceOwnerComponentOnAnyUser() {
3768        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
3769    }
3770
3771    private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
3772        if (packageName == null) {
3773            return false;
3774        }
3775        final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
3776        if (deviceOwner == null) {
3777            return false;
3778        }
3779        return packageName.equals(deviceOwner.getPackageName());
3780    }
3781
3782    private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
3783        if (mService != null) {
3784            try {
3785                return mService.getDeviceOwnerComponent(callingUserOnly);
3786            } catch (RemoteException re) {
3787                throw re.rethrowFromSystemServer();
3788            }
3789        }
3790        return null;
3791    }
3792
3793    /**
3794     * @return ID of the user who runs device owner, or {@link UserHandle#USER_NULL} if there's
3795     * no device owner.
3796     *
3797     * <p>Requires the MANAGE_USERS permission.
3798     *
3799     * @hide
3800     */
3801    public int getDeviceOwnerUserId() {
3802        if (mService != null) {
3803            try {
3804                return mService.getDeviceOwnerUserId();
3805            } catch (RemoteException re) {
3806                throw re.rethrowFromSystemServer();
3807            }
3808        }
3809        return UserHandle.USER_NULL;
3810    }
3811
3812    /**
3813     * Clears the current device owner. The caller must be the device owner. This function should be
3814     * used cautiously as once it is called it cannot be undone. The device owner can only be set as
3815     * a part of device setup before setup completes.
3816     *
3817     * @param packageName The package name of the device owner.
3818     * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
3819     *             does not own the current device owner component.
3820     */
3821    public void clearDeviceOwnerApp(String packageName) {
3822        throwIfParentInstance("clearDeviceOwnerApp");
3823        if (mService != null) {
3824            try {
3825                mService.clearDeviceOwner(packageName);
3826            } catch (RemoteException re) {
3827                throw re.rethrowFromSystemServer();
3828            }
3829        }
3830    }
3831
3832    /**
3833     * Returns the device owner package name, only if it's running on the calling user.
3834     *
3835     * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
3836     *
3837     * @hide
3838     */
3839    @SystemApi
3840    public @Nullable String getDeviceOwner() {
3841        throwIfParentInstance("getDeviceOwner");
3842        final ComponentName name = getDeviceOwnerComponentOnCallingUser();
3843        return name != null ? name.getPackageName() : null;
3844    }
3845
3846    /**
3847     * @return true if the device is managed by any device owner.
3848     *
3849     * <p>Requires the MANAGE_USERS permission.
3850     *
3851     * @hide
3852     */
3853    public boolean isDeviceManaged() {
3854        return getDeviceOwnerComponentOnAnyUser() != null;
3855    }
3856
3857    /**
3858     * Returns the device owner name.  Note this method *will* return the device owner
3859     * name when it's running on a different user.
3860     *
3861     * <p>Requires the MANAGE_USERS permission.
3862     *
3863     * @hide
3864     */
3865    @SystemApi
3866    public String getDeviceOwnerNameOnAnyUser() {
3867        throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
3868        if (mService != null) {
3869            try {
3870                return mService.getDeviceOwnerName();
3871            } catch (RemoteException re) {
3872                throw re.rethrowFromSystemServer();
3873            }
3874        }
3875        return null;
3876    }
3877
3878    /**
3879     * @hide
3880     * @deprecated Do not use
3881     * @removed
3882     */
3883    @Deprecated
3884    @SystemApi
3885    public @Nullable String getDeviceInitializerApp() {
3886        return null;
3887    }
3888
3889    /**
3890     * @hide
3891     * @deprecated Do not use
3892     * @removed
3893     */
3894    @Deprecated
3895    @SystemApi
3896    public @Nullable ComponentName getDeviceInitializerComponent() {
3897        return null;
3898    }
3899
3900    /**
3901     * @hide
3902     * @deprecated Use #ACTION_SET_PROFILE_OWNER
3903     * Sets the given component as an active admin and registers the package as the profile
3904     * owner for this user. The package must already be installed and there shouldn't be
3905     * an existing profile owner registered for this user. Also, this method must be called
3906     * before the user setup has been completed.
3907     * <p>
3908     * This method can only be called by system apps that hold MANAGE_USERS permission and
3909     * MANAGE_DEVICE_ADMINS permission.
3910     * @param admin The component to register as an active admin and profile owner.
3911     * @param ownerName The user-visible name of the entity that is managing this user.
3912     * @return whether the admin was successfully registered as the profile owner.
3913     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
3914     *         the user has already been set up.
3915     */
3916    @Deprecated
3917    @SystemApi
3918    public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
3919            throws IllegalArgumentException {
3920        throwIfParentInstance("setActiveProfileOwner");
3921        if (mService != null) {
3922            try {
3923                final int myUserId = myUserId();
3924                mService.setActiveAdmin(admin, false, myUserId);
3925                return mService.setProfileOwner(admin, ownerName, myUserId);
3926            } catch (RemoteException re) {
3927                throw re.rethrowFromSystemServer();
3928            }
3929        }
3930        return false;
3931    }
3932
3933    /**
3934     * Clears the active profile owner and removes all user restrictions. The caller must be from
3935     * the same package as the active profile owner for this user, otherwise a SecurityException
3936     * will be thrown.
3937     * <p>
3938     * This doesn't work for managed profile owners.
3939     *
3940     * @param admin The component to remove as the profile owner.
3941     * @throws SecurityException if {@code admin} is not an active profile owner.
3942     */
3943    public void clearProfileOwner(@NonNull ComponentName admin) {
3944        throwIfParentInstance("clearProfileOwner");
3945        if (mService != null) {
3946            try {
3947                mService.clearProfileOwner(admin);
3948            } catch (RemoteException re) {
3949                throw re.rethrowFromSystemServer();
3950            }
3951        }
3952    }
3953
3954    /**
3955     * @hide
3956     * Checks whether the user was already setup.
3957     */
3958    public boolean hasUserSetupCompleted() {
3959        if (mService != null) {
3960            try {
3961                return mService.hasUserSetupCompleted();
3962            } catch (RemoteException re) {
3963                throw re.rethrowFromSystemServer();
3964            }
3965        }
3966        return true;
3967    }
3968
3969    /**
3970     * @hide
3971     * Sets the given component as the profile owner of the given user profile. The package must
3972     * already be installed. There must not already be a profile owner for this user.
3973     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
3974     * this method.
3975     * Calling this after the setup phase of the specified user has completed is allowed only if:
3976     * - the caller is SYSTEM_UID.
3977     * - or the caller is the shell uid, and there are no accounts on the specified user.
3978     * @param admin the component name to be registered as profile owner.
3979     * @param ownerName the human readable name of the organisation associated with this DPM.
3980     * @param userHandle the userId to set the profile owner for.
3981     * @return whether the component was successfully registered as the profile owner.
3982     * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
3983     * preconditions mentioned are not met.
3984     */
3985    public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
3986            int userHandle) throws IllegalArgumentException {
3987        if (mService != null) {
3988            try {
3989                if (ownerName == null) {
3990                    ownerName = "";
3991                }
3992                return mService.setProfileOwner(admin, ownerName, userHandle);
3993            } catch (RemoteException re) {
3994                throw re.rethrowFromSystemServer();
3995            }
3996        }
3997        return false;
3998    }
3999
4000    /**
4001     * Sets the device owner information to be shown on the lock screen.
4002     * <p>
4003     * If the device owner information is {@code null} or empty then the device owner info is
4004     * cleared and the user owner info is shown on the lock screen if it is set.
4005     * <p>
4006     * If the device owner information contains only whitespaces then the message on the lock screen
4007     * will be blank and the user will not be allowed to change it.
4008     * <p>
4009     * If the device owner information needs to be localized, it is the responsibility of the
4010     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
4011     * and set a new version of this string accordingly.
4012     *
4013     * @param admin The name of the admin component to check.
4014     * @param info Device owner information which will be displayed instead of the user owner info.
4015     * @throws SecurityException if {@code admin} is not a device owner.
4016     */
4017    public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
4018        throwIfParentInstance("setDeviceOwnerLockScreenInfo");
4019        if (mService != null) {
4020            try {
4021                mService.setDeviceOwnerLockScreenInfo(admin, info);
4022            } catch (RemoteException re) {
4023                throw re.rethrowFromSystemServer();
4024            }
4025        }
4026    }
4027
4028    /**
4029     * @return The device owner information. If it is not set returns {@code null}.
4030     */
4031    public CharSequence getDeviceOwnerLockScreenInfo() {
4032        throwIfParentInstance("getDeviceOwnerLockScreenInfo");
4033        if (mService != null) {
4034            try {
4035                return mService.getDeviceOwnerLockScreenInfo();
4036            } catch (RemoteException re) {
4037                throw re.rethrowFromSystemServer();
4038            }
4039        }
4040        return null;
4041    }
4042
4043    /**
4044     * Called by device or profile owners to suspend packages for this user.
4045     * <p>
4046     * A suspended package will not be able to start activities. Its notifications will be hidden,
4047     * it will not show up in recents, will not be able to show toasts or dialogs or ring the
4048     * device.
4049     * <p>
4050     * The package must already be installed. If the package is uninstalled while suspended the
4051     * package will no longer be suspended. The admin can block this by using
4052     * {@link #setUninstallBlocked}.
4053     *
4054     * @param admin The name of the admin component to check.
4055     * @param packageNames The package names to suspend or unsuspend.
4056     * @param suspended If set to {@code true} than the packages will be suspended, if set to
4057     *            {@code false} the packages will be unsuspended.
4058     * @return an array of package names for which the suspended status is not set as requested in
4059     *         this method.
4060     * @throws SecurityException if {@code admin} is not a device or profile owner.
4061     */
4062    public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
4063            @NonNull String[] packageNames, boolean suspended) {
4064        throwIfParentInstance("setPackagesSuspended");
4065        if (mService != null) {
4066            try {
4067                return mService.setPackagesSuspended(admin, packageNames, suspended);
4068            } catch (RemoteException re) {
4069                throw re.rethrowFromSystemServer();
4070            }
4071        }
4072        return packageNames;
4073    }
4074
4075    /**
4076     * Called by device or profile owners to determine if a package is suspended.
4077     *
4078     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4079     * @param packageName The name of the package to retrieve the suspended status of.
4080     * @return {@code true} if the package is suspended or {@code false} if the package is not
4081     *         suspended, could not be found or an error occurred.
4082     * @throws SecurityException if {@code admin} is not a device or profile owner.
4083     * @throws NameNotFoundException if the package could not be found.
4084     */
4085    public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
4086            throws NameNotFoundException {
4087        throwIfParentInstance("isPackageSuspended");
4088        if (mService != null) {
4089            try {
4090                return mService.isPackageSuspended(admin, packageName);
4091            } catch (RemoteException e) {
4092                throw e.rethrowFromSystemServer();
4093            } catch (IllegalArgumentException ex) {
4094                throw new NameNotFoundException(packageName);
4095            }
4096        }
4097        return false;
4098    }
4099
4100    /**
4101     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
4102     * be used. Only the profile owner can call this.
4103     *
4104     * @see #isProfileOwnerApp
4105     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4106     * @throws SecurityException if {@code admin} is not a profile owner.
4107     */
4108    public void setProfileEnabled(@NonNull ComponentName admin) {
4109        throwIfParentInstance("setProfileEnabled");
4110        if (mService != null) {
4111            try {
4112                mService.setProfileEnabled(admin);
4113            } catch (RemoteException e) {
4114                throw e.rethrowFromSystemServer();
4115            }
4116        }
4117    }
4118
4119    /**
4120     * Sets the name of the profile. In the device owner case it sets the name of the user which it
4121     * is called from. Only a profile owner or device owner can call this. If this is never called
4122     * by the profile or device owner, the name will be set to default values.
4123     *
4124     * @see #isProfileOwnerApp
4125     * @see #isDeviceOwnerApp
4126     * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
4127     * @param profileName The name of the profile.
4128     * @throws SecurityException if {@code admin} is not a device or profile owner.
4129     */
4130    public void setProfileName(@NonNull ComponentName admin, String profileName) {
4131        throwIfParentInstance("setProfileName");
4132        if (mService != null) {
4133            try {
4134                mService.setProfileName(admin, profileName);
4135            } catch (RemoteException e) {
4136                throw e.rethrowFromSystemServer();
4137            }
4138        }
4139    }
4140
4141    /**
4142     * Used to determine if a particular package is registered as the profile owner for the
4143     * user. A profile owner is a special device admin that has additional privileges
4144     * within the profile.
4145     *
4146     * @param packageName The package name of the app to compare with the registered profile owner.
4147     * @return Whether or not the package is registered as the profile owner.
4148     */
4149    public boolean isProfileOwnerApp(String packageName) {
4150        throwIfParentInstance("isProfileOwnerApp");
4151        if (mService != null) {
4152            try {
4153                ComponentName profileOwner = mService.getProfileOwner(myUserId());
4154                return profileOwner != null
4155                        && profileOwner.getPackageName().equals(packageName);
4156            } catch (RemoteException re) {
4157                throw re.rethrowFromSystemServer();
4158            }
4159        }
4160        return false;
4161    }
4162
4163    /**
4164     * @hide
4165     * @return the packageName of the owner of the given user profile or {@code null} if no profile
4166     * owner has been set for that user.
4167     * @throws IllegalArgumentException if the userId is invalid.
4168     */
4169    @SystemApi
4170    public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
4171        throwIfParentInstance("getProfileOwner");
4172        return getProfileOwnerAsUser(Process.myUserHandle().getIdentifier());
4173    }
4174
4175    /**
4176     * @see #getProfileOwner()
4177     * @hide
4178     */
4179    public @Nullable ComponentName getProfileOwnerAsUser(final int userId)
4180            throws IllegalArgumentException {
4181        if (mService != null) {
4182            try {
4183                return mService.getProfileOwner(userId);
4184            } catch (RemoteException re) {
4185                throw re.rethrowFromSystemServer();
4186            }
4187        }
4188        return null;
4189    }
4190
4191    /**
4192     * @hide
4193     * @return the human readable name of the organisation associated with this DPM or {@code null}
4194     *         if one is not set.
4195     * @throws IllegalArgumentException if the userId is invalid.
4196     */
4197    public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
4198        if (mService != null) {
4199            try {
4200                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
4201            } catch (RemoteException re) {
4202                throw re.rethrowFromSystemServer();
4203            }
4204        }
4205        return null;
4206    }
4207
4208    /**
4209     * @hide
4210     * @param userId The user for whom to fetch the profile owner name, if any.
4211     * @return the human readable name of the organisation associated with this profile owner or
4212     *         null if one is not set.
4213     * @throws IllegalArgumentException if the userId is invalid.
4214     */
4215    @SystemApi
4216    public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
4217        throwIfParentInstance("getProfileOwnerNameAsUser");
4218        if (mService != null) {
4219            try {
4220                return mService.getProfileOwnerName(userId);
4221            } catch (RemoteException re) {
4222                throw re.rethrowFromSystemServer();
4223            }
4224        }
4225        return null;
4226    }
4227
4228    /**
4229     * Called by a profile owner or device owner to add a default intent handler activity for
4230     * intents that match a certain intent filter. This activity will remain the default intent
4231     * handler even if the set of potential event handlers for the intent filter changes and if the
4232     * intent preferences are reset.
4233     * <p>
4234     * The default disambiguation mechanism takes over if the activity is not installed (anymore).
4235     * When the activity is (re)installed, it is automatically reset as default intent handler for
4236     * the filter.
4237     * <p>
4238     * The calling device admin must be a profile owner or device owner. If it is not, a security
4239     * exception will be thrown.
4240     *
4241     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4242     * @param filter The IntentFilter for which a default handler is added.
4243     * @param activity The Activity that is added as default intent handler.
4244     * @throws SecurityException if {@code admin} is not a device or profile owner.
4245     */
4246    public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
4247            @NonNull ComponentName activity) {
4248        throwIfParentInstance("addPersistentPreferredActivity");
4249        if (mService != null) {
4250            try {
4251                mService.addPersistentPreferredActivity(admin, filter, activity);
4252            } catch (RemoteException e) {
4253                throw e.rethrowFromSystemServer();
4254            }
4255        }
4256    }
4257
4258    /**
4259     * Called by a profile owner or device owner to remove all persistent intent handler preferences
4260     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
4261     * <p>
4262     * The calling device admin must be a profile owner. If it is not, a security exception will be
4263     * thrown.
4264     *
4265     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4266     * @param packageName The name of the package for which preferences are removed.
4267     * @throws SecurityException if {@code admin} is not a device or profile owner.
4268     */
4269    public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
4270            String packageName) {
4271        throwIfParentInstance("clearPackagePersistentPreferredActivities");
4272        if (mService != null) {
4273            try {
4274                mService.clearPackagePersistentPreferredActivities(admin, packageName);
4275            } catch (RemoteException e) {
4276                throw e.rethrowFromSystemServer();
4277            }
4278        }
4279    }
4280
4281    /**
4282     * Called by a profile owner or device owner to grant permission to a package to manage
4283     * application restrictions for the calling user via {@link #setApplicationRestrictions} and
4284     * {@link #getApplicationRestrictions}.
4285     * <p>
4286     * This permission is persistent until it is later cleared by calling this method with a
4287     * {@code null} value or uninstalling the managing package.
4288     * <p>
4289     * The supplied application restriction managing package must be installed when calling this
4290     * API, otherwise an {@link NameNotFoundException} will be thrown.
4291     *
4292     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4293     * @param packageName The package name which will be given access to application restrictions
4294     *            APIs. If {@code null} is given the current package will be cleared.
4295     * @throws SecurityException if {@code admin} is not a device or profile owner.
4296     * @throws NameNotFoundException if {@code packageName} is not found
4297     */
4298    public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
4299            @Nullable String packageName) throws NameNotFoundException {
4300        throwIfParentInstance("setApplicationRestrictionsManagingPackage");
4301        if (mService != null) {
4302            try {
4303                if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
4304                    throw new NameNotFoundException(packageName);
4305                }
4306            } catch (RemoteException e) {
4307                throw e.rethrowFromSystemServer();
4308            }
4309        }
4310    }
4311
4312    /**
4313     * Called by a profile owner or device owner to retrieve the application restrictions managing
4314     * package for the current user, or {@code null} if none is set.
4315     *
4316     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4317     * @return The package name allowed to manage application restrictions on the current user, or
4318     *         {@code null} if none is set.
4319     * @throws SecurityException if {@code admin} is not a device or profile owner.
4320     */
4321    public @Nullable String getApplicationRestrictionsManagingPackage(
4322            @NonNull ComponentName admin) {
4323        throwIfParentInstance("getApplicationRestrictionsManagingPackage");
4324        if (mService != null) {
4325            try {
4326                return mService.getApplicationRestrictionsManagingPackage(admin);
4327            } catch (RemoteException e) {
4328                throw e.rethrowFromSystemServer();
4329            }
4330        }
4331        return null;
4332    }
4333
4334    /**
4335     * Called by any application to find out whether it has been granted permission via
4336     * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
4337     * for the calling user.
4338     *
4339     * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
4340     * that method.
4341     */
4342    public boolean isCallerApplicationRestrictionsManagingPackage() {
4343        throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
4344        if (mService != null) {
4345            try {
4346                return mService.isCallerApplicationRestrictionsManagingPackage();
4347            } catch (RemoteException e) {
4348                throw e.rethrowFromSystemServer();
4349            }
4350        }
4351        return false;
4352    }
4353
4354    /**
4355     * Sets the application restrictions for a given target application running in the calling user.
4356     * <p>
4357     * The caller must be a profile or device owner on that user, or the package allowed to manage
4358     * application restrictions via {@link #setApplicationRestrictionsManagingPackage}; otherwise a
4359     * security exception will be thrown.
4360     * <p>
4361     * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
4362     * <ul>
4363     * <li>{@code boolean}
4364     * <li>{@code int}
4365     * <li>{@code String} or {@code String[]}
4366     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
4367     * </ul>
4368     * <p>
4369     * If the restrictions are not available yet, but may be applied in the near future, the caller
4370     * can notify the target application of that by adding
4371     * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
4372     * <p>
4373     * The application restrictions are only made visible to the target application via
4374     * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
4375     * owner, and the application restrictions managing package via
4376     * {@link #getApplicationRestrictions}.
4377     *
4378     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
4379     *
4380     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4381     *            {@code null} if called by the application restrictions managing package.
4382     * @param packageName The name of the package to update restricted settings for.
4383     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
4384     *            set of active restrictions.
4385     * @throws SecurityException if {@code admin} is not a device or profile owner.
4386     * @see #setApplicationRestrictionsManagingPackage
4387     * @see UserManager#KEY_RESTRICTIONS_PENDING
4388     */
4389    @WorkerThread
4390    public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
4391            Bundle settings) {
4392        throwIfParentInstance("setApplicationRestrictions");
4393        if (mService != null) {
4394            try {
4395                mService.setApplicationRestrictions(admin, packageName, settings);
4396            } catch (RemoteException e) {
4397                throw e.rethrowFromSystemServer();
4398            }
4399        }
4400    }
4401
4402    /**
4403     * Sets a list of configuration features to enable for a TrustAgent component. This is meant to
4404     * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
4405     * agents but those enabled by this function call. If flag
4406     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
4407     * <p>
4408     * The calling device admin must have requested
4409     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
4410     * if not, a security exception will be thrown.
4411     * <p>
4412     * This method can be called on the {@link DevicePolicyManager} instance returned by
4413     * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
4414     * the parent profile.
4415     *
4416     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4417     * @param target Component name of the agent to be enabled.
4418     * @param configuration TrustAgent-specific feature bundle. If null for any admin, agent will be
4419     *            strictly disabled according to the state of the
4420     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS} flag.
4421     *            <p>
4422     *            If {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is set and options is not null for all
4423     *            admins, then it's up to the TrustAgent itself to aggregate the values from all
4424     *            device admins.
4425     *            <p>
4426     *            Consult documentation for the specific TrustAgent to determine legal options
4427     *            parameters.
4428     * @throws SecurityException if {@code admin} is not an active administrator or does not use
4429     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
4430     */
4431    public void setTrustAgentConfiguration(@NonNull ComponentName admin,
4432            @NonNull ComponentName target, PersistableBundle configuration) {
4433        if (mService != null) {
4434            try {
4435                mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
4436            } catch (RemoteException e) {
4437                throw e.rethrowFromSystemServer();
4438            }
4439        }
4440    }
4441
4442    /**
4443     * Gets configuration for the given trust agent based on aggregating all calls to
4444     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
4445     * all device admins.
4446     * <p>
4447     * This method can be called on the {@link DevicePolicyManager} instance returned by
4448     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
4449     * on the parent profile.
4450     *
4451     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
4452     * this function returns a list of configurations for all admins that declare
4453     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
4454     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
4455     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
4456     * for this {@param agent} or calls it with a null configuration, null is returned.
4457     * @param agent Which component to get enabled features for.
4458     * @return configuration for the given trust agent.
4459     */
4460    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
4461            @Nullable ComponentName admin, @NonNull ComponentName agent) {
4462        return getTrustAgentConfiguration(admin, agent, myUserId());
4463    }
4464
4465    /** @hide per-user version */
4466    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
4467            @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
4468        if (mService != null) {
4469            try {
4470                return mService.getTrustAgentConfiguration(admin, agent, userHandle,
4471                        mParentInstance);
4472            } catch (RemoteException e) {
4473                throw e.rethrowFromSystemServer();
4474            }
4475        }
4476        return new ArrayList<PersistableBundle>(); // empty list
4477    }
4478
4479    /**
4480     * Called by a profile owner of a managed profile to set whether caller-Id information from the
4481     * managed profile will be shown in the parent profile, for incoming calls.
4482     * <p>
4483     * The calling device admin must be a profile owner. If it is not, a security exception will be
4484     * thrown.
4485     *
4486     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4487     * @param disabled If true caller-Id information in the managed profile is not displayed.
4488     * @throws SecurityException if {@code admin} is not a device or profile owner.
4489     */
4490    public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
4491        throwIfParentInstance("setCrossProfileCallerIdDisabled");
4492        if (mService != null) {
4493            try {
4494                mService.setCrossProfileCallerIdDisabled(admin, disabled);
4495            } catch (RemoteException e) {
4496                throw e.rethrowFromSystemServer();
4497            }
4498        }
4499    }
4500
4501    /**
4502     * Called by a profile owner of a managed profile to determine whether or not caller-Id
4503     * information has been disabled.
4504     * <p>
4505     * The calling device admin must be a profile owner. If it is not, a security exception will be
4506     * thrown.
4507     *
4508     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4509     * @throws SecurityException if {@code admin} is not a device or profile owner.
4510     */
4511    public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
4512        throwIfParentInstance("getCrossProfileCallerIdDisabled");
4513        if (mService != null) {
4514            try {
4515                return mService.getCrossProfileCallerIdDisabled(admin);
4516            } catch (RemoteException e) {
4517                throw e.rethrowFromSystemServer();
4518            }
4519        }
4520        return false;
4521    }
4522
4523    /**
4524     * Determine whether or not caller-Id information has been disabled.
4525     *
4526     * @param userHandle The user for whom to check the caller-id permission
4527     * @hide
4528     */
4529    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
4530        if (mService != null) {
4531            try {
4532                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
4533            } catch (RemoteException e) {
4534                throw e.rethrowFromSystemServer();
4535            }
4536        }
4537        return false;
4538    }
4539
4540    /**
4541     * Called by a profile owner of a managed profile to set whether contacts search from the
4542     * managed profile will be shown in the parent profile, for incoming calls.
4543     * <p>
4544     * The calling device admin must be a profile owner. If it is not, a security exception will be
4545     * thrown.
4546     *
4547     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4548     * @param disabled If true contacts search in the managed profile is not displayed.
4549     * @throws SecurityException if {@code admin} is not a device or profile owner.
4550     */
4551    public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
4552            boolean disabled) {
4553        throwIfParentInstance("setCrossProfileContactsSearchDisabled");
4554        if (mService != null) {
4555            try {
4556                mService.setCrossProfileContactsSearchDisabled(admin, disabled);
4557            } catch (RemoteException e) {
4558                throw e.rethrowFromSystemServer();
4559            }
4560        }
4561    }
4562
4563    /**
4564     * Called by a profile owner of a managed profile to determine whether or not contacts search
4565     * has been disabled.
4566     * <p>
4567     * The calling device admin must be a profile owner. If it is not, a security exception will be
4568     * thrown.
4569     *
4570     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4571     * @throws SecurityException if {@code admin} is not a device or profile owner.
4572     */
4573    public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
4574        throwIfParentInstance("getCrossProfileContactsSearchDisabled");
4575        if (mService != null) {
4576            try {
4577                return mService.getCrossProfileContactsSearchDisabled(admin);
4578            } catch (RemoteException e) {
4579                throw e.rethrowFromSystemServer();
4580            }
4581        }
4582        return false;
4583    }
4584
4585
4586    /**
4587     * Determine whether or not contacts search has been disabled.
4588     *
4589     * @param userHandle The user for whom to check the contacts search permission
4590     * @hide
4591     */
4592    public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
4593        if (mService != null) {
4594            try {
4595                return mService
4596                        .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
4597            } catch (RemoteException e) {
4598                throw e.rethrowFromSystemServer();
4599            }
4600        }
4601        return false;
4602    }
4603
4604    /**
4605     * Start Quick Contact on the managed profile for the user, if the policy allows.
4606     *
4607     * @hide
4608     */
4609    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
4610            boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
4611        if (mService != null) {
4612            try {
4613                mService.startManagedQuickContact(actualLookupKey, actualContactId,
4614                        isContactIdIgnored, directoryId, originalIntent);
4615            } catch (RemoteException e) {
4616                throw e.rethrowFromSystemServer();
4617            }
4618        }
4619    }
4620
4621    /**
4622     * Start Quick Contact on the managed profile for the user, if the policy allows.
4623     * @hide
4624     */
4625    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
4626            Intent originalIntent) {
4627        startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
4628                originalIntent);
4629    }
4630
4631    /**
4632     * Called by a profile owner of a managed profile to set whether bluetooth devices can access
4633     * enterprise contacts.
4634     * <p>
4635     * The calling device admin must be a profile owner. If it is not, a security exception will be
4636     * thrown.
4637     * <p>
4638     * This API works on managed profile only.
4639     *
4640     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4641     * @param disabled If true, bluetooth devices cannot access enterprise contacts.
4642     * @throws SecurityException if {@code admin} is not a device or profile owner.
4643     */
4644    public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
4645        throwIfParentInstance("setBluetoothContactSharingDisabled");
4646        if (mService != null) {
4647            try {
4648                mService.setBluetoothContactSharingDisabled(admin, disabled);
4649            } catch (RemoteException e) {
4650                throw e.rethrowFromSystemServer();
4651            }
4652        }
4653    }
4654
4655    /**
4656     * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
4657     * cannot access enterprise contacts.
4658     * <p>
4659     * The calling device admin must be a profile owner. If it is not, a security exception will be
4660     * thrown.
4661     * <p>
4662     * This API works on managed profile only.
4663     *
4664     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4665     * @throws SecurityException if {@code admin} is not a device or profile owner.
4666     */
4667    public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
4668        throwIfParentInstance("getBluetoothContactSharingDisabled");
4669        if (mService != null) {
4670            try {
4671                return mService.getBluetoothContactSharingDisabled(admin);
4672            } catch (RemoteException e) {
4673                throw e.rethrowFromSystemServer();
4674            }
4675        }
4676        return true;
4677    }
4678
4679    /**
4680     * Determine whether or not Bluetooth devices cannot access contacts.
4681     * <p>
4682     * This API works on managed profile UserHandle only.
4683     *
4684     * @param userHandle The user for whom to check the caller-id permission
4685     * @hide
4686     */
4687    public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
4688        if (mService != null) {
4689            try {
4690                return mService.getBluetoothContactSharingDisabledForUser(userHandle
4691                        .getIdentifier());
4692            } catch (RemoteException e) {
4693                throw e.rethrowFromSystemServer();
4694            }
4695        }
4696        return true;
4697    }
4698
4699    /**
4700     * Called by the profile owner of a managed profile so that some intents sent in the managed
4701     * profile can also be resolved in the parent, or vice versa. Only activity intents are
4702     * supported.
4703     *
4704     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4705     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
4706     *            other profile
4707     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
4708     *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
4709     * @throws SecurityException if {@code admin} is not a device or profile owner.
4710     */
4711    public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
4712        throwIfParentInstance("addCrossProfileIntentFilter");
4713        if (mService != null) {
4714            try {
4715                mService.addCrossProfileIntentFilter(admin, filter, flags);
4716            } catch (RemoteException e) {
4717                throw e.rethrowFromSystemServer();
4718            }
4719        }
4720    }
4721
4722    /**
4723     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
4724     * that go from the managed profile to the parent, or from the parent to the managed profile.
4725     * Only removes those that have been set by the profile owner.
4726     *
4727     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4728     * @throws SecurityException if {@code admin} is not a device or profile owner.
4729     */
4730    public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
4731        throwIfParentInstance("clearCrossProfileIntentFilters");
4732        if (mService != null) {
4733            try {
4734                mService.clearCrossProfileIntentFilters(admin);
4735            } catch (RemoteException e) {
4736                throw e.rethrowFromSystemServer();
4737            }
4738        }
4739    }
4740
4741    /**
4742     * Called by a profile or device owner to set the permitted accessibility services. When set by
4743     * a device owner or profile owner the restriction applies to all profiles of the user the
4744     * device owner or profile owner is an admin for. By default the user can use any accessiblity
4745     * service. When zero or more packages have been added, accessiblity services that are not in
4746     * the list and not part of the system can not be enabled by the user.
4747     * <p>
4748     * Calling with a null value for the list disables the restriction so that all services can be
4749     * used, calling with an empty list only allows the builtin system's services.
4750     * <p>
4751     * System accesibility services are always available to the user the list can't modify this.
4752     *
4753     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4754     * @param packageNames List of accessibility service package names.
4755     * @return true if setting the restriction succeeded. It fail if there is one or more non-system
4756     *         accessibility services enabled, that are not in the list.
4757     * @throws SecurityException if {@code admin} is not a device or profile owner.
4758     */
4759    public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
4760            List<String> packageNames) {
4761        throwIfParentInstance("setPermittedAccessibilityServices");
4762        if (mService != null) {
4763            try {
4764                return mService.setPermittedAccessibilityServices(admin, packageNames);
4765            } catch (RemoteException e) {
4766                throw e.rethrowFromSystemServer();
4767            }
4768        }
4769        return false;
4770    }
4771
4772    /**
4773     * Returns the list of permitted accessibility services set by this device or profile owner.
4774     * <p>
4775     * An empty list means no accessibility services except system services are allowed. Null means
4776     * all accessibility services are allowed.
4777     *
4778     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4779     * @return List of accessiblity service package names.
4780     * @throws SecurityException if {@code admin} is not a device or profile owner.
4781     */
4782    public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
4783        throwIfParentInstance("getPermittedAccessibilityServices");
4784        if (mService != null) {
4785            try {
4786                return mService.getPermittedAccessibilityServices(admin);
4787            } catch (RemoteException e) {
4788                throw e.rethrowFromSystemServer();
4789            }
4790        }
4791        return null;
4792    }
4793
4794    /**
4795     * Called by the system to check if a specific accessibility service is disabled by admin.
4796     *
4797     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4798     * @param packageName Accessibility service package name that needs to be checked.
4799     * @param userHandle user id the admin is running as.
4800     * @return true if the accessibility service is permitted, otherwise false.
4801     *
4802     * @hide
4803     */
4804    public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
4805            @NonNull String packageName, int userHandle) {
4806        if (mService != null) {
4807            try {
4808                return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
4809                        userHandle);
4810            } catch (RemoteException e) {
4811                throw e.rethrowFromSystemServer();
4812            }
4813        }
4814        return false;
4815    }
4816
4817    /**
4818     * Returns the list of accessibility services permitted by the device or profiles
4819     * owners of this user.
4820     *
4821     * <p>Null means all accessibility services are allowed, if a non-null list is returned
4822     * it will contain the intersection of the permitted lists for any device or profile
4823     * owners that apply to this user. It will also include any system accessibility services.
4824     *
4825     * @param userId which user to check for.
4826     * @return List of accessiblity service package names.
4827     * @hide
4828     */
4829     @SystemApi
4830     public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
4831        throwIfParentInstance("getPermittedAccessibilityServices");
4832        if (mService != null) {
4833            try {
4834                return mService.getPermittedAccessibilityServicesForUser(userId);
4835            } catch (RemoteException e) {
4836                throw e.rethrowFromSystemServer();
4837            }
4838        }
4839        return null;
4840     }
4841
4842    /**
4843     * Called by a profile or device owner to set the permitted input methods services. When set by
4844     * a device owner or profile owner the restriction applies to all profiles of the user the
4845     * device owner or profile owner is an admin for. By default the user can use any input method.
4846     * When zero or more packages have been added, input method that are not in the list and not
4847     * part of the system can not be enabled by the user. This method will fail if it is called for
4848     * a admin that is not for the foreground user or a profile of the foreground user.
4849     * <p>
4850     * Calling with a null value for the list disables the restriction so that all input methods can
4851     * be used, calling with an empty list disables all but the system's own input methods.
4852     * <p>
4853     * System input methods are always available to the user this method can't modify this.
4854     *
4855     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4856     * @param packageNames List of input method package names.
4857     * @return true if setting the restriction succeeded. It will fail if there are one or more
4858     *         non-system input methods currently enabled that are not in the packageNames list.
4859     * @throws SecurityException if {@code admin} is not a device or profile owner.
4860     */
4861    public boolean setPermittedInputMethods(@NonNull ComponentName admin, List<String> packageNames) {
4862        throwIfParentInstance("setPermittedInputMethods");
4863        if (mService != null) {
4864            try {
4865                return mService.setPermittedInputMethods(admin, packageNames);
4866            } catch (RemoteException e) {
4867                throw e.rethrowFromSystemServer();
4868            }
4869        }
4870        return false;
4871    }
4872
4873
4874    /**
4875     * Returns the list of permitted input methods set by this device or profile owner.
4876     * <p>
4877     * An empty list means no input methods except system input methods are allowed. Null means all
4878     * input methods are allowed.
4879     *
4880     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4881     * @return List of input method package names.
4882     * @throws SecurityException if {@code admin} is not a device or profile owner.
4883     */
4884    public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
4885        throwIfParentInstance("getPermittedInputMethods");
4886        if (mService != null) {
4887            try {
4888                return mService.getPermittedInputMethods(admin);
4889            } catch (RemoteException e) {
4890                throw e.rethrowFromSystemServer();
4891            }
4892        }
4893        return null;
4894    }
4895
4896    /**
4897     * Called by the system to check if a specific input method is disabled by admin.
4898     *
4899     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4900     * @param packageName Input method package name that needs to be checked.
4901     * @param userHandle user id the admin is running as.
4902     * @return true if the input method is permitted, otherwise false.
4903     *
4904     * @hide
4905     */
4906    public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
4907            @NonNull String packageName, int userHandle) {
4908        if (mService != null) {
4909            try {
4910                return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
4911            } catch (RemoteException e) {
4912                throw e.rethrowFromSystemServer();
4913            }
4914        }
4915        return false;
4916    }
4917
4918    /**
4919     * Returns the list of input methods permitted by the device or profiles
4920     * owners of the current user.  (*Not* calling user, due to a limitation in InputMethodManager.)
4921     *
4922     * <p>Null means all input methods are allowed, if a non-null list is returned
4923     * it will contain the intersection of the permitted lists for any device or profile
4924     * owners that apply to this user. It will also include any system input methods.
4925     *
4926     * @return List of input method package names.
4927     * @hide
4928     */
4929    @SystemApi
4930    public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
4931        throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
4932        if (mService != null) {
4933            try {
4934                return mService.getPermittedInputMethodsForCurrentUser();
4935            } catch (RemoteException e) {
4936                throw e.rethrowFromSystemServer();
4937            }
4938        }
4939        return null;
4940    }
4941
4942    /**
4943     * Called by a device owner to get the list of apps to keep around as APKs even if no user has
4944     * currently installed it.
4945     *
4946     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4947     *
4948     * @return List of package names to keep cached.
4949     * @hide
4950     */
4951    public @Nullable List<String> getKeepUninstalledPackages(@NonNull ComponentName admin) {
4952        throwIfParentInstance("getKeepUninstalledPackages");
4953        if (mService != null) {
4954            try {
4955                return mService.getKeepUninstalledPackages(admin);
4956            } catch (RemoteException e) {
4957                throw e.rethrowFromSystemServer();
4958            }
4959        }
4960        return null;
4961    }
4962
4963    /**
4964     * Called by a device owner to set a list of apps to keep around as APKs even if no user has
4965     * currently installed it.
4966     *
4967     * <p>Please note that setting this policy does not imply that specified apps will be
4968     * automatically pre-cached.</p>
4969     *
4970     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4971     * @param packageNames List of package names to keep cached.
4972     * @throws SecurityException if {@code admin} is not a device owner.
4973     * @hide
4974     */
4975    public void setKeepUninstalledPackages(@NonNull ComponentName admin,
4976            @NonNull List<String> packageNames) {
4977        throwIfParentInstance("setKeepUninstalledPackages");
4978        if (mService != null) {
4979            try {
4980                mService.setKeepUninstalledPackages(admin, packageNames);
4981            } catch (RemoteException e) {
4982                throw e.rethrowFromSystemServer();
4983            }
4984        }
4985    }
4986
4987    /**
4988     * Called by a device owner to create a user with the specified name. The UserHandle returned
4989     * by this method should not be persisted as user handles are recycled as users are removed and
4990     * created. If you need to persist an identifier for this user, use
4991     * {@link UserManager#getSerialNumberForUser}.
4992     *
4993     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4994     * @param name the user's name
4995     * @see UserHandle
4996     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
4997     *         user could not be created.
4998     *
4999     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
5000     * @removed From {@link android.os.Build.VERSION_CODES#N}
5001     */
5002    @Deprecated
5003    public @Nullable UserHandle createUser(@NonNull ComponentName admin, String name) {
5004        return null;
5005    }
5006
5007    /**
5008     * Called by a device owner to create a user with the specified name. The UserHandle returned
5009     * by this method should not be persisted as user handles are recycled as users are removed and
5010     * created. If you need to persist an identifier for this user, use
5011     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
5012     * immediately.
5013     *
5014     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
5015     * as registered as an active admin on the new user.  The profile owner package will be
5016     * installed on the new user if it already is installed on the device.
5017     *
5018     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
5019     * profileOwnerComponent when onEnable is called.
5020     *
5021     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5022     * @param name the user's name
5023     * @param ownerName the human readable name of the organisation associated with this DPM.
5024     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
5025     *      the user.
5026     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
5027     *      on the new user.
5028     * @see UserHandle
5029     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
5030     *         user could not be created.
5031     *
5032     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
5033     * @removed From {@link android.os.Build.VERSION_CODES#N}
5034     */
5035    @Deprecated
5036    public @Nullable UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
5037            String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
5038        return null;
5039    }
5040
5041    /**
5042      * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
5043      */
5044    public static final int SKIP_SETUP_WIZARD = 0x0001;
5045
5046    /**
5047     * Flag used by {@link #createAndManageUser} to specify that the user should be created
5048     * ephemeral.
5049     * @hide
5050     */
5051    public static final int MAKE_USER_EPHEMERAL = 0x0002;
5052
5053    /**
5054     * Called by a device owner to create a user with the specified name and a given component of
5055     * the calling package as profile owner. The UserHandle returned by this method should not be
5056     * persisted as user handles are recycled as users are removed and created. If you need to
5057     * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
5058     * user will not be started in the background.
5059     * <p>
5060     * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
5061     * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
5062     * be registered as an active admin on the new user. The profile owner package will be installed
5063     * on the new user.
5064     * <p>
5065     * If the adminExtras are not null, they will be stored on the device until the user is started
5066     * for the first time. Then the extras will be passed to the admin when onEnable is called.
5067     *
5068     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5069     * @param name The user's name.
5070     * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
5071     *            same package as admin, otherwise no user is created and an
5072     *            IllegalArgumentException is thrown.
5073     * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
5074     *            user.
5075     * @param flags {@link #SKIP_SETUP_WIZARD} is supported.
5076     * @see UserHandle
5077     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
5078     *         user could not be created.
5079     * @throws SecurityException if {@code admin} is not a device owner.
5080     */
5081    public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
5082            @NonNull String name,
5083            @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
5084            int flags) {
5085        throwIfParentInstance("createAndManageUser");
5086        try {
5087            return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
5088        } catch (RemoteException re) {
5089            throw re.rethrowFromSystemServer();
5090        }
5091    }
5092
5093    /**
5094     * Called by a device owner to remove a user and all associated data. The primary user can not
5095     * be removed.
5096     *
5097     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5098     * @param userHandle the user to remove.
5099     * @return {@code true} if the user was removed, {@code false} otherwise.
5100     * @throws SecurityException if {@code admin} is not a device owner.
5101     */
5102    public boolean removeUser(@NonNull ComponentName admin, UserHandle userHandle) {
5103        throwIfParentInstance("removeUser");
5104        try {
5105            return mService.removeUser(admin, userHandle);
5106        } catch (RemoteException re) {
5107            throw re.rethrowFromSystemServer();
5108        }
5109    }
5110
5111    /**
5112     * Called by a device owner to switch the specified user to the foreground.
5113     *
5114     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5115     * @param userHandle the user to switch to; null will switch to primary.
5116     * @return {@code true} if the switch was successful, {@code false} otherwise.
5117     * @throws SecurityException if {@code admin} is not a device owner.
5118     * @see Intent#ACTION_USER_FOREGROUND
5119     */
5120    public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
5121        throwIfParentInstance("switchUser");
5122        try {
5123            return mService.switchUser(admin, userHandle);
5124        } catch (RemoteException re) {
5125            throw re.rethrowFromSystemServer();
5126        }
5127    }
5128
5129    /**
5130     * Retrieves the application restrictions for a given target application running in the calling
5131     * user.
5132     * <p>
5133     * The caller must be a profile or device owner on that user, or the package allowed to manage
5134     * application restrictions via {@link #setApplicationRestrictionsManagingPackage}; otherwise a
5135     * security exception will be thrown.
5136     *
5137     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
5138     *
5139     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5140     *            {@code null} if called by the application restrictions managing package.
5141     * @param packageName The name of the package to fetch restricted settings of.
5142     * @return {@link Bundle} of settings corresponding to what was set last time
5143     *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
5144     *         {@link Bundle} if no restrictions have been set.
5145     * @throws SecurityException if {@code admin} is not a device or profile owner.
5146     * @see {@link #setApplicationRestrictionsManagingPackage}
5147     */
5148    @WorkerThread
5149    public @NonNull Bundle getApplicationRestrictions(
5150            @Nullable ComponentName admin, String packageName) {
5151        throwIfParentInstance("getApplicationRestrictions");
5152        if (mService != null) {
5153            try {
5154                return mService.getApplicationRestrictions(admin, packageName);
5155            } catch (RemoteException e) {
5156                throw e.rethrowFromSystemServer();
5157            }
5158        }
5159        return null;
5160    }
5161
5162    /**
5163     * Called by a profile or device owner to set a user restriction specified by the key.
5164     * <p>
5165     * The calling device admin must be a profile or device owner; if it is not, a security
5166     * exception will be thrown.
5167     *
5168     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5169     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
5170     *            for the list of keys.
5171     * @throws SecurityException if {@code admin} is not a device or profile owner.
5172     */
5173    public void addUserRestriction(@NonNull ComponentName admin, String key) {
5174        throwIfParentInstance("addUserRestriction");
5175        if (mService != null) {
5176            try {
5177                mService.setUserRestriction(admin, key, true);
5178            } catch (RemoteException e) {
5179                throw e.rethrowFromSystemServer();
5180            }
5181        }
5182    }
5183
5184    /**
5185     * Called by a profile or device owner to clear a user restriction specified by the key.
5186     * <p>
5187     * The calling device admin must be a profile or device owner; if it is not, a security
5188     * exception will be thrown.
5189     *
5190     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5191     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
5192     *            for the list of keys.
5193     * @throws SecurityException if {@code admin} is not a device or profile owner.
5194     */
5195    public void clearUserRestriction(@NonNull ComponentName admin, String key) {
5196        throwIfParentInstance("clearUserRestriction");
5197        if (mService != null) {
5198            try {
5199                mService.setUserRestriction(admin, key, false);
5200            } catch (RemoteException e) {
5201                throw e.rethrowFromSystemServer();
5202            }
5203        }
5204    }
5205
5206    /**
5207     * Called by a profile or device owner to get user restrictions set with
5208     * {@link #addUserRestriction(ComponentName, String)}.
5209     * <p>
5210     * The target user may have more restrictions set by the system or other device owner / profile
5211     * owner. To get all the user restrictions currently set, use
5212     * {@link UserManager#getUserRestrictions()}.
5213     *
5214     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5215     * @throws SecurityException if {@code admin} is not a device or profile owner.
5216     */
5217    public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
5218        throwIfParentInstance("getUserRestrictions");
5219        Bundle ret = null;
5220        if (mService != null) {
5221            try {
5222                ret = mService.getUserRestrictions(admin);
5223            } catch (RemoteException e) {
5224                throw e.rethrowFromSystemServer();
5225            }
5226        }
5227        return ret == null ? new Bundle() : ret;
5228    }
5229
5230    /**
5231     * Called by profile or device owners to hide or unhide packages. When a package is hidden it is
5232     * unavailable for use, but the data and actual package file remain.
5233     *
5234     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5235     * @param packageName The name of the package to hide or unhide.
5236     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
5237     *            unhidden.
5238     * @return boolean Whether the hidden setting of the package was successfully updated.
5239     * @throws SecurityException if {@code admin} is not a device or profile owner.
5240     */
5241    public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
5242            boolean hidden) {
5243        throwIfParentInstance("setApplicationHidden");
5244        if (mService != null) {
5245            try {
5246                return mService.setApplicationHidden(admin, packageName, hidden);
5247            } catch (RemoteException e) {
5248                throw e.rethrowFromSystemServer();
5249            }
5250        }
5251        return false;
5252    }
5253
5254    /**
5255     * Called by profile or device owners to determine if a package is hidden.
5256     *
5257     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5258     * @param packageName The name of the package to retrieve the hidden status of.
5259     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
5260     * @throws SecurityException if {@code admin} is not a device or profile owner.
5261     */
5262    public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
5263        throwIfParentInstance("isApplicationHidden");
5264        if (mService != null) {
5265            try {
5266                return mService.isApplicationHidden(admin, packageName);
5267            } catch (RemoteException e) {
5268                throw e.rethrowFromSystemServer();
5269            }
5270        }
5271        return false;
5272    }
5273
5274    /**
5275     * Called by profile or device owners to re-enable a system app that was disabled by default
5276     * when the user was initialized.
5277     *
5278     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5279     * @param packageName The package to be re-enabled in the calling profile.
5280     * @throws SecurityException if {@code admin} is not a device or profile owner.
5281     */
5282    public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
5283        throwIfParentInstance("enableSystemApp");
5284        if (mService != null) {
5285            try {
5286                mService.enableSystemApp(admin, packageName);
5287            } catch (RemoteException e) {
5288                throw e.rethrowFromSystemServer();
5289            }
5290        }
5291    }
5292
5293    /**
5294     * Called by profile or device owners to re-enable system apps by intent that were disabled by
5295     * default when the user was initialized.
5296     *
5297     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5298     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
5299     *            intent will be re-enabled in the calling profile.
5300     * @return int The number of activities that matched the intent and were installed.
5301     * @throws SecurityException if {@code admin} is not a device or profile owner.
5302     */
5303    public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
5304        throwIfParentInstance("enableSystemApp");
5305        if (mService != null) {
5306            try {
5307                return mService.enableSystemAppWithIntent(admin, intent);
5308            } catch (RemoteException e) {
5309                throw e.rethrowFromSystemServer();
5310            }
5311        }
5312        return 0;
5313    }
5314
5315    /**
5316     * Called by a device owner or profile owner to disable account management for a specific type
5317     * of account.
5318     * <p>
5319     * The calling device admin must be a device owner or profile owner. If it is not, a security
5320     * exception will be thrown.
5321     * <p>
5322     * When account management is disabled for an account type, adding or removing an account of
5323     * that type will not be possible.
5324     * <p>
5325     * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
5326     * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
5327     * management for a specific type is disabled.
5328     *
5329     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5330     * @param accountType For which account management is disabled or enabled.
5331     * @param disabled The boolean indicating that account management will be disabled (true) or
5332     *            enabled (false).
5333     * @throws SecurityException if {@code admin} is not a device or profile owner.
5334     */
5335    public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
5336            boolean disabled) {
5337        throwIfParentInstance("setAccountManagementDisabled");
5338        if (mService != null) {
5339            try {
5340                mService.setAccountManagementDisabled(admin, accountType, disabled);
5341            } catch (RemoteException e) {
5342                throw e.rethrowFromSystemServer();
5343            }
5344        }
5345    }
5346
5347    /**
5348     * Gets the array of accounts for which account management is disabled by the profile owner.
5349     *
5350     * <p> Account management can be disabled/enabled by calling
5351     * {@link #setAccountManagementDisabled}.
5352     *
5353     * @return a list of account types for which account management has been disabled.
5354     *
5355     * @see #setAccountManagementDisabled
5356     */
5357    public @Nullable String[] getAccountTypesWithManagementDisabled() {
5358        throwIfParentInstance("getAccountTypesWithManagementDisabled");
5359        return getAccountTypesWithManagementDisabledAsUser(myUserId());
5360    }
5361
5362    /**
5363     * @see #getAccountTypesWithManagementDisabled()
5364     * @hide
5365     */
5366    public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
5367        if (mService != null) {
5368            try {
5369                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
5370            } catch (RemoteException e) {
5371                throw e.rethrowFromSystemServer();
5372            }
5373        }
5374
5375        return null;
5376    }
5377
5378    /**
5379     * Sets which packages may enter lock task mode.
5380     * <p>
5381     * Any packages that shares uid with an allowed package will also be allowed to activate lock
5382     * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
5383     * package list results in locked tasks belonging to those packages to be finished. This
5384     * function can only be called by the device owner.
5385     *
5386     * @param packages The list of packages allowed to enter lock task mode
5387     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5388     * @throws SecurityException if {@code admin} is not a device owner.
5389     * @see Activity#startLockTask()
5390     * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
5391     * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
5392     * @see UserManager#DISALLOW_CREATE_WINDOWS
5393     */
5394    public void setLockTaskPackages(@NonNull ComponentName admin, String[] packages)
5395            throws SecurityException {
5396        throwIfParentInstance("setLockTaskPackages");
5397        if (mService != null) {
5398            try {
5399                mService.setLockTaskPackages(admin, packages);
5400            } catch (RemoteException e) {
5401                throw e.rethrowFromSystemServer();
5402            }
5403        }
5404    }
5405
5406    /**
5407     * This function returns the list of packages allowed to start the lock task mode.
5408     *
5409     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5410     * @hide
5411     */
5412    public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
5413        throwIfParentInstance("getLockTaskPackages");
5414        if (mService != null) {
5415            try {
5416                return mService.getLockTaskPackages(admin);
5417            } catch (RemoteException e) {
5418                throw e.rethrowFromSystemServer();
5419            }
5420        }
5421        return null;
5422    }
5423
5424    /**
5425     * This function lets the caller know whether the given component is allowed to start the
5426     * lock task mode.
5427     * @param pkg The package to check
5428     */
5429    public boolean isLockTaskPermitted(String pkg) {
5430        throwIfParentInstance("isLockTaskPermitted");
5431        if (mService != null) {
5432            try {
5433                return mService.isLockTaskPermitted(pkg);
5434            } catch (RemoteException e) {
5435                throw e.rethrowFromSystemServer();
5436            }
5437        }
5438        return false;
5439    }
5440
5441    /**
5442     * Called by device owners to update {@link Settings.Global} settings. Validation that the value
5443     * of the setting is in the correct form for the setting type should be performed by the caller.
5444     * <p>
5445     * The settings that can be updated with this method are:
5446     * <ul>
5447     * <li>{@link Settings.Global#ADB_ENABLED}</li>
5448     * <li>{@link Settings.Global#AUTO_TIME}</li>
5449     * <li>{@link Settings.Global#AUTO_TIME_ZONE}</li>
5450     * <li>{@link Settings.Global#DATA_ROAMING}</li>
5451     * <li>{@link Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
5452     * <li>{@link Settings.Global#WIFI_SLEEP_POLICY}</li>
5453     * <li>{@link Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only available from
5454     * {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
5455     * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
5456     * <li>{@link Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This setting is only
5457     * available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
5458     * </ul>
5459     * <p>
5460     * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
5461     * <ul>
5462     * <li>{@link Settings.Global#BLUETOOTH_ON}. Use
5463     * {@link android.bluetooth.BluetoothAdapter#enable()} and
5464     * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
5465     * <li>{@link Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
5466     * <li>{@link Settings.Global#MODE_RINGER}. Use
5467     * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
5468     * <li>{@link Settings.Global#NETWORK_PREFERENCE}</li>
5469     * <li>{@link Settings.Global#WIFI_ON}. Use
5470     * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
5471     * </ul>
5472     *
5473     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5474     * @param setting The name of the setting to update.
5475     * @param value The value to update the setting to.
5476     * @throws SecurityException if {@code admin} is not a device owner.
5477     */
5478    public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
5479        throwIfParentInstance("setGlobalSetting");
5480        if (mService != null) {
5481            try {
5482                mService.setGlobalSetting(admin, setting, value);
5483            } catch (RemoteException e) {
5484                throw e.rethrowFromSystemServer();
5485            }
5486        }
5487    }
5488
5489    /**
5490     * Called by profile or device owners to update {@link Settings.Secure} settings. Validation
5491     * that the value of the setting is in the correct form for the setting type should be performed
5492     * by the caller.
5493     * <p>
5494     * The settings that can be updated by a profile or device owner with this method are:
5495     * <ul>
5496     * <li>{@link Settings.Secure#DEFAULT_INPUT_METHOD}</li>
5497     * <li>{@link Settings.Secure#INSTALL_NON_MARKET_APPS}</li>
5498     * <li>{@link Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
5499     * </ul>
5500     * <p>
5501     * A device owner can additionally update the following settings:
5502     * <ul>
5503     * <li>{@link Settings.Secure#LOCATION_MODE}</li>
5504     * </ul>
5505     *
5506     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5507     * @param setting The name of the setting to update.
5508     * @param value The value to update the setting to.
5509     * @throws SecurityException if {@code admin} is not a device or profile owner.
5510     */
5511    public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
5512        throwIfParentInstance("setSecureSetting");
5513        if (mService != null) {
5514            try {
5515                mService.setSecureSetting(admin, setting, value);
5516            } catch (RemoteException e) {
5517                throw e.rethrowFromSystemServer();
5518            }
5519        }
5520    }
5521
5522    /**
5523     * Designates a specific service component as the provider for making permission requests of a
5524     * local or remote administrator of the user.
5525     * <p/>
5526     * Only a profile owner can designate the restrictions provider.
5527     *
5528     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5529     * @param provider The component name of the service that implements
5530     *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
5531     *            provider previously assigned.
5532     * @throws SecurityException if {@code admin} is not a device or profile owner.
5533     */
5534    public void setRestrictionsProvider(@NonNull ComponentName admin,
5535            @Nullable ComponentName provider) {
5536        throwIfParentInstance("setRestrictionsProvider");
5537        if (mService != null) {
5538            try {
5539                mService.setRestrictionsProvider(admin, provider);
5540            } catch (RemoteException re) {
5541                throw re.rethrowFromSystemServer();
5542            }
5543        }
5544    }
5545
5546    /**
5547     * Called by profile or device owners to set the master volume mute on or off.
5548     * This has no effect when set on a managed profile.
5549     *
5550     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5551     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
5552     * @throws SecurityException if {@code admin} is not a device or profile owner.
5553     */
5554    public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
5555        throwIfParentInstance("setMasterVolumeMuted");
5556        if (mService != null) {
5557            try {
5558                mService.setMasterVolumeMuted(admin, on);
5559            } catch (RemoteException re) {
5560                throw re.rethrowFromSystemServer();
5561            }
5562        }
5563    }
5564
5565    /**
5566     * Called by profile or device owners to check whether the master volume mute is on or off.
5567     *
5568     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5569     * @return {@code true} if master volume is muted, {@code false} if it's not.
5570     * @throws SecurityException if {@code admin} is not a device or profile owner.
5571     */
5572    public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
5573        throwIfParentInstance("isMasterVolumeMuted");
5574        if (mService != null) {
5575            try {
5576                return mService.isMasterVolumeMuted(admin);
5577            } catch (RemoteException re) {
5578                throw re.rethrowFromSystemServer();
5579            }
5580        }
5581        return false;
5582    }
5583
5584    /**
5585     * Called by profile or device owners to change whether a user can uninstall a package.
5586     *
5587     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5588     * @param packageName package to change.
5589     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
5590     * @throws SecurityException if {@code admin} is not a device or profile owner.
5591     */
5592    public void setUninstallBlocked(@NonNull ComponentName admin, String packageName,
5593            boolean uninstallBlocked) {
5594        throwIfParentInstance("setUninstallBlocked");
5595        if (mService != null) {
5596            try {
5597                mService.setUninstallBlocked(admin, packageName, uninstallBlocked);
5598            } catch (RemoteException re) {
5599                throw re.rethrowFromSystemServer();
5600            }
5601        }
5602    }
5603
5604    /**
5605     * Check whether the user has been blocked by device policy from uninstalling a package.
5606     * Requires the caller to be the profile owner if checking a specific admin's policy.
5607     * <p>
5608     * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
5609     * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
5610     * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
5611     * will cause a NullPointerException to be raised.
5612     *
5613     * @param admin The name of the admin component whose blocking policy will be checked, or
5614     *            {@code null} to check whether any admin has blocked the uninstallation.
5615     * @param packageName package to check.
5616     * @return true if uninstallation is blocked.
5617     * @throws SecurityException if {@code admin} is not a device or profile owner.
5618     */
5619    public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
5620        throwIfParentInstance("isUninstallBlocked");
5621        if (mService != null) {
5622            try {
5623                return mService.isUninstallBlocked(admin, packageName);
5624            } catch (RemoteException re) {
5625                throw re.rethrowFromSystemServer();
5626            }
5627        }
5628        return false;
5629    }
5630
5631    /**
5632     * Called by the profile owner of a managed profile to enable widget providers from a given
5633     * package to be available in the parent profile. As a result the user will be able to add
5634     * widgets from the white-listed package running under the profile to a widget host which runs
5635     * under the parent profile, for example the home screen. Note that a package may have zero or
5636     * more provider components, where each component provides a different widget type.
5637     * <p>
5638     * <strong>Note:</strong> By default no widget provider package is white-listed.
5639     *
5640     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5641     * @param packageName The package from which widget providers are white-listed.
5642     * @return Whether the package was added.
5643     * @throws SecurityException if {@code admin} is not a profile owner.
5644     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
5645     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
5646     */
5647    public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
5648        throwIfParentInstance("addCrossProfileWidgetProvider");
5649        if (mService != null) {
5650            try {
5651                return mService.addCrossProfileWidgetProvider(admin, packageName);
5652            } catch (RemoteException re) {
5653                throw re.rethrowFromSystemServer();
5654            }
5655        }
5656        return false;
5657    }
5658
5659    /**
5660     * Called by the profile owner of a managed profile to disable widget providers from a given
5661     * package to be available in the parent profile. For this method to take effect the package
5662     * should have been added via
5663     * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
5664     * <p>
5665     * <strong>Note:</strong> By default no widget provider package is white-listed.
5666     *
5667     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5668     * @param packageName The package from which widget providers are no longer white-listed.
5669     * @return Whether the package was removed.
5670     * @throws SecurityException if {@code admin} is not a profile owner.
5671     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
5672     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
5673     */
5674    public boolean removeCrossProfileWidgetProvider(
5675            @NonNull ComponentName admin, String packageName) {
5676        throwIfParentInstance("removeCrossProfileWidgetProvider");
5677        if (mService != null) {
5678            try {
5679                return mService.removeCrossProfileWidgetProvider(admin, packageName);
5680            } catch (RemoteException re) {
5681                throw re.rethrowFromSystemServer();
5682            }
5683        }
5684        return false;
5685    }
5686
5687    /**
5688     * Called by the profile owner of a managed profile to query providers from which packages are
5689     * available in the parent profile.
5690     *
5691     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5692     * @return The white-listed package list.
5693     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
5694     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
5695     * @throws SecurityException if {@code admin} is not a profile owner.
5696     */
5697    public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
5698        throwIfParentInstance("getCrossProfileWidgetProviders");
5699        if (mService != null) {
5700            try {
5701                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
5702                if (providers != null) {
5703                    return providers;
5704                }
5705            } catch (RemoteException re) {
5706                throw re.rethrowFromSystemServer();
5707            }
5708        }
5709        return Collections.emptyList();
5710    }
5711
5712    /**
5713     * Called by profile or device owners to set the user's photo.
5714     *
5715     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5716     * @param icon the bitmap to set as the photo.
5717     * @throws SecurityException if {@code admin} is not a device or profile owner.
5718     */
5719    public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
5720        throwIfParentInstance("setUserIcon");
5721        try {
5722            mService.setUserIcon(admin, icon);
5723        } catch (RemoteException re) {
5724            throw re.rethrowFromSystemServer();
5725        }
5726    }
5727
5728    /**
5729     * Called by device owners to set a local system update policy. When a new policy is set,
5730     * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
5731     *
5732     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
5733     *            components in the device owner package can set system update policies and the most
5734     *            recent policy takes effect.
5735     * @param policy the new policy, or {@code null} to clear the current policy.
5736     * @throws SecurityException if {@code admin} is not a device owner.
5737     * @see SystemUpdatePolicy
5738     */
5739    public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
5740        throwIfParentInstance("setSystemUpdatePolicy");
5741        if (mService != null) {
5742            try {
5743                mService.setSystemUpdatePolicy(admin, policy);
5744            } catch (RemoteException re) {
5745                throw re.rethrowFromSystemServer();
5746            }
5747        }
5748    }
5749
5750    /**
5751     * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
5752     *
5753     * @return The current policy object, or {@code null} if no policy is set.
5754     */
5755    public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
5756        throwIfParentInstance("getSystemUpdatePolicy");
5757        if (mService != null) {
5758            try {
5759                return mService.getSystemUpdatePolicy();
5760            } catch (RemoteException re) {
5761                throw re.rethrowFromSystemServer();
5762            }
5763        }
5764        return null;
5765    }
5766
5767    /**
5768     * Called by a device owner to disable the keyguard altogether.
5769     * <p>
5770     * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
5771     * type. However, this call has no effect if a password, pin or pattern is currently set. If a
5772     * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
5773     * disabled.
5774     *
5775     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5776     * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
5777     * @return {@code false} if attempting to disable the keyguard while a lock password was in
5778     *         place. {@code true} otherwise.
5779     * @throws SecurityException if {@code admin} is not a device owner.
5780     */
5781    public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
5782        throwIfParentInstance("setKeyguardDisabled");
5783        try {
5784            return mService.setKeyguardDisabled(admin, disabled);
5785        } catch (RemoteException re) {
5786            throw re.rethrowFromSystemServer();
5787        }
5788    }
5789
5790    /**
5791     * Called by device owner to disable the status bar. Disabling the status bar blocks
5792     * notifications, quick settings and other screen overlays that allow escaping from a single use
5793     * device.
5794     *
5795     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5796     * @param disabled {@code true} disables the status bar, {@code false} reenables it.
5797     * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
5798     * @throws SecurityException if {@code admin} is not a device owner.
5799     */
5800    public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
5801        throwIfParentInstance("setStatusBarDisabled");
5802        try {
5803            return mService.setStatusBarDisabled(admin, disabled);
5804        } catch (RemoteException re) {
5805            throw re.rethrowFromSystemServer();
5806        }
5807    }
5808
5809    /**
5810     * Callable by the system update service to notify device owners about pending updates.
5811     * The caller must hold {@link android.Manifest.permission#NOTIFY_PENDING_SYSTEM_UPDATE}
5812     * permission.
5813     *
5814     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()} indicating
5815     *        when the current pending update was first available. -1 if no update is available.
5816     * @hide
5817     */
5818    @SystemApi
5819    public void notifyPendingSystemUpdate(long updateReceivedTime) {
5820        throwIfParentInstance("notifyPendingSystemUpdate");
5821        if (mService != null) {
5822            try {
5823                mService.notifyPendingSystemUpdate(updateReceivedTime);
5824            } catch (RemoteException re) {
5825                throw re.rethrowFromSystemServer();
5826            }
5827        }
5828    }
5829
5830    /**
5831     * Called by profile or device owners to set the default response for future runtime permission
5832     * requests by applications. The policy can allow for normal operation which prompts the user to
5833     * grant a permission, or can allow automatic granting or denying of runtime permission requests
5834     * by an application. This also applies to new permissions declared by app updates. When a
5835     * permission is denied or granted this way, the effect is equivalent to setting the permission
5836     * grant state via {@link #setPermissionGrantState}.
5837     * <p/>
5838     * As this policy only acts on runtime permission requests, it only applies to applications
5839     * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
5840     *
5841     * @param admin Which profile or device owner this request is associated with.
5842     * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
5843     *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
5844     * @throws SecurityException if {@code admin} is not a device or profile owner.
5845     * @see #setPermissionGrantState
5846     */
5847    public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
5848        throwIfParentInstance("setPermissionPolicy");
5849        try {
5850            mService.setPermissionPolicy(admin, policy);
5851        } catch (RemoteException re) {
5852            throw re.rethrowFromSystemServer();
5853        }
5854    }
5855
5856    /**
5857     * Returns the current runtime permission policy set by the device or profile owner. The
5858     * default is {@link #PERMISSION_POLICY_PROMPT}.
5859     * @param admin Which profile or device owner this request is associated with.
5860     * @return the current policy for future permission requests.
5861     */
5862    public int getPermissionPolicy(ComponentName admin) {
5863        throwIfParentInstance("getPermissionPolicy");
5864        try {
5865            return mService.getPermissionPolicy(admin);
5866        } catch (RemoteException re) {
5867            throw re.rethrowFromSystemServer();
5868        }
5869    }
5870
5871    /**
5872     * Sets the grant state of a runtime permission for a specific application. The state can be
5873     * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
5874     * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
5875     * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
5876     * the permission is granted and the user cannot manage it through the UI. This might affect all
5877     * permissions in a group that the runtime permission belongs to. This method can only be called
5878     * by a profile or device owner.
5879     * <p/>
5880     * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
5881     * the permission. It retains the previous grant, if any.
5882     * <p/>
5883     * Permissions can be granted or revoked only for applications built with a
5884     * {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
5885     *
5886     * @param admin Which profile or device owner this request is associated with.
5887     * @param packageName The application to grant or revoke a permission to.
5888     * @param permission The permission to grant or revoke.
5889     * @param grantState The permission grant state which is one of
5890     *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
5891     *            {@link #PERMISSION_GRANT_STATE_GRANTED},
5892     * @return whether the permission was successfully granted or revoked.
5893     * @throws SecurityException if {@code admin} is not a device or profile owner.
5894     * @see #PERMISSION_GRANT_STATE_DENIED
5895     * @see #PERMISSION_GRANT_STATE_DEFAULT
5896     * @see #PERMISSION_GRANT_STATE_GRANTED
5897     */
5898    public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName,
5899            String permission, int grantState) {
5900        throwIfParentInstance("setPermissionGrantState");
5901        try {
5902            return mService.setPermissionGrantState(admin, packageName, permission, grantState);
5903        } catch (RemoteException re) {
5904            throw re.rethrowFromSystemServer();
5905        }
5906    }
5907
5908    /**
5909     * Returns the current grant state of a runtime permission for a specific application.
5910     *
5911     * @param admin Which profile or device owner this request is associated with.
5912     * @param packageName The application to check the grant state for.
5913     * @param permission The permission to check for.
5914     * @return the current grant state specified by device policy. If the profile or device owner
5915     *         has not set a grant state, the return value is
5916     *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
5917     *         permission is currently granted for the package.
5918     *         <p/>
5919     *         If a grant state was set by the profile or device owner, then the return value will
5920     *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
5921     *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
5922     *         currently denied or granted.
5923     * @throws SecurityException if {@code admin} is not a device or profile owner.
5924     * @see #setPermissionGrantState(ComponentName, String, String, int)
5925     * @see PackageManager#checkPermission(String, String)
5926     */
5927    public int getPermissionGrantState(@NonNull ComponentName admin, String packageName,
5928            String permission) {
5929        throwIfParentInstance("getPermissionGrantState");
5930        try {
5931            return mService.getPermissionGrantState(admin, packageName, permission);
5932        } catch (RemoteException re) {
5933            throw re.rethrowFromSystemServer();
5934        }
5935    }
5936
5937    /**
5938     * Returns if provisioning a managed profile or device is possible or not.
5939     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
5940     * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
5941     * @return if provisioning a managed profile or device is possible or not.
5942     * @throws IllegalArgumentException if the supplied action is not valid.
5943     */
5944    public boolean isProvisioningAllowed(String action) {
5945        throwIfParentInstance("isProvisioningAllowed");
5946        try {
5947            return mService.isProvisioningAllowed(action);
5948        } catch (RemoteException re) {
5949            throw re.rethrowFromSystemServer();
5950        }
5951    }
5952
5953    /**
5954     * Return if this user is a managed profile of another user. An admin can become the profile
5955     * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
5956     * user with {@link #createAndManageUser}
5957     * @param admin Which profile owner this request is associated with.
5958     * @return if this user is a managed profile of another user.
5959     */
5960    public boolean isManagedProfile(@NonNull ComponentName admin) {
5961        throwIfParentInstance("isManagedProfile");
5962        try {
5963            return mService.isManagedProfile(admin);
5964        } catch (RemoteException re) {
5965            throw re.rethrowFromSystemServer();
5966        }
5967    }
5968
5969    /**
5970     * @hide
5971     * Return if this user is a system-only user. An admin can manage a device from a system only
5972     * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
5973     * @param admin Which device owner this request is associated with.
5974     * @return if this user is a system-only user.
5975     */
5976    public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
5977        try {
5978            return mService.isSystemOnlyUser(admin);
5979        } catch (RemoteException re) {
5980            throw re.rethrowFromSystemServer();
5981        }
5982    }
5983
5984    /**
5985     * Called by device owner to get the MAC address of the Wi-Fi device.
5986     *
5987     * @param admin Which device owner this request is associated with.
5988     * @return the MAC address of the Wi-Fi device, or null when the information is not available.
5989     *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
5990     *         <p>
5991     *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
5992     * @throws SecurityException if {@code admin} is not a device owner.
5993     */
5994    public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
5995        throwIfParentInstance("getWifiMacAddress");
5996        try {
5997            return mService.getWifiMacAddress(admin);
5998        } catch (RemoteException re) {
5999            throw re.rethrowFromSystemServer();
6000        }
6001    }
6002
6003    /**
6004     * Called by device owner to reboot the device. If there is an ongoing call on the device,
6005     * throws an {@link IllegalStateException}.
6006     * @param admin Which device owner the request is associated with.
6007     * @throws IllegalStateException if device has an ongoing call.
6008     * @throws SecurityException if {@code admin} is not a device owner.
6009     * @see TelephonyManager#CALL_STATE_IDLE
6010     */
6011    public void reboot(@NonNull ComponentName admin) {
6012        throwIfParentInstance("reboot");
6013        try {
6014            mService.reboot(admin);
6015        } catch (RemoteException re) {
6016            throw re.rethrowFromSystemServer();
6017        }
6018    }
6019
6020    /**
6021     * Called by a device admin to set the short support message. This will be displayed to the user
6022     * in settings screens where funtionality has been disabled by the admin. The message should be
6023     * limited to a short statement such as "This setting is disabled by your administrator. Contact
6024     * someone@example.com for support." If the message is longer than 200 characters it may be
6025     * truncated.
6026     * <p>
6027     * If the short support message needs to be localized, it is the responsibility of the
6028     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
6029     * and set a new version of this string accordingly.
6030     *
6031     * @see #setLongSupportMessage
6032     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6033     * @param message Short message to be displayed to the user in settings or null to clear the
6034     *            existing message.
6035     * @throws SecurityException if {@code admin} is not an active administrator.
6036     */
6037    public void setShortSupportMessage(@NonNull ComponentName admin,
6038            @Nullable CharSequence message) {
6039        throwIfParentInstance("setShortSupportMessage");
6040        if (mService != null) {
6041            try {
6042                mService.setShortSupportMessage(admin, message);
6043            } catch (RemoteException e) {
6044                throw e.rethrowFromSystemServer();
6045            }
6046        }
6047    }
6048
6049    /**
6050     * Called by a device admin to get the short support message.
6051     *
6052     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6053     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
6054     *         null if no message has been set.
6055     * @throws SecurityException if {@code admin} is not an active administrator.
6056     */
6057    public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
6058        throwIfParentInstance("getShortSupportMessage");
6059        if (mService != null) {
6060            try {
6061                return mService.getShortSupportMessage(admin);
6062            } catch (RemoteException e) {
6063                throw e.rethrowFromSystemServer();
6064            }
6065        }
6066        return null;
6067    }
6068
6069    /**
6070     * Called by a device admin to set the long support message. This will be displayed to the user
6071     * in the device administators settings screen.
6072     * <p>
6073     * If the long support message needs to be localized, it is the responsibility of the
6074     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
6075     * and set a new version of this string accordingly.
6076     *
6077     * @see #setShortSupportMessage
6078     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6079     * @param message Long message to be displayed to the user in settings or null to clear the
6080     *            existing message.
6081     * @throws SecurityException if {@code admin} is not an active administrator.
6082     */
6083    public void setLongSupportMessage(@NonNull ComponentName admin,
6084            @Nullable CharSequence message) {
6085        throwIfParentInstance("setLongSupportMessage");
6086        if (mService != null) {
6087            try {
6088                mService.setLongSupportMessage(admin, message);
6089            } catch (RemoteException e) {
6090                throw e.rethrowFromSystemServer();
6091            }
6092        }
6093    }
6094
6095    /**
6096     * Called by a device admin to get the long support message.
6097     *
6098     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6099     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
6100     *         null if no message has been set.
6101     * @throws SecurityException if {@code admin} is not an active administrator.
6102     */
6103    public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
6104        throwIfParentInstance("getLongSupportMessage");
6105        if (mService != null) {
6106            try {
6107                return mService.getLongSupportMessage(admin);
6108            } catch (RemoteException e) {
6109                throw e.rethrowFromSystemServer();
6110            }
6111        }
6112        return null;
6113    }
6114
6115    /**
6116     * Called by the system to get the short support message.
6117     *
6118     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6119     * @param userHandle user id the admin is running as.
6120     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
6121     *
6122     * @hide
6123     */
6124    public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
6125            int userHandle) {
6126        if (mService != null) {
6127            try {
6128                return mService.getShortSupportMessageForUser(admin, userHandle);
6129            } catch (RemoteException e) {
6130                throw e.rethrowFromSystemServer();
6131            }
6132        }
6133        return null;
6134    }
6135
6136
6137    /**
6138     * Called by the system to get the long support message.
6139     *
6140     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6141     * @param userHandle user id the admin is running as.
6142     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
6143     *
6144     * @hide
6145     */
6146    public @Nullable CharSequence getLongSupportMessageForUser(
6147            @NonNull ComponentName admin, int userHandle) {
6148        if (mService != null) {
6149            try {
6150                return mService.getLongSupportMessageForUser(admin, userHandle);
6151            } catch (RemoteException e) {
6152                throw e.rethrowFromSystemServer();
6153            }
6154        }
6155        return null;
6156    }
6157
6158    /**
6159     * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
6160     * whose calls act on the parent profile.
6161     *
6162     * <p>The following methods are supported for the parent instance, all other methods will
6163     * throw a SecurityException when called on the parent instance:
6164     * <ul>
6165     * <li>{@link #getPasswordQuality}</li>
6166     * <li>{@link #setPasswordQuality}</li>
6167     * <li>{@link #getPasswordMinimumLength}</li>
6168     * <li>{@link #setPasswordMinimumLength}</li>
6169     * <li>{@link #getPasswordMinimumUpperCase}</li>
6170     * <li>{@link #setPasswordMinimumUpperCase}</li>
6171     * <li>{@link #getPasswordMinimumLowerCase}</li>
6172     * <li>{@link #setPasswordMinimumLowerCase}</li>
6173     * <li>{@link #getPasswordMinimumLetters}</li>
6174     * <li>{@link #setPasswordMinimumLetters}</li>
6175     * <li>{@link #getPasswordMinimumNumeric}</li>
6176     * <li>{@link #setPasswordMinimumNumeric}</li>
6177     * <li>{@link #getPasswordMinimumSymbols}</li>
6178     * <li>{@link #setPasswordMinimumSymbols}</li>
6179     * <li>{@link #getPasswordMinimumNonLetter}</li>
6180     * <li>{@link #setPasswordMinimumNonLetter}</li>
6181     * <li>{@link #getPasswordHistoryLength}</li>
6182     * <li>{@link #setPasswordHistoryLength}</li>
6183     * <li>{@link #getPasswordExpirationTimeout}</li>
6184     * <li>{@link #setPasswordExpirationTimeout}</li>
6185     * <li>{@link #getPasswordExpiration}</li>
6186     * <li>{@link #getPasswordMaximumLength}</li>
6187     * <li>{@link #isActivePasswordSufficient}</li>
6188     * <li>{@link #getCurrentFailedPasswordAttempts}</li>
6189     * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
6190     * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
6191     * <li>{@link #getMaximumTimeToLock}</li>
6192     * <li>{@link #setMaximumTimeToLock}</li>
6193     * <li>{@link #lockNow}</li>
6194     * <li>{@link #getKeyguardDisabledFeatures}</li>
6195     * <li>{@link #setKeyguardDisabledFeatures}</li>
6196     * <li>{@link #getTrustAgentConfiguration}</li>
6197     * <li>{@link #setTrustAgentConfiguration}</li>
6198     * <li>{@link #getRequiredStrongAuthTimeout}</li>
6199     * <li>{@link #setRequiredStrongAuthTimeout}</li>
6200     * </ul>
6201     *
6202     * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
6203     * @throws SecurityException if {@code admin} is not a profile owner.
6204     */
6205    public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
6206        throwIfParentInstance("getParentProfileInstance");
6207        try {
6208            if (!mService.isManagedProfile(admin)) {
6209                throw new SecurityException("The current user does not have a parent profile.");
6210            }
6211            return new DevicePolicyManager(mContext, mService, true);
6212        } catch (RemoteException e) {
6213            throw e.rethrowFromSystemServer();
6214        }
6215    }
6216
6217    /**
6218     * Called by device owner to control the security logging feature. Logging can only be
6219     * enabled on single user devices where the sole user is managed by the device owner.
6220     *
6221     * <p> Security logs contain various information intended for security auditing purposes.
6222     * See {@link SecurityEvent} for details.
6223     *
6224     * <p>There must be only one user on the device, managed by the device owner.
6225     * Otherwise a {@link SecurityException} will be thrown.
6226     *
6227     * @param admin Which device owner this request is associated with.
6228     * @param enabled whether security logging should be enabled or not.
6229     * @throws SecurityException if {@code admin} is not a device owner.
6230     * @see #retrieveSecurityLogs
6231     */
6232    public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
6233        throwIfParentInstance("setSecurityLoggingEnabled");
6234        try {
6235            mService.setSecurityLoggingEnabled(admin, enabled);
6236        } catch (RemoteException re) {
6237            throw re.rethrowFromSystemServer();
6238        }
6239    }
6240
6241    /**
6242     * Return whether security logging is enabled or not by the device owner.
6243     *
6244     * <p>Can only be called by the device owner, otherwise a {@link SecurityException} will be
6245     * thrown.
6246     *
6247     * @param admin Which device owner this request is associated with.
6248     * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
6249     * @throws SecurityException if {@code admin} is not a device owner.
6250     */
6251    public boolean isSecurityLoggingEnabled(@NonNull ComponentName admin) {
6252        throwIfParentInstance("isSecurityLoggingEnabled");
6253        try {
6254            return mService.isSecurityLoggingEnabled(admin);
6255        } catch (RemoteException re) {
6256            throw re.rethrowFromSystemServer();
6257        }
6258    }
6259
6260    /**
6261     * Called by device owner to retrieve all new security logging entries since the last call to
6262     * this API after device boots.
6263     *
6264     * <p> Access to the logs is rate limited and it will only return new logs after the device
6265     * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
6266     *
6267     * <p>There must be only one user on the device, managed by the device owner.
6268     * Otherwise a {@link SecurityException} will be thrown.
6269     *
6270     * @param admin Which device owner this request is associated with.
6271     * @return the new batch of security logs which is a list of {@link SecurityEvent},
6272     * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
6273     * @throws SecurityException if {@code admin} is not a device owner.
6274     */
6275    public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
6276        throwIfParentInstance("retrieveSecurityLogs");
6277        try {
6278            ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
6279            if (list != null) {
6280                return list.getList();
6281            } else {
6282                // Rate limit exceeded.
6283                return null;
6284            }
6285        } catch (RemoteException re) {
6286            throw re.rethrowFromSystemServer();
6287        }
6288    }
6289
6290    /**
6291     * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
6292     * profile.
6293     *
6294     * @hide
6295     */
6296    public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
6297        mContext.checkSelfPermission(
6298                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
6299        if (!uInfo.isManagedProfile()) {
6300            throw new SecurityException("The user " + uInfo.id
6301                    + " does not have a parent profile.");
6302        }
6303        return new DevicePolicyManager(mContext, mService, true);
6304    }
6305
6306    /**
6307     * Called by device owners to retrieve device logs from before the device's last reboot.
6308     * <p>
6309     * <strong> This API is not supported on all devices. Calling this API on unsupported devices
6310     * will result in {@code null} being returned. The device logs are retrieved from a RAM region
6311     * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
6312     * about data corruption when parsing. </strong>
6313     * <p>
6314     * There must be only one user on the device, managed by the device owner. Otherwise a
6315     * {@link SecurityException} will be thrown.
6316     *
6317     * @param admin Which device owner this request is associated with.
6318     * @return Device logs from before the latest reboot of the system, or {@code null} if this API
6319     *         is not supported on the device.
6320     * @throws SecurityException if {@code admin} is not a device owner.
6321     */
6322    public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
6323            @NonNull ComponentName admin) {
6324        throwIfParentInstance("retrievePreRebootSecurityLogs");
6325        try {
6326            ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
6327            if (list != null) {
6328                return list.getList();
6329            } else {
6330                return null;
6331            }
6332        } catch (RemoteException re) {
6333            throw re.rethrowFromSystemServer();
6334        }
6335    }
6336
6337    /**
6338     * Called by a profile owner of a managed profile to set the color used for customization. This
6339     * color is used as background color of the confirm credentials screen for that user. The
6340     * default color is teal (#00796B).
6341     * <p>
6342     * The confirm credentials screen can be created using
6343     * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
6344     *
6345     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6346     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
6347     * @throws SecurityException if {@code admin} is not a profile owner.
6348     */
6349    public void setOrganizationColor(@NonNull ComponentName admin, int color) {
6350        throwIfParentInstance("setOrganizationColor");
6351        try {
6352            // always enforce alpha channel to have 100% opacity
6353            color |= 0xFF000000;
6354            mService.setOrganizationColor(admin, color);
6355        } catch (RemoteException re) {
6356            throw re.rethrowFromSystemServer();
6357        }
6358    }
6359
6360    /**
6361     * @hide
6362     *
6363     * Sets the color used for customization.
6364     *
6365     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
6366     * @param userId which user to set the color to.
6367     * @RequiresPermission(allOf = {
6368     *       Manifest.permission.MANAGE_USERS,
6369     *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
6370     */
6371    public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
6372        try {
6373            // always enforce alpha channel to have 100% opacity
6374            color |= 0xFF000000;
6375            mService.setOrganizationColorForUser(color, userId);
6376        } catch (RemoteException re) {
6377            throw re.rethrowFromSystemServer();
6378        }
6379    }
6380
6381    /**
6382     * Called by a profile owner of a managed profile to retrieve the color used for customization.
6383     * This color is used as background color of the confirm credentials screen for that user.
6384     *
6385     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6386     * @return The 24bit (0xRRGGBB) representation of the color to be used.
6387     * @throws SecurityException if {@code admin} is not a profile owner.
6388     */
6389    public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
6390        throwIfParentInstance("getOrganizationColor");
6391        try {
6392            return mService.getOrganizationColor(admin);
6393        } catch (RemoteException re) {
6394            throw re.rethrowFromSystemServer();
6395        }
6396    }
6397
6398    /**
6399     * @hide
6400     * Retrieve the customization color for a given user.
6401     *
6402     * @param userHandle The user id of the user we're interested in.
6403     * @return The 24bit (0xRRGGBB) representation of the color to be used.
6404     */
6405    public @ColorInt int getOrganizationColorForUser(int userHandle) {
6406        try {
6407            return mService.getOrganizationColorForUser(userHandle);
6408        } catch (RemoteException re) {
6409            throw re.rethrowFromSystemServer();
6410        }
6411    }
6412
6413    /**
6414     * Called by a profile owner of a managed profile to set the name of the organization under
6415     * management.
6416     * <p>
6417     * If the organization name needs to be localized, it is the responsibility of the
6418     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
6419     * and set a new version of this string accordingly.
6420     *
6421     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6422     * @param title The organization name or {@code null} to clear a previously set name.
6423     * @throws SecurityException if {@code admin} is not a profile owner.
6424     */
6425    public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
6426        throwIfParentInstance("setOrganizationName");
6427        try {
6428            mService.setOrganizationName(admin, title);
6429        } catch (RemoteException re) {
6430            throw re.rethrowFromSystemServer();
6431        }
6432    }
6433
6434    /**
6435     * Called by a profile owner of a managed profile to retrieve the name of the organization under
6436     * management.
6437     *
6438     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6439     * @return The organization name or {@code null} if none is set.
6440     * @throws SecurityException if {@code admin} is not a profile owner.
6441     */
6442    public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
6443        throwIfParentInstance("getOrganizationName");
6444        try {
6445            return mService.getOrganizationName(admin);
6446        } catch (RemoteException re) {
6447            throw re.rethrowFromSystemServer();
6448        }
6449    }
6450
6451    /**
6452     * Retrieve the default title message used in the confirm credentials screen for a given user.
6453     *
6454     * @param userHandle The user id of the user we're interested in.
6455     * @return The organization name or {@code null} if none is set.
6456     *
6457     * @hide
6458     */
6459    public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
6460        try {
6461            return mService.getOrganizationNameForUser(userHandle);
6462        } catch (RemoteException re) {
6463            throw re.rethrowFromSystemServer();
6464        }
6465    }
6466
6467    /**
6468     * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
6469     *         return {@link #STATE_USER_UNMANAGED}
6470     * @hide
6471     */
6472    @SystemApi
6473    @UserProvisioningState
6474    public int getUserProvisioningState() {
6475        throwIfParentInstance("getUserProvisioningState");
6476        if (mService != null) {
6477            try {
6478                return mService.getUserProvisioningState();
6479            } catch (RemoteException e) {
6480                throw e.rethrowFromSystemServer();
6481            }
6482        }
6483        return STATE_USER_UNMANAGED;
6484    }
6485
6486    /**
6487     * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
6488     *
6489     * @param state to store
6490     * @param userHandle for user
6491     * @hide
6492     */
6493    public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
6494        if (mService != null) {
6495            try {
6496                mService.setUserProvisioningState(state, userHandle);
6497            } catch (RemoteException e) {
6498                throw e.rethrowFromSystemServer();
6499            }
6500        }
6501    }
6502
6503    /**
6504     * Indicates the entity that controls the device or profile owner. Two users/profiles are
6505     * affiliated if the set of ids set by their device or profile owners intersect.
6506     *
6507     * @param admin Which profile or device owner this request is associated with.
6508     * @param ids A list of opaque non-empty affiliation ids. Duplicate elements will be ignored.
6509     *
6510     * @throws NullPointerException if {@code ids} is null or contains null elements.
6511     * @throws IllegalArgumentException if {@code ids} contains an empty string.
6512     */
6513    public void setAffiliationIds(@NonNull ComponentName admin, @NonNull List<String> ids) {
6514        throwIfParentInstance("setAffiliationIds");
6515        try {
6516            mService.setAffiliationIds(admin, ids);
6517        } catch (RemoteException e) {
6518            throw e.rethrowFromSystemServer();
6519        }
6520    }
6521
6522    /**
6523     * Returns the list of affiliation ids previously set via {@link #setAffiliationIds}, or an
6524     * empty list if none have been set.
6525     */
6526    public @NonNull List<String> getAffiliationIds(@NonNull ComponentName admin) {
6527        throwIfParentInstance("getAffiliationIds");
6528        try {
6529            return mService.getAffiliationIds(admin);
6530        } catch (RemoteException e) {
6531            throw e.rethrowFromSystemServer();
6532        }
6533    }
6534
6535    /**
6536     * @hide
6537     * Returns whether this user/profile is affiliated with the device.
6538     * <p>
6539     * By definition, the user that the device owner runs on is always affiliated with the device.
6540     * Any other user/profile is considered affiliated with the device if the set specified by its
6541     * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
6542     *
6543     */
6544    public boolean isAffiliatedUser() {
6545        throwIfParentInstance("isAffiliatedUser");
6546        try {
6547            return mService.isAffiliatedUser();
6548        } catch (RemoteException e) {
6549            throw e.rethrowFromSystemServer();
6550        }
6551    }
6552
6553    /**
6554     * @hide
6555     * Returns whether the uninstall for {@code packageName} for the current user is in queue
6556     * to be started
6557     * @param packageName the package to check for
6558     * @return whether the uninstall intent for {@code packageName} is pending
6559     */
6560    public boolean isUninstallInQueue(String packageName) {
6561        try {
6562            return mService.isUninstallInQueue(packageName);
6563        } catch (RemoteException re) {
6564            throw re.rethrowFromSystemServer();
6565        }
6566    }
6567
6568    /**
6569     * @hide
6570     * @param packageName the package containing active DAs to be uninstalled
6571     */
6572    public void uninstallPackageWithActiveAdmins(String packageName) {
6573        try {
6574            mService.uninstallPackageWithActiveAdmins(packageName);
6575        } catch (RemoteException re) {
6576            throw re.rethrowFromSystemServer();
6577        }
6578    }
6579
6580    /**
6581     * @hide
6582     * Remove a test admin synchronously without sending it a broadcast about being removed.
6583     * If the admin is a profile owner or device owner it will still be removed.
6584     *
6585     * @param userHandle user id to remove the admin for.
6586     * @param admin The administration compononent to remove.
6587     * @throws SecurityException if the caller is not shell / root or the admin package
6588     *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
6589     */
6590    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
6591        try {
6592            mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
6593        } catch (RemoteException re) {
6594            throw re.rethrowFromSystemServer();
6595        }
6596    }
6597
6598    /**
6599     * @hide
6600     * @return whether {@link android.provider.Settings.Global#DEVICE_PROVISIONED} has ever been set
6601     * to 1.
6602     */
6603    public boolean isDeviceProvisioned() {
6604        try {
6605            return mService.isDeviceProvisioned();
6606        } catch (RemoteException re) {
6607            throw re.rethrowFromSystemServer();
6608        }
6609    }
6610
6611    /**
6612     * @hide
6613     * Writes that the provisioning configuration has been applied.
6614     */
6615    public void setDeviceProvisioningConfigApplied() {
6616        try {
6617            mService.setDeviceProvisioningConfigApplied();
6618        } catch (RemoteException re) {
6619            throw re.rethrowFromSystemServer();
6620        }
6621    }
6622
6623    /**
6624     * @hide
6625     * @return whether the provisioning configuration has been applied.
6626     */
6627    public boolean isDeviceProvisioningConfigApplied() {
6628        try {
6629            return mService.isDeviceProvisioningConfigApplied();
6630        } catch (RemoteException re) {
6631            throw re.rethrowFromSystemServer();
6632        }
6633    }
6634
6635    /**
6636     * @hide
6637     * Force update user setup completed status. This API has no effect on user build.
6638     * @throws {@link SecurityException} if the caller has no
6639     *         {@link android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
6640     *         not {@link UserHandle.SYSTEM_USER}
6641     */
6642    public void forceUpdateUserSetupComplete() {
6643        try {
6644            mService.forceUpdateUserSetupComplete();
6645        } catch (RemoteException re) {
6646            throw re.rethrowFromSystemServer();
6647        }
6648    }
6649
6650    private void throwIfParentInstance(String functionName) {
6651        if (mParentInstance) {
6652            throw new SecurityException(functionName + " cannot be called on the parent instance");
6653        }
6654    }
6655
6656    /**
6657     * @hide
6658     * Enable backup service.
6659     * <p>This includes all backup and restore mechanisms.
6660     * Setting this to {@code false} will make backup service no-op or return empty results.
6661     *
6662     * <p>There must be only one user on the device, managed by the device owner.
6663     * Otherwise a {@link SecurityException} will be thrown.
6664     *
6665     * <p>Backup service is off by default when device owner is present.
6666     */
6667    public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
6668        try {
6669            mService.setBackupServiceEnabled(admin, enabled);
6670        } catch (RemoteException re) {
6671            throw re.rethrowFromSystemServer();
6672        }
6673    }
6674
6675    /**
6676     * @hide
6677     * @return {@code true} if backup service is enabled, {@code false} otherwise.
6678     */
6679    public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
6680        try {
6681            return mService.isBackupServiceEnabled(admin);
6682        } catch (RemoteException re) {
6683            throw re.rethrowFromSystemServer();
6684        }
6685    }
6686
6687    /**
6688     * Called by a device owner to control the network logging feature. Logging can only be
6689     * enabled on single user devices where the sole user is managed by the device owner. If a new
6690     * user is added on the device, logging is disabled.
6691     *
6692     * <p> Network logs contain DNS lookup and connect() library call events.
6693     *
6694     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6695     * @param enabled whether network logging should be enabled or not.
6696     * @throws {@link SecurityException} if {@code admin} is not a device owner.
6697     * @see #retrieveNetworkLogs
6698     */
6699    public void setNetworkLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
6700        throwIfParentInstance("setNetworkLoggingEnabled");
6701        try {
6702            mService.setNetworkLoggingEnabled(admin, enabled);
6703        } catch (RemoteException re) {
6704            throw re.rethrowFromSystemServer();
6705        }
6706    }
6707
6708    /**
6709     * Return whether network logging is enabled by a device owner.
6710     *
6711     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6712     * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
6713     * @throws {@link SecurityException} if {@code admin} is not a device owner.
6714     */
6715    public boolean isNetworkLoggingEnabled(@NonNull ComponentName admin) {
6716        throwIfParentInstance("isNetworkLoggingEnabled");
6717        try {
6718            return mService.isNetworkLoggingEnabled(admin);
6719        } catch (RemoteException re) {
6720            throw re.rethrowFromSystemServer();
6721        }
6722    }
6723
6724    /**
6725     * Called by device owner to retrieve the most recent batch of network logging events.
6726     * A device owner has to provide a batchToken provided as part of
6727     * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
6728     * token of the most recent available batch of logs, {@code null} will be returned.
6729     *
6730     * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
6731     *
6732     * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
6733     *
6734     * <p> Access to the logs is rate limited and this method will only return a new batch of logs
6735     * after the device device owner has been notified via
6736     * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
6737     *
6738     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6739     * @param batchToken A token of the batch to retrieve
6740     * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
6741     *        {@code null} if the batch represented by batchToken is no longer available or if
6742     *        logging is disabled.
6743     * @throws {@link SecurityException} if {@code admin} is not a device owner.
6744     * @see DeviceAdminReceiver#onNetworkLogsAvailable
6745     */
6746    public @Nullable List<NetworkEvent> retrieveNetworkLogs(@NonNull ComponentName admin,
6747            long batchToken) {
6748        throwIfParentInstance("retrieveNetworkLogs");
6749        try {
6750            return mService.retrieveNetworkLogs(admin, batchToken);
6751        } catch (RemoteException re) {
6752            throw re.rethrowFromSystemServer();
6753        }
6754    }
6755
6756    /**
6757     * Called by a device owner to bind to a service from a profile owner of a managed profile or
6758     * vice versa. See {@link #getBindDeviceAdminTargetUsers} for a definition of which
6759     * device/profile owners are allowed to bind to services of another profile/device owner.
6760     * <p>
6761     * The service must be unexported. Note that the {@link Context} used to obtain this
6762     * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
6763     * to bind to the {@link android.app.Service}.
6764     *
6765     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6766     * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
6767     *        explicit component name or a package name to match an
6768     *        {@link IntentFilter} published by a service.
6769     * @param conn Receives information as the service is started and stopped. This must be a
6770     *        valid {@link ServiceConnection} object; it must not be {@code null}.
6771     * @param flags Operation options for the binding operation. See
6772     *        {@link Context#bindService(Intent, ServiceConnection, int)}.
6773     * @param targetUser Which user to bind to. Must be one of the users returned by
6774     *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
6775     *        be thrown.
6776     * @return If you have successfully bound to the service, {@code true} is returned;
6777     *         {@code false} is returned if the connection is not made and you will not
6778     *         receive the service object.
6779     *
6780     * @see Context#bindService(Intent, ServiceConnection, int)
6781     * @see #getBindDeviceAdminTargetUsers(ComponentName)
6782     */
6783    public boolean bindDeviceAdminServiceAsUser(
6784            @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
6785            @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
6786        throwIfParentInstance("bindDeviceAdminServiceAsUser");
6787        // Keep this in sync with ContextImpl.bindServiceCommon.
6788        try {
6789            final IServiceConnection sd = mContext.getServiceDispatcher(conn, null, flags);
6790            serviceIntent.prepareToLeaveProcess(mContext);
6791            return mService.bindDeviceAdminServiceAsUser(admin,
6792                    mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
6793                    sd, flags, targetUser.getIdentifier());
6794        } catch (RemoteException re) {
6795            throw re.rethrowFromSystemServer();
6796        }
6797    }
6798
6799    /**
6800     * Returns the list of target users that the calling device or profile owner can use when
6801     * calling {@link #bindDeviceAdminServiceAsUser}.
6802     * <p>
6803     * A device owner can bind to a service from a profile owner of a managed profile and
6804     * vice versa, provided that:
6805     * <ul>
6806     * <li>Both belong to the same package name.
6807     * <li>The managed profile is a profile of the user where the device owner is set.
6808     *     See {@link UserManager#getUserProfiles()}
6809     * <li>Both users are affiliated.
6810     *         STOPSHIP(b/32326223) Add reference to setAffiliationIds here once public.
6811     * </ul>
6812     */
6813    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
6814        throwIfParentInstance("getBindDeviceAdminTargetUsers");
6815        try {
6816            return mService.getBindDeviceAdminTargetUsers(admin);
6817        } catch (RemoteException re) {
6818            throw re.rethrowFromSystemServer();
6819        }
6820    }
6821
6822    /**
6823     * Called by the system to get the time at which the device owner last retrieved security
6824     * logging entries.
6825     *
6826     * @return the time at which the device owner most recently retrieved security logging entries,
6827     *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
6828     * @throws SecurityException if the caller is not the device owner, does not hold the
6829     *         MANAGE_USERS permission and is not the system.
6830     *
6831     * @hide
6832     */
6833    @TestApi
6834    public long getLastSecurityLogRetrievalTime() {
6835        try {
6836            return mService.getLastSecurityLogRetrievalTime();
6837        } catch (RemoteException re) {
6838            throw re.rethrowFromSystemServer();
6839        }
6840    }
6841
6842    /**
6843     * Called by the system to get the time at which the device owner last requested a bug report.
6844     *
6845     * @return the time at which the device owner most recently requested a bug report, in
6846     *         milliseconds since epoch; -1 if a bug report was never requested.
6847     * @throws SecurityException if the caller is not the device owner, does not hold the
6848     *         MANAGE_USERS permission and is not the system.
6849     *
6850     * @hide
6851     */
6852    @TestApi
6853    public long getLastBugReportRequestTime() {
6854        try {
6855            return mService.getLastBugReportRequestTime();
6856        } catch (RemoteException re) {
6857            throw re.rethrowFromSystemServer();
6858        }
6859    }
6860
6861    /**
6862     * Called by the system to get the time at which the device owner last retrieved network logging
6863     * events.
6864     *
6865     * @return the time at which the device owner most recently retrieved network logging events, in
6866     *         milliseconds since epoch; -1 if network logging events were never retrieved.
6867     * @throws SecurityException if the caller is not the device owner, does not hold the
6868     *         MANAGE_USERS permission and is not the system.
6869     *
6870     * @hide
6871     */
6872    @TestApi
6873    public long getLastNetworkLogRetrievalTime() {
6874        try {
6875            return mService.getLastNetworkLogRetrievalTime();
6876        } catch (RemoteException re) {
6877            throw re.rethrowFromSystemServer();
6878        }
6879    }
6880}
6881