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