DevicePolicyManager.java revision 23374d63ecfd076c41c855bc59f63570cf265a7c
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.CallbackExecutor;
20import android.annotation.ColorInt;
21import android.annotation.Condemned;
22import android.annotation.IntDef;
23import android.annotation.NonNull;
24import android.annotation.Nullable;
25import android.annotation.RequiresPermission;
26import android.annotation.SdkConstant;
27import android.annotation.SdkConstant.SdkConstantType;
28import android.annotation.SuppressLint;
29import android.annotation.SystemApi;
30import android.annotation.SystemService;
31import android.annotation.TestApi;
32import android.annotation.UserIdInt;
33import android.annotation.WorkerThread;
34import android.app.Activity;
35import android.app.IServiceConnection;
36import android.app.KeyguardManager;
37import android.app.admin.SecurityLog.SecurityEvent;
38import android.content.ComponentName;
39import android.content.Context;
40import android.content.Intent;
41import android.content.IntentFilter;
42import android.content.ServiceConnection;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.IPackageDataObserver;
45import android.content.pm.PackageManager;
46import android.content.pm.PackageManager.NameNotFoundException;
47import android.content.pm.ParceledListSlice;
48import android.content.pm.UserInfo;
49import android.graphics.Bitmap;
50import android.net.ProxyInfo;
51import android.net.Uri;
52import android.os.Bundle;
53import android.os.Handler;
54import android.os.HandlerExecutor;
55import android.os.Parcelable;
56import android.os.PersistableBundle;
57import android.os.Process;
58import android.os.RemoteCallback;
59import android.os.RemoteException;
60import android.os.UserHandle;
61import android.os.UserManager;
62import android.provider.ContactsContract.Directory;
63import android.security.AttestedKeyPair;
64import android.security.Credentials;
65import android.security.KeyChain;
66import android.security.KeyChainException;
67import android.security.keymaster.KeymasterCertificateChain;
68import android.security.keystore.AttestationUtils;
69import android.security.keystore.KeyAttestationException;
70import android.security.keystore.KeyGenParameterSpec;
71import android.security.keystore.ParcelableKeyGenParameterSpec;
72import android.service.restrictions.RestrictionsReceiver;
73import android.telephony.TelephonyManager;
74import android.util.ArraySet;
75import android.util.Log;
76
77import com.android.internal.R;
78import com.android.internal.annotations.VisibleForTesting;
79import com.android.internal.util.Preconditions;
80import com.android.org.conscrypt.TrustedCertificateStore;
81
82import java.io.ByteArrayInputStream;
83import java.io.IOException;
84import java.lang.annotation.Retention;
85import java.lang.annotation.RetentionPolicy;
86import java.net.InetSocketAddress;
87import java.net.Proxy;
88import java.security.KeyFactory;
89import java.security.KeyPair;
90import java.security.NoSuchAlgorithmException;
91import java.security.PrivateKey;
92import java.security.cert.Certificate;
93import java.security.cert.CertificateException;
94import java.security.cert.CertificateFactory;
95import java.security.cert.X509Certificate;
96import java.security.spec.InvalidKeySpecException;
97import java.security.spec.PKCS8EncodedKeySpec;
98import java.util.ArrayList;
99import java.util.Arrays;
100import java.util.Collections;
101import java.util.List;
102import java.util.Set;
103import java.util.concurrent.Executor;
104
105/**
106 * Public interface for managing policies enforced on a device. Most clients of this class must be
107 * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
108 * administrator</a>. Additionally, a device administrator may be registered as either a profile or
109 * device owner. A given method is accessible to all device administrators unless the documentation
110 * for that method specifies that it is restricted to either device or profile owners. Any
111 * application calling an api may only pass as an argument a device administrator component it
112 * owns. Otherwise, a {@link SecurityException} will be thrown.
113 * <div class="special reference">
114 * <h3>Developer Guides</h3>
115 * <p>
116 * For more information about managing policies for device administration, read the <a href=
117 * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
118 * guide. </div>
119 */
120@SystemService(Context.DEVICE_POLICY_SERVICE)
121public class DevicePolicyManager {
122    private static String TAG = "DevicePolicyManager";
123
124    private final Context mContext;
125    private final IDevicePolicyManager mService;
126    private final boolean mParentInstance;
127
128    /** @hide */
129    public DevicePolicyManager(Context context, IDevicePolicyManager service) {
130        this(context, service, false);
131    }
132
133    /** @hide */
134    @VisibleForTesting
135    protected DevicePolicyManager(Context context, IDevicePolicyManager service,
136            boolean parentInstance) {
137        mContext = context;
138        mService = service;
139        mParentInstance = parentInstance;
140    }
141
142    /** @hide test will override it. */
143    @VisibleForTesting
144    protected int myUserId() {
145        return UserHandle.myUserId();
146    }
147
148    /**
149     * Activity action: Starts the provisioning flow which sets up a managed profile.
150     *
151     * <p>A managed profile allows data separation for example for the usage of a
152     * device as a personal and corporate device. The user which provisioning is started from and
153     * the managed profile share a launcher.
154     *
155     * <p>This intent will typically be sent by a mobile device management application (MDM).
156     * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
157     * control over the profile.
158     *
159     * <p>It is possible to check if provisioning is allowed or not by querying the method
160     * {@link #isProvisioningAllowed(String)}.
161     *
162     * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
163     * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
164     * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
165     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
166     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
167     *
168     * <p>The intent may also contain the following extras:
169     * <ul>
170     * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
171     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
172     * {@link android.os.Build.VERSION_CODES#N}</li>
173     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
174     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
175     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
176     * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
177     * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
178     * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
179     * </ul>
180     *
181     * <p>When managed provisioning has completed, broadcasts are sent to the application specified
182     * in the provisioning intent. The
183     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
184     * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
185     * the primary profile.
186     *
187     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
188     * completed, along with the above broadcast, activity intent
189     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
190     *
191     * <p>If provisioning fails, the managedProfile is removed so the device returns to its
192     * previous state.
193     *
194     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
195     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
196     * the provisioning flow was successful, although this doesn't guarantee the full flow will
197     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
198     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
199     */
200    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
201    public static final String ACTION_PROVISION_MANAGED_PROFILE
202        = "android.app.action.PROVISION_MANAGED_PROFILE";
203
204    /**
205     * Activity action: Starts the provisioning flow which sets up a managed user.
206     *
207     * <p>This intent will typically be sent by a mobile device management application (MDM).
208     * Provisioning configures the user as managed user and sets the MDM as the profile
209     * owner who has full control over the user. Provisioning can only happen before user setup has
210     * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
211     * allowed.
212     *
213     * <p>The intent contains the following extras:
214     * <ul>
215     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
216     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
217     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
218     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
219     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
220     * </ul>
221     *
222     * <p>If provisioning fails, the device returns to its previous state.
223     *
224     * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
225     * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
226     * the provisioning flow was successful, although this doesn't guarantee the full flow will
227     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
228     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
229     *
230     * @hide
231     */
232    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
233    public static final String ACTION_PROVISION_MANAGED_USER
234        = "android.app.action.PROVISION_MANAGED_USER";
235
236    /**
237     * Activity action: Starts the provisioning flow which sets up a managed device.
238     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
239     *
240     * <p> During device owner provisioning a device admin app is set as the owner of the device.
241     * A device owner has full control over the device. The device owner can not be modified by the
242     * user.
243     *
244     * <p> A typical use case would be a device that is owned by a company, but used by either an
245     * employee or client.
246     *
247     * <p> An intent with this action can be sent only on an unprovisioned device.
248     * It is possible to check if provisioning is allowed or not by querying the method
249     * {@link #isProvisioningAllowed(String)}.
250     *
251     * <p>The intent contains the following extras:
252     * <ul>
253     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
254     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
255     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
256     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
257     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
258     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
259     * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
260     * </ul>
261     *
262     * <p>When device owner provisioning has completed, an intent of the type
263     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
264     * device owner.
265     *
266     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
267     * completed, along with the above broadcast, activity intent
268     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
269     *
270     * <p>If provisioning fails, the device is factory reset.
271     *
272     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
273     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
274     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
275     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
276     */
277    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
278    public static final String ACTION_PROVISION_MANAGED_DEVICE
279        = "android.app.action.PROVISION_MANAGED_DEVICE";
280
281    /**
282     * Activity action: launch when user provisioning completed, i.e.
283     * {@link #getUserProvisioningState()} returns one of the complete state.
284     *
285     * <p> Please note that the API behavior is not necessarily consistent across various releases,
286     * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
287     * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
288     *
289     * <p> The activity must be protected by permission
290     * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
291     * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
292     * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
293     * components are not started by this intent.
294     * @hide
295     */
296    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
297    @SystemApi
298    public static final String ACTION_STATE_USER_SETUP_COMPLETE =
299            "android.app.action.STATE_USER_SETUP_COMPLETE";
300
301    /**
302     * Activity action: Starts the provisioning flow which sets up a managed device.
303     *
304     * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
305     * the device. A device owner has full control over the device. The device owner can not be
306     * modified by the user and the only way of resetting the device is via factory reset.
307     *
308     * <p>A typical use case would be a device that is owned by a company, but used by either an
309     * employee or client.
310     *
311     * <p>The provisioning message should be sent to an unprovisioned device.
312     *
313     * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
314     * by a privileged app with the permission
315     * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
316     *
317     * <p>The provisioning intent contains the following properties:
318     * <ul>
319     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
320     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
321     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
322     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
323     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL}, optional</li>
324     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI}, optional</li>
325     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
326     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
327     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
328     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
329     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
330     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
331     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
332     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
333     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
334     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
335     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
336     * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
337     * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
338     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li></ul>
339     *
340     * @hide
341     */
342    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
343    @SystemApi
344    public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
345            "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
346
347    /**
348     * Activity action: Starts the provisioning flow which sets up a managed device.
349     * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
350     *
351     * <p>NOTE: This is only supported on split system user devices, and puts the device into a
352     * management state that is distinct from that reached by
353     * {@link #ACTION_PROVISION_MANAGED_DEVICE} - specifically the device owner runs on the system
354     * user, and only has control over device-wide policies, not individual users and their data.
355     * The primary benefit is that multiple non-system users are supported when provisioning using
356     * this form of device management.
357     *
358     * <p>During device owner provisioning a device admin app is set as the owner of the device.
359     * A device owner has full control over the device. The device owner can not be modified by the
360     * user.
361     *
362     * <p>A typical use case would be a device that is owned by a company, but used by either an
363     * employee or client.
364     *
365     * <p>An intent with this action can be sent only on an unprovisioned device.
366     * It is possible to check if provisioning is allowed or not by querying the method
367     * {@link #isProvisioningAllowed(String)}.
368     *
369     * <p>The intent contains the following extras:
370     * <ul>
371     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
372     * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
373     * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
374     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
375     * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
376     * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
377     * </ul>
378     *
379     * <p>When device owner provisioning has completed, an intent of the type
380     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
381     * device owner.
382     *
383     * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
384     * completed, along with the above broadcast, activity intent
385     * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
386     *
387     * <p>If provisioning fails, the device is factory reset.
388     *
389     * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
390     * of the provisioning flow was successful, although this doesn't guarantee the full flow will
391     * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
392     * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
393     *
394     * @hide
395     */
396    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
397    public static final String ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE
398        = "android.app.action.PROVISION_MANAGED_SHAREABLE_DEVICE";
399
400    /**
401     * Activity action: Finalizes management provisioning, should be used after user-setup
402     * has been completed and {@link #getUserProvisioningState()} returns one of:
403     * <ul>
404     * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
405     * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
406     * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
407     * </ul>
408     *
409     * @hide
410     */
411    @SystemApi
412    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
413    public static final String ACTION_PROVISION_FINALIZATION
414            = "android.app.action.PROVISION_FINALIZATION";
415
416    /**
417     * Action: Bugreport sharing with device owner has been accepted by the user.
418     *
419     * @hide
420     */
421    public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
422            "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
423
424    /**
425     * Action: Bugreport sharing with device owner has been declined by the user.
426     *
427     * @hide
428     */
429    public static final String ACTION_BUGREPORT_SHARING_DECLINED =
430            "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
431
432    /**
433     * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
434     *
435     * @hide
436     */
437    public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
438            "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
439
440    /**
441     * Extra for shared bugreport's SHA-256 hash.
442     *
443     * @hide
444     */
445    public static final String EXTRA_REMOTE_BUGREPORT_HASH =
446            "android.intent.extra.REMOTE_BUGREPORT_HASH";
447
448    /**
449     * Extra for remote bugreport notification shown type.
450     *
451     * @hide
452     */
453    public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
454            "android.app.extra.bugreport_notification_type";
455
456    /**
457     * Notification type for a started remote bugreport flow.
458     *
459     * @hide
460     */
461    public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
462
463    /**
464     * Notification type for a bugreport that has already been accepted to be shared, but is still
465     * being taken.
466     *
467     * @hide
468     */
469    public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
470
471    /**
472     * Notification type for a bugreport that has been taken and can be shared or declined.
473     *
474     * @hide
475     */
476    public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
477
478    /**
479     * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
480     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
481     *
482     * @hide
483     */
484    public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
485
486    /**
487     * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
488     * allows a mobile device management application or NFC programmer application which starts
489     * managed provisioning to pass data to the management application instance after provisioning.
490     * <p>
491     * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
492     * sends the intent to pass data to itself on the newly created profile.
493     * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
494     * instance of the app on the primary user.
495     * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
496     * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
497     * message should contain a stringified {@link java.util.Properties} instance, whose string
498     * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
499     * management application after provisioning.
500     *
501     * <p>
502     * In both cases the application receives the data in
503     * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
504     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
505     * during the managed provisioning.
506     */
507    public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
508            "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
509
510    /**
511     * A String extra holding the package name of the mobile device management application that
512     * will be set as the profile owner or device owner.
513     *
514     * <p>If an application starts provisioning directly via an intent with action
515     * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
516     * application that started provisioning. The package will be set as profile owner in that case.
517     *
518     * <p>This package is set as device owner when device owner provisioning is started by an NFC
519     * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
520     *
521     * <p> When this extra is set, the application must have exactly one device admin receiver.
522     * This receiver will be set as the profile or device owner and active admin.
523     *
524     * @see DeviceAdminReceiver
525     * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
526     * supported, but only if there is only one device admin receiver in the package that requires
527     * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
528     */
529    @Deprecated
530    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
531        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
532
533    /**
534     * A ComponentName extra indicating the device admin receiver of the mobile device management
535     * application that will be set as the profile owner or device owner and active admin.
536     *
537     * <p>If an application starts provisioning directly via an intent with action
538     * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
539     * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
540     * component has to match the package name of the application that started provisioning.
541     *
542     * <p>This component is set as device owner and active admin when device owner provisioning is
543     * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
544     * message containing an NFC record with MIME type
545     * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
546     * flattened to a string, via {@link ComponentName#flattenToShortString()}.
547     *
548     * @see DeviceAdminReceiver
549     */
550    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
551        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
552
553    /**
554     * An {@link android.accounts.Account} extra holding the account to migrate during managed
555     * profile provisioning. If the account supplied is present in the primary user, it will be
556     * copied, along with its credentials to the managed profile and removed from the primary user.
557     *
558     * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}.
559     */
560
561    public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
562        = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
563
564    /**
565     * Boolean extra to indicate that the migrated account should be kept. This is used in
566     * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
567     * the account will not be removed from the primary user after it is migrated to the newly
568     * created user or profile.
569     *
570     * <p> Defaults to {@code false}
571     *
572     * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
573     * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}
574     */
575    public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
576            = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
577
578    /**
579     * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
580     * device.
581     */
582    @Deprecated
583    public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
584        = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
585
586    /**
587     * A integer extra indicating the predominant color to show during the provisioning.
588     * Refer to {@link android.graphics.Color} for how the color is represented.
589     *
590     * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
591     * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
592     */
593    public static final String EXTRA_PROVISIONING_MAIN_COLOR =
594             "android.app.extra.PROVISIONING_MAIN_COLOR";
595
596    /**
597     * A Boolean extra that can be used by the mobile device management application to skip the
598     * disabling of system apps during provisioning when set to {@code true}.
599     *
600     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
601     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
602     */
603    public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
604            "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
605
606    /**
607     * A String extra holding the time zone {@link android.app.AlarmManager} that the device
608     * will be set to.
609     *
610     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
611     * provisioning via an NFC bump.
612     */
613    public static final String EXTRA_PROVISIONING_TIME_ZONE
614        = "android.app.extra.PROVISIONING_TIME_ZONE";
615
616    /**
617     * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
618     * {@link android.app.AlarmManager}.
619     *
620     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
621     * provisioning via an NFC bump.
622     */
623    public static final String EXTRA_PROVISIONING_LOCAL_TIME
624        = "android.app.extra.PROVISIONING_LOCAL_TIME";
625
626    /**
627     * A String extra holding the {@link java.util.Locale} that the device will be set to.
628     * Format: xx_yy, where xx is the language code, and yy the country code.
629     *
630     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
631     * provisioning via an NFC bump.
632     */
633    public static final String EXTRA_PROVISIONING_LOCALE
634        = "android.app.extra.PROVISIONING_LOCALE";
635
636    /**
637     * A String extra holding the ssid of the wifi network that should be used during nfc device
638     * owner provisioning for downloading the mobile device management application.
639     *
640     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
641     * provisioning via an NFC bump.
642     */
643    public static final String EXTRA_PROVISIONING_WIFI_SSID
644        = "android.app.extra.PROVISIONING_WIFI_SSID";
645
646    /**
647     * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
648     * is hidden or not.
649     *
650     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
651     * provisioning via an NFC bump.
652     */
653    public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
654        = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
655
656    /**
657     * A String extra indicating the security type of the wifi network in
658     * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA} or
659     * {@code WEP}.
660     *
661     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
662     * provisioning via an NFC bump.
663     */
664    public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
665        = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
666
667    /**
668     * A String extra holding the password of the wifi network in
669     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
670     *
671     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
672     * provisioning via an NFC bump.
673     */
674    public static final String EXTRA_PROVISIONING_WIFI_PASSWORD
675        = "android.app.extra.PROVISIONING_WIFI_PASSWORD";
676
677    /**
678     * A String extra holding the proxy host for the wifi network in
679     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
680     *
681     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
682     * provisioning via an NFC bump.
683     */
684    public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
685        = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
686
687    /**
688     * An int extra holding the proxy port for the wifi network in
689     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
690     *
691     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
692     * provisioning via an NFC bump.
693     */
694    public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
695        = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
696
697    /**
698     * A String extra holding the proxy bypass for the wifi network in
699     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
700     *
701     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
702     * provisioning via an NFC bump.
703     */
704    public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
705        = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
706
707    /**
708     * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
709     * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
710     *
711     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
712     * provisioning via an NFC bump.
713     */
714    public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
715        = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
716
717    /**
718     * A String extra holding a url that specifies the download location of the device admin
719     * package. When not provided it is assumed that the device admin package is already installed.
720     *
721     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
722     * provisioning via an NFC bump.
723     */
724    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
725        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
726
727    /**
728     * A String extra holding the localized name of the organization under management.
729     *
730     * The name is displayed only during provisioning.
731     *
732     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
733     *
734     * @hide
735     */
736    @SystemApi
737    public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
738            "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
739
740    /**
741     * A String extra holding a url to the website of the device provider so the user can open it
742     * during provisioning. If the url is not HTTPS, an error will be shown.
743     *
744     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
745     *
746     * @hide
747     */
748    @SystemApi
749    public static final String EXTRA_PROVISIONING_SUPPORT_URL =
750            "android.app.extra.PROVISIONING_SUPPORT_URL";
751
752    /**
753     * A String extra holding the localized name of the device admin package. It should be the same
754     * as the app label of the package.
755     *
756     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
757     *
758     * @hide
759     */
760    @SystemApi
761    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
762            "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
763
764    /**
765     * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
766     * shown during the provisioning.
767     * <h5>The following URI schemes are accepted:</h5>
768     * <ul>
769     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
770     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
771     * </ul>
772     *
773     * <p> It is the responsibility of the caller to provide an image with a reasonable
774     * pixel density for the device.
775     *
776     * <p> If a content: URI is passed, the intent should have the flag
777     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
778     * {@link android.content.ClipData} of the intent too.
779     *
780     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
781     *
782     * @hide
783     */
784    @SystemApi
785    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
786            "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
787
788    /**
789     * An int extra holding a minimum required version code for the device admin package. If the
790     * device admin is already installed on the device, it will only be re-downloaded from
791     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
792     * installed package is less than this version code.
793     *
794     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
795     * provisioning via an NFC bump.
796     */
797    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
798        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
799
800    /**
801     * A String extra holding a http cookie header which should be used in the http request to the
802     * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
803     *
804     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
805     * provisioning via an NFC bump.
806     */
807    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
808        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
809
810    /**
811     * A String extra holding the URL-safe base64 encoded SHA-256 or SHA-1 hash (see notes below) of
812     * the file at download location specified in
813     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
814     *
815     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
816     * present. The provided checksum must match the checksum of the file at the download
817     * location. If the checksum doesn't match an error will be shown to the user and the user will
818     * be asked to factory reset the device.
819     *
820     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
821     * provisioning via an NFC bump.
822     *
823     * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
824     * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
825     * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
826     * addition to SHA-1. Support for SHA-1 is likely to be removed in future OS releases.
827     */
828    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
829        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
830
831    /**
832     * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
833     * android package archive at the download location specified in {@link
834     * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
835     *
836     * <p>The signatures of an android package archive can be obtained using
837     * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
838     * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
839     *
840     * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
841     * present. The provided checksum must match the checksum of any signature of the file at
842     * the download location. If the checksum does not match an error will be shown to the user and
843     * the user will be asked to factory reset the device.
844     *
845     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
846     * provisioning via an NFC bump.
847     */
848    public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
849        = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
850
851    /**
852     * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
853     * has completed successfully.
854     *
855     * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
856     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
857     *
858     * <p>This intent will contain the following extras
859     * <ul>
860     * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
861     * profile.</li>
862     * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
863     * be migrated at provisioning time, if any.</li>
864     * </ul>
865     */
866    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
867    public static final String ACTION_MANAGED_PROFILE_PROVISIONED
868        = "android.app.action.MANAGED_PROFILE_PROVISIONED";
869
870    /**
871     * Activity action: This activity action is sent to indicate that provisioning of a managed
872     * profile or managed device has completed successfully. It'll be sent at the same time as
873     * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
874     * delivered faster as it's an activity intent.
875     *
876     * <p>The intent is only sent to the new device or profile owner.
877     *
878     * @see #ACTION_PROVISION_MANAGED_PROFILE
879     * @see #ACTION_PROVISION_MANAGED_DEVICE
880     */
881    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
882    public static final String ACTION_PROVISIONING_SUCCESSFUL =
883            "android.app.action.PROVISIONING_SUCCESSFUL";
884
885    /**
886     * A boolean extra indicating whether device encryption can be skipped as part of device owner
887     * or managed profile provisioning.
888     *
889     * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
890     * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
891     *
892     * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
893     * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
894     */
895    public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
896             "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
897
898    /**
899     * A {@link Uri} extra pointing to a logo image. This image will be shown during the
900     * provisioning. If this extra is not passed, a default image will be shown.
901     * <h5>The following URI schemes are accepted:</h5>
902     * <ul>
903     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
904     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
905     * </ul>
906     *
907     * <p> It is the responsibility of the caller to provide an image with a reasonable
908     * pixel density for the device.
909     *
910     * <p> If a content: URI is passed, the intent should have the flag
911     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
912     * {@link android.content.ClipData} of the intent too.
913     *
914     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
915     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
916     */
917    public static final String EXTRA_PROVISIONING_LOGO_URI =
918            "android.app.extra.PROVISIONING_LOGO_URI";
919
920    /**
921     * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
922     * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
923     * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
924     * content.
925     *
926     * <p> The extra typically contains one disclaimer from the company of mobile device
927     * management application (MDM), and one disclaimer from the organization.
928     *
929     * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
930     *
931     * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
932     *
933     * <p> Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
934     * {@link #ACTION_PROVISION_MANAGED_DEVICE}
935     */
936    public static final String EXTRA_PROVISIONING_DISCLAIMERS =
937            "android.app.extra.PROVISIONING_DISCLAIMERS";
938
939    /**
940     * A String extra of localized disclaimer header.
941     *
942     * <p> The extra is typically the company name of mobile device management application (MDM)
943     * or the organization name.
944     *
945     * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
946     *
947     * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
948     * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
949     * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
950     *
951     * <pre>
952     *  &lt;meta-data
953     *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
954     *      android:resource="@string/disclaimer_header"
955     * /&gt;</pre>
956     */
957    public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
958            "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
959
960    /**
961     * A {@link Uri} extra pointing to disclaimer content.
962     *
963     * <h5>The following URI schemes are accepted:</h5>
964     * <ul>
965     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
966     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
967     * </ul>
968     *
969     * <p> Styled text is supported in the disclaimer content. The content is parsed by
970     * {@link android.text.Html#fromHtml(String)} and displayed in a
971     * {@link android.widget.TextView}.
972     *
973     * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
974     * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
975     * {@link android.content.ClipData} of the intent too.
976     *
977     * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
978     *
979     * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
980     * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
981     * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
982     *
983     * <pre>
984     *  &lt;meta-data
985     *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
986     *      android:resource="@string/disclaimer_content"
987     * /&gt;</pre>
988     */
989    public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
990            "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
991
992    /**
993     * A boolean extra indicating if user setup should be skipped, for when provisioning is started
994     * during setup-wizard.
995     *
996     * <p>If unspecified, defaults to {@code true} to match the behavior in
997     * {@link android.os.Build.VERSION_CODES#M} and earlier.
998     *
999     * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or
1000     * {@link #ACTION_PROVISION_MANAGED_USER}.
1001     *
1002     * @hide
1003     */
1004    public static final String EXTRA_PROVISIONING_SKIP_USER_SETUP =
1005            "android.app.extra.PROVISIONING_SKIP_USER_SETUP";
1006
1007    /**
1008     * A boolean extra indicating if the user consent steps from the provisioning flow should be
1009     * skipped. If unspecified, defaults to {@code false}.
1010     *
1011     * It can only be used by an existing device owner trying to create a managed profile via
1012     * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1013     */
1014    public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1015            "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1016
1017    /**
1018     * This MIME type is used for starting the device owner provisioning.
1019     *
1020     * <p>During device owner provisioning a device admin app is set as the owner of the device.
1021     * A device owner has full control over the device. The device owner can not be modified by the
1022     * user and the only way of resetting the device is if the device owner app calls a factory
1023     * reset.
1024     *
1025     * <p> A typical use case would be a device that is owned by a company, but used by either an
1026     * employee or client.
1027     *
1028     * <p> The NFC message must be sent to an unprovisioned device.
1029     *
1030     * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1031     * contains the following properties:
1032     * <ul>
1033     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1034     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1035     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1036     * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1037     * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1038     * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1039     * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1040     * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1041     * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1042     * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1043     * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1044     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1045     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1046     * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1047     * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1048     * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from
1049     * {@link android.os.Build.VERSION_CODES#M} </li></ul>
1050     *
1051     * <p>
1052     * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1053     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1054     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1055     * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1056     */
1057    public static final String MIME_TYPE_PROVISIONING_NFC
1058        = "application/com.android.managedprovisioning";
1059
1060    /**
1061     * Activity action: ask the user to add a new device administrator to the system.
1062     * The desired policy is the ComponentName of the policy in the
1063     * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
1064     * bring the user through adding the device administrator to the system (or
1065     * allowing them to reject it).
1066     *
1067     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1068     * field to provide the user with additional explanation (in addition
1069     * to your component's description) about what is being added.
1070     *
1071     * <p>If your administrator is already active, this will ordinarily return immediately (without
1072     * user intervention).  However, if your administrator has been updated and is requesting
1073     * additional uses-policy flags, the user will be presented with the new list.  New policies
1074     * will not be available to the updated administrator until the user has accepted the new list.
1075     */
1076    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1077    public static final String ACTION_ADD_DEVICE_ADMIN
1078            = "android.app.action.ADD_DEVICE_ADMIN";
1079
1080    /**
1081     * @hide
1082     * Activity action: ask the user to add a new device administrator as the profile owner
1083     * for this user. Only system apps can launch this intent.
1084     *
1085     * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
1086     * extra field. This will invoke a UI to bring the user through adding the profile owner admin
1087     * to remotely control restrictions on the user.
1088     *
1089     * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
1090     * result of whether or not the user approved the action. If approved, the result will
1091     * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
1092     * as a profile owner.
1093     *
1094     * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1095     * field to provide the user with additional explanation (in addition
1096     * to your component's description) about what is being added.
1097     *
1098     * <p>If there is already a profile owner active or the caller is not a system app, the
1099     * operation will return a failure result.
1100     */
1101    @SystemApi
1102    public static final String ACTION_SET_PROFILE_OWNER
1103            = "android.app.action.SET_PROFILE_OWNER";
1104
1105    /**
1106     * @hide
1107     * Name of the profile owner admin that controls the user.
1108     */
1109    @SystemApi
1110    public static final String EXTRA_PROFILE_OWNER_NAME
1111            = "android.app.extra.PROFILE_OWNER_NAME";
1112
1113    /**
1114     * Broadcast action: send when any policy admin changes a policy.
1115     * This is generally used to find out when a new policy is in effect.
1116     *
1117     * @hide
1118     */
1119    public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1120            = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
1121
1122    /**
1123     * Broadcast action: sent when the device owner is set, changed or cleared.
1124     *
1125     * This broadcast is sent only to the primary user.
1126     * @see #ACTION_PROVISION_MANAGED_DEVICE
1127     * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1128     */
1129    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1130    public static final String ACTION_DEVICE_OWNER_CHANGED
1131            = "android.app.action.DEVICE_OWNER_CHANGED";
1132
1133    /**
1134     * The ComponentName of the administrator component.
1135     *
1136     * @see #ACTION_ADD_DEVICE_ADMIN
1137     */
1138    public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
1139
1140    /**
1141     * An optional CharSequence providing additional explanation for why the
1142     * admin is being added.
1143     *
1144     * @see #ACTION_ADD_DEVICE_ADMIN
1145     */
1146    public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
1147
1148    /**
1149     * Constant to indicate the feature of disabling the camera. Used as argument to
1150     * {@link #createAdminSupportIntent(String)}.
1151     * @see #setCameraDisabled(ComponentName, boolean)
1152     */
1153    public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
1154
1155    /**
1156     * Constant to indicate the feature of disabling screen captures. Used as argument to
1157     * {@link #createAdminSupportIntent(String)}.
1158     * @see #setScreenCaptureDisabled(ComponentName, boolean)
1159     */
1160    public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
1161
1162    /**
1163     * A String indicating a specific restricted feature. Can be a user restriction from the
1164     * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1165     * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
1166     * @see #createAdminSupportIntent(String)
1167     * @hide
1168     */
1169    @TestApi
1170    public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1171
1172    /**
1173     * Activity action: have the user enter a new password. This activity should
1174     * be launched after using {@link #setPasswordQuality(ComponentName, int)},
1175     * or {@link #setPasswordMinimumLength(ComponentName, int)} to have the user
1176     * enter a new password that meets the current requirements. You can use
1177     * {@link #isActivePasswordSufficient()} to determine whether you need to
1178     * have the user select a new password in order to meet the current
1179     * constraints. Upon being resumed from this activity, you can check the new
1180     * password characteristics to see if they are sufficient.
1181     *
1182     * If the intent is launched from within a managed profile with a profile
1183     * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1184     * this will trigger entering a new password for the parent of the profile.
1185     * For all other cases it will trigger entering a new password for the user
1186     * or profile it is launched from.
1187     *
1188     * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1189     */
1190    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1191    public static final String ACTION_SET_NEW_PASSWORD
1192            = "android.app.action.SET_NEW_PASSWORD";
1193
1194    /**
1195     * Activity action: have the user enter a new password for the parent profile.
1196     * If the intent is launched from within a managed profile, this will trigger
1197     * entering a new password for the parent of the profile. In all other cases
1198     * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
1199     */
1200    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1201    public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1202            = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1203
1204    /**
1205     * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1206     * Network logging was enabled and the user tapped the notification.
1207     * <p class="note">This is a protected intent that can only be sent by the system.</p>
1208     * @hide
1209     */
1210    public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1211            = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1212
1213    /**
1214     * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1215     * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1216     * {@link #EXTRA_DELEGATION_SCOPES} key.
1217     *
1218     * <p class=”note”> Note: This is a protected intent that can only be sent by the system.</p>
1219     */
1220    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1221    public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1222            "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1223
1224    /**
1225     * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1226     * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1227     */
1228    public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1229
1230    /**
1231     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1232     * the parent profile to access intents sent from the managed profile.
1233     * That is, when an app in the managed profile calls
1234     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1235     * matching activity in the parent profile.
1236     */
1237    public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1238
1239    /**
1240     * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1241     * the managed profile to access intents sent from the parent profile.
1242     * That is, when an app in the parent profile calls
1243     * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1244     * matching activity in the managed profile.
1245     */
1246    public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1247
1248    /**
1249     * Broadcast action: notify that a new local system update policy has been set by the device
1250     * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1251     */
1252    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1253    public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1254            = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1255
1256    /**
1257     * Broadcast action to notify ManagedProvisioning that
1258     * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has changed.
1259     * @hide
1260     */
1261    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1262    public static final String ACTION_DATA_SHARING_RESTRICTION_CHANGED =
1263            "android.app.action.DATA_SHARING_RESTRICTION_CHANGED";
1264
1265    /**
1266     * Broadcast action from ManagedProvisioning to notify that the latest change to
1267     * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
1268     * applied (cross profile intent filters updated). Only usesd for CTS tests.
1269     * @hide
1270     */
1271    @TestApi
1272    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1273    public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
1274            "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
1275
1276    /**
1277     * Permission policy to prompt user for new permission requests for runtime permissions.
1278     * Already granted or denied permissions are not affected by this.
1279     */
1280    public static final int PERMISSION_POLICY_PROMPT = 0;
1281
1282    /**
1283     * Permission policy to always grant new permission requests for runtime permissions.
1284     * Already granted or denied permissions are not affected by this.
1285     */
1286    public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1287
1288    /**
1289     * Permission policy to always deny new permission requests for runtime permissions.
1290     * Already granted or denied permissions are not affected by this.
1291     */
1292    public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1293
1294    /**
1295     * Runtime permission state: The user can manage the permission
1296     * through the UI.
1297     */
1298    public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1299
1300    /**
1301     * Runtime permission state: The permission is granted to the app
1302     * and the user cannot manage the permission through the UI.
1303     */
1304    public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1305
1306    /**
1307     * Runtime permission state: The permission is denied to the app
1308     * and the user cannot manage the permission through the UI.
1309     */
1310    public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1311
1312    /**
1313     * Delegation of certificate installation and management. This scope grants access to the
1314     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1315     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1316     */
1317    public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1318
1319    /**
1320     * Delegation of application restrictions management. This scope grants access to the
1321     * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1322     */
1323    public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1324
1325    /**
1326     * Delegation of application uninstall block. This scope grants access to the
1327     * {@link #setUninstallBlocked} API.
1328     */
1329    public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1330
1331    /**
1332     * Delegation of permission policy and permission grant state. This scope grants access to the
1333     * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1334     * and {@link #setPermissionGrantState} APIs.
1335     */
1336    public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1337
1338    /**
1339     * Delegation of package access state. This scope grants access to the
1340     * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1341     * {@link #setPackagesSuspended} APIs.
1342     */
1343    public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1344
1345    /**
1346     * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1347     * API.
1348     */
1349    public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1350
1351    /**
1352     * Delegation for installing existing packages. This scope grants access to the
1353     * {@link #installExistingPackage} API.
1354     */
1355    public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
1356            "delegation-install-existing-package";
1357
1358    /**
1359     * Delegation of management of uninstalled packages. This scope grants access to the
1360     * {@code #setKeepUninstalledPackages} and {@code #getKeepUninstalledPackages} APIs.
1361     */
1362    public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1363            "delegation-keep-uninstalled-packages";
1364
1365    /**
1366     * No management for current user in-effect. This is the default.
1367     * @hide
1368     */
1369    @SystemApi
1370    public static final int STATE_USER_UNMANAGED = 0;
1371
1372    /**
1373     * Management partially setup, user setup needs to be completed.
1374     * @hide
1375     */
1376    @SystemApi
1377    public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1378
1379    /**
1380     * Management partially setup, user setup completed.
1381     * @hide
1382     */
1383    @SystemApi
1384    public static final int STATE_USER_SETUP_COMPLETE = 2;
1385
1386    /**
1387     * Management setup and active on current user.
1388     * @hide
1389     */
1390    @SystemApi
1391    public static final int STATE_USER_SETUP_FINALIZED = 3;
1392
1393    /**
1394     * Management partially setup on a managed profile.
1395     * @hide
1396     */
1397    @SystemApi
1398    public static final int STATE_USER_PROFILE_COMPLETE = 4;
1399
1400    /**
1401     * @hide
1402     */
1403    @IntDef(prefix = { "STATE_USER_" }, value = {
1404            STATE_USER_UNMANAGED,
1405            STATE_USER_SETUP_INCOMPLETE,
1406            STATE_USER_SETUP_COMPLETE,
1407            STATE_USER_SETUP_FINALIZED,
1408            STATE_USER_PROFILE_COMPLETE
1409    })
1410    @Retention(RetentionPolicy.SOURCE)
1411    public @interface UserProvisioningState {}
1412
1413    /**
1414     * Result code for {@link #checkProvisioningPreCondition}.
1415     *
1416     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1417     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1418     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when provisioning is allowed.
1419     *
1420     * @hide
1421     */
1422    public static final int CODE_OK = 0;
1423
1424    /**
1425     * Result code for {@link #checkProvisioningPreCondition}.
1426     *
1427     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1428     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the device already has a device
1429     * owner.
1430     *
1431     * @hide
1432     */
1433    public static final int CODE_HAS_DEVICE_OWNER = 1;
1434
1435    /**
1436     * Result code for {@link #checkProvisioningPreCondition}.
1437     *
1438     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1439     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user has a profile owner and for
1440     * {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
1441     *
1442     * @hide
1443     */
1444    public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
1445
1446    /**
1447     * Result code for {@link #checkProvisioningPreCondition}.
1448     *
1449     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1450     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user isn't running.
1451     *
1452     * @hide
1453     */
1454    public static final int CODE_USER_NOT_RUNNING = 3;
1455
1456    /**
1457     * Result code for {@link #checkProvisioningPreCondition}.
1458     *
1459     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1460     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the device has already been setup and
1461     * for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
1462     *
1463     * @hide
1464     */
1465    public static final int CODE_USER_SETUP_COMPLETED = 4;
1466
1467    /**
1468     * Code used to indicate that the device also has a user other than the system user.
1469     *
1470     * @hide
1471     */
1472    public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
1473
1474    /**
1475     * Code used to indicate that device has an account that prevents provisioning.
1476     *
1477     * @hide
1478     */
1479    public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
1480
1481    /**
1482     * Result code for {@link #checkProvisioningPreCondition}.
1483     *
1484     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1485     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the user is not a system user.
1486     *
1487     * @hide
1488     */
1489    public static final int CODE_NOT_SYSTEM_USER = 7;
1490
1491    /**
1492     * Result code for {@link #checkProvisioningPreCondition}.
1493     *
1494     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1495     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} and {@link #ACTION_PROVISION_MANAGED_USER}
1496     * when the device is a watch and is already paired.
1497     *
1498     * @hide
1499     */
1500    public static final int CODE_HAS_PAIRED = 8;
1501
1502    /**
1503     * Result code for {@link #checkProvisioningPreCondition}.
1504     *
1505     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
1506     * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
1507     *
1508     * @see {@link PackageManager#FEATURE_MANAGED_USERS}
1509     * @hide
1510     */
1511    public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
1512
1513    /**
1514     * Result code for {@link #checkProvisioningPreCondition}.
1515     *
1516     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user.
1517     *
1518     * @hide
1519     */
1520    public static final int CODE_SYSTEM_USER = 10;
1521
1522    /**
1523     * Result code for {@link #checkProvisioningPreCondition}.
1524     *
1525     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
1526     * managed profiles.
1527     *
1528     * @hide
1529     */
1530    public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
1531
1532    /**
1533     * Result code for {@link #checkProvisioningPreCondition}.
1534     *
1535     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} and
1536     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices not running with split system
1537     * user.
1538     *
1539     * @hide
1540     */
1541    public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
1542
1543    /**
1544     * Result code for {@link #checkProvisioningPreCondition}.
1545     *
1546     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1547     * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1548     * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices which do no support device
1549     * admins.
1550     *
1551     * @hide
1552     */
1553    public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
1554
1555    /**
1556     * Result code for {@link #checkProvisioningPreCondition}.
1557     *
1558     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the device the user is a
1559     * system user on a split system user device.
1560     *
1561     * @hide
1562     */
1563    public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
1564
1565    /**
1566     * Result code for {@link #checkProvisioningPreCondition}.
1567     *
1568     * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when adding a managed profile is
1569     * disallowed by {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
1570     *
1571     * @hide
1572     */
1573    public static final int CODE_ADD_MANAGED_PROFILE_DISALLOWED = 15;
1574
1575    /**
1576     * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
1577     * conditions.
1578     *
1579     * @hide
1580     */
1581    @Retention(RetentionPolicy.SOURCE)
1582    @IntDef(prefix = { "CODE_" }, value = {
1583            CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
1584            CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
1585            CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
1586            CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
1587            CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER, CODE_ADD_MANAGED_PROFILE_DISALLOWED
1588    })
1589    public @interface ProvisioningPreCondition {}
1590
1591    /**
1592     * Disable all configurable SystemUI features during LockTask mode. This includes,
1593     * <ul>
1594     *     <li>system info area in the status bar (connectivity icons, clock, etc.)
1595     *     <li>notifications (including alerts, icons, and the notification shade)
1596     *     <li>Home button
1597     *     <li>Recents button and UI
1598     *     <li>global actions menu (i.e. power button menu)
1599     *     <li>keyguard
1600     * </ul>
1601     *
1602     * This is the default configuration for LockTask.
1603     *
1604     * @see #setLockTaskFeatures(ComponentName, int)
1605     */
1606    public static final int LOCK_TASK_FEATURE_NONE = 0;
1607
1608    /**
1609     * Enable the system info area in the status bar during LockTask mode. The system info area
1610     * usually occupies the right side of the status bar (although this can differ across OEMs). It
1611     * includes all system information indicators, such as date and time, connectivity, battery,
1612     * vibration mode, etc.
1613     *
1614     * @see #setLockTaskFeatures(ComponentName, int)
1615     */
1616    public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
1617
1618    /**
1619     * Enable notifications during LockTask mode. This includes notification icons on the status
1620     * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
1621     * Settings panel will still be disabled.
1622     *
1623     * @see #setLockTaskFeatures(ComponentName, int)
1624     */
1625    public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
1626
1627    /**
1628     * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
1629     * to be registered as the default launcher with
1630     * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
1631     * package needs to be whitelisted for LockTask with
1632     * {@link #setLockTaskPackages(ComponentName, String[])}.
1633     *
1634     * @see #setLockTaskFeatures(ComponentName, int)
1635     */
1636    public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
1637
1638    /**
1639     * Enable the Recents button and the Recents screen during LockTask mode.
1640     *
1641     * @see #setLockTaskFeatures(ComponentName, int)
1642     */
1643    public static final int LOCK_TASK_FEATURE_RECENTS = 1 << 3;
1644
1645    /**
1646     * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
1647     * the user long-presses the power button, for example. Note that the user may not be able to
1648     * power off the device if this flag is not set.
1649     *
1650     * @see #setLockTaskFeatures(ComponentName, int)
1651     */
1652    public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
1653
1654    /**
1655     * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
1656     * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
1657     * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
1658     * credential.
1659     *
1660     * @see #setLockTaskFeatures(ComponentName, int)
1661     */
1662    public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
1663
1664    /**
1665     * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
1666     *
1667     * @hide
1668     */
1669    @Retention(RetentionPolicy.SOURCE)
1670    @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
1671            LOCK_TASK_FEATURE_NONE,
1672            LOCK_TASK_FEATURE_SYSTEM_INFO,
1673            LOCK_TASK_FEATURE_NOTIFICATIONS,
1674            LOCK_TASK_FEATURE_HOME,
1675            LOCK_TASK_FEATURE_RECENTS,
1676            LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
1677            LOCK_TASK_FEATURE_KEYGUARD
1678    })
1679    public @interface LockTaskFeature {}
1680
1681    /**
1682     * Service action: Action for a service that device owner and profile owner can optionally
1683     * own.  If a device owner or a profile owner has such a service, the system tries to keep
1684     * a bound connection to it, in order to keep their process always running.
1685     * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
1686     * permission.
1687     */
1688    @SdkConstant(SdkConstantType.SERVICE_ACTION)
1689    public static final String ACTION_DEVICE_ADMIN_SERVICE
1690            = "android.app.action.DEVICE_ADMIN_SERVICE";
1691
1692    /** @hide */
1693    @Retention(RetentionPolicy.SOURCE)
1694    @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
1695        ID_TYPE_BASE_INFO,
1696        ID_TYPE_SERIAL,
1697        ID_TYPE_IMEI,
1698        ID_TYPE_MEID
1699    })
1700    public @interface AttestationIdType {}
1701
1702    /**
1703     * Specifies that the device should attest its manufacturer details. For use with
1704     * {@link #generateKeyPair}.
1705     *
1706     * @see #generateKeyPair
1707     */
1708    public static final int ID_TYPE_BASE_INFO = 1;
1709
1710    /**
1711     * Specifies that the device should attest its serial number. For use with
1712     * {@link #generateKeyPair}.
1713     *
1714     * @see #generateKeyPair
1715     */
1716    public static final int ID_TYPE_SERIAL = 2;
1717
1718    /**
1719     * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
1720     *
1721     * @see #generateKeyPair
1722     */
1723    public static final int ID_TYPE_IMEI = 4;
1724
1725    /**
1726     * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
1727     *
1728     * @see #generateKeyPair
1729     */
1730    public static final int ID_TYPE_MEID = 8;
1731
1732    /**
1733     * Broadcast action: sent when the profile owner is set, changed or cleared.
1734     *
1735     * This broadcast is sent only to the user managed by the new profile owner.
1736     * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1737     */
1738    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1739    public static final String ACTION_PROFILE_OWNER_CHANGED =
1740            "android.app.action.PROFILE_OWNER_CHANGED";
1741
1742    /**
1743     * Return true if the given administrator component is currently active (enabled) in the system.
1744     *
1745     * @param admin The administrator component to check for.
1746     * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
1747     *         otherwise
1748     */
1749    public boolean isAdminActive(@NonNull ComponentName admin) {
1750        throwIfParentInstance("isAdminActive");
1751        return isAdminActiveAsUser(admin, myUserId());
1752    }
1753
1754    /**
1755     * @see #isAdminActive(ComponentName)
1756     * @hide
1757     */
1758    public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
1759        if (mService != null) {
1760            try {
1761                return mService.isAdminActive(admin, userId);
1762            } catch (RemoteException e) {
1763                throw e.rethrowFromSystemServer();
1764            }
1765        }
1766        return false;
1767    }
1768
1769    /**
1770     * Return true if the given administrator component is currently being removed
1771     * for the user.
1772     * @hide
1773     */
1774    public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
1775        if (mService != null) {
1776            try {
1777                return mService.isRemovingAdmin(admin, userId);
1778            } catch (RemoteException e) {
1779                throw e.rethrowFromSystemServer();
1780            }
1781        }
1782        return false;
1783    }
1784
1785    /**
1786     * Return a list of all currently active device administrators' component
1787     * names.  If there are no administrators {@code null} may be
1788     * returned.
1789     */
1790    public @Nullable List<ComponentName> getActiveAdmins() {
1791        throwIfParentInstance("getActiveAdmins");
1792        return getActiveAdminsAsUser(myUserId());
1793    }
1794
1795    /**
1796     * @see #getActiveAdmins()
1797     * @hide
1798     */
1799    public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
1800        if (mService != null) {
1801            try {
1802                return mService.getActiveAdmins(userId);
1803            } catch (RemoteException e) {
1804                throw e.rethrowFromSystemServer();
1805            }
1806        }
1807        return null;
1808    }
1809
1810    /**
1811     * Used by package administration code to determine if a package can be stopped
1812     * or uninstalled.
1813     * @hide
1814     */
1815    @SystemApi
1816    @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1817    public boolean packageHasActiveAdmins(String packageName) {
1818        return packageHasActiveAdmins(packageName, myUserId());
1819    }
1820
1821    /**
1822     * Used by package administration code to determine if a package can be stopped
1823     * or uninstalled.
1824     * @hide
1825     */
1826    public boolean packageHasActiveAdmins(String packageName, int userId) {
1827        if (mService != null) {
1828            try {
1829                return mService.packageHasActiveAdmins(packageName, userId);
1830            } catch (RemoteException e) {
1831                throw e.rethrowFromSystemServer();
1832            }
1833        }
1834        return false;
1835    }
1836
1837    /**
1838     * Remove a current administration component.  This can only be called
1839     * by the application that owns the administration component; if you
1840     * try to remove someone else's component, a security exception will be
1841     * thrown.
1842     *
1843     * <p>Note that the operation is not synchronous and the admin might still be active (as
1844     * indicated by {@link #getActiveAdmins()}) by the time this method returns.
1845     *
1846     * @param admin The administration compononent to remove.
1847     * @throws SecurityException if the caller is not in the owner application of {@code admin}.
1848     */
1849    public void removeActiveAdmin(@NonNull ComponentName admin) {
1850        throwIfParentInstance("removeActiveAdmin");
1851        if (mService != null) {
1852            try {
1853                mService.removeActiveAdmin(admin, myUserId());
1854            } catch (RemoteException e) {
1855                throw e.rethrowFromSystemServer();
1856            }
1857        }
1858    }
1859
1860    /**
1861     * Returns true if an administrator has been granted a particular device policy. This can be
1862     * used to check whether the administrator was activated under an earlier set of policies, but
1863     * requires additional policies after an upgrade.
1864     *
1865     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
1866     *            active administrator, or an exception will be thrown.
1867     * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
1868     * @throws SecurityException if {@code admin} is not an active administrator.
1869     */
1870    public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
1871        throwIfParentInstance("hasGrantedPolicy");
1872        if (mService != null) {
1873            try {
1874                return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
1875            } catch (RemoteException e) {
1876                throw e.rethrowFromSystemServer();
1877            }
1878        }
1879        return false;
1880    }
1881
1882    /**
1883     * Returns true if the Profile Challenge is available to use for the given profile user.
1884     *
1885     * @hide
1886     */
1887    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
1888        if (mService != null) {
1889            try {
1890                return mService.isSeparateProfileChallengeAllowed(userHandle);
1891            } catch (RemoteException e) {
1892                throw e.rethrowFromSystemServer();
1893            }
1894        }
1895        return false;
1896    }
1897
1898    /**
1899     * Constant for {@link #setPasswordQuality}: the policy has no requirements
1900     * for the password.  Note that quality constants are ordered so that higher
1901     * values are more restrictive.
1902     */
1903    public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
1904
1905    /**
1906     * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
1907     * recognition technology.  This implies technologies that can recognize the identity of
1908     * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
1909     * Note that quality constants are ordered so that higher values are more restrictive.
1910     */
1911    public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
1912
1913    /**
1914     * Constant for {@link #setPasswordQuality}: the policy requires some kind
1915     * of password or pattern, but doesn't care what it is. Note that quality constants
1916     * are ordered so that higher values are more restrictive.
1917     */
1918    public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
1919
1920    /**
1921     * Constant for {@link #setPasswordQuality}: the user must have entered a
1922     * password containing at least numeric characters.  Note that quality
1923     * constants are ordered so that higher values are more restrictive.
1924     */
1925    public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
1926
1927    /**
1928     * Constant for {@link #setPasswordQuality}: the user must have entered a
1929     * password containing at least numeric characters with no repeating (4444)
1930     * or ordered (1234, 4321, 2468) sequences.  Note that quality
1931     * constants are ordered so that higher values are more restrictive.
1932     */
1933    public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
1934
1935    /**
1936     * Constant for {@link #setPasswordQuality}: the user must have entered a
1937     * password containing at least alphabetic (or other symbol) characters.
1938     * Note that quality constants are ordered so that higher values are more
1939     * restrictive.
1940     */
1941    public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
1942
1943    /**
1944     * Constant for {@link #setPasswordQuality}: the user must have entered a
1945     * password containing at least <em>both></em> numeric <em>and</em>
1946     * alphabetic (or other symbol) characters.  Note that quality constants are
1947     * ordered so that higher values are more restrictive.
1948     */
1949    public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
1950
1951    /**
1952     * Constant for {@link #setPasswordQuality}: the user must have entered a
1953     * password containing at least a letter, a numerical digit and a special
1954     * symbol, by default. With this password quality, passwords can be
1955     * restricted to contain various sets of characters, like at least an
1956     * uppercase letter, etc. These are specified using various methods,
1957     * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
1958     * that quality constants are ordered so that higher values are more
1959     * restrictive.
1960     */
1961    public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
1962
1963    /**
1964     * Constant for {@link #setPasswordQuality}: the user is not allowed to
1965     * modify password. In case this password quality is set, the password is
1966     * managed by a profile owner. The profile owner can set any password,
1967     * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
1968     * that quality constants are ordered so that higher values are more
1969     * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
1970     * the highest.
1971     * @hide
1972     */
1973    public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
1974
1975    /**
1976     * @hide
1977     *
1978     * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
1979     * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
1980     * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
1981     * used by authenticator to exempt their accounts from this:
1982     *
1983     * <ul>
1984     *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
1985     *     <p>In order to make an apk test-only, add android:testOnly="true" to the
1986     *     &lt;application&gt; tag in the manifest.
1987     *
1988     *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
1989     *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
1990     *     Some authenticators claim to have any features, so to detect it, we also check
1991     *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
1992     *     if any of the accounts have it.
1993     * </ul>
1994     */
1995    @SystemApi
1996    @TestApi
1997    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
1998            "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
1999
2000    /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
2001    @SystemApi
2002    @TestApi
2003    public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
2004            "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
2005
2006    /**
2007     * Called by an application that is administering the device to set the password restrictions it
2008     * is imposing. After setting this, the user will not be able to enter a new password that is
2009     * not at least as restrictive as what has been set. Note that the current password will remain
2010     * until the user has set a new one, so the change does not take place immediately. To prompt
2011     * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2012     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
2013     * <p>
2014     * Quality constants are ordered so that higher values are more restrictive; thus the highest
2015     * requested quality constant (between the policy set here, the user's preference, and any other
2016     * considerations) is the one that is in effect.
2017     * <p>
2018     * The calling device admin must have requested
2019     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2020     * not, a security exception will be thrown.
2021     * <p>
2022     * This method can be called on the {@link DevicePolicyManager} instance returned by
2023     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2024     * profile.
2025     *
2026     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2027     * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
2028     *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
2029     *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2030     *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
2031     * @throws SecurityException if {@code admin} is not an active administrator or if {@code admin}
2032     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2033     */
2034    public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
2035        if (mService != null) {
2036            try {
2037                mService.setPasswordQuality(admin, quality, mParentInstance);
2038            } catch (RemoteException e) {
2039                throw e.rethrowFromSystemServer();
2040            }
2041        }
2042    }
2043
2044    /**
2045     * Retrieve the current minimum password quality for a particular admin or all admins that set
2046     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2047     * a separate challenge are not taken into account.
2048     *
2049     * <p>This method can be called on the {@link DevicePolicyManager} instance
2050     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2051     * restrictions on the parent profile.
2052     *
2053     * @param admin The name of the admin component to check, or {@code null} to aggregate
2054     * all admins.
2055     */
2056    public int getPasswordQuality(@Nullable ComponentName admin) {
2057        return getPasswordQuality(admin, myUserId());
2058    }
2059
2060    /** @hide per-user version */
2061    public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
2062        if (mService != null) {
2063            try {
2064                return mService.getPasswordQuality(admin, userHandle, mParentInstance);
2065            } catch (RemoteException e) {
2066                throw e.rethrowFromSystemServer();
2067            }
2068        }
2069        return PASSWORD_QUALITY_UNSPECIFIED;
2070    }
2071
2072    /**
2073     * Called by an application that is administering the device to set the minimum allowed password
2074     * length. After setting this, the user will not be able to enter a new password that is not at
2075     * least as restrictive as what has been set. Note that the current password will remain until
2076     * the user has set a new one, so the change does not take place immediately. To prompt the user
2077     * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2078     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2079     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2080     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2081     * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
2082     * {@link #setPasswordQuality}.
2083     * <p>
2084     * The calling device admin must have requested
2085     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2086     * not, a security exception will be thrown.
2087     * <p>
2088     * This method can be called on the {@link DevicePolicyManager} instance returned by
2089     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2090     * profile.
2091     *
2092     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2093     * @param length The new desired minimum password length. A value of 0 means there is no
2094     *            restriction.
2095     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2096     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2097     */
2098    public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
2099        if (mService != null) {
2100            try {
2101                mService.setPasswordMinimumLength(admin, length, mParentInstance);
2102            } catch (RemoteException e) {
2103                throw e.rethrowFromSystemServer();
2104            }
2105        }
2106    }
2107
2108    /**
2109     * Retrieve the current minimum password length for a particular admin or all admins that set
2110     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2111     * a separate challenge are not taken into account.
2112     *
2113     * <p>This method can be called on the {@link DevicePolicyManager} instance
2114     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2115     * restrictions on the parent profile.
2116     *
2117     * user and its profiles or a particular one.
2118     * @param admin The name of the admin component to check, or {@code null} to aggregate
2119     * all admins.
2120     */
2121    public int getPasswordMinimumLength(@Nullable ComponentName admin) {
2122        return getPasswordMinimumLength(admin, myUserId());
2123    }
2124
2125    /** @hide per-user version */
2126    public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
2127        if (mService != null) {
2128            try {
2129                return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
2130            } catch (RemoteException e) {
2131                throw e.rethrowFromSystemServer();
2132            }
2133        }
2134        return 0;
2135    }
2136
2137    /**
2138     * Called by an application that is administering the device to set the minimum number of upper
2139     * case letters required in the password. After setting this, the user will not be able to enter
2140     * a new password that is not at least as restrictive as what has been set. Note that the
2141     * current password will remain until the user has set a new one, so the change does not take
2142     * place immediately. To prompt the user for a new password, use
2143     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2144     * setting this value. This constraint is only imposed if the administrator has also requested
2145     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2146     * <p>
2147     * The calling device admin must have requested
2148     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2149     * not, a security exception will be thrown.
2150     * <p>
2151     * This method can be called on the {@link DevicePolicyManager} instance returned by
2152     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2153     * profile.
2154     *
2155     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2156     * @param length The new desired minimum number of upper case letters required in the password.
2157     *            A value of 0 means there is no restriction.
2158     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2159     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2160     */
2161    public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
2162        if (mService != null) {
2163            try {
2164                mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
2165            } catch (RemoteException e) {
2166                throw e.rethrowFromSystemServer();
2167            }
2168        }
2169    }
2170
2171    /**
2172     * Retrieve the current number of upper case letters required in the password
2173     * for a particular admin or all admins that set restrictions on this user and
2174     * its participating profiles. Restrictions on profiles that have a separate challenge
2175     * are not taken into account.
2176     * This is the same value as set by
2177     * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
2178     * and only applies when the password quality is
2179     * {@link #PASSWORD_QUALITY_COMPLEX}.
2180     *
2181     * <p>This method can be called on the {@link DevicePolicyManager} instance
2182     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2183     * restrictions on the parent profile.
2184     *
2185     * @param admin The name of the admin component to check, or {@code null} to
2186     *            aggregate all admins.
2187     * @return The minimum number of upper case letters required in the
2188     *         password.
2189     */
2190    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
2191        return getPasswordMinimumUpperCase(admin, myUserId());
2192    }
2193
2194    /** @hide per-user version */
2195    public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
2196        if (mService != null) {
2197            try {
2198                return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
2199            } catch (RemoteException e) {
2200                throw e.rethrowFromSystemServer();
2201            }
2202        }
2203        return 0;
2204    }
2205
2206    /**
2207     * Called by an application that is administering the device to set the minimum number of lower
2208     * case letters required in the password. After setting this, the user will not be able to enter
2209     * a new password that is not at least as restrictive as what has been set. Note that the
2210     * current password will remain until the user has set a new one, so the change does not take
2211     * place immediately. To prompt the user for a new password, use
2212     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2213     * setting this value. This constraint is only imposed if the administrator has also requested
2214     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2215     * <p>
2216     * The calling device admin must have requested
2217     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2218     * not, a security exception will be thrown.
2219     * <p>
2220     * This method can be called on the {@link DevicePolicyManager} instance returned by
2221     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2222     * profile.
2223     *
2224     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2225     * @param length The new desired minimum number of lower case letters required in the password.
2226     *            A value of 0 means there is no restriction.
2227     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2228     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2229     */
2230    public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
2231        if (mService != null) {
2232            try {
2233                mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
2234            } catch (RemoteException e) {
2235                throw e.rethrowFromSystemServer();
2236            }
2237        }
2238    }
2239
2240    /**
2241     * Retrieve the current number of lower case letters required in the password
2242     * for a particular admin or all admins that set restrictions on this user
2243     * and its participating profiles. Restrictions on profiles that have
2244     * a separate challenge are not taken into account.
2245     * This is the same value as set by
2246     * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
2247     * and only applies when the password quality is
2248     * {@link #PASSWORD_QUALITY_COMPLEX}.
2249     *
2250     * <p>This method can be called on the {@link DevicePolicyManager} instance
2251     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2252     * restrictions on the parent profile.
2253     *
2254     * @param admin The name of the admin component to check, or {@code null} to
2255     *            aggregate all admins.
2256     * @return The minimum number of lower case letters required in the
2257     *         password.
2258     */
2259    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
2260        return getPasswordMinimumLowerCase(admin, myUserId());
2261    }
2262
2263    /** @hide per-user version */
2264    public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
2265        if (mService != null) {
2266            try {
2267                return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
2268            } catch (RemoteException e) {
2269                throw e.rethrowFromSystemServer();
2270            }
2271        }
2272        return 0;
2273    }
2274
2275    /**
2276     * Called by an application that is administering the device to set the minimum number of
2277     * letters required in the password. After setting this, the user will not be able to enter a
2278     * new password that is not at least as restrictive as what has been set. Note that the current
2279     * password will remain until the user has set a new one, so the change does not take place
2280     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2281     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2282     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2283     * {@link #setPasswordQuality}. The default value is 1.
2284     * <p>
2285     * The calling device admin must have requested
2286     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2287     * not, a security exception will be thrown.
2288     * <p>
2289     * This method can be called on the {@link DevicePolicyManager} instance returned by
2290     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2291     * profile.
2292     *
2293     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2294     * @param length The new desired minimum number of letters required in the password. A value of
2295     *            0 means there is no restriction.
2296     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2297     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2298     */
2299    public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
2300        if (mService != null) {
2301            try {
2302                mService.setPasswordMinimumLetters(admin, length, mParentInstance);
2303            } catch (RemoteException e) {
2304                throw e.rethrowFromSystemServer();
2305            }
2306        }
2307    }
2308
2309    /**
2310     * Retrieve the current number of letters required in the password
2311     * for a particular admin or all admins that set restrictions on this user
2312     * and its participating profiles. Restrictions on profiles that have
2313     * a separate challenge are not taken into account.
2314     * This is the same value as set by
2315     * {@link #setPasswordMinimumLetters(ComponentName, int)}
2316     * and only applies when the password quality is
2317     * {@link #PASSWORD_QUALITY_COMPLEX}.
2318     *
2319     * <p>This method can be called on the {@link DevicePolicyManager} instance
2320     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2321     * restrictions on the parent profile.
2322     *
2323     * @param admin The name of the admin component to check, or {@code null} to
2324     *            aggregate all admins.
2325     * @return The minimum number of letters required in the password.
2326     */
2327    public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
2328        return getPasswordMinimumLetters(admin, myUserId());
2329    }
2330
2331    /** @hide per-user version */
2332    public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
2333        if (mService != null) {
2334            try {
2335                return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
2336            } catch (RemoteException e) {
2337                throw e.rethrowFromSystemServer();
2338            }
2339        }
2340        return 0;
2341    }
2342
2343    /**
2344     * Called by an application that is administering the device to set the minimum number of
2345     * numerical digits required in the password. After setting this, the user will not be able to
2346     * enter a new password that is not at least as restrictive as what has been set. Note that the
2347     * current password will remain until the user has set a new one, so the change does not take
2348     * place immediately. To prompt the user for a new password, use
2349     * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2350     * setting this value. This constraint is only imposed if the administrator has also requested
2351     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 1.
2352     * <p>
2353     * The calling device admin must have requested
2354     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2355     * not, a security exception will be thrown.
2356     * <p>
2357     * This method can be called on the {@link DevicePolicyManager} instance returned by
2358     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2359     * profile.
2360     *
2361     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2362     * @param length The new desired minimum number of numerical digits required in the password. A
2363     *            value of 0 means there is no restriction.
2364     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2365     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2366     */
2367    public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
2368        if (mService != null) {
2369            try {
2370                mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
2371            } catch (RemoteException e) {
2372                throw e.rethrowFromSystemServer();
2373            }
2374        }
2375    }
2376
2377    /**
2378     * Retrieve the current number of numerical digits required in the password
2379     * for a particular admin or all admins that set restrictions on this user
2380     * and its participating profiles. Restrictions on profiles that have
2381     * a separate challenge are not taken into account.
2382     * This is the same value as set by
2383     * {@link #setPasswordMinimumNumeric(ComponentName, int)}
2384     * and only applies when the password quality is
2385     * {@link #PASSWORD_QUALITY_COMPLEX}.
2386     *
2387     * <p>This method can be called on the {@link DevicePolicyManager} instance
2388     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2389     * restrictions on the parent profile.
2390     *
2391     * @param admin The name of the admin component to check, or {@code null} to
2392     *            aggregate all admins.
2393     * @return The minimum number of numerical digits required in the password.
2394     */
2395    public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
2396        return getPasswordMinimumNumeric(admin, myUserId());
2397    }
2398
2399    /** @hide per-user version */
2400    public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
2401        if (mService != null) {
2402            try {
2403                return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
2404            } catch (RemoteException e) {
2405                throw e.rethrowFromSystemServer();
2406            }
2407        }
2408        return 0;
2409    }
2410
2411    /**
2412     * Called by an application that is administering the device to set the minimum number of
2413     * symbols required in the password. After setting this, the user will not be able to enter a
2414     * new password that is not at least as restrictive as what has been set. Note that the current
2415     * password will remain until the user has set a new one, so the change does not take place
2416     * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2417     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2418     * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2419     * {@link #setPasswordQuality}. The default value is 1.
2420     * <p>
2421     * The calling device admin must have requested
2422     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2423     * not, a security exception will be thrown.
2424     * <p>
2425     * This method can be called on the {@link DevicePolicyManager} instance returned by
2426     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2427     * profile.
2428     *
2429     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2430     * @param length The new desired minimum number of symbols required in the password. A value of
2431     *            0 means there is no restriction.
2432     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2433     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2434     */
2435    public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
2436        if (mService != null) {
2437            try {
2438                mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
2439            } catch (RemoteException e) {
2440                throw e.rethrowFromSystemServer();
2441            }
2442        }
2443    }
2444
2445    /**
2446     * Retrieve the current number of symbols required in the password
2447     * for a particular admin or all admins that set restrictions on this user
2448     * and its participating profiles. Restrictions on profiles that have
2449     * a separate challenge are not taken into account. This is the same value as
2450     * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
2451     * and only applies when the password quality is
2452     * {@link #PASSWORD_QUALITY_COMPLEX}.
2453     *
2454     * <p>This method can be called on the {@link DevicePolicyManager} instance
2455     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2456     * restrictions on the parent profile.
2457     *
2458     * @param admin The name of the admin component to check, or {@code null} to
2459     *            aggregate all admins.
2460     * @return The minimum number of symbols required in the password.
2461     */
2462    public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
2463        return getPasswordMinimumSymbols(admin, myUserId());
2464    }
2465
2466    /** @hide per-user version */
2467    public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
2468        if (mService != null) {
2469            try {
2470                return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
2471            } catch (RemoteException e) {
2472                throw e.rethrowFromSystemServer();
2473            }
2474        }
2475        return 0;
2476    }
2477
2478    /**
2479     * Called by an application that is administering the device to set the minimum number of
2480     * non-letter characters (numerical digits or symbols) required in the password. After setting
2481     * this, the user will not be able to enter a new password that is not at least as restrictive
2482     * as what has been set. Note that the current password will remain until the user has set a new
2483     * one, so the change does not take place immediately. To prompt the user for a new password,
2484     * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2485     * setting this value. This constraint is only imposed if the administrator has also requested
2486     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2487     * <p>
2488     * The calling device admin must have requested
2489     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2490     * not, a security exception will be thrown.
2491     * <p>
2492     * This method can be called on the {@link DevicePolicyManager} instance returned by
2493     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2494     * profile.
2495     *
2496     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2497     * @param length The new desired minimum number of letters required in the password. A value of
2498     *            0 means there is no restriction.
2499     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2500     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2501     */
2502    public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
2503        if (mService != null) {
2504            try {
2505                mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
2506            } catch (RemoteException e) {
2507                throw e.rethrowFromSystemServer();
2508            }
2509        }
2510    }
2511
2512    /**
2513     * Retrieve the current number of non-letter characters required in the password
2514     * for a particular admin or all admins that set restrictions on this user
2515     * and its participating profiles. Restrictions on profiles that have
2516     * a separate challenge are not taken into account.
2517     * This is the same value as set by
2518     * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
2519     * and only applies when the password quality is
2520     * {@link #PASSWORD_QUALITY_COMPLEX}.
2521     *
2522     * <p>This method can be called on the {@link DevicePolicyManager} instance
2523     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2524     * restrictions on the parent profile.
2525     *
2526     * @param admin The name of the admin component to check, or {@code null} to
2527     *            aggregate all admins.
2528     * @return The minimum number of letters required in the password.
2529     */
2530    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
2531        return getPasswordMinimumNonLetter(admin, myUserId());
2532    }
2533
2534    /** @hide per-user version */
2535    public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
2536        if (mService != null) {
2537            try {
2538                return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
2539            } catch (RemoteException e) {
2540                throw e.rethrowFromSystemServer();
2541            }
2542        }
2543        return 0;
2544    }
2545
2546    /**
2547     * Called by an application that is administering the device to set the length of the password
2548     * history. After setting this, the user will not be able to enter a new password that is the
2549     * same as any password in the history. Note that the current password will remain until the
2550     * user has set a new one, so the change does not take place immediately. To prompt the user for
2551     * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2552     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2553     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2554     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX} {@link #PASSWORD_QUALITY_ALPHABETIC}, or
2555     * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
2556     * <p>
2557     * The calling device admin must have requested
2558     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2559     * not, a security exception will be thrown.
2560     * <p>
2561     * This method can be called on the {@link DevicePolicyManager} instance returned by
2562     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2563     * profile.
2564     *
2565     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2566     * @param length The new desired length of password history. A value of 0 means there is no
2567     *            restriction.
2568     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2569     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2570     */
2571    public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
2572        if (mService != null) {
2573            try {
2574                mService.setPasswordHistoryLength(admin, length, mParentInstance);
2575            } catch (RemoteException e) {
2576                throw e.rethrowFromSystemServer();
2577            }
2578        }
2579    }
2580
2581    /**
2582     * Called by a device admin to set the password expiration timeout. Calling this method will
2583     * restart the countdown for password expiration for the given admin, as will changing the
2584     * device password (for all admins).
2585     * <p>
2586     * The provided timeout is the time delta in ms and will be added to the current time. For
2587     * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
2588     * 432000000 ms for timeout.
2589     * <p>
2590     * To disable password expiration, a value of 0 may be used for timeout.
2591     * <p>
2592     * The calling device admin must have requested
2593     * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
2594     * not, a security exception will be thrown.
2595     * <p>
2596     * Note that setting the password will automatically reset the expiration time for all active
2597     * admins. Active admins do not need to explicitly call this method in that case.
2598     * <p>
2599     * This method can be called on the {@link DevicePolicyManager} instance returned by
2600     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2601     * profile.
2602     *
2603     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2604     * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
2605     *            there is no restriction (unlimited).
2606     * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2607     *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
2608     */
2609    public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
2610        if (mService != null) {
2611            try {
2612                mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
2613            } catch (RemoteException e) {
2614                throw e.rethrowFromSystemServer();
2615            }
2616        }
2617    }
2618
2619    /**
2620     * Get the password expiration timeout for the given admin. The expiration timeout is the
2621     * recurring expiration timeout provided in the call to
2622     * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
2623     * aggregate of all participating policy administrators if {@code admin} is null. Admins that
2624     * have set restrictions on profiles that have a separate challenge are not taken into account.
2625     *
2626     * <p>This method can be called on the {@link DevicePolicyManager} instance
2627     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2628     * restrictions on the parent profile.
2629     *
2630     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2631     * @return The timeout for the given admin or the minimum of all timeouts
2632     */
2633    public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
2634        if (mService != null) {
2635            try {
2636                return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
2637            } catch (RemoteException e) {
2638                throw e.rethrowFromSystemServer();
2639            }
2640        }
2641        return 0;
2642    }
2643
2644    /**
2645     * Get the current password expiration time for a particular admin or all admins that set
2646     * restrictions on this user and its participating profiles. Restrictions on profiles that have
2647     * a separate challenge are not taken into account. If admin is {@code null}, then a composite
2648     * of all expiration times is returned - which will be the minimum of all of them.
2649     *
2650     * <p>This method can be called on the {@link DevicePolicyManager} instance
2651     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2652     * the password expiration for the parent profile.
2653     *
2654     * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
2655     * @return The password expiration time, in milliseconds since epoch.
2656     */
2657    public long getPasswordExpiration(@Nullable ComponentName admin) {
2658        if (mService != null) {
2659            try {
2660                return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
2661            } catch (RemoteException e) {
2662                throw e.rethrowFromSystemServer();
2663            }
2664        }
2665        return 0;
2666    }
2667
2668    /**
2669     * Retrieve the current password history length for a particular admin or all admins that
2670     * set restrictions on this user and its participating profiles. Restrictions on profiles that
2671     * have a separate challenge are not taken into account.
2672     *
2673     * <p>This method can be called on the {@link DevicePolicyManager} instance
2674     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2675     * restrictions on the parent profile.
2676     *
2677     * @param admin The name of the admin component to check, or {@code null} to aggregate
2678     * all admins.
2679     * @return The length of the password history
2680     */
2681    public int getPasswordHistoryLength(@Nullable ComponentName admin) {
2682        return getPasswordHistoryLength(admin, myUserId());
2683    }
2684
2685    /** @hide per-user version */
2686    public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
2687        if (mService != null) {
2688            try {
2689                return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
2690            } catch (RemoteException e) {
2691                throw e.rethrowFromSystemServer();
2692            }
2693        }
2694        return 0;
2695    }
2696
2697    /**
2698     * Return the maximum password length that the device supports for a
2699     * particular password quality.
2700     * @param quality The quality being interrogated.
2701     * @return Returns the maximum length that the user can enter.
2702     */
2703    public int getPasswordMaximumLength(int quality) {
2704        // Kind-of arbitrary.
2705        return 16;
2706    }
2707
2708    /**
2709     * The maximum number of characters allowed in the password blacklist.
2710     */
2711    private static final int PASSWORD_BLACKLIST_CHARACTER_LIMIT = 128 * 1000;
2712
2713    /**
2714     * Throws an exception if the password blacklist is too large.
2715     *
2716     * @hide
2717     */
2718    public static void enforcePasswordBlacklistSize(List<String> blacklist) {
2719        if (blacklist == null) {
2720            return;
2721        }
2722        long characterCount = 0;
2723        for (final String item : blacklist) {
2724            characterCount += item.length();
2725        }
2726        if (characterCount > PASSWORD_BLACKLIST_CHARACTER_LIMIT) {
2727            throw new IllegalArgumentException("128 thousand blacklist character limit exceeded by "
2728                      + (characterCount - PASSWORD_BLACKLIST_CHARACTER_LIMIT) + " characters");
2729        }
2730    }
2731
2732    /**
2733     * Called by an application that is administering the device to blacklist passwords.
2734     * <p>
2735     * Any blacklisted password or PIN is prevented from being enrolled by the user or the admin.
2736     * Note that the match against the blacklist is case insensitive. The blacklist applies for all
2737     * password qualities requested by {@link #setPasswordQuality} however it is not taken into
2738     * consideration by {@link #isActivePasswordSufficient}.
2739     * <p>
2740     * The blacklist can be cleared by passing {@code null} or an empty list. The blacklist is
2741     * given a name that is used to track which blacklist is currently set by calling {@link
2742     * #getPasswordBlacklistName}. If the blacklist is being cleared, the name is ignored and {@link
2743     * #getPasswordBlacklistName} will return {@code null}. The name can only be {@code null} when
2744     * the blacklist is being cleared.
2745     * <p>
2746     * The blacklist is limited to a total of 128 thousand characters rather than limiting to a
2747     * number of entries.
2748     * <p>
2749     * This method can be called on the {@link DevicePolicyManager} instance returned by
2750     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2751     * profile.
2752     *
2753     * @param admin the {@link DeviceAdminReceiver} this request is associated with
2754     * @param name name to associate with the blacklist
2755     * @param blacklist list of passwords to blacklist or {@code null} to clear the blacklist
2756     * @return whether the new blacklist was successfully installed
2757     * @throws SecurityException if {@code admin} is not a device or profile owner
2758     * @throws IllegalArgumentException if the blacklist surpasses the character limit
2759     * @throws NullPointerException if {@code name} is {@code null} when setting a non-empty list
2760     *
2761     * @see #getPasswordBlacklistName
2762     * @see #isActivePasswordSufficient
2763     * @see #resetPasswordWithToken
2764     */
2765    public boolean setPasswordBlacklist(@NonNull ComponentName admin, @Nullable String name,
2766            @Nullable List<String> blacklist) {
2767        enforcePasswordBlacklistSize(blacklist);
2768
2769        try {
2770            return mService.setPasswordBlacklist(admin, name, blacklist, mParentInstance);
2771        } catch (RemoteException re) {
2772            throw re.rethrowFromSystemServer();
2773        }
2774    }
2775
2776    /**
2777     * Get the name of the password blacklist set by the given admin.
2778     *
2779     * @param admin the {@link DeviceAdminReceiver} this request is associated with
2780     * @return the name of the blacklist or {@code null} if no blacklist is set
2781     *
2782     * @see #setPasswordBlacklist
2783     */
2784    public @Nullable String getPasswordBlacklistName(@NonNull ComponentName admin) {
2785        try {
2786            return mService.getPasswordBlacklistName(admin, myUserId(), mParentInstance);
2787        } catch (RemoteException re) {
2788            throw re.rethrowFromSystemServer();
2789        }
2790    }
2791
2792    /**
2793     * Test if a given password is blacklisted.
2794     *
2795     * @param userId the user to valiate for
2796     * @param password the password to check against the blacklist
2797     * @return whether the password is blacklisted
2798     *
2799     * @see #setPasswordBlacklist
2800     *
2801     * @hide
2802     */
2803    @RequiresPermission(android.Manifest.permission.TEST_BLACKLISTED_PASSWORD)
2804    public boolean isPasswordBlacklisted(@UserIdInt int userId, @NonNull String password) {
2805        try {
2806            return mService.isPasswordBlacklisted(userId, password);
2807        } catch (RemoteException re) {
2808            throw re.rethrowFromSystemServer();
2809        }
2810    }
2811
2812    /**
2813     * Determine whether the current password the user has set is sufficient to meet the policy
2814     * requirements (e.g. quality, minimum length) that have been requested by the admins of this
2815     * user and its participating profiles. Restrictions on profiles that have a separate challenge
2816     * are not taken into account. The user must be unlocked in order to perform the check. The
2817     * password blacklist is not considered when checking sufficiency.
2818     * <p>
2819     * The calling device admin must have requested
2820     * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2821     * not, a security exception will be thrown.
2822     * <p>
2823     * This method can be called on the {@link DevicePolicyManager} instance returned by
2824     * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
2825     * the parent profile is sufficient.
2826     *
2827     * @return Returns true if the password meets the current requirements, else false.
2828     * @throws SecurityException if the calling application does not own an active administrator
2829     *             that uses {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2830     * @throws IllegalStateException if the user is not unlocked.
2831     */
2832    public boolean isActivePasswordSufficient() {
2833        if (mService != null) {
2834            try {
2835                return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
2836            } catch (RemoteException e) {
2837                throw e.rethrowFromSystemServer();
2838            }
2839        }
2840        return false;
2841    }
2842
2843    /**
2844     * When called by a profile owner of a managed profile returns true if the profile uses unified
2845     * challenge with its parent user.
2846     *
2847     * <strong>Note: This method is not concerned with password quality and will return false if
2848     * the profile has empty password as a separate challenge.
2849     *
2850     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2851     * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
2852     * @see UserManager#DISALLOW_UNIFIED_PASSWORD
2853     */
2854    public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
2855        throwIfParentInstance("isUsingUnifiedPassword");
2856        if (mService != null) {
2857            try {
2858                return mService.isUsingUnifiedPassword(admin);
2859            } catch (RemoteException e) {
2860                throw e.rethrowFromSystemServer();
2861            }
2862        }
2863        return true;
2864    }
2865
2866    /**
2867     * Determine whether the current profile password the user has set is sufficient
2868     * to meet the policy requirements (e.g. quality, minimum length) that have been
2869     * requested by the admins of the parent user and its profiles.
2870     *
2871     * @param userHandle the userId of the profile to check the password for.
2872     * @return Returns true if the password would meet the current requirements, else false.
2873     * @throws SecurityException if {@code userHandle} is not a managed profile.
2874     * @hide
2875     */
2876    public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
2877        if (mService != null) {
2878            try {
2879                return mService.isProfileActivePasswordSufficientForParent(userHandle);
2880            } catch (RemoteException e) {
2881                throw e.rethrowFromSystemServer();
2882            }
2883        }
2884        return false;
2885    }
2886
2887    /**
2888     * Retrieve the number of times the user has failed at entering a password since that last
2889     * successful password entry.
2890     * <p>
2891     * This method can be called on the {@link DevicePolicyManager} instance returned by
2892     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
2893     * password attemts for the parent user.
2894     * <p>
2895     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2896     * to be able to call this method; if it has not, a security exception will be thrown.
2897     *
2898     * @return The number of times user has entered an incorrect password since the last correct
2899     *         password entry.
2900     * @throws SecurityException if the calling application does not own an active administrator
2901     *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
2902     */
2903    public int getCurrentFailedPasswordAttempts() {
2904        return getCurrentFailedPasswordAttempts(myUserId());
2905    }
2906
2907    /**
2908     * Retrieve the number of times the given user has failed at entering a
2909     * password since that last successful password entry.
2910     *
2911     * <p>The calling device admin must have requested
2912     * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
2913     * not and it is not the system uid, a security exception will be thrown.
2914     *
2915     * @hide
2916     */
2917    public int getCurrentFailedPasswordAttempts(int userHandle) {
2918        if (mService != null) {
2919            try {
2920                return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
2921            } catch (RemoteException e) {
2922                throw e.rethrowFromSystemServer();
2923            }
2924        }
2925        return -1;
2926    }
2927
2928    /**
2929     * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
2930     *
2931     * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
2932     * @hide
2933     */
2934    public boolean getDoNotAskCredentialsOnBoot() {
2935        if (mService != null) {
2936            try {
2937                return mService.getDoNotAskCredentialsOnBoot();
2938            } catch (RemoteException e) {
2939                throw e.rethrowFromSystemServer();
2940            }
2941        }
2942        return false;
2943    }
2944
2945    /**
2946     * Setting this to a value greater than zero enables a built-in policy that will perform a
2947     * device or profile wipe after too many incorrect device-unlock passwords have been entered.
2948     * This built-in policy combines watching for failed passwords and wiping the device, and
2949     * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2950     * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
2951     * <p>
2952     * To implement any other policy (e.g. wiping data for a particular application only, erasing or
2953     * revoking credentials, or reporting the failure to a server), you should implement
2954     * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
2955     * use this API, because if the maximum count is reached, the device or profile will be wiped
2956     * immediately, and your callback will not be invoked.
2957     * <p>
2958     * This method can be called on the {@link DevicePolicyManager} instance returned by
2959     * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
2960     * profile.
2961     *
2962     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2963     * @param num The number of failed password attempts at which point the device or profile will
2964     *            be wiped.
2965     * @throws SecurityException if {@code admin} is not an active administrator or does not use
2966     *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
2967     *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
2968     */
2969    public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
2970        if (mService != null) {
2971            try {
2972                mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
2973            } catch (RemoteException e) {
2974                throw e.rethrowFromSystemServer();
2975            }
2976        }
2977    }
2978
2979    /**
2980     * Retrieve the current maximum number of login attempts that are allowed before the device
2981     * or profile is wiped, for a particular admin or all admins that set restrictions on this user
2982     * and its participating profiles. Restrictions on profiles that have a separate challenge are
2983     * not taken into account.
2984     *
2985     * <p>This method can be called on the {@link DevicePolicyManager} instance
2986     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2987     * the value for the parent profile.
2988     *
2989     * @param admin The name of the admin component to check, or {@code null} to aggregate
2990     * all admins.
2991     */
2992    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
2993        return getMaximumFailedPasswordsForWipe(admin, myUserId());
2994    }
2995
2996    /** @hide per-user version */
2997    public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
2998        if (mService != null) {
2999            try {
3000                return mService.getMaximumFailedPasswordsForWipe(
3001                        admin, userHandle, mParentInstance);
3002            } catch (RemoteException e) {
3003                throw e.rethrowFromSystemServer();
3004            }
3005        }
3006        return 0;
3007    }
3008
3009    /**
3010     * Returns the profile with the smallest maximum failed passwords for wipe,
3011     * for the given user. So for primary user, it might return the primary or
3012     * a managed profile. For a secondary user, it would be the same as the
3013     * user passed in.
3014     * @hide Used only by Keyguard
3015     */
3016    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
3017        if (mService != null) {
3018            try {
3019                return mService.getProfileWithMinimumFailedPasswordsForWipe(
3020                        userHandle, mParentInstance);
3021            } catch (RemoteException e) {
3022                throw e.rethrowFromSystemServer();
3023            }
3024        }
3025        return UserHandle.USER_NULL;
3026    }
3027
3028    /**
3029     * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
3030     * to change the password again until the user has entered it.
3031     */
3032    public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
3033
3034    /**
3035     * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
3036     * credentials on device boot.
3037     * If the flag is set, the device can be booted without asking for user password.
3038     * The absence of this flag does not change the current boot requirements. This flag
3039     * can be set by the device owner only. If the app is not the device owner, the flag
3040     * is ignored. Once the flag is set, it cannot be reverted back without resetting the
3041     * device to factory defaults.
3042     */
3043    public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
3044
3045    /**
3046     * Force a new password for device unlock (the password needed to access the entire device) or
3047     * the work profile challenge on the current user. This takes effect immediately.
3048     * <p>
3049     * <em>For device owner and profile owners targeting SDK level
3050     * {@link android.os.Build.VERSION_CODES#O} or above, this API is no longer available and will
3051     * throw {@link SecurityException}. Please use the new API {@link #resetPasswordWithToken}
3052     * instead. </em>
3053     * <p>
3054     * <em>Note: This API has been limited as of {@link android.os.Build.VERSION_CODES#N} for
3055     * device admins that are not device owner and not profile owner.
3056     * The password can now only be changed if there is currently no password set.  Device owner
3057     * and profile owner can still do this when user is unlocked and does not have a managed
3058     * profile.</em>
3059     * <p>
3060     * The given password must be sufficient for the current password quality and length constraints
3061     * as returned by {@link #getPasswordQuality(ComponentName)} and
3062     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3063     * it will be rejected and false returned. Note that the password may be a stronger quality
3064     * (containing alphanumeric characters when the requested quality is only numeric), in which
3065     * case the currently active quality will be increased to match.
3066     * <p>
3067     * Calling with a null or empty password will clear any existing PIN, pattern or password if the
3068     * current password constraints allow it. <em>Note: This will not work in
3069     * {@link android.os.Build.VERSION_CODES#N} and later for managed profiles, or for device admins
3070     * that are not device owner or profile owner.  Once set, the password cannot be changed to null
3071     * or empty except by these admins.</em>
3072     * <p>
3073     * The calling device admin must have requested
3074     * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
3075     * not, a security exception will be thrown.
3076     *
3077     * @param password The new password for the user. Null or empty clears the password.
3078     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3079     *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3080     * @return Returns true if the password was applied, or false if it is not acceptable for the
3081     *         current constraints or if the user has not been decrypted yet.
3082     * @throws SecurityException if the calling application does not own an active administrator
3083     *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
3084     * @throws IllegalStateException if the calling user is locked or has a managed profile.
3085     */
3086    public boolean resetPassword(String password, int flags) {
3087        throwIfParentInstance("resetPassword");
3088        if (mService != null) {
3089            try {
3090                return mService.resetPassword(password, flags);
3091            } catch (RemoteException e) {
3092                throw e.rethrowFromSystemServer();
3093            }
3094        }
3095        return false;
3096    }
3097
3098    /**
3099     * Called by a profile or device owner to provision a token which can later be used to reset the
3100     * device lockscreen password (if called by device owner), or managed profile challenge (if
3101     * called by profile owner), via {@link #resetPasswordWithToken}.
3102     * <p>
3103     * If the user currently has a lockscreen password, the provisioned token will not be
3104     * immediately usable; it only becomes active after the user performs a confirm credential
3105     * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
3106     * If the user has no lockscreen password, the token is activated immediately. In all cases,
3107     * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
3108     * For security reasons, un-activated tokens are only stored in memory and will be lost once
3109     * the device reboots. In this case a new token needs to be provisioned again.
3110     * <p>
3111     * Once provisioned and activated, the token will remain effective even if the user changes
3112     * or clears the lockscreen password.
3113     * <p>
3114     * <em>This token is highly sensitive and should be treated at the same level as user
3115     * credentials. In particular, NEVER store this token on device in plaintext. Do not store
3116     * the plaintext token in device-encrypted storage if it will be needed to reset password on
3117     * file-based encryption devices before user unlocks. Consider carefully how any password token
3118     * will be stored on your server and who will need access to them. Tokens may be the subject of
3119     * legal access requests.
3120     * </em>
3121     *
3122     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3123     * @param token a secure token a least 32-byte long, which must be generated by a
3124     *        cryptographically strong random number generator.
3125     * @return true if the operation is successful, false otherwise.
3126     * @throws SecurityException if admin is not a device or profile owner.
3127     * @throws IllegalArgumentException if the supplied token is invalid.
3128     */
3129    public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
3130        throwIfParentInstance("setResetPasswordToken");
3131        if (mService != null) {
3132            try {
3133                return mService.setResetPasswordToken(admin, token);
3134            } catch (RemoteException e) {
3135                throw e.rethrowFromSystemServer();
3136            }
3137        }
3138        return false;
3139    }
3140
3141    /**
3142     * Called by a profile or device owner to revoke the current password reset token.
3143     *
3144     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3145     * @return true if the operation is successful, false otherwise.
3146     * @throws SecurityException if admin is not a device or profile owner.
3147     */
3148    public boolean clearResetPasswordToken(ComponentName admin) {
3149        throwIfParentInstance("clearResetPasswordToken");
3150        if (mService != null) {
3151            try {
3152                return mService.clearResetPasswordToken(admin);
3153            } catch (RemoteException e) {
3154                throw e.rethrowFromSystemServer();
3155            }
3156        }
3157        return false;
3158    }
3159
3160    /**
3161     * Called by a profile or device owner to check if the current reset password token is active.
3162     *
3163     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3164     * @return true if the token is active, false otherwise.
3165     * @throws SecurityException if admin is not a device or profile owner.
3166     * @throws IllegalStateException if no token has been set.
3167     */
3168    public boolean isResetPasswordTokenActive(ComponentName admin) {
3169        throwIfParentInstance("isResetPasswordTokenActive");
3170        if (mService != null) {
3171            try {
3172                return mService.isResetPasswordTokenActive(admin);
3173            } catch (RemoteException e) {
3174                throw e.rethrowFromSystemServer();
3175            }
3176        }
3177        return false;
3178    }
3179
3180    /**
3181     * Called by device or profile owner to force set a new device unlock password or a managed
3182     * profile challenge on current user. This takes effect immediately.
3183     * <p>
3184     * Unlike {@link #resetPassword}, this API can change the password even before the user or
3185     * device is unlocked or decrypted. The supplied token must have been previously provisioned via
3186     * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
3187     * <p>
3188     * The given password must be sufficient for the current password quality and length constraints
3189     * as returned by {@link #getPasswordQuality(ComponentName)} and
3190     * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3191     * it will be rejected and false returned. Note that the password may be a stronger quality, for
3192     * example, a password containing alphanumeric characters when the requested quality is only
3193     * numeric.
3194     * <p>
3195     * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
3196     * password if the current password constraints allow it.
3197     *
3198     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3199     * @param password The new password for the user. {@code null} or empty clears the password.
3200     * @param token the password reset token previously provisioned by
3201     *        {@link #setResetPasswordToken}.
3202     * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3203     *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3204     * @return Returns true if the password was applied, or false if it is not acceptable for the
3205     *         current constraints.
3206     * @throws SecurityException if admin is not a device or profile owner.
3207     * @throws IllegalStateException if the provided token is not valid.
3208     */
3209    public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
3210            byte[] token, int flags) {
3211        throwIfParentInstance("resetPassword");
3212        if (mService != null) {
3213            try {
3214                return mService.resetPasswordWithToken(admin, password, token, flags);
3215            } catch (RemoteException e) {
3216                throw e.rethrowFromSystemServer();
3217            }
3218        }
3219        return false;
3220    }
3221
3222    /**
3223     * Called by an application that is administering the device to set the maximum time for user
3224     * activity until the device will lock. This limits the length that the user can set. It takes
3225     * effect immediately.
3226     * <p>
3227     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3228     * to be able to call this method; if it has not, a security exception will be thrown.
3229     * <p>
3230     * This method can be called on the {@link DevicePolicyManager} instance returned by
3231     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3232     * profile.
3233     *
3234     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3235     * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
3236     *            is no restriction.
3237     * @throws SecurityException if {@code admin} is not an active administrator or it does not use
3238     *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3239     */
3240    public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
3241        if (mService != null) {
3242            try {
3243                mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
3244            } catch (RemoteException e) {
3245                throw e.rethrowFromSystemServer();
3246            }
3247        }
3248    }
3249
3250    /**
3251     * Retrieve the current maximum time to unlock for a particular admin or all admins that set
3252     * restrictions on this user and its participating profiles. Restrictions on profiles that have
3253     * a separate challenge are not taken into account.
3254     *
3255     * <p>This method can be called on the {@link DevicePolicyManager} instance
3256     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3257     * restrictions on the parent profile.
3258     *
3259     * @param admin The name of the admin component to check, or {@code null} to aggregate
3260     * all admins.
3261     * @return time in milliseconds for the given admin or the minimum value (strictest) of
3262     * all admins if admin is null. Returns 0 if there are no restrictions.
3263     */
3264    public long getMaximumTimeToLock(@Nullable ComponentName admin) {
3265        return getMaximumTimeToLock(admin, myUserId());
3266    }
3267
3268    /** @hide per-user version */
3269    public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
3270        if (mService != null) {
3271            try {
3272                return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
3273            } catch (RemoteException e) {
3274                throw e.rethrowFromSystemServer();
3275            }
3276        }
3277        return 0;
3278    }
3279
3280    /**
3281     * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
3282     * strong auth (e.g. fingerprint, trust agents) times out, i.e. the user has to use a strong
3283     * authentication method like password, pin or pattern.
3284     *
3285     * <p>This timeout is used internally to reset the timer to require strong auth again after
3286     * specified timeout each time it has been successfully used.
3287     *
3288     * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
3289     *
3290     * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3291     *
3292     * <p>The calling device admin must be a device or profile owner. If it is not,
3293     * a {@link SecurityException} will be thrown.
3294     *
3295     * <p>The calling device admin can verify the value it has set by calling
3296     * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
3297     *
3298     * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
3299     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3300     * profile.
3301     *
3302     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3303     * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
3304     *         with strong authentication method. A value of 0 means the admin is not participating
3305     *         in controlling the timeout.
3306     *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
3307     *         72 hours, respectively. Though discouraged, the admin may choose to require strong
3308     *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
3309     *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3310     *
3311     * @throws SecurityException if {@code admin} is not a device or profile owner.
3312     */
3313    public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
3314            long timeoutMs) {
3315        if (mService != null) {
3316            try {
3317                mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
3318            } catch (RemoteException e) {
3319                throw e.rethrowFromSystemServer();
3320            }
3321        }
3322    }
3323
3324    /**
3325     * Determine for how long the user will be able to use secondary, non strong auth for
3326     * authentication, since last strong method authentication (password, pin or pattern) was used.
3327     * After the returned timeout the user is required to use strong authentication method.
3328     *
3329     * <p>This method can be called on the {@link DevicePolicyManager} instance
3330     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3331     * restrictions on the parent profile.
3332     *
3333     * @param admin The name of the admin component to check, or {@code null} to aggregate
3334     *         accross all participating admins.
3335     * @return The timeout in milliseconds or 0 if not configured for the provided admin.
3336     */
3337    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
3338        return getRequiredStrongAuthTimeout(admin, myUserId());
3339    }
3340
3341    /** @hide per-user version */
3342    public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
3343        if (mService != null) {
3344            try {
3345                return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
3346            } catch (RemoteException e) {
3347                throw e.rethrowFromSystemServer();
3348            }
3349        }
3350        return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
3351    }
3352
3353    /**
3354     * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
3355     * keyring. The user's credential will need to be entered again in order to derive the
3356     * credential encryption key that will be stored back in the keyring for future use.
3357     * <p>
3358     * This flag can only be used by a profile owner when locking a managed profile when
3359     * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3360     * <p>
3361     * In order to secure user data, the user will be stopped and restarted so apps should wait
3362     * until they are next run to perform further actions.
3363     */
3364    public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
3365
3366    /** @hide */
3367    @Retention(RetentionPolicy.SOURCE)
3368    @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
3369            FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
3370    })
3371    public @interface LockNowFlag {}
3372
3373    /**
3374     * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3375     * this call.
3376     * <p>
3377     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3378     * to be able to call this method; if it has not, a security exception will be thrown.
3379     * <p>
3380     * This method can be called on the {@link DevicePolicyManager} instance returned by
3381     * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3382     * <p>
3383     * Equivalent to calling {@link #lockNow(int)} with no flags.
3384     *
3385     * @throws SecurityException if the calling application does not own an active administrator
3386     *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3387     */
3388    public void lockNow() {
3389        lockNow(0);
3390    }
3391
3392    /**
3393     * Make the device lock immediately, as if the lock screen timeout has expired at the point of
3394     * this call.
3395     * <p>
3396     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3397     * to be able to call this method; if it has not, a security exception will be thrown.
3398     * <p>
3399     * This method can be called on the {@link DevicePolicyManager} instance returned by
3400     * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
3401     *
3402     * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
3403     * @throws SecurityException if the calling application does not own an active administrator
3404     *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
3405     *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
3406     *             that is not a profile
3407     *             owner of a managed profile.
3408     * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
3409     *             passed when locking the parent profile.
3410     * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
3411     *             flag is passed when {@link #getStorageEncryptionStatus} does not return
3412     *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3413     */
3414    public void lockNow(@LockNowFlag int flags) {
3415        if (mService != null) {
3416            try {
3417                mService.lockNow(flags, mParentInstance);
3418            } catch (RemoteException e) {
3419                throw e.rethrowFromSystemServer();
3420            }
3421        }
3422    }
3423
3424    /**
3425     * Flag for {@link #wipeData(int)}: also erase the device's external
3426     * storage (such as SD cards).
3427     */
3428    public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
3429
3430    /**
3431     * Flag for {@link #wipeData(int)}: also erase the factory reset protection
3432     * data.
3433     *
3434     * <p>This flag may only be set by device owner admins; if it is set by
3435     * other admins a {@link SecurityException} will be thrown.
3436     */
3437    public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
3438
3439    /**
3440     * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
3441     *
3442     * TODO(b/35851809): make this public.
3443     * @hide
3444     */
3445    public static final int WIPE_EUICC = 0x0004;
3446
3447
3448    /**
3449     * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
3450     * other users will remain unaffected. Calling from the primary user will cause the device to
3451     * reboot, erasing all device data - including all the secondary users and their data - while
3452     * booting up.
3453     * <p>
3454     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
3455     * be able to call this method; if it has not, a security exception will be thrown.
3456     *
3457     * @param flags Bit mask of additional options: currently supported flags are
3458     *            {@link #WIPE_EXTERNAL_STORAGE} and {@link #WIPE_RESET_PROTECTION_DATA}.
3459     * @throws SecurityException if the calling application does not own an active administrator
3460     *             that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
3461     */
3462    public void wipeData(int flags) {
3463        throwIfParentInstance("wipeData");
3464        final String wipeReasonForUser = mContext.getString(
3465                R.string.work_profile_deleted_description_dpm_wipe);
3466        wipeDataInternal(flags, wipeReasonForUser);
3467    }
3468
3469    /**
3470     * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
3471     * other users will remain unaffected, the provided reason for wiping data can be shown to
3472     * user. Calling from the primary user will cause the device to reboot, erasing all device data
3473     * - including all the secondary users and their data - while booting up. In this case, we don't
3474     * show the reason to the user since the device would be factory reset.
3475     * <p>
3476     * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
3477     * be able to call this method; if it has not, a security exception will be thrown.
3478     *
3479     * @param flags Bit mask of additional options: currently supported flags are
3480     *            {@link #WIPE_EXTERNAL_STORAGE} and {@link #WIPE_RESET_PROTECTION_DATA}.
3481     * @param reason a string that contains the reason for wiping data, which can be
3482     *                          presented to the user.
3483     * @throws SecurityException if the calling application does not own an active administrator
3484     *             that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
3485     * @throws IllegalArgumentException if the input reason string is null or empty.
3486     */
3487    public void wipeDataWithReason(int flags, @NonNull CharSequence reason) {
3488        throwIfParentInstance("wipeDataWithReason");
3489        Preconditions.checkNotNull(reason, "CharSequence is null");
3490        wipeDataInternal(flags, reason.toString());
3491    }
3492
3493    /**
3494     * Internal function for both {@link #wipeData(int)} and
3495     * {@link #wipeDataWithReason(int, CharSequence)} to call.
3496     *
3497     * @see #wipeData(int)
3498     * @see #wipeDataWithReason(int, CharSequence)
3499     * @hide
3500     */
3501    private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
3502        if (mService != null) {
3503            try {
3504                mService.wipeDataWithReason(flags, wipeReasonForUser);
3505            } catch (RemoteException e) {
3506                throw e.rethrowFromSystemServer();
3507            }
3508        }
3509    }
3510
3511    /**
3512     * Called by an application that is administering the device to set the
3513     * global proxy and exclusion list.
3514     * <p>
3515     * The calling device admin must have requested
3516     * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
3517     * this method; if it has not, a security exception will be thrown.
3518     * Only the first device admin can set the proxy. If a second admin attempts
3519     * to set the proxy, the {@link ComponentName} of the admin originally setting the
3520     * proxy will be returned. If successful in setting the proxy, {@code null} will
3521     * be returned.
3522     * The method can be called repeatedly by the device admin alrady setting the
3523     * proxy to update the proxy and exclusion list.
3524     *
3525     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3526     * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
3527     *            Pass Proxy.NO_PROXY to reset the proxy.
3528     * @param exclusionList a list of domains to be excluded from the global proxy.
3529     * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
3530     *            of the device admin that sets the proxy.
3531     * @hide
3532     */
3533    public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
3534            List<String> exclusionList ) {
3535        throwIfParentInstance("setGlobalProxy");
3536        if (proxySpec == null) {
3537            throw new NullPointerException();
3538        }
3539        if (mService != null) {
3540            try {
3541                String hostSpec;
3542                String exclSpec;
3543                if (proxySpec.equals(Proxy.NO_PROXY)) {
3544                    hostSpec = null;
3545                    exclSpec = null;
3546                } else {
3547                    if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
3548                        throw new IllegalArgumentException();
3549                    }
3550                    InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
3551                    String hostName = sa.getHostName();
3552                    int port = sa.getPort();
3553                    StringBuilder hostBuilder = new StringBuilder();
3554                    hostSpec = hostBuilder.append(hostName)
3555                        .append(":").append(Integer.toString(port)).toString();
3556                    if (exclusionList == null) {
3557                        exclSpec = "";
3558                    } else {
3559                        StringBuilder listBuilder = new StringBuilder();
3560                        boolean firstDomain = true;
3561                        for (String exclDomain : exclusionList) {
3562                            if (!firstDomain) {
3563                                listBuilder = listBuilder.append(",");
3564                            } else {
3565                                firstDomain = false;
3566                            }
3567                            listBuilder = listBuilder.append(exclDomain.trim());
3568                        }
3569                        exclSpec = listBuilder.toString();
3570                    }
3571                    if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
3572                            != android.net.Proxy.PROXY_VALID)
3573                        throw new IllegalArgumentException();
3574                }
3575                return mService.setGlobalProxy(admin, hostSpec, exclSpec);
3576            } catch (RemoteException e) {
3577                throw e.rethrowFromSystemServer();
3578            }
3579        }
3580        return null;
3581    }
3582
3583    /**
3584     * Set a network-independent global HTTP proxy. This is not normally what you want for typical
3585     * HTTP proxies - they are generally network dependent. However if you're doing something
3586     * unusual like general internal filtering this may be useful. On a private network where the
3587     * proxy is not accessible, you may break HTTP using this.
3588     * <p>
3589     * This method requires the caller to be the device owner.
3590     * <p>
3591     * This proxy is only a recommendation and it is possible that some apps will ignore it.
3592     *
3593     * @see ProxyInfo
3594     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3595     * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
3596     *            {@code null} value will clear the global HTTP proxy.
3597     * @throws SecurityException if {@code admin} is not the device owner.
3598     */
3599    public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
3600            proxyInfo) {
3601        throwIfParentInstance("setRecommendedGlobalProxy");
3602        if (mService != null) {
3603            try {
3604                mService.setRecommendedGlobalProxy(admin, proxyInfo);
3605            } catch (RemoteException e) {
3606                throw e.rethrowFromSystemServer();
3607            }
3608        }
3609    }
3610
3611    /**
3612     * Returns the component name setting the global proxy.
3613     * @return ComponentName object of the device admin that set the global proxy, or {@code null}
3614     *         if no admin has set the proxy.
3615     * @hide
3616     */
3617    public @Nullable ComponentName getGlobalProxyAdmin() {
3618        if (mService != null) {
3619            try {
3620                return mService.getGlobalProxyAdmin(myUserId());
3621            } catch (RemoteException e) {
3622                throw e.rethrowFromSystemServer();
3623            }
3624        }
3625        return null;
3626    }
3627
3628    /**
3629     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3630     * indicating that encryption is not supported.
3631     */
3632    public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
3633
3634    /**
3635     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3636     * indicating that encryption is supported, but is not currently active.
3637     */
3638    public static final int ENCRYPTION_STATUS_INACTIVE = 1;
3639
3640    /**
3641     * Result code for {@link #getStorageEncryptionStatus}:
3642     * indicating that encryption is not currently active, but is currently
3643     * being activated.  This is only reported by devices that support
3644     * encryption of data and only when the storage is currently
3645     * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
3646     * to become encrypted will never return this value.
3647     */
3648    public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
3649
3650    /**
3651     * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
3652     * indicating that encryption is active.
3653     * <p>
3654     * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3655     */
3656    public static final int ENCRYPTION_STATUS_ACTIVE = 3;
3657
3658    /**
3659     * Result code for {@link #getStorageEncryptionStatus}:
3660     * indicating that encryption is active, but an encryption key has not
3661     * been set by the user.
3662     */
3663    public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
3664
3665    /**
3666     * Result code for {@link #getStorageEncryptionStatus}:
3667     * indicating that encryption is active and the encryption key is tied to the user or profile.
3668     * <p>
3669     * This value is only returned to apps targeting API level 24 and above. For apps targeting
3670     * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
3671     * encryption key is specific to the user or profile.
3672     */
3673    public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
3674
3675    /**
3676     * Activity action: begin the process of encrypting data on the device.  This activity should
3677     * be launched after using {@link #setStorageEncryption} to request encryption be activated.
3678     * After resuming from this activity, use {@link #getStorageEncryption}
3679     * to check encryption status.  However, on some devices this activity may never return, as
3680     * it may trigger a reboot and in some cases a complete data wipe of the device.
3681     */
3682    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3683    public static final String ACTION_START_ENCRYPTION
3684            = "android.app.action.START_ENCRYPTION";
3685
3686    /**
3687     * Broadcast action: notify managed provisioning that new managed user is created.
3688     *
3689     * @hide
3690     */
3691    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3692    public static final String ACTION_MANAGED_USER_CREATED =
3693            "android.app.action.MANAGED_USER_CREATED";
3694
3695    /**
3696     * Widgets are enabled in keyguard
3697     */
3698    public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
3699
3700    /**
3701     * Disable all keyguard widgets. Has no effect.
3702     */
3703    public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
3704
3705    /**
3706     * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
3707     */
3708    public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
3709
3710    /**
3711     * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3712     */
3713    public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
3714
3715    /**
3716     * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
3717     */
3718    public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
3719
3720    /**
3721     * Ignore trust agent state on secure keyguard screens
3722     * (e.g. PIN/Pattern/Password).
3723     */
3724    public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
3725
3726    /**
3727     * Disable fingerprint sensor on keyguard secure screens (e.g. PIN/Pattern/Password).
3728     */
3729    public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
3730
3731    /**
3732     * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
3733     */
3734    public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
3735
3736    /**
3737     * Disable all current and future keyguard customizations.
3738     */
3739    public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
3740
3741    /**
3742     * Keyguard features that when set on a managed profile that doesn't have its own challenge will
3743     * affect the profile's parent user. These can also be set on the managed profile's parent
3744     * {@link DevicePolicyManager} instance.
3745     *
3746     * @hide
3747     */
3748    public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
3749            DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
3750            | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
3751
3752    /**
3753     * Called by an application that is administering the device to request that the storage system
3754     * be encrypted.
3755     * <p>
3756     * When multiple device administrators attempt to control device encryption, the most secure,
3757     * supported setting will always be used. If any device administrator requests device
3758     * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
3759     * device encryption while another device administrator has enabled it, the call to disable will
3760     * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
3761     * <p>
3762     * This policy controls encryption of the secure (application data) storage area. Data written
3763     * to other storage areas may or may not be encrypted, and this policy does not require or
3764     * control the encryption of any other storage areas. There is one exception: If
3765     * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
3766     * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
3767     * written to disk within the encrypted storage area.
3768     * <p>
3769     * Important Note: On some devices, it is possible to encrypt storage without requiring the user
3770     * to create a device PIN or Password. In this case, the storage is encrypted, but the
3771     * encryption key may not be fully secured. For maximum security, the administrator should also
3772     * require (and check for) a pattern, PIN, or password.
3773     *
3774     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3775     * @param encrypt true to request encryption, false to release any previous request
3776     * @return the new request status (for all active admins) - will be one of
3777     *         {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE}, or
3778     *         {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value of the requests; Use
3779     *         {@link #getStorageEncryptionStatus()} to query the actual device state.
3780     * @throws SecurityException if {@code admin} is not an active administrator or does not use
3781     *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
3782     */
3783    public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
3784        throwIfParentInstance("setStorageEncryption");
3785        if (mService != null) {
3786            try {
3787                return mService.setStorageEncryption(admin, encrypt);
3788            } catch (RemoteException e) {
3789                throw e.rethrowFromSystemServer();
3790            }
3791        }
3792        return ENCRYPTION_STATUS_UNSUPPORTED;
3793    }
3794
3795    /**
3796     * Called by an application that is administering the device to
3797     * determine the requested setting for secure storage.
3798     *
3799     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
3800     * this will return the requested encryption setting as an aggregate of all active
3801     * administrators.
3802     * @return true if the admin(s) are requesting encryption, false if not.
3803     */
3804    public boolean getStorageEncryption(@Nullable ComponentName admin) {
3805        throwIfParentInstance("getStorageEncryption");
3806        if (mService != null) {
3807            try {
3808                return mService.getStorageEncryption(admin, myUserId());
3809            } catch (RemoteException e) {
3810                throw e.rethrowFromSystemServer();
3811            }
3812        }
3813        return false;
3814    }
3815
3816    /**
3817     * Called by an application that is administering the device to
3818     * determine the current encryption status of the device.
3819     * <p>
3820     * Depending on the returned status code, the caller may proceed in different
3821     * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
3822     * storage system does not support encryption.  If the
3823     * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
3824     * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
3825     * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
3826     * storage system has enabled encryption but no password is set so further action
3827     * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
3828     * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
3829     * no further action is required.
3830     *
3831     * @return current status of encryption. The value will be one of
3832     * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
3833     * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
3834     * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
3835     */
3836    public int getStorageEncryptionStatus() {
3837        throwIfParentInstance("getStorageEncryptionStatus");
3838        return getStorageEncryptionStatus(myUserId());
3839    }
3840
3841    /** @hide per-user version */
3842    public int getStorageEncryptionStatus(int userHandle) {
3843        if (mService != null) {
3844            try {
3845                return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
3846            } catch (RemoteException e) {
3847                throw e.rethrowFromSystemServer();
3848            }
3849        }
3850        return ENCRYPTION_STATUS_UNSUPPORTED;
3851    }
3852
3853    /**
3854     * Mark a CA certificate as approved by the device user. This means that they have been notified
3855     * of the installation, were made aware of the risks, viewed the certificate and still wanted to
3856     * keep the certificate on the device.
3857     *
3858     * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
3859     * this certificate.
3860     *
3861     * @hide
3862     */
3863    public boolean approveCaCert(String alias, int userHandle, boolean approval) {
3864        if (mService != null) {
3865            try {
3866                return mService.approveCaCert(alias, userHandle, approval);
3867            } catch (RemoteException e) {
3868                throw e.rethrowFromSystemServer();
3869            }
3870        }
3871        return false;
3872    }
3873
3874    /**
3875     * Check whether a CA certificate has been approved by the device user.
3876     *
3877     * @hide
3878     */
3879    public boolean isCaCertApproved(String alias, int userHandle) {
3880        if (mService != null) {
3881            try {
3882                return mService.isCaCertApproved(alias, userHandle);
3883            } catch (RemoteException e) {
3884                throw e.rethrowFromSystemServer();
3885            }
3886        }
3887        return false;
3888    }
3889
3890    /**
3891     * Installs the given certificate as a user CA.
3892     *
3893     * The caller must be a profile or device owner on that user, or a delegate package given the
3894     * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3895     * security exception will be thrown.
3896     *
3897     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3898     *              {@code null} if calling from a delegated certificate installer.
3899     * @param certBuffer encoded form of the certificate to install.
3900     *
3901     * @return false if the certBuffer cannot be parsed or installation is
3902     *         interrupted, true otherwise.
3903     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3904     *         owner.
3905     * @see #setDelegatedScopes
3906     * @see #DELEGATION_CERT_INSTALL
3907     */
3908    public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3909        throwIfParentInstance("installCaCert");
3910        if (mService != null) {
3911            try {
3912                return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
3913            } catch (RemoteException e) {
3914                throw e.rethrowFromSystemServer();
3915            }
3916        }
3917        return false;
3918    }
3919
3920    /**
3921     * Uninstalls the given certificate from trusted user CAs, if present.
3922     *
3923     * The caller must be a profile or device owner on that user, or a delegate package given the
3924     * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
3925     * security exception will be thrown.
3926     *
3927     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3928     *              {@code null} if calling from a delegated certificate installer.
3929     * @param certBuffer encoded form of the certificate to remove.
3930     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3931     *         owner.
3932     * @see #setDelegatedScopes
3933     * @see #DELEGATION_CERT_INSTALL
3934     */
3935    public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
3936        throwIfParentInstance("uninstallCaCert");
3937        if (mService != null) {
3938            try {
3939                final String alias = getCaCertAlias(certBuffer);
3940                mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
3941            } catch (CertificateException e) {
3942                Log.w(TAG, "Unable to parse certificate", e);
3943            } catch (RemoteException e) {
3944                throw e.rethrowFromSystemServer();
3945            }
3946        }
3947    }
3948
3949    /**
3950     * Returns all CA certificates that are currently trusted, excluding system CA certificates.
3951     * If a user has installed any certificates by other means than device policy these will be
3952     * included too.
3953     *
3954     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3955     *              {@code null} if calling from a delegated certificate installer.
3956     * @return a List of byte[] arrays, each encoding one user CA certificate.
3957     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3958     *         owner.
3959     */
3960    public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
3961        final List<byte[]> certs = new ArrayList<byte[]>();
3962        throwIfParentInstance("getInstalledCaCerts");
3963        if (mService != null) {
3964            try {
3965                mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
3966                final TrustedCertificateStore certStore = new TrustedCertificateStore();
3967                for (String alias : certStore.userAliases()) {
3968                    try {
3969                        certs.add(certStore.getCertificate(alias).getEncoded());
3970                    } catch (CertificateException ce) {
3971                        Log.w(TAG, "Could not encode certificate: " + alias, ce);
3972                    }
3973                }
3974            } catch (RemoteException re) {
3975                throw re.rethrowFromSystemServer();
3976            }
3977        }
3978        return certs;
3979    }
3980
3981    /**
3982     * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
3983     * means other than device policy will also be removed, except for system CA certificates.
3984     *
3985     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
3986     *              {@code null} if calling from a delegated certificate installer.
3987     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
3988     *         owner.
3989     */
3990    public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
3991        throwIfParentInstance("uninstallAllUserCaCerts");
3992        if (mService != null) {
3993            try {
3994                mService.uninstallCaCerts(admin, mContext.getPackageName(),
3995                        new TrustedCertificateStore().userAliases() .toArray(new String[0]));
3996            } catch (RemoteException re) {
3997                throw re.rethrowFromSystemServer();
3998            }
3999        }
4000    }
4001
4002    /**
4003     * Returns whether this certificate is installed as a trusted CA.
4004     *
4005     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4006     *              {@code null} if calling from a delegated certificate installer.
4007     * @param certBuffer encoded form of the certificate to look up.
4008     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4009     *         owner.
4010     */
4011    public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
4012        throwIfParentInstance("hasCaCertInstalled");
4013        if (mService != null) {
4014            try {
4015                mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
4016                return getCaCertAlias(certBuffer) != null;
4017            } catch (RemoteException re) {
4018                throw re.rethrowFromSystemServer();
4019            } catch (CertificateException ce) {
4020                Log.w(TAG, "Could not parse certificate", ce);
4021            }
4022        }
4023        return false;
4024    }
4025
4026    /**
4027     * Called by a device or profile owner, or delegated certificate installer, to install a
4028     * certificate and corresponding private key. All apps within the profile will be able to access
4029     * the certificate and use the private key, given direct user approval.
4030     *
4031     * <p>Access to the installed credentials will not be granted to the caller of this API without
4032     * direct user approval. This is for security - should a certificate installer become
4033     * compromised, certificates it had already installed will be protected.
4034     *
4035     * <p>If the installer must have access to the credentials, call
4036     * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
4037     *
4038     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4039     *            {@code null} if calling from a delegated certificate installer.
4040     * @param privKey The private key to install.
4041     * @param cert The certificate to install.
4042     * @param alias The private key alias under which to install the certificate. If a certificate
4043     * with that alias already exists, it will be overwritten.
4044     * @return {@code true} if the keys were installed, {@code false} otherwise.
4045     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4046     *         owner.
4047     * @see #setDelegatedScopes
4048     * @see #DELEGATION_CERT_INSTALL
4049     */
4050    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4051            @NonNull Certificate cert, @NonNull String alias) {
4052        return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
4053    }
4054
4055    /**
4056     * Called by a device or profile owner, or delegated certificate installer, to install a
4057     * certificate chain and corresponding private key for the leaf certificate. All apps within the
4058     * profile will be able to access the certificate chain and use the private key, given direct
4059     * user approval.
4060     *
4061     * <p>The caller of this API may grant itself access to the certificate and private key
4062     * immediately, without user approval. It is a best practice not to request this unless strictly
4063     * necessary since it opens up additional security vulnerabilities.
4064     *
4065     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4066     *        {@code null} if calling from a delegated certificate installer.
4067     * @param privKey The private key to install.
4068     * @param certs The certificate chain to install. The chain should start with the leaf
4069     *        certificate and include the chain of trust in order. This will be returned by
4070     *        {@link android.security.KeyChain#getCertificateChain}.
4071     * @param alias The private key alias under which to install the certificate. If a certificate
4072     *        with that alias already exists, it will be overwritten.
4073     * @param requestAccess {@code true} to request that the calling app be granted access to the
4074     *        credentials immediately. Otherwise, access to the credentials will be gated by user
4075     *        approval.
4076     * @return {@code true} if the keys were installed, {@code false} otherwise.
4077     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4078     *         owner.
4079     * @see android.security.KeyChain#getCertificateChain
4080     * @see #setDelegatedScopes
4081     * @see #DELEGATION_CERT_INSTALL
4082     */
4083    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4084            @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
4085        return installKeyPair(admin, privKey, certs, alias, requestAccess, true);
4086    }
4087
4088    /**
4089     * Called by a device or profile owner, or delegated certificate installer, to install a
4090     * certificate chain and corresponding private key for the leaf certificate. All apps within the
4091     * profile will be able to access the certificate chain and use the private key, given direct
4092     * user approval (if the user is allowed to select the private key).
4093     *
4094     * <p>The caller of this API may grant itself access to the certificate and private key
4095     * immediately, without user approval. It is a best practice not to request this unless strictly
4096     * necessary since it opens up additional security vulnerabilities.
4097     *
4098     * <p>Whether this key is offered to the user for approval at all or not depends on the
4099     * {@code isUserSelectable} parameter.
4100     *
4101     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4102     *        {@code null} if calling from a delegated certificate installer.
4103     * @param privKey The private key to install.
4104     * @param certs The certificate chain to install. The chain should start with the leaf
4105     *        certificate and include the chain of trust in order. This will be returned by
4106     *        {@link android.security.KeyChain#getCertificateChain}.
4107     * @param alias The private key alias under which to install the certificate. If a certificate
4108     *        with that alias already exists, it will be overwritten.
4109     * @param requestAccess {@code true} to request that the calling app be granted access to the
4110     *        credentials immediately. Otherwise, access to the credentials will be gated by user
4111     *        approval.
4112     * @param isUserSelectable {@code true} to indicate that a user can select this key via the
4113     *        Certificate Selection prompt, false to indicate that this key can only be granted
4114     *        access by implementing
4115     *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
4116     * @return {@code true} if the keys were installed, {@code false} otherwise.
4117     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4118     *         owner.
4119     * @see android.security.KeyChain#getCertificateChain
4120     * @see #setDelegatedScopes
4121     * @see #DELEGATION_CERT_INSTALL
4122     */
4123    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4124            @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess,
4125            boolean isUserSelectable) {
4126        throwIfParentInstance("installKeyPair");
4127        try {
4128            final byte[] pemCert = Credentials.convertToPem(certs[0]);
4129            byte[] pemChain = null;
4130            if (certs.length > 1) {
4131                pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
4132            }
4133            final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
4134                    .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
4135            return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
4136                    pemChain, alias, requestAccess, isUserSelectable);
4137        } catch (RemoteException e) {
4138            throw e.rethrowFromSystemServer();
4139        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
4140            Log.w(TAG, "Failed to obtain private key material", e);
4141        } catch (CertificateException | IOException e) {
4142            Log.w(TAG, "Could not pem-encode certificate", e);
4143        }
4144        return false;
4145    }
4146
4147    /**
4148     * Called by a device or profile owner, or delegated certificate installer, to remove a
4149     * certificate and private key pair installed under a given alias.
4150     *
4151     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4152     *        {@code null} if calling from a delegated certificate installer.
4153     * @param alias The private key alias under which the certificate is installed.
4154     * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
4155     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4156     *         owner.
4157     * @see #setDelegatedScopes
4158     * @see #DELEGATION_CERT_INSTALL
4159     */
4160    public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
4161        throwIfParentInstance("removeKeyPair");
4162        try {
4163            return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4164        } catch (RemoteException e) {
4165            throw e.rethrowFromSystemServer();
4166        }
4167    }
4168
4169    /**
4170     * Called by a device or profile owner, or delegated certificate installer, to generate a
4171     * new private/public key pair. If the device supports key generation via secure hardware,
4172     * this method is useful for creating a key in KeyChain that never left the secure hardware.
4173     *
4174     * Access to the key is controlled the same way as in {@link #installKeyPair}.
4175     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4176     *            {@code null} if calling from a delegated certificate installer.
4177     * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
4178     * @param keySpec Specification of the key to generate, see
4179     * {@link java.security.KeyPairGenerator}.
4180     * @param idAttestationFlags A bitmask of all the identifiers that should be included in the
4181     *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
4182     *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), or {@code 0} if no device
4183     *        identification is required in the attestation record.
4184     *        Device owner, profile owner and their delegated certificate installer can use
4185     *        {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device information
4186     *        including manufacturer, model, brand, device and product in the attestation record.
4187     *        Only device owner and their delegated certificate installer can use
4188     *        {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID} to request
4189     *        unique device identifiers to be attested.
4190     *        <p>
4191     *        If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
4192     *        is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
4193     *        <p>
4194     *        If any flag is specified, then an attestation challenge must be included in the
4195     *        {@code keySpec}.
4196     * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
4197     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4198     *         owner. If Device ID attestation is requested (using {@link #ID_TYPE_SERIAL},
4199     *         {@link #ID_TYPE_IMEI} or {@link #ID_TYPE_MEID}), the caller must be the Device Owner
4200     *         or the Certificate Installer delegate.
4201     * @throws IllegalArgumentException if the alias in {@code keySpec} is empty, if the
4202     *         algorithm specification in {@code keySpec} is not {@code RSAKeyGenParameterSpec}
4203     *         or {@code ECGenParameterSpec}, or if Device ID attestation was requested but the
4204     *         {@code keySpec} does not contain an attestation challenge.
4205     * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
4206     */
4207    public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
4208            @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
4209            @AttestationIdType int idAttestationFlags) {
4210        throwIfParentInstance("generateKeyPair");
4211        try {
4212            final ParcelableKeyGenParameterSpec parcelableSpec =
4213                    new ParcelableKeyGenParameterSpec(keySpec);
4214            KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
4215
4216            // Translate ID attestation flags to values used by AttestationUtils
4217            final boolean success = mService.generateKeyPair(
4218                    admin, mContext.getPackageName(), algorithm, parcelableSpec,
4219                    idAttestationFlags, attestationChain);
4220            if (!success) {
4221                Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
4222                return null;
4223            }
4224
4225            final String alias = keySpec.getKeystoreAlias();
4226            final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
4227            Certificate[] outputChain = null;
4228            try {
4229                if (AttestationUtils.isChainValid(attestationChain)) {
4230                    outputChain = AttestationUtils.parseCertificateChain(attestationChain);
4231                }
4232            } catch (KeyAttestationException e) {
4233                Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
4234                mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4235                return null;
4236            }
4237            return new AttestedKeyPair(keyPair, outputChain);
4238        } catch (RemoteException e) {
4239            throw e.rethrowFromSystemServer();
4240        } catch (KeyChainException e) {
4241            Log.w(TAG, "Failed to generate key", e);
4242        } catch (InterruptedException e) {
4243            Log.w(TAG, "Interrupted while generating key", e);
4244            Thread.currentThread().interrupt();
4245        }
4246        return null;
4247    }
4248
4249
4250    /**
4251     * Called by a device or profile owner, or delegated certificate installer, to associate
4252     * certificates with a key pair that was generated using {@link #generateKeyPair}, and
4253     * set whether the key is available for the user to choose in the certificate selection
4254     * prompt.
4255     *
4256     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4257     *            {@code null} if calling from a delegated certificate installer.
4258     * @param alias The private key alias under which to install the certificate. The {@code alias}
4259     *        should denote an existing private key. If a certificate with that alias already
4260     *        exists, it will be overwritten.
4261     * @param certs The certificate chain to install. The chain should start with the leaf
4262     *        certificate and include the chain of trust in order. This will be returned by
4263     *        {@link android.security.KeyChain#getCertificateChain}.
4264     * @param isUserSelectable {@code true} to indicate that a user can select this key via the
4265     *        certificate selection prompt, {@code false} to indicate that this key can only be
4266     *        granted access by implementing
4267     *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
4268     * @return {@code true} if the provided {@code alias} exists and the certificates has been
4269     *        successfully associated with it, {@code false} otherwise.
4270     * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4271     *         owner, or {@code admin} is null but the calling application is not a delegated
4272     *         certificate installer.
4273     */
4274    public boolean setKeyPairCertificate(@Nullable ComponentName admin,
4275            @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
4276        throwIfParentInstance("setKeyPairCertificate");
4277        try {
4278            final byte[] pemCert = Credentials.convertToPem(certs.get(0));
4279            byte[] pemChain = null;
4280            if (certs.size() > 1) {
4281                pemChain = Credentials.convertToPem(
4282                        certs.subList(1, certs.size()).toArray(new Certificate[0]));
4283            }
4284            return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
4285                    pemChain, isUserSelectable);
4286        } catch (RemoteException e) {
4287            throw e.rethrowFromSystemServer();
4288        } catch (CertificateException | IOException e) {
4289            Log.w(TAG, "Could not pem-encode certificate", e);
4290        }
4291        return false;
4292    }
4293
4294
4295    /**
4296     * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
4297     * doesn't exist.
4298     */
4299    private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
4300        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4301        final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
4302                              new ByteArrayInputStream(certBuffer));
4303        return new TrustedCertificateStore().getCertificateAlias(cert);
4304    }
4305
4306    /**
4307     * Called by a profile owner or device owner to grant access to privileged certificate
4308     * manipulation APIs to a third-party certificate installer app. Granted APIs include
4309     * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
4310     * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
4311     * <p>
4312     * Delegated certificate installer is a per-user state. The delegated access is persistent until
4313     * it is later cleared by calling this method with a null value or uninstallling the certificate
4314     * installer.
4315     * <p>
4316     * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
4317     * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
4318     * supplied certificate installer package must be installed when calling this API, otherwise an
4319     * {@link IllegalArgumentException} will be thrown.
4320     *
4321     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4322     * @param installerPackage The package name of the certificate installer which will be given
4323     *            access. If {@code null} is given the current package will be cleared.
4324     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4325     *
4326     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
4327     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
4328     */
4329    @Deprecated
4330    public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
4331            installerPackage) throws SecurityException {
4332        throwIfParentInstance("setCertInstallerPackage");
4333        if (mService != null) {
4334            try {
4335                mService.setCertInstallerPackage(admin, installerPackage);
4336            } catch (RemoteException e) {
4337                throw e.rethrowFromSystemServer();
4338            }
4339        }
4340    }
4341
4342    /**
4343     * Called by a profile owner or device owner to retrieve the certificate installer for the user,
4344     * or {@code null} if none is set. If there are multiple delegates this function will return one
4345     * of them.
4346     *
4347     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4348     * @return The package name of the current delegated certificate installer, or {@code null} if
4349     *         none is set.
4350     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4351     *
4352     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
4353     * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
4354     */
4355    @Deprecated
4356    public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
4357            throws SecurityException {
4358        throwIfParentInstance("getCertInstallerPackage");
4359        if (mService != null) {
4360            try {
4361                return mService.getCertInstallerPackage(admin);
4362            } catch (RemoteException e) {
4363                throw e.rethrowFromSystemServer();
4364            }
4365        }
4366        return null;
4367    }
4368
4369    /**
4370     * Called by a profile owner or device owner to grant access to privileged APIs to another app.
4371     * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
4372     * constants.
4373     * <p>
4374     * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
4375     * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
4376     * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
4377     * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
4378     * <p>
4379     * Delegated scopes are a per-user state. The delegated access is persistent until it is later
4380     * cleared by calling this method with an empty {@code scopes} list or uninstalling the
4381     * {@code delegatePackage}.
4382     *
4383     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4384     * @param delegatePackage The package name of the app which will be given access.
4385     * @param scopes The groups of privileged APIs whose access should be granted to
4386     *            {@code delegatedPackage}.
4387     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4388     */
4389     public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
4390            @NonNull List<String> scopes) {
4391        throwIfParentInstance("setDelegatedScopes");
4392        if (mService != null) {
4393            try {
4394                mService.setDelegatedScopes(admin, delegatePackage, scopes);
4395            } catch (RemoteException e) {
4396                throw e.rethrowFromSystemServer();
4397            }
4398        }
4399    }
4400
4401    /**
4402     * Called by a profile owner or device owner to retrieve a list of the scopes given to a
4403     * delegate package. Other apps can use this method to retrieve their own delegated scopes by
4404     * passing {@code null} for {@code admin} and their own package name as
4405     * {@code delegatedPackage}.
4406     *
4407     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4408     *            {@code null} if the caller is {@code delegatedPackage}.
4409     * @param delegatedPackage The package name of the app whose scopes should be retrieved.
4410     * @return A list containing the scopes given to {@code delegatedPackage}.
4411     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4412     */
4413     @NonNull
4414     public List<String> getDelegatedScopes(@Nullable ComponentName admin,
4415             @NonNull String delegatedPackage) {
4416         throwIfParentInstance("getDelegatedScopes");
4417         if (mService != null) {
4418             try {
4419                 return mService.getDelegatedScopes(admin, delegatedPackage);
4420             } catch (RemoteException e) {
4421                 throw e.rethrowFromSystemServer();
4422             }
4423         }
4424         return null;
4425    }
4426
4427    /**
4428     * Called by a profile owner or device owner to retrieve a list of delegate packages that were
4429     * granted a delegation scope.
4430     *
4431     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4432     * @param delegationScope The scope whose delegates should be retrieved.
4433     * @return A list of package names of the current delegated packages for
4434               {@code delegationScope}.
4435     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4436     */
4437     @Nullable
4438     public List<String> getDelegatePackages(@NonNull ComponentName admin,
4439             @NonNull String delegationScope) {
4440        throwIfParentInstance("getDelegatePackages");
4441        if (mService != null) {
4442            try {
4443                return mService.getDelegatePackages(admin, delegationScope);
4444            } catch (RemoteException e) {
4445                throw e.rethrowFromSystemServer();
4446            }
4447        }
4448        return null;
4449    }
4450
4451    /**
4452     * Called by a device or profile owner to configure an always-on VPN connection through a
4453     * specific application for the current user. This connection is automatically granted and
4454     * persisted after a reboot.
4455     * <p>
4456     * To support the always-on feature, an app must
4457     * <ul>
4458     *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
4459     *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
4460     *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
4461     *     <li><i>not</i> explicitly opt out of the feature through
4462     *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
4463     * </ul>
4464     * The call will fail if called with the package name of an unsupported VPN app.
4465     *
4466     * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
4467     *        remove an existing always-on VPN configuration.
4468     * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
4469     *        {@code false} otherwise. This carries the risk that any failure of the VPN provider
4470     *        could break networking for all apps. This has no effect when clearing.
4471     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4472     * @throws NameNotFoundException if {@code vpnPackage} is not installed.
4473     * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
4474     *         set as always-on, or if always-on VPN is not available.
4475     */
4476    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
4477            boolean lockdownEnabled)
4478            throws NameNotFoundException, UnsupportedOperationException {
4479        throwIfParentInstance("setAlwaysOnVpnPackage");
4480        if (mService != null) {
4481            try {
4482                if (!mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled)) {
4483                    throw new NameNotFoundException(vpnPackage);
4484                }
4485            } catch (RemoteException e) {
4486                throw e.rethrowFromSystemServer();
4487            }
4488        }
4489    }
4490
4491    /**
4492     * Called by a device or profile owner to read the name of the package administering an
4493     * always-on VPN connection for the current user. If there is no such package, or the always-on
4494     * VPN is provided by the system instead of by an application, {@code null} will be returned.
4495     *
4496     * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
4497     *         is set.
4498     * @throws SecurityException if {@code admin} is not a device or a profile owner.
4499     */
4500    public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
4501        throwIfParentInstance("getAlwaysOnVpnPackage");
4502        if (mService != null) {
4503            try {
4504                return mService.getAlwaysOnVpnPackage(admin);
4505            } catch (RemoteException e) {
4506                throw e.rethrowFromSystemServer();
4507            }
4508        }
4509        return null;
4510    }
4511
4512    /**
4513     * Called by an application that is administering the device to disable all cameras on the
4514     * device, for this user. After setting this, no applications running as this user will be able
4515     * to access any cameras on the device.
4516     * <p>
4517     * If the caller is device owner, then the restriction will be applied to all users.
4518     * <p>
4519     * The calling device admin must have requested
4520     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
4521     * not, a security exception will be thrown.
4522     *
4523     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4524     * @param disabled Whether or not the camera should be disabled.
4525     * @throws SecurityException if {@code admin} is not an active administrator or does not use
4526     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
4527     */
4528    public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
4529        throwIfParentInstance("setCameraDisabled");
4530        if (mService != null) {
4531            try {
4532                mService.setCameraDisabled(admin, disabled);
4533            } catch (RemoteException e) {
4534                throw e.rethrowFromSystemServer();
4535            }
4536        }
4537    }
4538
4539    /**
4540     * Determine whether or not the device's cameras have been disabled for this user,
4541     * either by the calling admin, if specified, or all admins.
4542     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4543     * have disabled the camera
4544     */
4545    public boolean getCameraDisabled(@Nullable ComponentName admin) {
4546        throwIfParentInstance("getCameraDisabled");
4547        return getCameraDisabled(admin, myUserId());
4548    }
4549
4550    /** @hide per-user version */
4551    public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
4552        if (mService != null) {
4553            try {
4554                return mService.getCameraDisabled(admin, userHandle);
4555            } catch (RemoteException e) {
4556                throw e.rethrowFromSystemServer();
4557            }
4558        }
4559        return false;
4560    }
4561
4562    /**
4563     * Called by a device owner to request a bugreport.
4564     * <p>
4565     * If the device contains secondary users or profiles, they must be affiliated with the device.
4566     * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
4567     *
4568     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4569     * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
4570     *         wasn't triggered because a previous bugreport operation is still active (either the
4571     *         bugreport is still running or waiting for the user to share or decline)
4572     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
4573     *         profile or secondary user that is not affiliated with the device.
4574     * @see #isAffiliatedUser
4575     */
4576    public boolean requestBugreport(@NonNull ComponentName admin) {
4577        throwIfParentInstance("requestBugreport");
4578        if (mService != null) {
4579            try {
4580                return mService.requestBugreport(admin);
4581            } catch (RemoteException e) {
4582                throw e.rethrowFromSystemServer();
4583            }
4584        }
4585        return false;
4586    }
4587
4588    /**
4589     * Determine whether or not creating a guest user has been disabled for the device
4590     *
4591     * @hide
4592     */
4593    public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
4594        // Currently guest users can always be created if multi-user is enabled
4595        // TODO introduce a policy for guest user creation
4596        return false;
4597    }
4598
4599    /**
4600     * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
4601     * screen capture also prevents the content from being shown on display devices that do not have
4602     * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
4603     * secure surfaces and secure displays.
4604     * <p>
4605     * The calling device admin must be a device or profile owner. If it is not, a security
4606     * exception will be thrown.
4607     * <p>
4608     * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
4609     * assist requests for all activities of the relevant user.
4610     *
4611     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4612     * @param disabled Whether screen capture is disabled or not.
4613     * @throws SecurityException if {@code admin} is not a device or profile owner.
4614     */
4615    public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
4616        throwIfParentInstance("setScreenCaptureDisabled");
4617        if (mService != null) {
4618            try {
4619                mService.setScreenCaptureDisabled(admin, disabled);
4620            } catch (RemoteException e) {
4621                throw e.rethrowFromSystemServer();
4622            }
4623        }
4624    }
4625
4626    /**
4627     * Determine whether or not screen capture has been disabled by the calling
4628     * admin, if specified, or all admins.
4629     * @param admin The name of the admin component to check, or {@code null} to check whether any admins
4630     * have disabled screen capture.
4631     */
4632    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
4633        throwIfParentInstance("getScreenCaptureDisabled");
4634        return getScreenCaptureDisabled(admin, myUserId());
4635    }
4636
4637    /** @hide per-user version */
4638    public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
4639        if (mService != null) {
4640            try {
4641                return mService.getScreenCaptureDisabled(admin, userHandle);
4642            } catch (RemoteException e) {
4643                throw e.rethrowFromSystemServer();
4644            }
4645        }
4646        return false;
4647    }
4648
4649    /**
4650     * Called by a device or profile owner to set whether auto time is required. If auto time is
4651     * required, no user will be able set the date and time and network date and time will be used.
4652     * <p>
4653     * Note: if auto time is required the user can still manually set the time zone.
4654     * <p>
4655     * The calling device admin must be a device or profile owner. If it is not, a security
4656     * exception will be thrown.
4657     *
4658     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4659     * @param required Whether auto time is set required or not.
4660     * @throws SecurityException if {@code admin} is not a device owner.
4661     */
4662    public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
4663        throwIfParentInstance("setAutoTimeRequired");
4664        if (mService != null) {
4665            try {
4666                mService.setAutoTimeRequired(admin, required);
4667            } catch (RemoteException e) {
4668                throw e.rethrowFromSystemServer();
4669            }
4670        }
4671    }
4672
4673    /**
4674     * @return true if auto time is required.
4675     */
4676    public boolean getAutoTimeRequired() {
4677        throwIfParentInstance("getAutoTimeRequired");
4678        if (mService != null) {
4679            try {
4680                return mService.getAutoTimeRequired();
4681            } catch (RemoteException e) {
4682                throw e.rethrowFromSystemServer();
4683            }
4684        }
4685        return false;
4686    }
4687
4688    /**
4689     * Called by a device owner to set whether all users created on the device should be ephemeral.
4690     * <p>
4691     * The system user is exempt from this policy - it is never ephemeral.
4692     * <p>
4693     * The calling device admin must be the device owner. If it is not, a security exception will be
4694     * thrown.
4695     *
4696     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4697     * @param forceEphemeralUsers If true, all the existing users will be deleted and all
4698     *            subsequently created users will be ephemeral.
4699     * @throws SecurityException if {@code admin} is not a device owner.
4700     * @hide
4701     */
4702    public void setForceEphemeralUsers(
4703            @NonNull ComponentName admin, boolean forceEphemeralUsers) {
4704        throwIfParentInstance("setForceEphemeralUsers");
4705        if (mService != null) {
4706            try {
4707                mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
4708            } catch (RemoteException e) {
4709                throw e.rethrowFromSystemServer();
4710            }
4711        }
4712    }
4713
4714    /**
4715     * @return true if all users are created ephemeral.
4716     * @throws SecurityException if {@code admin} is not a device owner.
4717     * @hide
4718     */
4719    public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
4720        throwIfParentInstance("getForceEphemeralUsers");
4721        if (mService != null) {
4722            try {
4723                return mService.getForceEphemeralUsers(admin);
4724            } catch (RemoteException e) {
4725                throw e.rethrowFromSystemServer();
4726            }
4727        }
4728        return false;
4729    }
4730
4731    /**
4732     * Called by an application that is administering the device to disable keyguard customizations,
4733     * such as widgets. After setting this, keyguard features will be disabled according to the
4734     * provided feature list.
4735     * <p>
4736     * The calling device admin must have requested
4737     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
4738     * if it has not, a security exception will be thrown.
4739     * <p>
4740     * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
4741     * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
4742     * profile owner of a managed profile can set:
4743     * <ul>
4744     * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
4745     * is no separate challenge set on the managed profile.
4746     * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT} which affects the managed profile challenge if
4747     * there is one, or the parent user otherwise.
4748     * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
4749     * by applications in the managed profile.
4750     * </ul>
4751     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and {@link #KEYGUARD_DISABLE_FINGERPRINT} can also be
4752     * set on the {@link DevicePolicyManager} instance returned by
4753     * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4754     * profile.
4755     * <p>
4756     * Requests to disable other features on a managed profile will be ignored.
4757     * <p>
4758     * The admin can check which features have been disabled by calling
4759     * {@link #getKeyguardDisabledFeatures(ComponentName)}
4760     *
4761     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4762     * @param which {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
4763     *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
4764     *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
4765     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
4766     *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
4767     *            {@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FEATURES_ALL}
4768     * @throws SecurityException if {@code admin} is not an active administrator or does not user
4769     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
4770     */
4771    public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
4772        if (mService != null) {
4773            try {
4774                mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
4775            } catch (RemoteException e) {
4776                throw e.rethrowFromSystemServer();
4777            }
4778        }
4779    }
4780
4781    /**
4782     * Determine whether or not features have been disabled in keyguard either by the calling
4783     * admin, if specified, or all admins that set restrictions on this user and its participating
4784     * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
4785     *
4786     * <p>This method can be called on the {@link DevicePolicyManager} instance
4787     * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4788     * restrictions on the parent profile.
4789     *
4790     * @param admin The name of the admin component to check, or {@code null} to check whether any
4791     * admins have disabled features in keyguard.
4792     * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
4793     * for a list.
4794     */
4795    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
4796        return getKeyguardDisabledFeatures(admin, myUserId());
4797    }
4798
4799    /** @hide per-user version */
4800    public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
4801        if (mService != null) {
4802            try {
4803                return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
4804            } catch (RemoteException e) {
4805                throw e.rethrowFromSystemServer();
4806            }
4807        }
4808        return KEYGUARD_DISABLE_FEATURES_NONE;
4809    }
4810
4811    /**
4812     * @hide
4813     */
4814    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
4815            int userHandle) {
4816        if (mService != null) {
4817            try {
4818                mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
4819            } catch (RemoteException e) {
4820                throw e.rethrowFromSystemServer();
4821            }
4822        }
4823    }
4824
4825    /**
4826     * @hide
4827     */
4828    public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
4829        setActiveAdmin(policyReceiver, refreshing, myUserId());
4830    }
4831
4832    /**
4833     * @hide
4834     */
4835    public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
4836        if (mService != null) {
4837            try {
4838                mService.getRemoveWarning(admin, result, myUserId());
4839            } catch (RemoteException e) {
4840                throw e.rethrowFromSystemServer();
4841            }
4842        }
4843    }
4844
4845    /**
4846     * @hide
4847     */
4848    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
4849        if (mService != null) {
4850            try {
4851                mService.setActivePasswordState(metrics, userHandle);
4852            } catch (RemoteException e) {
4853                throw e.rethrowFromSystemServer();
4854            }
4855        }
4856    }
4857
4858    /**
4859     * @hide
4860     */
4861    public void reportPasswordChanged(@UserIdInt int userId) {
4862        if (mService != null) {
4863            try {
4864                mService.reportPasswordChanged(userId);
4865            } catch (RemoteException e) {
4866                throw e.rethrowFromSystemServer();
4867            }
4868        }
4869    }
4870
4871    /**
4872     * @hide
4873     */
4874    public void reportFailedPasswordAttempt(int userHandle) {
4875        if (mService != null) {
4876            try {
4877                mService.reportFailedPasswordAttempt(userHandle);
4878            } catch (RemoteException e) {
4879                throw e.rethrowFromSystemServer();
4880            }
4881        }
4882    }
4883
4884    /**
4885     * @hide
4886     */
4887    public void reportSuccessfulPasswordAttempt(int userHandle) {
4888        if (mService != null) {
4889            try {
4890                mService.reportSuccessfulPasswordAttempt(userHandle);
4891            } catch (RemoteException e) {
4892                throw e.rethrowFromSystemServer();
4893            }
4894        }
4895    }
4896
4897    /**
4898     * @hide
4899     */
4900    public void reportFailedFingerprintAttempt(int userHandle) {
4901        if (mService != null) {
4902            try {
4903                mService.reportFailedFingerprintAttempt(userHandle);
4904            } catch (RemoteException e) {
4905                throw e.rethrowFromSystemServer();
4906            }
4907        }
4908    }
4909
4910    /**
4911     * @hide
4912     */
4913    public void reportSuccessfulFingerprintAttempt(int userHandle) {
4914        if (mService != null) {
4915            try {
4916                mService.reportSuccessfulFingerprintAttempt(userHandle);
4917            } catch (RemoteException e) {
4918                throw e.rethrowFromSystemServer();
4919            }
4920        }
4921    }
4922
4923    /**
4924     * Should be called when keyguard has been dismissed.
4925     * @hide
4926     */
4927    public void reportKeyguardDismissed(int userHandle) {
4928        if (mService != null) {
4929            try {
4930                mService.reportKeyguardDismissed(userHandle);
4931            } catch (RemoteException e) {
4932                throw e.rethrowFromSystemServer();
4933            }
4934        }
4935    }
4936
4937    /**
4938     * Should be called when keyguard view has been shown to the user.
4939     * @hide
4940     */
4941    public void reportKeyguardSecured(int userHandle) {
4942        if (mService != null) {
4943            try {
4944                mService.reportKeyguardSecured(userHandle);
4945            } catch (RemoteException e) {
4946                throw e.rethrowFromSystemServer();
4947            }
4948        }
4949    }
4950
4951    /**
4952     * @hide
4953     * Sets the given package as the device owner.
4954     * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
4955     * @param who the component name to be registered as device owner.
4956     * @return whether the package was successfully registered as the device owner.
4957     * @throws IllegalArgumentException if the package name is null or invalid
4958     * @throws IllegalStateException If the preconditions mentioned are not met.
4959     */
4960    public boolean setDeviceOwner(ComponentName who) {
4961        return setDeviceOwner(who, null);
4962    }
4963
4964    /**
4965     * @hide
4966     */
4967    public boolean setDeviceOwner(ComponentName who, int userId)  {
4968        return setDeviceOwner(who, null, userId);
4969    }
4970
4971    /**
4972     * @hide
4973     */
4974    public boolean setDeviceOwner(ComponentName who, String ownerName) {
4975        return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
4976    }
4977
4978    /**
4979     * @hide
4980     * Sets the given package as the device owner. The package must already be installed. There
4981     * must not already be a device owner.
4982     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
4983     * this method.
4984     * Calling this after the setup phase of the primary user has completed is allowed only if
4985     * the caller is the shell uid, and there are no additional users and no accounts.
4986     * @param who the component name to be registered as device owner.
4987     * @param ownerName the human readable name of the institution that owns this device.
4988     * @param userId ID of the user on which the device owner runs.
4989     * @return whether the package was successfully registered as the device owner.
4990     * @throws IllegalArgumentException if the package name is null or invalid
4991     * @throws IllegalStateException If the preconditions mentioned are not met.
4992     */
4993    public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
4994            throws IllegalArgumentException, IllegalStateException {
4995        if (mService != null) {
4996            try {
4997                return mService.setDeviceOwner(who, ownerName, userId);
4998            } catch (RemoteException re) {
4999                throw re.rethrowFromSystemServer();
5000            }
5001        }
5002        return false;
5003    }
5004
5005    /**
5006     * Used to determine if a particular package has been registered as a Device Owner app.
5007     * A device owner app is a special device admin that cannot be deactivated by the user, once
5008     * activated as a device admin. It also cannot be uninstalled. To check whether a particular
5009     * package is currently registered as the device owner app, pass in the package name from
5010     * {@link Context#getPackageName()} to this method.<p/>This is useful for device
5011     * admin apps that want to check whether they are also registered as the device owner app. The
5012     * exact mechanism by which a device admin app is registered as a device owner app is defined by
5013     * the setup process.
5014     * @param packageName the package name of the app, to compare with the registered device owner
5015     * app, if any.
5016     * @return whether or not the package is registered as the device owner app.
5017     */
5018    public boolean isDeviceOwnerApp(String packageName) {
5019        throwIfParentInstance("isDeviceOwnerApp");
5020        return isDeviceOwnerAppOnCallingUser(packageName);
5021    }
5022
5023    /**
5024     * @return true if a package is registered as device owner, only when it's running on the
5025     * calling user.
5026     *
5027     * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
5028     * @hide
5029     */
5030    public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
5031        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
5032    }
5033
5034    /**
5035     * @return true if a package is registered as device owner, even if it's running on a different
5036     * user.
5037     *
5038     * <p>Requires the MANAGE_USERS permission.
5039     *
5040     * @hide
5041     */
5042    public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
5043        return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
5044    }
5045
5046    /**
5047     * @return device owner component name, only when it's running on the calling user.
5048     *
5049     * @hide
5050     */
5051    public ComponentName getDeviceOwnerComponentOnCallingUser() {
5052        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
5053    }
5054
5055    /**
5056     * @return device owner component name, even if it's running on a different user.
5057     *
5058     * @hide
5059     */
5060    @SystemApi
5061    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5062    public ComponentName getDeviceOwnerComponentOnAnyUser() {
5063        return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
5064    }
5065
5066    private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
5067        if (packageName == null) {
5068            return false;
5069        }
5070        final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
5071        if (deviceOwner == null) {
5072            return false;
5073        }
5074        return packageName.equals(deviceOwner.getPackageName());
5075    }
5076
5077    private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
5078        if (mService != null) {
5079            try {
5080                return mService.getDeviceOwnerComponent(callingUserOnly);
5081            } catch (RemoteException re) {
5082                throw re.rethrowFromSystemServer();
5083            }
5084        }
5085        return null;
5086    }
5087
5088    /**
5089     * @return ID of the user who runs device owner, or {@link UserHandle#USER_NULL} if there's
5090     * no device owner.
5091     *
5092     * <p>Requires the MANAGE_USERS permission.
5093     *
5094     * @hide
5095     */
5096    public int getDeviceOwnerUserId() {
5097        if (mService != null) {
5098            try {
5099                return mService.getDeviceOwnerUserId();
5100            } catch (RemoteException re) {
5101                throw re.rethrowFromSystemServer();
5102            }
5103        }
5104        return UserHandle.USER_NULL;
5105    }
5106
5107    /**
5108     * Clears the current device owner. The caller must be the device owner. This function should be
5109     * used cautiously as once it is called it cannot be undone. The device owner can only be set as
5110     * a part of device setup, before it completes.
5111     * <p>
5112     * While some policies previously set by the device owner will be cleared by this method, it is
5113     * a best-effort process and some other policies will still remain in place after the device
5114     * owner is cleared.
5115     *
5116     * @param packageName The package name of the device owner.
5117     * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
5118     *             does not own the current device owner component.
5119     *
5120     * @deprecated This method is expected to be used for testing purposes only. The device owner
5121     * will lose control of the device and its data after calling it. In order to protect any
5122     * sensitive data that remains on the device, it is advised that the device owner factory resets
5123     * the device instead of calling this method. See {@link #wipeData(int)}.
5124     */
5125    @Deprecated
5126    public void clearDeviceOwnerApp(String packageName) {
5127        throwIfParentInstance("clearDeviceOwnerApp");
5128        if (mService != null) {
5129            try {
5130                mService.clearDeviceOwner(packageName);
5131            } catch (RemoteException re) {
5132                throw re.rethrowFromSystemServer();
5133            }
5134        }
5135    }
5136
5137    /**
5138     * Returns the device owner package name, only if it's running on the calling user.
5139     *
5140     * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
5141     *
5142     * @hide
5143     */
5144    @SystemApi
5145    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5146    public @Nullable String getDeviceOwner() {
5147        throwIfParentInstance("getDeviceOwner");
5148        final ComponentName name = getDeviceOwnerComponentOnCallingUser();
5149        return name != null ? name.getPackageName() : null;
5150    }
5151
5152    /**
5153     * Called by the system to find out whether the device is managed by a Device Owner.
5154     *
5155     * @return whether the device is managed by a Device Owner.
5156     * @throws SecurityException if the caller is not the device owner, does not hold the
5157     *         MANAGE_USERS permission and is not the system.
5158     *
5159     * @hide
5160     */
5161    @SystemApi
5162    @TestApi
5163    @SuppressLint("Doclava125")
5164    public boolean isDeviceManaged() {
5165        try {
5166            return mService.hasDeviceOwner();
5167        } catch (RemoteException re) {
5168            throw re.rethrowFromSystemServer();
5169        }
5170    }
5171
5172    /**
5173     * Returns the device owner name.  Note this method *will* return the device owner
5174     * name when it's running on a different user.
5175     *
5176     * @hide
5177     */
5178    @SystemApi
5179    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5180    public String getDeviceOwnerNameOnAnyUser() {
5181        throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
5182        if (mService != null) {
5183            try {
5184                return mService.getDeviceOwnerName();
5185            } catch (RemoteException re) {
5186                throw re.rethrowFromSystemServer();
5187            }
5188        }
5189        return null;
5190    }
5191
5192    /**
5193     * @hide
5194     * @deprecated Do not use
5195     * @removed
5196     */
5197    @Deprecated
5198    @SystemApi
5199    @SuppressLint("Doclava125")
5200    public @Nullable String getDeviceInitializerApp() {
5201        return null;
5202    }
5203
5204    /**
5205     * @hide
5206     * @deprecated Do not use
5207     * @removed
5208     */
5209    @Deprecated
5210    @SystemApi
5211    @SuppressLint("Doclava125")
5212    public @Nullable ComponentName getDeviceInitializerComponent() {
5213        return null;
5214    }
5215
5216    /**
5217     * @hide
5218     * @deprecated Use #ACTION_SET_PROFILE_OWNER
5219     * Sets the given component as an active admin and registers the package as the profile
5220     * owner for this user. The package must already be installed and there shouldn't be
5221     * an existing profile owner registered for this user. Also, this method must be called
5222     * before the user setup has been completed.
5223     * <p>
5224     * This method can only be called by system apps that hold MANAGE_USERS permission and
5225     * MANAGE_DEVICE_ADMINS permission.
5226     * @param admin The component to register as an active admin and profile owner.
5227     * @param ownerName The user-visible name of the entity that is managing this user.
5228     * @return whether the admin was successfully registered as the profile owner.
5229     * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
5230     *         the user has already been set up.
5231     */
5232    @Deprecated
5233    @SystemApi
5234    @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
5235    public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
5236            throws IllegalArgumentException {
5237        throwIfParentInstance("setActiveProfileOwner");
5238        if (mService != null) {
5239            try {
5240                final int myUserId = myUserId();
5241                mService.setActiveAdmin(admin, false, myUserId);
5242                return mService.setProfileOwner(admin, ownerName, myUserId);
5243            } catch (RemoteException re) {
5244                throw re.rethrowFromSystemServer();
5245            }
5246        }
5247        return false;
5248    }
5249
5250    /**
5251     * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
5252     * a SecurityException will be thrown. This method is not available to managed profile owners.
5253     * <p>
5254     * While some policies previously set by the profile owner will be cleared by this method, it is
5255     * a best-effort process and some other policies will still remain in place after the profile
5256     * owner is cleared.
5257     *
5258     * @param admin The component to remove as the profile owner.
5259     * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
5260     * being called from a managed profile.
5261     *
5262     * @deprecated This method is expected to be used for testing purposes only. The profile owner
5263     * will lose control of the user and its data after calling it. In order to protect any
5264     * sensitive data that remains on this user, it is advised that the profile owner deletes it
5265     * instead of calling this method. See {@link #wipeData(int)}.
5266     */
5267    @Deprecated
5268    public void clearProfileOwner(@NonNull ComponentName admin) {
5269        throwIfParentInstance("clearProfileOwner");
5270        if (mService != null) {
5271            try {
5272                mService.clearProfileOwner(admin);
5273            } catch (RemoteException re) {
5274                throw re.rethrowFromSystemServer();
5275            }
5276        }
5277    }
5278
5279    /**
5280     * @hide
5281     * Checks whether the user was already setup.
5282     */
5283    public boolean hasUserSetupCompleted() {
5284        if (mService != null) {
5285            try {
5286                return mService.hasUserSetupCompleted();
5287            } catch (RemoteException re) {
5288                throw re.rethrowFromSystemServer();
5289            }
5290        }
5291        return true;
5292    }
5293
5294    /**
5295     * @hide
5296     * Sets the given component as the profile owner of the given user profile. The package must
5297     * already be installed. There must not already be a profile owner for this user.
5298     * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
5299     * this method.
5300     * Calling this after the setup phase of the specified user has completed is allowed only if:
5301     * - the caller is SYSTEM_UID.
5302     * - or the caller is the shell uid, and there are no accounts on the specified user.
5303     * @param admin the component name to be registered as profile owner.
5304     * @param ownerName the human readable name of the organisation associated with this DPM.
5305     * @param userHandle the userId to set the profile owner for.
5306     * @return whether the component was successfully registered as the profile owner.
5307     * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
5308     * preconditions mentioned are not met.
5309     */
5310    public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
5311            int userHandle) throws IllegalArgumentException {
5312        if (mService != null) {
5313            try {
5314                if (ownerName == null) {
5315                    ownerName = "";
5316                }
5317                return mService.setProfileOwner(admin, ownerName, userHandle);
5318            } catch (RemoteException re) {
5319                throw re.rethrowFromSystemServer();
5320            }
5321        }
5322        return false;
5323    }
5324
5325    /**
5326     * Sets the device owner information to be shown on the lock screen.
5327     * <p>
5328     * If the device owner information is {@code null} or empty then the device owner info is
5329     * cleared and the user owner info is shown on the lock screen if it is set.
5330     * <p>
5331     * If the device owner information contains only whitespaces then the message on the lock screen
5332     * will be blank and the user will not be allowed to change it.
5333     * <p>
5334     * If the device owner information needs to be localized, it is the responsibility of the
5335     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
5336     * and set a new version of this string accordingly.
5337     *
5338     * @param admin The name of the admin component to check.
5339     * @param info Device owner information which will be displayed instead of the user owner info.
5340     * @throws SecurityException if {@code admin} is not a device owner.
5341     */
5342    public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
5343        throwIfParentInstance("setDeviceOwnerLockScreenInfo");
5344        if (mService != null) {
5345            try {
5346                mService.setDeviceOwnerLockScreenInfo(admin, info);
5347            } catch (RemoteException re) {
5348                throw re.rethrowFromSystemServer();
5349            }
5350        }
5351    }
5352
5353    /**
5354     * @return The device owner information. If it is not set returns {@code null}.
5355     */
5356    public CharSequence getDeviceOwnerLockScreenInfo() {
5357        throwIfParentInstance("getDeviceOwnerLockScreenInfo");
5358        if (mService != null) {
5359            try {
5360                return mService.getDeviceOwnerLockScreenInfo();
5361            } catch (RemoteException re) {
5362                throw re.rethrowFromSystemServer();
5363            }
5364        }
5365        return null;
5366    }
5367
5368    /**
5369     * Called by device or profile owners to suspend packages for this user. This function can be
5370     * called by a device owner, profile owner, or by a delegate given the
5371     * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
5372     * <p>
5373     * A suspended package will not be able to start activities. Its notifications will be hidden,
5374     * it will not show up in recents, will not be able to show toasts or dialogs or ring the
5375     * device.
5376     * <p>
5377     * The package must already be installed. If the package is uninstalled while suspended the
5378     * package will no longer be suspended. The admin can block this by using
5379     * {@link #setUninstallBlocked}.
5380     *
5381     * @param admin The name of the admin component to check, or {@code null} if the caller is a
5382     *            package access delegate.
5383     * @param packageNames The package names to suspend or unsuspend.
5384     * @param suspended If set to {@code true} than the packages will be suspended, if set to
5385     *            {@code false} the packages will be unsuspended.
5386     * @return an array of package names for which the suspended status is not set as requested in
5387     *         this method.
5388     * @throws SecurityException if {@code admin} is not a device or profile owner.
5389     * @see #setDelegatedScopes
5390     * @see #DELEGATION_PACKAGE_ACCESS
5391     */
5392    public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
5393            @NonNull String[] packageNames, boolean suspended) {
5394        throwIfParentInstance("setPackagesSuspended");
5395        if (mService != null) {
5396            try {
5397                return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
5398                        suspended);
5399            } catch (RemoteException re) {
5400                throw re.rethrowFromSystemServer();
5401            }
5402        }
5403        return packageNames;
5404    }
5405
5406    /**
5407     * Determine if a package is suspended. This function can be called by a device owner, profile
5408     * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
5409     * {@link #setDelegatedScopes}.
5410     *
5411     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5412     *            {@code null} if the caller is a package access delegate.
5413     * @param packageName The name of the package to retrieve the suspended status of.
5414     * @return {@code true} if the package is suspended or {@code false} if the package is not
5415     *         suspended, could not be found or an error occurred.
5416     * @throws SecurityException if {@code admin} is not a device or profile owner.
5417     * @throws NameNotFoundException if the package could not be found.
5418     * @see #setDelegatedScopes
5419     * @see #DELEGATION_PACKAGE_ACCESS
5420     */
5421    public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
5422            throws NameNotFoundException {
5423        throwIfParentInstance("isPackageSuspended");
5424        if (mService != null) {
5425            try {
5426                return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
5427            } catch (RemoteException e) {
5428                throw e.rethrowFromSystemServer();
5429            } catch (IllegalArgumentException ex) {
5430                throw new NameNotFoundException(packageName);
5431            }
5432        }
5433        return false;
5434    }
5435
5436    /**
5437     * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
5438     * be used. Only the profile owner can call this.
5439     *
5440     * @see #isProfileOwnerApp
5441     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5442     * @throws SecurityException if {@code admin} is not a profile owner.
5443     */
5444    public void setProfileEnabled(@NonNull ComponentName admin) {
5445        throwIfParentInstance("setProfileEnabled");
5446        if (mService != null) {
5447            try {
5448                mService.setProfileEnabled(admin);
5449            } catch (RemoteException e) {
5450                throw e.rethrowFromSystemServer();
5451            }
5452        }
5453    }
5454
5455    /**
5456     * Sets the name of the profile. In the device owner case it sets the name of the user which it
5457     * is called from. Only a profile owner or device owner can call this. If this is never called
5458     * by the profile or device owner, the name will be set to default values.
5459     *
5460     * @see #isProfileOwnerApp
5461     * @see #isDeviceOwnerApp
5462     * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
5463     * @param profileName The name of the profile.
5464     * @throws SecurityException if {@code admin} is not a device or profile owner.
5465     */
5466    public void setProfileName(@NonNull ComponentName admin, String profileName) {
5467        throwIfParentInstance("setProfileName");
5468        if (mService != null) {
5469            try {
5470                mService.setProfileName(admin, profileName);
5471            } catch (RemoteException e) {
5472                throw e.rethrowFromSystemServer();
5473            }
5474        }
5475    }
5476
5477    /**
5478     * Used to determine if a particular package is registered as the profile owner for the
5479     * user. A profile owner is a special device admin that has additional privileges
5480     * within the profile.
5481     *
5482     * @param packageName The package name of the app to compare with the registered profile owner.
5483     * @return Whether or not the package is registered as the profile owner.
5484     */
5485    public boolean isProfileOwnerApp(String packageName) {
5486        throwIfParentInstance("isProfileOwnerApp");
5487        if (mService != null) {
5488            try {
5489                ComponentName profileOwner = mService.getProfileOwner(myUserId());
5490                return profileOwner != null
5491                        && profileOwner.getPackageName().equals(packageName);
5492            } catch (RemoteException re) {
5493                throw re.rethrowFromSystemServer();
5494            }
5495        }
5496        return false;
5497    }
5498
5499    /**
5500     * @hide
5501     * @return the packageName of the owner of the given user profile or {@code null} if no profile
5502     * owner has been set for that user.
5503     * @throws IllegalArgumentException if the userId is invalid.
5504     */
5505    @SystemApi
5506    public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
5507        throwIfParentInstance("getProfileOwner");
5508        return getProfileOwnerAsUser(Process.myUserHandle().getIdentifier());
5509    }
5510
5511    /**
5512     * @see #getProfileOwner()
5513     * @hide
5514     */
5515    public @Nullable ComponentName getProfileOwnerAsUser(final int userId)
5516            throws IllegalArgumentException {
5517        if (mService != null) {
5518            try {
5519                return mService.getProfileOwner(userId);
5520            } catch (RemoteException re) {
5521                throw re.rethrowFromSystemServer();
5522            }
5523        }
5524        return null;
5525    }
5526
5527    /**
5528     * @hide
5529     * @return the human readable name of the organisation associated with this DPM or {@code null}
5530     *         if one is not set.
5531     * @throws IllegalArgumentException if the userId is invalid.
5532     */
5533    public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
5534        if (mService != null) {
5535            try {
5536                return mService.getProfileOwnerName(Process.myUserHandle().getIdentifier());
5537            } catch (RemoteException re) {
5538                throw re.rethrowFromSystemServer();
5539            }
5540        }
5541        return null;
5542    }
5543
5544    /**
5545     * @hide
5546     * @param userId The user for whom to fetch the profile owner name, if any.
5547     * @return the human readable name of the organisation associated with this profile owner or
5548     *         null if one is not set.
5549     * @throws IllegalArgumentException if the userId is invalid.
5550     */
5551    @SystemApi
5552    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5553    public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
5554        throwIfParentInstance("getProfileOwnerNameAsUser");
5555        if (mService != null) {
5556            try {
5557                return mService.getProfileOwnerName(userId);
5558            } catch (RemoteException re) {
5559                throw re.rethrowFromSystemServer();
5560            }
5561        }
5562        return null;
5563    }
5564
5565    /**
5566     * Called by a profile owner or device owner to add a default intent handler activity for
5567     * intents that match a certain intent filter. This activity will remain the default intent
5568     * handler even if the set of potential event handlers for the intent filter changes and if the
5569     * intent preferences are reset.
5570     * <p>
5571     * The default disambiguation mechanism takes over if the activity is not installed (anymore).
5572     * When the activity is (re)installed, it is automatically reset as default intent handler for
5573     * the filter.
5574     * <p>
5575     * The calling device admin must be a profile owner or device owner. If it is not, a security
5576     * exception will be thrown.
5577     *
5578     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5579     * @param filter The IntentFilter for which a default handler is added.
5580     * @param activity The Activity that is added as default intent handler.
5581     * @throws SecurityException if {@code admin} is not a device or profile owner.
5582     */
5583    public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
5584            @NonNull ComponentName activity) {
5585        throwIfParentInstance("addPersistentPreferredActivity");
5586        if (mService != null) {
5587            try {
5588                mService.addPersistentPreferredActivity(admin, filter, activity);
5589            } catch (RemoteException e) {
5590                throw e.rethrowFromSystemServer();
5591            }
5592        }
5593    }
5594
5595    /**
5596     * Called by a profile owner or device owner to remove all persistent intent handler preferences
5597     * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
5598     * <p>
5599     * The calling device admin must be a profile owner. If it is not, a security exception will be
5600     * thrown.
5601     *
5602     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5603     * @param packageName The name of the package for which preferences are removed.
5604     * @throws SecurityException if {@code admin} is not a device or profile owner.
5605     */
5606    public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
5607            String packageName) {
5608        throwIfParentInstance("clearPackagePersistentPreferredActivities");
5609        if (mService != null) {
5610            try {
5611                mService.clearPackagePersistentPreferredActivities(admin, packageName);
5612            } catch (RemoteException e) {
5613                throw e.rethrowFromSystemServer();
5614            }
5615        }
5616    }
5617
5618    /**
5619     * Called by a profile owner or device owner to grant permission to a package to manage
5620     * application restrictions for the calling user via {@link #setApplicationRestrictions} and
5621     * {@link #getApplicationRestrictions}.
5622     * <p>
5623     * This permission is persistent until it is later cleared by calling this method with a
5624     * {@code null} value or uninstalling the managing package.
5625     * <p>
5626     * The supplied application restriction managing package must be installed when calling this
5627     * API, otherwise an {@link NameNotFoundException} will be thrown.
5628     *
5629     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5630     * @param packageName The package name which will be given access to application restrictions
5631     *            APIs. If {@code null} is given the current package will be cleared.
5632     * @throws SecurityException if {@code admin} is not a device or profile owner.
5633     * @throws NameNotFoundException if {@code packageName} is not found
5634     *
5635     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5636     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5637     */
5638    @Deprecated
5639    public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
5640            @Nullable String packageName) throws NameNotFoundException {
5641        throwIfParentInstance("setApplicationRestrictionsManagingPackage");
5642        if (mService != null) {
5643            try {
5644                if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
5645                    throw new NameNotFoundException(packageName);
5646                }
5647            } catch (RemoteException e) {
5648                throw e.rethrowFromSystemServer();
5649            }
5650        }
5651    }
5652
5653    /**
5654     * Called by a profile owner or device owner to retrieve the application restrictions managing
5655     * package for the current user, or {@code null} if none is set. If there are multiple
5656     * delegates this function will return one of them.
5657     *
5658     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5659     * @return The package name allowed to manage application restrictions on the current user, or
5660     *         {@code null} if none is set.
5661     * @throws SecurityException if {@code admin} is not a device or profile owner.
5662     *
5663     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5664     * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
5665     */
5666    @Deprecated
5667    @Nullable
5668    public String getApplicationRestrictionsManagingPackage(
5669            @NonNull ComponentName admin) {
5670        throwIfParentInstance("getApplicationRestrictionsManagingPackage");
5671        if (mService != null) {
5672            try {
5673                return mService.getApplicationRestrictionsManagingPackage(admin);
5674            } catch (RemoteException e) {
5675                throw e.rethrowFromSystemServer();
5676            }
5677        }
5678        return null;
5679    }
5680
5681    /**
5682     * Called by any application to find out whether it has been granted permission via
5683     * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
5684     * for the calling user.
5685     *
5686     * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
5687     * that method.
5688     *
5689     * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
5690     * instead.
5691     */
5692    @Deprecated
5693    public boolean isCallerApplicationRestrictionsManagingPackage() {
5694        throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
5695        if (mService != null) {
5696            try {
5697                return mService.isCallerApplicationRestrictionsManagingPackage(
5698                        mContext.getPackageName());
5699            } catch (RemoteException e) {
5700                throw e.rethrowFromSystemServer();
5701            }
5702        }
5703        return false;
5704    }
5705
5706    /**
5707     * Sets the application restrictions for a given target application running in the calling user.
5708     * <p>
5709     * The caller must be a profile or device owner on that user, or the package allowed to manage
5710     * application restrictions via {@link #setDelegatedScopes} with the
5711     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
5712     * <p>
5713     * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
5714     * <ul>
5715     * <li>{@code boolean}
5716     * <li>{@code int}
5717     * <li>{@code String} or {@code String[]}
5718     * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
5719     * </ul>
5720     * <p>
5721     * If the restrictions are not available yet, but may be applied in the near future, the caller
5722     * can notify the target application of that by adding
5723     * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
5724     * <p>
5725     * The application restrictions are only made visible to the target application via
5726     * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
5727     * owner, and the application restrictions managing package via
5728     * {@link #getApplicationRestrictions}.
5729     *
5730     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
5731     *
5732     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5733     *            {@code null} if called by the application restrictions managing package.
5734     * @param packageName The name of the package to update restricted settings for.
5735     * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
5736     *            set of active restrictions.
5737     * @throws SecurityException if {@code admin} is not a device or profile owner.
5738     * @see #setDelegatedScopes
5739     * @see #DELEGATION_APP_RESTRICTIONS
5740     * @see UserManager#KEY_RESTRICTIONS_PENDING
5741     */
5742    @WorkerThread
5743    public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
5744            Bundle settings) {
5745        throwIfParentInstance("setApplicationRestrictions");
5746        if (mService != null) {
5747            try {
5748                mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
5749                        settings);
5750            } catch (RemoteException e) {
5751                throw e.rethrowFromSystemServer();
5752            }
5753        }
5754    }
5755
5756    /**
5757     * Sets a list of configuration features to enable for a TrustAgent component. This is meant to
5758     * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
5759     * agents but those enabled by this function call. If flag
5760     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
5761     * <p>
5762     * The calling device admin must have requested
5763     * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
5764     * if not, a security exception will be thrown.
5765     * <p>
5766     * This method can be called on the {@link DevicePolicyManager} instance returned by
5767     * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
5768     * the parent profile.
5769     *
5770     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5771     * @param target Component name of the agent to be enabled.
5772     * @param configuration TrustAgent-specific feature bundle. If null for any admin, agent will be
5773     *            strictly disabled according to the state of the
5774     *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS} flag.
5775     *            <p>
5776     *            If {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is set and options is not null for all
5777     *            admins, then it's up to the TrustAgent itself to aggregate the values from all
5778     *            device admins.
5779     *            <p>
5780     *            Consult documentation for the specific TrustAgent to determine legal options
5781     *            parameters.
5782     * @throws SecurityException if {@code admin} is not an active administrator or does not use
5783     *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
5784     */
5785    public void setTrustAgentConfiguration(@NonNull ComponentName admin,
5786            @NonNull ComponentName target, PersistableBundle configuration) {
5787        if (mService != null) {
5788            try {
5789                mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
5790            } catch (RemoteException e) {
5791                throw e.rethrowFromSystemServer();
5792            }
5793        }
5794    }
5795
5796    /**
5797     * Gets configuration for the given trust agent based on aggregating all calls to
5798     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
5799     * all device admins.
5800     * <p>
5801     * This method can be called on the {@link DevicePolicyManager} instance returned by
5802     * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
5803     * on the parent profile.
5804     *
5805     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
5806     * this function returns a list of configurations for all admins that declare
5807     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
5808     * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
5809     * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
5810     * for this {@param agent} or calls it with a null configuration, null is returned.
5811     * @param agent Which component to get enabled features for.
5812     * @return configuration for the given trust agent.
5813     */
5814    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5815            @Nullable ComponentName admin, @NonNull ComponentName agent) {
5816        return getTrustAgentConfiguration(admin, agent, myUserId());
5817    }
5818
5819    /** @hide per-user version */
5820    public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
5821            @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
5822        if (mService != null) {
5823            try {
5824                return mService.getTrustAgentConfiguration(admin, agent, userHandle,
5825                        mParentInstance);
5826            } catch (RemoteException e) {
5827                throw e.rethrowFromSystemServer();
5828            }
5829        }
5830        return new ArrayList<PersistableBundle>(); // empty list
5831    }
5832
5833    /**
5834     * Called by a profile owner of a managed profile to set whether caller-Id information from the
5835     * managed profile will be shown in the parent profile, for incoming calls.
5836     * <p>
5837     * The calling device admin must be a profile owner. If it is not, a security exception will be
5838     * thrown.
5839     *
5840     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5841     * @param disabled If true caller-Id information in the managed profile is not displayed.
5842     * @throws SecurityException if {@code admin} is not a device or profile owner.
5843     */
5844    public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
5845        throwIfParentInstance("setCrossProfileCallerIdDisabled");
5846        if (mService != null) {
5847            try {
5848                mService.setCrossProfileCallerIdDisabled(admin, disabled);
5849            } catch (RemoteException e) {
5850                throw e.rethrowFromSystemServer();
5851            }
5852        }
5853    }
5854
5855    /**
5856     * Called by a profile owner of a managed profile to determine whether or not caller-Id
5857     * information has been disabled.
5858     * <p>
5859     * The calling device admin must be a profile owner. If it is not, a security exception will be
5860     * thrown.
5861     *
5862     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5863     * @throws SecurityException if {@code admin} is not a device or profile owner.
5864     */
5865    public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
5866        throwIfParentInstance("getCrossProfileCallerIdDisabled");
5867        if (mService != null) {
5868            try {
5869                return mService.getCrossProfileCallerIdDisabled(admin);
5870            } catch (RemoteException e) {
5871                throw e.rethrowFromSystemServer();
5872            }
5873        }
5874        return false;
5875    }
5876
5877    /**
5878     * Determine whether or not caller-Id information has been disabled.
5879     *
5880     * @param userHandle The user for whom to check the caller-id permission
5881     * @hide
5882     */
5883    public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
5884        if (mService != null) {
5885            try {
5886                return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
5887            } catch (RemoteException e) {
5888                throw e.rethrowFromSystemServer();
5889            }
5890        }
5891        return false;
5892    }
5893
5894    /**
5895     * Called by a profile owner of a managed profile to set whether contacts search from the
5896     * managed profile will be shown in the parent profile, for incoming calls.
5897     * <p>
5898     * The calling device admin must be a profile owner. If it is not, a security exception will be
5899     * thrown.
5900     *
5901     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5902     * @param disabled If true contacts search in the managed profile is not displayed.
5903     * @throws SecurityException if {@code admin} is not a device or profile owner.
5904     */
5905    public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
5906            boolean disabled) {
5907        throwIfParentInstance("setCrossProfileContactsSearchDisabled");
5908        if (mService != null) {
5909            try {
5910                mService.setCrossProfileContactsSearchDisabled(admin, disabled);
5911            } catch (RemoteException e) {
5912                throw e.rethrowFromSystemServer();
5913            }
5914        }
5915    }
5916
5917    /**
5918     * Called by a profile owner of a managed profile to determine whether or not contacts search
5919     * has been disabled.
5920     * <p>
5921     * The calling device admin must be a profile owner. If it is not, a security exception will be
5922     * thrown.
5923     *
5924     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5925     * @throws SecurityException if {@code admin} is not a device or profile owner.
5926     */
5927    public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
5928        throwIfParentInstance("getCrossProfileContactsSearchDisabled");
5929        if (mService != null) {
5930            try {
5931                return mService.getCrossProfileContactsSearchDisabled(admin);
5932            } catch (RemoteException e) {
5933                throw e.rethrowFromSystemServer();
5934            }
5935        }
5936        return false;
5937    }
5938
5939
5940    /**
5941     * Determine whether or not contacts search has been disabled.
5942     *
5943     * @param userHandle The user for whom to check the contacts search permission
5944     * @hide
5945     */
5946    public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
5947        if (mService != null) {
5948            try {
5949                return mService
5950                        .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
5951            } catch (RemoteException e) {
5952                throw e.rethrowFromSystemServer();
5953            }
5954        }
5955        return false;
5956    }
5957
5958    /**
5959     * Start Quick Contact on the managed profile for the user, if the policy allows.
5960     *
5961     * @hide
5962     */
5963    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5964            boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
5965        if (mService != null) {
5966            try {
5967                mService.startManagedQuickContact(actualLookupKey, actualContactId,
5968                        isContactIdIgnored, directoryId, originalIntent);
5969            } catch (RemoteException e) {
5970                throw e.rethrowFromSystemServer();
5971            }
5972        }
5973    }
5974
5975    /**
5976     * Start Quick Contact on the managed profile for the user, if the policy allows.
5977     * @hide
5978     */
5979    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5980            Intent originalIntent) {
5981        startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
5982                originalIntent);
5983    }
5984
5985    /**
5986     * Called by a profile owner of a managed profile to set whether bluetooth devices can access
5987     * enterprise contacts.
5988     * <p>
5989     * The calling device admin must be a profile owner. If it is not, a security exception will be
5990     * thrown.
5991     * <p>
5992     * This API works on managed profile only.
5993     *
5994     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5995     * @param disabled If true, bluetooth devices cannot access enterprise contacts.
5996     * @throws SecurityException if {@code admin} is not a device or profile owner.
5997     */
5998    public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
5999        throwIfParentInstance("setBluetoothContactSharingDisabled");
6000        if (mService != null) {
6001            try {
6002                mService.setBluetoothContactSharingDisabled(admin, disabled);
6003            } catch (RemoteException e) {
6004                throw e.rethrowFromSystemServer();
6005            }
6006        }
6007    }
6008
6009    /**
6010     * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
6011     * cannot access enterprise contacts.
6012     * <p>
6013     * The calling device admin must be a profile owner. If it is not, a security exception will be
6014     * thrown.
6015     * <p>
6016     * This API works on managed profile only.
6017     *
6018     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6019     * @throws SecurityException if {@code admin} is not a device or profile owner.
6020     */
6021    public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
6022        throwIfParentInstance("getBluetoothContactSharingDisabled");
6023        if (mService != null) {
6024            try {
6025                return mService.getBluetoothContactSharingDisabled(admin);
6026            } catch (RemoteException e) {
6027                throw e.rethrowFromSystemServer();
6028            }
6029        }
6030        return true;
6031    }
6032
6033    /**
6034     * Determine whether or not Bluetooth devices cannot access contacts.
6035     * <p>
6036     * This API works on managed profile UserHandle only.
6037     *
6038     * @param userHandle The user for whom to check the caller-id permission
6039     * @hide
6040     */
6041    public boolean getBluetoothContactSharingDisabled(UserHandle userHandle) {
6042        if (mService != null) {
6043            try {
6044                return mService.getBluetoothContactSharingDisabledForUser(userHandle
6045                        .getIdentifier());
6046            } catch (RemoteException e) {
6047                throw e.rethrowFromSystemServer();
6048            }
6049        }
6050        return true;
6051    }
6052
6053    /**
6054     * Called by the profile owner of a managed profile so that some intents sent in the managed
6055     * profile can also be resolved in the parent, or vice versa. Only activity intents are
6056     * supported.
6057     *
6058     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6059     * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
6060     *            other profile
6061     * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
6062     *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
6063     * @throws SecurityException if {@code admin} is not a device or profile owner.
6064     */
6065    public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
6066        throwIfParentInstance("addCrossProfileIntentFilter");
6067        if (mService != null) {
6068            try {
6069                mService.addCrossProfileIntentFilter(admin, filter, flags);
6070            } catch (RemoteException e) {
6071                throw e.rethrowFromSystemServer();
6072            }
6073        }
6074    }
6075
6076    /**
6077     * Called by a profile owner of a managed profile to remove the cross-profile intent filters
6078     * that go from the managed profile to the parent, or from the parent to the managed profile.
6079     * Only removes those that have been set by the profile owner.
6080     * <p>
6081     * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
6082     * the profile is created, some of them ensure the proper functioning of the profile, while
6083     * others enable sharing of data from the parent to the managed profile for user convenience.
6084     * These default intent filters are not cleared when this API is called. If the default cross
6085     * profile data sharing is not desired, they can be disabled with
6086     * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
6087     *
6088     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6089     * @throws SecurityException if {@code admin} is not a device or profile owner.
6090     */
6091    public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
6092        throwIfParentInstance("clearCrossProfileIntentFilters");
6093        if (mService != null) {
6094            try {
6095                mService.clearCrossProfileIntentFilters(admin);
6096            } catch (RemoteException e) {
6097                throw e.rethrowFromSystemServer();
6098            }
6099        }
6100    }
6101
6102    /**
6103     * Called by a profile or device owner to set the permitted accessibility services. When set by
6104     * a device owner or profile owner the restriction applies to all profiles of the user the
6105     * device owner or profile owner is an admin for. By default the user can use any accessiblity
6106     * service. When zero or more packages have been added, accessiblity services that are not in
6107     * the list and not part of the system can not be enabled by the user.
6108     * <p>
6109     * Calling with a null value for the list disables the restriction so that all services can be
6110     * used, calling with an empty list only allows the builtin system's services.
6111     * <p>
6112     * System accessibility services are always available to the user the list can't modify this.
6113     *
6114     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6115     * @param packageNames List of accessibility service package names.
6116     * @return true if setting the restriction succeeded. It fail if there is one or more non-system
6117     *         accessibility services enabled, that are not in the list.
6118     * @throws SecurityException if {@code admin} is not a device or profile owner.
6119     */
6120    public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
6121            List<String> packageNames) {
6122        throwIfParentInstance("setPermittedAccessibilityServices");
6123        if (mService != null) {
6124            try {
6125                return mService.setPermittedAccessibilityServices(admin, packageNames);
6126            } catch (RemoteException e) {
6127                throw e.rethrowFromSystemServer();
6128            }
6129        }
6130        return false;
6131    }
6132
6133    /**
6134     * Returns the list of permitted accessibility services set by this device or profile owner.
6135     * <p>
6136     * An empty list means no accessibility services except system services are allowed. Null means
6137     * all accessibility services are allowed.
6138     *
6139     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6140     * @return List of accessiblity service package names.
6141     * @throws SecurityException if {@code admin} is not a device or profile owner.
6142     */
6143    public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
6144        throwIfParentInstance("getPermittedAccessibilityServices");
6145        if (mService != null) {
6146            try {
6147                return mService.getPermittedAccessibilityServices(admin);
6148            } catch (RemoteException e) {
6149                throw e.rethrowFromSystemServer();
6150            }
6151        }
6152        return null;
6153    }
6154
6155    /**
6156     * Called by the system to check if a specific accessibility service is disabled by admin.
6157     *
6158     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6159     * @param packageName Accessibility service package name that needs to be checked.
6160     * @param userHandle user id the admin is running as.
6161     * @return true if the accessibility service is permitted, otherwise false.
6162     *
6163     * @hide
6164     */
6165    public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
6166            @NonNull String packageName, int userHandle) {
6167        if (mService != null) {
6168            try {
6169                return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
6170                        userHandle);
6171            } catch (RemoteException e) {
6172                throw e.rethrowFromSystemServer();
6173            }
6174        }
6175        return false;
6176    }
6177
6178    /**
6179     * Returns the list of accessibility services permitted by the device or profiles
6180     * owners of this user.
6181     *
6182     * <p>Null means all accessibility services are allowed, if a non-null list is returned
6183     * it will contain the intersection of the permitted lists for any device or profile
6184     * owners that apply to this user. It will also include any system accessibility services.
6185     *
6186     * @param userId which user to check for.
6187     * @return List of accessiblity service package names.
6188     * @hide
6189     */
6190     @SystemApi
6191     public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
6192        throwIfParentInstance("getPermittedAccessibilityServices");
6193        if (mService != null) {
6194            try {
6195                return mService.getPermittedAccessibilityServicesForUser(userId);
6196            } catch (RemoteException e) {
6197                throw e.rethrowFromSystemServer();
6198            }
6199        }
6200        return null;
6201     }
6202
6203    /**
6204     * Called by a profile or device owner to set the permitted input methods services. When set by
6205     * a device owner or profile owner the restriction applies to all profiles of the user the
6206     * device owner or profile owner is an admin for. By default the user can use any input method.
6207     * When zero or more packages have been added, input method that are not in the list and not
6208     * part of the system can not be enabled by the user. This method will fail if it is called for
6209     * a admin that is not for the foreground user or a profile of the foreground user.
6210     * <p>
6211     * Calling with a null value for the list disables the restriction so that all input methods can
6212     * be used, calling with an empty list disables all but the system's own input methods.
6213     * <p>
6214     * System input methods are always available to the user this method can't modify this.
6215     *
6216     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6217     * @param packageNames List of input method package names.
6218     * @return true if setting the restriction succeeded. It will fail if there are one or more
6219     *         non-system input methods currently enabled that are not in the packageNames list.
6220     * @throws SecurityException if {@code admin} is not a device or profile owner.
6221     */
6222    public boolean setPermittedInputMethods(
6223            @NonNull ComponentName admin, List<String> packageNames) {
6224        throwIfParentInstance("setPermittedInputMethods");
6225        if (mService != null) {
6226            try {
6227                return mService.setPermittedInputMethods(admin, packageNames);
6228            } catch (RemoteException e) {
6229                throw e.rethrowFromSystemServer();
6230            }
6231        }
6232        return false;
6233    }
6234
6235
6236    /**
6237     * Returns the list of permitted input methods set by this device or profile owner.
6238     * <p>
6239     * An empty list means no input methods except system input methods are allowed. Null means all
6240     * input methods are allowed.
6241     *
6242     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6243     * @return List of input method package names.
6244     * @throws SecurityException if {@code admin} is not a device or profile owner.
6245     */
6246    public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
6247        throwIfParentInstance("getPermittedInputMethods");
6248        if (mService != null) {
6249            try {
6250                return mService.getPermittedInputMethods(admin);
6251            } catch (RemoteException e) {
6252                throw e.rethrowFromSystemServer();
6253            }
6254        }
6255        return null;
6256    }
6257
6258    /**
6259     * Called by the system to check if a specific input method is disabled by admin.
6260     *
6261     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6262     * @param packageName Input method package name that needs to be checked.
6263     * @param userHandle user id the admin is running as.
6264     * @return true if the input method is permitted, otherwise false.
6265     *
6266     * @hide
6267     */
6268    public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
6269            @NonNull String packageName, int userHandle) {
6270        if (mService != null) {
6271            try {
6272                return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
6273            } catch (RemoteException e) {
6274                throw e.rethrowFromSystemServer();
6275            }
6276        }
6277        return false;
6278    }
6279
6280    /**
6281     * Returns the list of input methods permitted by the device or profiles
6282     * owners of the current user.  (*Not* calling user, due to a limitation in InputMethodManager.)
6283     *
6284     * <p>Null means all input methods are allowed, if a non-null list is returned
6285     * it will contain the intersection of the permitted lists for any device or profile
6286     * owners that apply to this user. It will also include any system input methods.
6287     *
6288     * @return List of input method package names.
6289     * @hide
6290     */
6291    @SystemApi
6292    public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
6293        throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
6294        if (mService != null) {
6295            try {
6296                return mService.getPermittedInputMethodsForCurrentUser();
6297            } catch (RemoteException e) {
6298                throw e.rethrowFromSystemServer();
6299            }
6300        }
6301        return null;
6302    }
6303
6304    /**
6305     * Called by a profile owner of a managed profile to set the packages that are allowed to use
6306     * a {@link android.service.notification.NotificationListenerService} in the primary user to
6307     * see notifications from the managed profile. By default all packages are permitted by this
6308     * policy. When zero or more packages have been added, notification listeners installed on the
6309     * primary user that are not in the list and are not part of the system won't receive events
6310     * for managed profile notifications.
6311     * <p>
6312     * Calling with a {@code null} value for the list disables the restriction so that all
6313     * notification listener services be used. Calling with an empty list disables all but the
6314     * system's own notification listeners. System notification listener services are always
6315     * available to the user.
6316     * <p>
6317     * If a device or profile owner want to stop notification listeners in their user from seeing
6318     * that user's notifications they should prevent that service from running instead (e.g. via
6319     * {@link #setApplicationHidden(ComponentName, String, boolean)})
6320     *
6321     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6322     * @param packageList List of package names to whitelist
6323     * @return true if setting the restriction succeeded. It will fail if called outside a managed
6324     * profile
6325     * @throws SecurityException if {@code admin} is not a profile owner.
6326     *
6327     * @see android.service.notification.NotificationListenerService
6328     */
6329    public boolean setPermittedCrossProfileNotificationListeners(
6330            @NonNull ComponentName admin, @Nullable List<String> packageList) {
6331        throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
6332        if (mService != null) {
6333            try {
6334                return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
6335            } catch (RemoteException e) {
6336                throw e.rethrowFromSystemServer();
6337            }
6338        }
6339        return false;
6340    }
6341
6342    /**
6343     * Returns the list of packages installed on the primary user that allowed to use a
6344     * {@link android.service.notification.NotificationListenerService} to receive
6345     * notifications from this managed profile, as set by the profile owner.
6346     * <p>
6347     * An empty list means no notification listener services except system ones are allowed.
6348     * A {@code null} return value indicates that all notification listeners are allowed.
6349     */
6350    public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
6351            @NonNull ComponentName admin) {
6352        throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
6353        if (mService != null) {
6354            try {
6355                return mService.getPermittedCrossProfileNotificationListeners(admin);
6356            } catch (RemoteException e) {
6357                throw e.rethrowFromSystemServer();
6358            }
6359        }
6360        return null;
6361    }
6362
6363    /**
6364     * Returns true if {@code NotificationListenerServices} from the given package are allowed to
6365     * receive events for notifications from the given user id. Can only be called by the system uid
6366     *
6367     * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
6368     *
6369     * @hide
6370     */
6371    public boolean isNotificationListenerServicePermitted(
6372            @NonNull String packageName, @UserIdInt int userId) {
6373        if (mService != null) {
6374            try {
6375                return mService.isNotificationListenerServicePermitted(packageName, userId);
6376            } catch (RemoteException e) {
6377                throw e.rethrowFromSystemServer();
6378            }
6379        }
6380        return true;
6381    }
6382
6383    /**
6384     * Get the list of apps to keep around as APKs even if no user has currently installed it. This
6385     * function can be called by a device owner or by a delegate given the
6386     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
6387     * <p>
6388     * Please note that packages returned in this method are not automatically pre-cached.
6389     *
6390     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6391     *            {@code null} if the caller is a keep uninstalled packages delegate.
6392     * @return List of package names to keep cached.
6393     * @see #setDelegatedScopes
6394     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
6395     */
6396    public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
6397        throwIfParentInstance("getKeepUninstalledPackages");
6398        if (mService != null) {
6399            try {
6400                return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
6401            } catch (RemoteException e) {
6402                throw e.rethrowFromSystemServer();
6403            }
6404        }
6405        return null;
6406    }
6407
6408    /**
6409     * Set a list of apps to keep around as APKs even if no user has currently installed it. This
6410     * function can be called by a device owner or by a delegate given the
6411     * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
6412     *
6413     * <p>Please note that setting this policy does not imply that specified apps will be
6414     * automatically pre-cached.</p>
6415     *
6416     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6417     *            {@code null} if the caller is a keep uninstalled packages delegate.
6418     * @param packageNames List of package names to keep cached.
6419     * @throws SecurityException if {@code admin} is not a device owner.
6420     * @see #setDelegatedScopes
6421     * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
6422     */
6423    public void setKeepUninstalledPackages(@Nullable ComponentName admin,
6424            @NonNull List<String> packageNames) {
6425        throwIfParentInstance("setKeepUninstalledPackages");
6426        if (mService != null) {
6427            try {
6428                mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
6429            } catch (RemoteException e) {
6430                throw e.rethrowFromSystemServer();
6431            }
6432        }
6433    }
6434
6435    /**
6436     * Called by a device owner to create a user with the specified name. The UserHandle returned
6437     * by this method should not be persisted as user handles are recycled as users are removed and
6438     * created. If you need to persist an identifier for this user, use
6439     * {@link UserManager#getSerialNumberForUser}.
6440     *
6441     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6442     * @param name the user's name
6443     * @see UserHandle
6444     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6445     *         user could not be created.
6446     *
6447     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
6448     * @removed From {@link android.os.Build.VERSION_CODES#N}
6449     */
6450    @Deprecated
6451    public @Nullable UserHandle createUser(@NonNull ComponentName admin, String name) {
6452        return null;
6453    }
6454
6455    /**
6456     * Called by a device owner to create a user with the specified name. The UserHandle returned
6457     * by this method should not be persisted as user handles are recycled as users are removed and
6458     * created. If you need to persist an identifier for this user, use
6459     * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
6460     * immediately.
6461     *
6462     * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
6463     * as registered as an active admin on the new user.  The profile owner package will be
6464     * installed on the new user if it already is installed on the device.
6465     *
6466     * <p>If the optionalInitializeData is not null, then the extras will be passed to the
6467     * profileOwnerComponent when onEnable is called.
6468     *
6469     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6470     * @param name the user's name
6471     * @param ownerName the human readable name of the organisation associated with this DPM.
6472     * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
6473     *      the user.
6474     * @param adminExtras Extras that will be passed to onEnable of the admin receiver
6475     *      on the new user.
6476     * @see UserHandle
6477     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6478     *         user could not be created.
6479     *
6480     * @deprecated From {@link android.os.Build.VERSION_CODES#M}
6481     * @removed From {@link android.os.Build.VERSION_CODES#N}
6482     */
6483    @Deprecated
6484    public @Nullable UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
6485            String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
6486        return null;
6487    }
6488
6489    /**
6490      * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
6491      */
6492    public static final int SKIP_SETUP_WIZARD = 0x0001;
6493
6494    /**
6495     * Flag used by {@link #createAndManageUser} to specify that the user should be created
6496     * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
6497     * device.
6498     */
6499    public static final int MAKE_USER_EPHEMERAL = 0x0002;
6500
6501    /**
6502     * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
6503     * demo user.
6504     * @hide
6505     */
6506    public static final int MAKE_USER_DEMO = 0x0004;
6507
6508    /**
6509     * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
6510     * the disabling of system apps during provisioning.
6511     */
6512    public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
6513
6514    /**
6515     * @hide
6516     */
6517    @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
6518            SKIP_SETUP_WIZARD,
6519            MAKE_USER_EPHEMERAL,
6520            MAKE_USER_DEMO,
6521            LEAVE_ALL_SYSTEM_APPS_ENABLED
6522    })
6523    @Retention(RetentionPolicy.SOURCE)
6524    public @interface CreateAndManageUserFlags {}
6525
6526
6527    /**
6528     * Called by a device owner to create a user with the specified name and a given component of
6529     * the calling package as profile owner. The UserHandle returned by this method should not be
6530     * persisted as user handles are recycled as users are removed and created. If you need to
6531     * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
6532     * user will not be started in the background.
6533     * <p>
6534     * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
6535     * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
6536     * be registered as an active admin on the new user. The profile owner package will be installed
6537     * on the new user.
6538     * <p>
6539     * If the adminExtras are not null, they will be stored on the device until the user is started
6540     * for the first time. Then the extras will be passed to the admin when onEnable is called.
6541     *
6542     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6543     * @param name The user's name.
6544     * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
6545     *            same package as admin, otherwise no user is created and an
6546     *            IllegalArgumentException is thrown.
6547     * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
6548     *            user.
6549     * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
6550     *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
6551     * @see UserHandle
6552     * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
6553     *         user could not be created.
6554     * @throws SecurityException if {@code admin} is not a device owner.
6555     */
6556    public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
6557            @NonNull String name,
6558            @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
6559            @CreateAndManageUserFlags int flags) {
6560        throwIfParentInstance("createAndManageUser");
6561        try {
6562            return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
6563        } catch (RemoteException re) {
6564            throw re.rethrowFromSystemServer();
6565        }
6566    }
6567
6568    /**
6569     * Called by a device owner to remove a user/profile and all associated data. The primary user
6570     * can not be removed.
6571     *
6572     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6573     * @param userHandle the user to remove.
6574     * @return {@code true} if the user was removed, {@code false} otherwise.
6575     * @throws SecurityException if {@code admin} is not a device owner.
6576     */
6577    public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6578        throwIfParentInstance("removeUser");
6579        try {
6580            return mService.removeUser(admin, userHandle);
6581        } catch (RemoteException re) {
6582            throw re.rethrowFromSystemServer();
6583        }
6584    }
6585
6586    /**
6587     * Called by a device owner to switch the specified secondary user to the foreground.
6588     *
6589     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6590     * @param userHandle the user to switch to; null will switch to primary.
6591     * @return {@code true} if the switch was successful, {@code false} otherwise.
6592     * @throws SecurityException if {@code admin} is not a device owner.
6593     * @see Intent#ACTION_USER_FOREGROUND
6594     * @see #getSecondaryUsers(ComponentName)
6595     */
6596    public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
6597        throwIfParentInstance("switchUser");
6598        try {
6599            return mService.switchUser(admin, userHandle);
6600        } catch (RemoteException re) {
6601            throw re.rethrowFromSystemServer();
6602        }
6603    }
6604
6605    /**
6606     * Called by a device owner to start the specified secondary user in background.
6607     *
6608     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6609     * @param userHandle the user to be stopped.
6610     * @return {@code true} if the user can be started, {@code false} otherwise.
6611     * @throws SecurityException if {@code admin} is not a device owner.
6612     * @see #getSecondaryUsers(ComponentName)
6613     */
6614    public boolean startUserInBackground(
6615            @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6616        throwIfParentInstance("startUserInBackground");
6617        try {
6618            return mService.startUserInBackground(admin, userHandle);
6619        } catch (RemoteException re) {
6620            throw re.rethrowFromSystemServer();
6621        }
6622    }
6623
6624    /**
6625     * Called by a device owner to stop the specified secondary user.
6626     *
6627     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6628     * @param userHandle the user to be stopped.
6629     * @return {@code true} if the user can be stopped, {@code false} otherwise.
6630     * @throws SecurityException if {@code admin} is not a device owner.
6631     * @see #getSecondaryUsers(ComponentName)
6632     */
6633    public boolean stopUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
6634        throwIfParentInstance("stopUser");
6635        try {
6636            return mService.stopUser(admin, userHandle);
6637        } catch (RemoteException re) {
6638            throw re.rethrowFromSystemServer();
6639        }
6640    }
6641
6642    /**
6643     * Called by a profile owner of secondary user that is affiliated with the device to stop the
6644     * calling user and switch back to primary.
6645     *
6646     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6647     * @return {@code true} if the exit was successful, {@code false} otherwise.
6648     * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
6649     * @see #getSecondaryUsers(ComponentName)
6650     */
6651    public boolean logoutUser(@NonNull ComponentName admin) {
6652        throwIfParentInstance("logoutUser");
6653        try {
6654            return mService.logoutUser(admin);
6655        } catch (RemoteException re) {
6656            throw re.rethrowFromSystemServer();
6657        }
6658    }
6659
6660    /**
6661     * Called by a device owner to list all secondary users on the device. Managed profiles are not
6662     * considered as secondary users.
6663     * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
6664     * and {@link #stopUser}.
6665     *
6666     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6667     * @return list of other {@link UserHandle}s on the device.
6668     * @throws SecurityException if {@code admin} is not a device owner.
6669     * @see #removeUser(ComponentName, UserHandle)
6670     * @see #switchUser(ComponentName, UserHandle)
6671     * @see #startUserInBackground(ComponentName, UserHandle)
6672     * @see #stopUser(ComponentName, UserHandle)
6673     */
6674    public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
6675        throwIfParentInstance("getSecondaryUsers");
6676        try {
6677            return mService.getSecondaryUsers(admin);
6678        } catch (RemoteException re) {
6679            throw re.rethrowFromSystemServer();
6680        }
6681    }
6682
6683    /**
6684     * Checks if the profile owner is running in an ephemeral user.
6685     *
6686     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6687     * @return whether the profile owner is running in an ephemeral user.
6688     */
6689    public boolean isEphemeralUser(@NonNull ComponentName admin) {
6690        throwIfParentInstance("isEphemeralUser");
6691        try {
6692            return mService.isEphemeralUser(admin);
6693        } catch (RemoteException re) {
6694            throw re.rethrowFromSystemServer();
6695        }
6696    }
6697
6698    /**
6699     * Retrieves the application restrictions for a given target application running in the calling
6700     * user.
6701     * <p>
6702     * The caller must be a profile or device owner on that user, or the package allowed to manage
6703     * application restrictions via {@link #setDelegatedScopes} with the
6704     * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
6705     *
6706     * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
6707     *
6708     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6709     *            {@code null} if called by the application restrictions managing package.
6710     * @param packageName The name of the package to fetch restricted settings of.
6711     * @return {@link Bundle} of settings corresponding to what was set last time
6712     *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
6713     *         {@link Bundle} if no restrictions have been set.
6714     * @throws SecurityException if {@code admin} is not a device or profile owner.
6715     * @see #setDelegatedScopes
6716     * @see #DELEGATION_APP_RESTRICTIONS
6717     */
6718    @WorkerThread
6719    public @NonNull Bundle getApplicationRestrictions(
6720            @Nullable ComponentName admin, String packageName) {
6721        throwIfParentInstance("getApplicationRestrictions");
6722        if (mService != null) {
6723            try {
6724                return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
6725                        packageName);
6726            } catch (RemoteException e) {
6727                throw e.rethrowFromSystemServer();
6728            }
6729        }
6730        return null;
6731    }
6732
6733    /**
6734     * Called by a profile or device owner to set a user restriction specified by the key.
6735     * <p>
6736     * The calling device admin must be a profile or device owner; if it is not, a security
6737     * exception will be thrown.
6738     *
6739     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6740     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6741     *            for the list of keys.
6742     * @throws SecurityException if {@code admin} is not a device or profile owner.
6743     */
6744    public void addUserRestriction(@NonNull ComponentName admin, String key) {
6745        throwIfParentInstance("addUserRestriction");
6746        if (mService != null) {
6747            try {
6748                mService.setUserRestriction(admin, key, true);
6749            } catch (RemoteException e) {
6750                throw e.rethrowFromSystemServer();
6751            }
6752        }
6753    }
6754
6755    /**
6756     * Called by a profile or device owner to clear a user restriction specified by the key.
6757     * <p>
6758     * The calling device admin must be a profile or device owner; if it is not, a security
6759     * exception will be thrown.
6760     *
6761     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6762     * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
6763     *            for the list of keys.
6764     * @throws SecurityException if {@code admin} is not a device or profile owner.
6765     */
6766    public void clearUserRestriction(@NonNull ComponentName admin, String key) {
6767        throwIfParentInstance("clearUserRestriction");
6768        if (mService != null) {
6769            try {
6770                mService.setUserRestriction(admin, key, false);
6771            } catch (RemoteException e) {
6772                throw e.rethrowFromSystemServer();
6773            }
6774        }
6775    }
6776
6777    /**
6778     * Called by a profile or device owner to get user restrictions set with
6779     * {@link #addUserRestriction(ComponentName, String)}.
6780     * <p>
6781     * The target user may have more restrictions set by the system or other device owner / profile
6782     * owner. To get all the user restrictions currently set, use
6783     * {@link UserManager#getUserRestrictions()}.
6784     *
6785     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6786     * @throws SecurityException if {@code admin} is not a device or profile owner.
6787     */
6788    public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
6789        throwIfParentInstance("getUserRestrictions");
6790        Bundle ret = null;
6791        if (mService != null) {
6792            try {
6793                ret = mService.getUserRestrictions(admin);
6794            } catch (RemoteException e) {
6795                throw e.rethrowFromSystemServer();
6796            }
6797        }
6798        return ret == null ? new Bundle() : ret;
6799    }
6800
6801    /**
6802     * Called by any app to display a support dialog when a feature was disabled by an admin.
6803     * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
6804     * display the dialog. It will tell the user that the feature indicated by {@code restriction}
6805     * was disabled by an admin, and include a link for more information. The default content of
6806     * the dialog can be changed by the restricting admin via
6807     * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
6808     * set (i.e. the feature is available), then the return value will be {@code null}.
6809     * @param restriction Indicates for which feature the dialog should be displayed. Can be a
6810     *            user restriction from {@link UserManager}, e.g.
6811     *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
6812     *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
6813     * @return Intent An intent to be used to start the dialog-activity if the restriction is
6814     *            set by an admin, or null if the restriction does not exist or no admin set it.
6815     */
6816    public Intent createAdminSupportIntent(@NonNull String restriction) {
6817        throwIfParentInstance("createAdminSupportIntent");
6818        if (mService != null) {
6819            try {
6820                return mService.createAdminSupportIntent(restriction);
6821            } catch (RemoteException e) {
6822                throw e.rethrowFromSystemServer();
6823            }
6824        }
6825        return null;
6826    }
6827
6828    /**
6829     * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
6830     * actual package file remain. This function can be called by a device owner, profile owner, or
6831     * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6832     * {@link #setDelegatedScopes}.
6833     *
6834     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6835     *            {@code null} if the caller is a package access delegate.
6836     * @param packageName The name of the package to hide or unhide.
6837     * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
6838     *            unhidden.
6839     * @return boolean Whether the hidden setting of the package was successfully updated.
6840     * @throws SecurityException if {@code admin} is not a device or profile owner.
6841     * @see #setDelegatedScopes
6842     * @see #DELEGATION_PACKAGE_ACCESS
6843     */
6844    public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
6845            boolean hidden) {
6846        throwIfParentInstance("setApplicationHidden");
6847        if (mService != null) {
6848            try {
6849                return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
6850                        hidden);
6851            } catch (RemoteException e) {
6852                throw e.rethrowFromSystemServer();
6853            }
6854        }
6855        return false;
6856    }
6857
6858    /**
6859     * Determine if a package is hidden. This function can be called by a device owner, profile
6860     * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6861     * {@link #setDelegatedScopes}.
6862     *
6863     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6864     *            {@code null} if the caller is a package access delegate.
6865     * @param packageName The name of the package to retrieve the hidden status of.
6866     * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
6867     * @throws SecurityException if {@code admin} is not a device or profile owner.
6868     * @see #setDelegatedScopes
6869     * @see #DELEGATION_PACKAGE_ACCESS
6870     */
6871    public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
6872        throwIfParentInstance("isApplicationHidden");
6873        if (mService != null) {
6874            try {
6875                return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName);
6876            } catch (RemoteException e) {
6877                throw e.rethrowFromSystemServer();
6878            }
6879        }
6880        return false;
6881    }
6882
6883    /**
6884     * Re-enable a system app that was disabled by default when the user was initialized. This
6885     * function can be called by a device owner, profile owner, or by a delegate given the
6886     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6887     *
6888     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6889     *            {@code null} if the caller is an enable system app delegate.
6890     * @param packageName The package to be re-enabled in the calling profile.
6891     * @throws SecurityException if {@code admin} is not a device or profile owner.
6892     * @see #setDelegatedScopes
6893     * @see #DELEGATION_PACKAGE_ACCESS
6894     */
6895    public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
6896        throwIfParentInstance("enableSystemApp");
6897        if (mService != null) {
6898            try {
6899                mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
6900            } catch (RemoteException e) {
6901                throw e.rethrowFromSystemServer();
6902            }
6903        }
6904    }
6905
6906    /**
6907     * Re-enable system apps by intent that were disabled by default when the user was initialized.
6908     * This function can be called by a device owner, profile owner, or by a delegate given the
6909     * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
6910     *
6911     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6912     *            {@code null} if the caller is an enable system app delegate.
6913     * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
6914     *            intent will be re-enabled in the calling profile.
6915     * @return int The number of activities that matched the intent and were installed.
6916     * @throws SecurityException if {@code admin} is not a device or profile owner.
6917     * @see #setDelegatedScopes
6918     * @see #DELEGATION_PACKAGE_ACCESS
6919     */
6920    public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
6921        throwIfParentInstance("enableSystemApp");
6922        if (mService != null) {
6923            try {
6924                return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
6925            } catch (RemoteException e) {
6926                throw e.rethrowFromSystemServer();
6927            }
6928        }
6929        return 0;
6930    }
6931
6932    /**
6933     * Install an existing package that has been installed in another user, or has been kept after
6934     * removal via {@link #setKeepUninstalledPackages}.
6935     * This function can be called by a device owner, profile owner or a delegate given
6936     * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
6937     * When called in a secondary user or managed profile, the user/profile must be affiliated with
6938     * the device. See {@link #isAffiliatedUser}.
6939     *
6940     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6941     * @param packageName The package to be installed in the calling profile.
6942     * @return {@code true} if the app is installed; {@code false} otherwise.
6943     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
6944     * an affiliated user or profile.
6945     * @see #setKeepUninstalledPackages
6946     * @see #setDelegatedScopes
6947     * @see #isAffiliatedUser
6948     * @see #DELEGATION_PACKAGE_ACCESS
6949     */
6950    public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
6951        throwIfParentInstance("installExistingPackage");
6952        if (mService != null) {
6953            try {
6954                return mService.installExistingPackage(admin, mContext.getPackageName(),
6955                        packageName);
6956            } catch (RemoteException e) {
6957                throw e.rethrowFromSystemServer();
6958            }
6959        }
6960        return false;
6961    }
6962
6963    /**
6964     * Called by a device owner or profile owner to disable account management for a specific type
6965     * of account.
6966     * <p>
6967     * The calling device admin must be a device owner or profile owner. If it is not, a security
6968     * exception will be thrown.
6969     * <p>
6970     * When account management is disabled for an account type, adding or removing an account of
6971     * that type will not be possible.
6972     * <p>
6973     * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
6974     * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
6975     * management for a specific type is disabled.
6976     *
6977     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6978     * @param accountType For which account management is disabled or enabled.
6979     * @param disabled The boolean indicating that account management will be disabled (true) or
6980     *            enabled (false).
6981     * @throws SecurityException if {@code admin} is not a device or profile owner.
6982     */
6983    public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
6984            boolean disabled) {
6985        throwIfParentInstance("setAccountManagementDisabled");
6986        if (mService != null) {
6987            try {
6988                mService.setAccountManagementDisabled(admin, accountType, disabled);
6989            } catch (RemoteException e) {
6990                throw e.rethrowFromSystemServer();
6991            }
6992        }
6993    }
6994
6995    /**
6996     * Gets the array of accounts for which account management is disabled by the profile owner.
6997     *
6998     * <p> Account management can be disabled/enabled by calling
6999     * {@link #setAccountManagementDisabled}.
7000     *
7001     * @return a list of account types for which account management has been disabled.
7002     *
7003     * @see #setAccountManagementDisabled
7004     */
7005    public @Nullable String[] getAccountTypesWithManagementDisabled() {
7006        throwIfParentInstance("getAccountTypesWithManagementDisabled");
7007        return getAccountTypesWithManagementDisabledAsUser(myUserId());
7008    }
7009
7010    /**
7011     * @see #getAccountTypesWithManagementDisabled()
7012     * @hide
7013     */
7014    public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7015        if (mService != null) {
7016            try {
7017                return mService.getAccountTypesWithManagementDisabledAsUser(userId);
7018            } catch (RemoteException e) {
7019                throw e.rethrowFromSystemServer();
7020            }
7021        }
7022
7023        return null;
7024    }
7025
7026    /**
7027     * Sets which packages may enter lock task mode.
7028     * <p>
7029     * Any packages that share uid with an allowed package will also be allowed to activate lock
7030     * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
7031     * package list results in locked tasks belonging to those packages to be finished.
7032     * <p>
7033     * This function can only be called by the device owner or by a profile owner of a user/profile
7034     * that is affiliated with the device. See {@link #isAffiliatedUser}. Any packages
7035     * set via this method will be cleared if the user becomes unaffiliated.
7036     *
7037     * @param packages The list of packages allowed to enter lock task mode
7038     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7039     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
7040     * an affiliated user or profile.
7041     * @see #isAffiliatedUser
7042     * @see Activity#startLockTask()
7043     * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
7044     * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
7045     * @see UserManager#DISALLOW_CREATE_WINDOWS
7046     */
7047    public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
7048            throws SecurityException {
7049        throwIfParentInstance("setLockTaskPackages");
7050        if (mService != null) {
7051            try {
7052                mService.setLockTaskPackages(admin, packages);
7053            } catch (RemoteException e) {
7054                throw e.rethrowFromSystemServer();
7055            }
7056        }
7057    }
7058
7059    /**
7060     * Returns the list of packages allowed to start the lock task mode.
7061     *
7062     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
7063     * an affiliated user or profile.
7064     * @see #isAffiliatedUser
7065     * @see #setLockTaskPackages
7066     */
7067    public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
7068        throwIfParentInstance("getLockTaskPackages");
7069        if (mService != null) {
7070            try {
7071                return mService.getLockTaskPackages(admin);
7072            } catch (RemoteException e) {
7073                throw e.rethrowFromSystemServer();
7074            }
7075        }
7076        return new String[0];
7077    }
7078
7079    /**
7080     * This function lets the caller know whether the given component is allowed to start the
7081     * lock task mode.
7082     * @param pkg The package to check
7083     */
7084    public boolean isLockTaskPermitted(String pkg) {
7085        throwIfParentInstance("isLockTaskPermitted");
7086        if (mService != null) {
7087            try {
7088                return mService.isLockTaskPermitted(pkg);
7089            } catch (RemoteException e) {
7090                throw e.rethrowFromSystemServer();
7091            }
7092        }
7093        return false;
7094    }
7095
7096    /**
7097     * Sets which system features to enable for LockTask mode.
7098     * <p>
7099     * Feature flags set through this method will only take effect for the duration when the device
7100     * is in LockTask mode. If this method is not called, none of the features listed here will be
7101     * enabled.
7102     * <p>
7103     * This function can only be called by the device owner or by a profile owner of a user/profile
7104     * that is affiliated with the device. See {@link #isAffiliatedUser}. Any features
7105     * set via this method will be cleared if the user becomes unaffiliated.
7106     *
7107     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7108     * @param flags Bitfield of feature flags:
7109     *              {@link #LOCK_TASK_FEATURE_NONE} (default),
7110     *              {@link #LOCK_TASK_FEATURE_SYSTEM_INFO},
7111     *              {@link #LOCK_TASK_FEATURE_NOTIFICATIONS},
7112     *              {@link #LOCK_TASK_FEATURE_HOME},
7113     *              {@link #LOCK_TASK_FEATURE_RECENTS},
7114     *              {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS},
7115     *              {@link #LOCK_TASK_FEATURE_KEYGUARD}
7116     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
7117     * an affiliated user or profile.
7118     * @see #isAffiliatedUser
7119     */
7120    public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
7121        throwIfParentInstance("setLockTaskFeatures");
7122        if (mService != null) {
7123            try {
7124                mService.setLockTaskFeatures(admin, flags);
7125            } catch (RemoteException e) {
7126                throw e.rethrowFromSystemServer();
7127            }
7128        }
7129    }
7130
7131    /**
7132     * Gets which system features are enabled for LockTask mode.
7133     *
7134     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7135     * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
7136     * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
7137     * an affiliated user or profile.
7138     * @see #isAffiliatedUser
7139     * @see #setLockTaskFeatures
7140     */
7141    public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
7142        throwIfParentInstance("getLockTaskFeatures");
7143        if (mService != null) {
7144            try {
7145                return mService.getLockTaskFeatures(admin);
7146            } catch (RemoteException e) {
7147                throw e.rethrowFromSystemServer();
7148            }
7149        }
7150        return 0;
7151    }
7152
7153    /**
7154     * Called by device owner to update {@link android.provider.Settings.Global} settings.
7155     * Validation that the value of the setting is in the correct form for the setting type should
7156     * be performed by the caller.
7157     * <p>
7158     * The settings that can be updated with this method are:
7159     * <ul>
7160     * <li>{@link android.provider.Settings.Global#ADB_ENABLED}</li>
7161     * <li>{@link android.provider.Settings.Global#AUTO_TIME}</li>
7162     * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE}</li>
7163     * <li>{@link android.provider.Settings.Global#DATA_ROAMING}</li>
7164     * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
7165     * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}</li>
7166     * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
7167     * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
7168     * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
7169     * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
7170     * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
7171     * </ul>
7172     * <p>
7173     * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
7174     * <ul>
7175     * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
7176     * {@link android.bluetooth.BluetoothAdapter#enable()} and
7177     * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
7178     * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
7179     * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
7180     * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
7181     * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
7182     * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
7183     * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
7184     * </ul>
7185     *
7186     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7187     * @param setting The name of the setting to update.
7188     * @param value The value to update the setting to.
7189     * @throws SecurityException if {@code admin} is not a device owner.
7190     */
7191    public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
7192        throwIfParentInstance("setGlobalSetting");
7193        if (mService != null) {
7194            try {
7195                mService.setGlobalSetting(admin, setting, value);
7196            } catch (RemoteException e) {
7197                throw e.rethrowFromSystemServer();
7198            }
7199        }
7200    }
7201
7202    /**
7203     * Called by device owner to update {@link android.provider.Settings.System} settings.
7204     * Validation that the value of the setting is in the correct form for the setting type should
7205     * be performed by the caller.
7206     * <p>
7207     * The settings that can be updated with this method are:
7208     * <ul>
7209     * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
7210     * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
7211     * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
7212     * </ul>
7213     * <p>
7214     *
7215     * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
7216     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7217     * @param setting The name of the setting to update.
7218     * @param value The value to update the setting to.
7219     * @throws SecurityException if {@code admin} is not a device owner.
7220     */
7221    public void setSystemSetting(@NonNull ComponentName admin, @NonNull String setting,
7222            String value) {
7223        throwIfParentInstance("setSystemSetting");
7224        if (mService != null) {
7225            try {
7226                mService.setSystemSetting(admin, setting, value);
7227            } catch (RemoteException e) {
7228                throw e.rethrowFromSystemServer();
7229            }
7230        }
7231    }
7232
7233    /**
7234     * Called by device owner to set the system wall clock time. This only takes effect if called
7235     * when {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false} will be
7236     * returned.
7237     *
7238     * @param admin Which {@link DeviceAdminReceiver} this request is associated with
7239     * @param millis time in milliseconds since the Epoch
7240     * @return {@code true} if set time succeeded, {@code false} otherwise.
7241     * @throws SecurityException if {@code admin} is not a device owner.
7242     */
7243    public boolean setTime(@NonNull ComponentName admin, long millis) {
7244        throwIfParentInstance("setTime");
7245        if (mService != null) {
7246            try {
7247                return mService.setTime(admin, millis);
7248            } catch (RemoteException e) {
7249                throw e.rethrowFromSystemServer();
7250            }
7251        }
7252        return false;
7253    }
7254
7255    /**
7256     * Called by device owner to set the system's persistent default time zone. This only takes
7257     * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE} is 0, otherwise
7258     * {@code false} will be returned.
7259     *
7260     * @see android.app.AlarmManager#setTimeZone(String)
7261     * @param admin Which {@link DeviceAdminReceiver} this request is associated with
7262     * @param timeZone one of the Olson ids from the list returned by
7263     *     {@link java.util.TimeZone#getAvailableIDs}
7264     * @return {@code true} if set timezone succeeded, {@code false} otherwise.
7265     * @throws SecurityException if {@code admin} is not a device owner.
7266     */
7267    public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
7268        throwIfParentInstance("setTimeZone");
7269        if (mService != null) {
7270            try {
7271                return mService.setTimeZone(admin, timeZone);
7272            } catch (RemoteException e) {
7273                throw e.rethrowFromSystemServer();
7274            }
7275        }
7276        return false;
7277    }
7278
7279    /**
7280     * Called by profile or device owners to update {@link android.provider.Settings.Secure}
7281     * settings. Validation that the value of the setting is in the correct form for the setting
7282     * type should be performed by the caller.
7283     * <p>
7284     * The settings that can be updated by a profile or device owner with this method are:
7285     * <ul>
7286     * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
7287     * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
7288     * </ul>
7289     * <p>
7290     * A device owner can additionally update the following settings:
7291     * <ul>
7292     * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}</li>
7293     * </ul>
7294     *
7295     * <strong>Note: Starting from Android O, apps should no longer call this method with the
7296     * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
7297     * deprecated. Instead, device owners or profile owners should use the restriction
7298     * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
7299     * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
7300     * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
7301     * an {@link UnsupportedOperationException} is thrown.
7302     * </strong>
7303     *
7304     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7305     * @param setting The name of the setting to update.
7306     * @param value The value to update the setting to.
7307     * @throws SecurityException if {@code admin} is not a device or profile owner.
7308     */
7309    public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
7310        throwIfParentInstance("setSecureSetting");
7311        if (mService != null) {
7312            try {
7313                mService.setSecureSetting(admin, setting, value);
7314            } catch (RemoteException e) {
7315                throw e.rethrowFromSystemServer();
7316            }
7317        }
7318    }
7319
7320    /**
7321     * Designates a specific service component as the provider for making permission requests of a
7322     * local or remote administrator of the user.
7323     * <p/>
7324     * Only a profile owner can designate the restrictions provider.
7325     *
7326     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7327     * @param provider The component name of the service that implements
7328     *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
7329     *            provider previously assigned.
7330     * @throws SecurityException if {@code admin} is not a device or profile owner.
7331     */
7332    public void setRestrictionsProvider(@NonNull ComponentName admin,
7333            @Nullable ComponentName provider) {
7334        throwIfParentInstance("setRestrictionsProvider");
7335        if (mService != null) {
7336            try {
7337                mService.setRestrictionsProvider(admin, provider);
7338            } catch (RemoteException re) {
7339                throw re.rethrowFromSystemServer();
7340            }
7341        }
7342    }
7343
7344    /**
7345     * Called by profile or device owners to set the master volume mute on or off.
7346     * This has no effect when set on a managed profile.
7347     *
7348     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7349     * @param on {@code true} to mute master volume, {@code false} to turn mute off.
7350     * @throws SecurityException if {@code admin} is not a device or profile owner.
7351     */
7352    public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
7353        throwIfParentInstance("setMasterVolumeMuted");
7354        if (mService != null) {
7355            try {
7356                mService.setMasterVolumeMuted(admin, on);
7357            } catch (RemoteException re) {
7358                throw re.rethrowFromSystemServer();
7359            }
7360        }
7361    }
7362
7363    /**
7364     * Called by profile or device owners to check whether the master volume mute is on or off.
7365     *
7366     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7367     * @return {@code true} if master volume is muted, {@code false} if it's not.
7368     * @throws SecurityException if {@code admin} is not a device or profile owner.
7369     */
7370    public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
7371        throwIfParentInstance("isMasterVolumeMuted");
7372        if (mService != null) {
7373            try {
7374                return mService.isMasterVolumeMuted(admin);
7375            } catch (RemoteException re) {
7376                throw re.rethrowFromSystemServer();
7377            }
7378        }
7379        return false;
7380    }
7381
7382    /**
7383     * Change whether a user can uninstall a package. This function can be called by a device owner,
7384     * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
7385     * {@link #setDelegatedScopes}.
7386     *
7387     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7388     *             {@code null} if the caller is a block uninstall delegate.
7389     * @param packageName package to change.
7390     * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
7391     * @throws SecurityException if {@code admin} is not a device or profile owner.
7392     * @see #setDelegatedScopes
7393     * @see #DELEGATION_BLOCK_UNINSTALL
7394     */
7395    public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
7396            boolean uninstallBlocked) {
7397        throwIfParentInstance("setUninstallBlocked");
7398        if (mService != null) {
7399            try {
7400                mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
7401                    uninstallBlocked);
7402            } catch (RemoteException re) {
7403                throw re.rethrowFromSystemServer();
7404            }
7405        }
7406    }
7407
7408    /**
7409     * Check whether the user has been blocked by device policy from uninstalling a package.
7410     * Requires the caller to be the profile owner if checking a specific admin's policy.
7411     * <p>
7412     * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
7413     * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
7414     * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
7415     * will cause a NullPointerException to be raised.
7416     *
7417     * @param admin The name of the admin component whose blocking policy will be checked, or
7418     *            {@code null} to check whether any admin has blocked the uninstallation.
7419     * @param packageName package to check.
7420     * @return true if uninstallation is blocked.
7421     * @throws SecurityException if {@code admin} is not a device or profile owner.
7422     */
7423    public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
7424        throwIfParentInstance("isUninstallBlocked");
7425        if (mService != null) {
7426            try {
7427                return mService.isUninstallBlocked(admin, packageName);
7428            } catch (RemoteException re) {
7429                throw re.rethrowFromSystemServer();
7430            }
7431        }
7432        return false;
7433    }
7434
7435    /**
7436     * Called by the profile owner of a managed profile to enable widget providers from a given
7437     * package to be available in the parent profile. As a result the user will be able to add
7438     * widgets from the white-listed package running under the profile to a widget host which runs
7439     * under the parent profile, for example the home screen. Note that a package may have zero or
7440     * more provider components, where each component provides a different widget type.
7441     * <p>
7442     * <strong>Note:</strong> By default no widget provider package is white-listed.
7443     *
7444     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7445     * @param packageName The package from which widget providers are white-listed.
7446     * @return Whether the package was added.
7447     * @throws SecurityException if {@code admin} is not a profile owner.
7448     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
7449     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
7450     */
7451    public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
7452        throwIfParentInstance("addCrossProfileWidgetProvider");
7453        if (mService != null) {
7454            try {
7455                return mService.addCrossProfileWidgetProvider(admin, packageName);
7456            } catch (RemoteException re) {
7457                throw re.rethrowFromSystemServer();
7458            }
7459        }
7460        return false;
7461    }
7462
7463    /**
7464     * Called by the profile owner of a managed profile to disable widget providers from a given
7465     * package to be available in the parent profile. For this method to take effect the package
7466     * should have been added via
7467     * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
7468     * <p>
7469     * <strong>Note:</strong> By default no widget provider package is white-listed.
7470     *
7471     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7472     * @param packageName The package from which widget providers are no longer white-listed.
7473     * @return Whether the package was removed.
7474     * @throws SecurityException if {@code admin} is not a profile owner.
7475     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
7476     * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
7477     */
7478    public boolean removeCrossProfileWidgetProvider(
7479            @NonNull ComponentName admin, String packageName) {
7480        throwIfParentInstance("removeCrossProfileWidgetProvider");
7481        if (mService != null) {
7482            try {
7483                return mService.removeCrossProfileWidgetProvider(admin, packageName);
7484            } catch (RemoteException re) {
7485                throw re.rethrowFromSystemServer();
7486            }
7487        }
7488        return false;
7489    }
7490
7491    /**
7492     * Called by the profile owner of a managed profile to query providers from which packages are
7493     * available in the parent profile.
7494     *
7495     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7496     * @return The white-listed package list.
7497     * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
7498     * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
7499     * @throws SecurityException if {@code admin} is not a profile owner.
7500     */
7501    public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
7502        throwIfParentInstance("getCrossProfileWidgetProviders");
7503        if (mService != null) {
7504            try {
7505                List<String> providers = mService.getCrossProfileWidgetProviders(admin);
7506                if (providers != null) {
7507                    return providers;
7508                }
7509            } catch (RemoteException re) {
7510                throw re.rethrowFromSystemServer();
7511            }
7512        }
7513        return Collections.emptyList();
7514    }
7515
7516    /**
7517     * Called by profile or device owners to set the user's photo.
7518     *
7519     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7520     * @param icon the bitmap to set as the photo.
7521     * @throws SecurityException if {@code admin} is not a device or profile owner.
7522     */
7523    public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
7524        throwIfParentInstance("setUserIcon");
7525        try {
7526            mService.setUserIcon(admin, icon);
7527        } catch (RemoteException re) {
7528            throw re.rethrowFromSystemServer();
7529        }
7530    }
7531
7532    /**
7533     * Called by device owners to set a local system update policy. When a new policy is set,
7534     * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
7535     *
7536     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
7537     *            components in the device owner package can set system update policies and the most
7538     *            recent policy takes effect.
7539     * @param policy the new policy, or {@code null} to clear the current policy.
7540     * @throws SecurityException if {@code admin} is not a device owner.
7541     * @see SystemUpdatePolicy
7542     */
7543    public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
7544        throwIfParentInstance("setSystemUpdatePolicy");
7545        if (mService != null) {
7546            try {
7547                mService.setSystemUpdatePolicy(admin, policy);
7548            } catch (RemoteException re) {
7549                throw re.rethrowFromSystemServer();
7550            }
7551        }
7552    }
7553
7554    /**
7555     * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
7556     *
7557     * @return The current policy object, or {@code null} if no policy is set.
7558     */
7559    public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
7560        throwIfParentInstance("getSystemUpdatePolicy");
7561        if (mService != null) {
7562            try {
7563                return mService.getSystemUpdatePolicy();
7564            } catch (RemoteException re) {
7565                throw re.rethrowFromSystemServer();
7566            }
7567        }
7568        return null;
7569    }
7570
7571    /**
7572     * Called by a device owner or profile owner of secondary users that is affiliated with the
7573     * device to disable the keyguard altogether.
7574     * <p>
7575     * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
7576     * type. However, this call has no effect if a password, pin or pattern is currently set. If a
7577     * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
7578     * disabled.
7579     *
7580     * <p>
7581     * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
7582     * keyguard if it is currently shown.
7583     *
7584     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7585     * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
7586     * @return {@code false} if attempting to disable the keyguard while a lock password was in
7587     *         place. {@code true} otherwise.
7588     * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
7589     * secondary user that is affiliated with the device.
7590     * @see #isAffiliatedUser
7591     * @see #getSecondaryUsers
7592     */
7593    public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
7594        throwIfParentInstance("setKeyguardDisabled");
7595        try {
7596            return mService.setKeyguardDisabled(admin, disabled);
7597        } catch (RemoteException re) {
7598            throw re.rethrowFromSystemServer();
7599        }
7600    }
7601
7602    /**
7603     * Called by device owner or profile owner of secondary users  that is affiliated with the
7604     * device to disable the status bar. Disabling the status bar blocks notifications, quick
7605     * settings and other screen overlays that allow escaping from a single use device.
7606     * <p>
7607     * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
7608     * status bar in LockTask mode can be configured with
7609     * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
7610     * LockTask mode will be registered, but will only take effect when the device leaves LockTask
7611     * mode.
7612     *
7613     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7614     * @param disabled {@code true} disables the status bar, {@code false} reenables it.
7615     * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
7616     * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
7617     * secondary user that is affiliated with the device.
7618     * @see #isAffiliatedUser
7619     * @see #getSecondaryUsers
7620     */
7621    public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
7622        throwIfParentInstance("setStatusBarDisabled");
7623        try {
7624            return mService.setStatusBarDisabled(admin, disabled);
7625        } catch (RemoteException re) {
7626            throw re.rethrowFromSystemServer();
7627        }
7628    }
7629
7630    /**
7631     * Called by the system update service to notify device and profile owners of pending system
7632     * updates.
7633     *
7634     * This method should only be used when it is unknown whether the pending system
7635     * update is a security patch. Otherwise, use
7636     * {@link #notifyPendingSystemUpdate(long, boolean)}.
7637     *
7638     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
7639     *         indicating when the current pending update was first available. {@code -1} if no
7640     *         update is available.
7641     * @see #notifyPendingSystemUpdate(long, boolean)
7642     * @hide
7643     */
7644    @SystemApi
7645    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
7646    public void notifyPendingSystemUpdate(long updateReceivedTime) {
7647        throwIfParentInstance("notifyPendingSystemUpdate");
7648        if (mService != null) {
7649            try {
7650                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
7651            } catch (RemoteException re) {
7652                throw re.rethrowFromSystemServer();
7653            }
7654        }
7655    }
7656
7657    /**
7658     * Called by the system update service to notify device and profile owners of pending system
7659     * updates.
7660     *
7661     * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
7662     * when it is known whether the pending system update is a security patch.
7663     *
7664     * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
7665     *         indicating when the current pending update was first available. {@code -1} if no
7666     *         update is available.
7667     * @param isSecurityPatch {@code true} if this system update is purely a security patch;
7668     *         {@code false} if not.
7669     * @see #notifyPendingSystemUpdate(long)
7670     * @hide
7671     */
7672    @SystemApi
7673    @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
7674    public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
7675        throwIfParentInstance("notifyPendingSystemUpdate");
7676        if (mService != null) {
7677            try {
7678                mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
7679                        isSecurityPatch));
7680            } catch (RemoteException re) {
7681                throw re.rethrowFromSystemServer();
7682            }
7683        }
7684    }
7685
7686    /**
7687     * Called by device or profile owners to get information about a pending system update.
7688     *
7689     * @param admin Which profile or device owner this request is associated with.
7690     * @return Information about a pending system update or {@code null} if no update pending.
7691     * @throws SecurityException if {@code admin} is not a device or profile owner.
7692     * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
7693     */
7694    public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
7695        throwIfParentInstance("getPendingSystemUpdate");
7696        try {
7697            return mService.getPendingSystemUpdate(admin);
7698        } catch (RemoteException re) {
7699            throw re.rethrowFromSystemServer();
7700        }
7701    }
7702
7703    /**
7704     * Set the default response for future runtime permission requests by applications. This
7705     * function can be called by a device owner, profile owner, or by a delegate given the
7706     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7707     * The policy can allow for normal operation which prompts the user to grant a permission, or
7708     * can allow automatic granting or denying of runtime permission requests by an application.
7709     * This also applies to new permissions declared by app updates. When a permission is denied or
7710     * granted this way, the effect is equivalent to setting the permission * grant state via
7711     * {@link #setPermissionGrantState}.
7712     * <p/>
7713     * As this policy only acts on runtime permission requests, it only applies to applications
7714     * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
7715     *
7716     * @param admin Which profile or device owner this request is associated with.
7717     * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
7718     *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
7719     * @throws SecurityException if {@code admin} is not a device or profile owner.
7720     * @see #setPermissionGrantState
7721     * @see #setDelegatedScopes
7722     * @see #DELEGATION_PERMISSION_GRANT
7723     */
7724    public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
7725        throwIfParentInstance("setPermissionPolicy");
7726        try {
7727            mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
7728        } catch (RemoteException re) {
7729            throw re.rethrowFromSystemServer();
7730        }
7731    }
7732
7733    /**
7734     * Returns the current runtime permission policy set by the device or profile owner. The
7735     * default is {@link #PERMISSION_POLICY_PROMPT}.
7736     *
7737     * @param admin Which profile or device owner this request is associated with.
7738     * @return the current policy for future permission requests.
7739     */
7740    public int getPermissionPolicy(ComponentName admin) {
7741        throwIfParentInstance("getPermissionPolicy");
7742        try {
7743            return mService.getPermissionPolicy(admin);
7744        } catch (RemoteException re) {
7745            throw re.rethrowFromSystemServer();
7746        }
7747    }
7748
7749    /**
7750     * Sets the grant state of a runtime permission for a specific application. The state can be
7751     * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
7752     * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
7753     * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
7754     * the permission is granted and the user cannot manage it through the UI. This might affect all
7755     * permissions in a group that the runtime permission belongs to. This method can only be called
7756     * by a profile owner, device owner, or a delegate given the
7757     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7758     * <p/>
7759     * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
7760     * the permission. It retains the previous grant, if any.
7761     * <p/>
7762     * Permissions can be granted or revoked only for applications built with a
7763     * {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
7764     *
7765     * @param admin Which profile or device owner this request is associated with.
7766     * @param packageName The application to grant or revoke a permission to.
7767     * @param permission The permission to grant or revoke.
7768     * @param grantState The permission grant state which is one of
7769     *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
7770     *            {@link #PERMISSION_GRANT_STATE_GRANTED},
7771     * @return whether the permission was successfully granted or revoked.
7772     * @throws SecurityException if {@code admin} is not a device or profile owner.
7773     * @see #PERMISSION_GRANT_STATE_DENIED
7774     * @see #PERMISSION_GRANT_STATE_DEFAULT
7775     * @see #PERMISSION_GRANT_STATE_GRANTED
7776     * @see #setDelegatedScopes
7777     * @see #DELEGATION_PERMISSION_GRANT
7778     */
7779    public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName,
7780            String permission, int grantState) {
7781        throwIfParentInstance("setPermissionGrantState");
7782        try {
7783            return mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
7784                    permission, grantState);
7785        } catch (RemoteException re) {
7786            throw re.rethrowFromSystemServer();
7787        }
7788    }
7789
7790    /**
7791     * Returns the current grant state of a runtime permission for a specific application. This
7792     * function can be called by a device owner, profile owner, or by a delegate given the
7793     * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
7794     *
7795     * @param admin Which profile or device owner this request is associated with, or {@code null}
7796     *            if the caller is a permission grant delegate.
7797     * @param packageName The application to check the grant state for.
7798     * @param permission The permission to check for.
7799     * @return the current grant state specified by device policy. If the profile or device owner
7800     *         has not set a grant state, the return value is
7801     *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
7802     *         permission is currently granted for the package.
7803     *         <p/>
7804     *         If a grant state was set by the profile or device owner, then the return value will
7805     *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
7806     *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
7807     *         currently denied or granted.
7808     * @throws SecurityException if {@code admin} is not a device or profile owner.
7809     * @see #setPermissionGrantState(ComponentName, String, String, int)
7810     * @see PackageManager#checkPermission(String, String)
7811     * @see #setDelegatedScopes
7812     * @see #DELEGATION_PERMISSION_GRANT
7813     */
7814    public int getPermissionGrantState(@Nullable ComponentName admin, String packageName,
7815            String permission) {
7816        throwIfParentInstance("getPermissionGrantState");
7817        try {
7818            return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
7819                    permission);
7820        } catch (RemoteException re) {
7821            throw re.rethrowFromSystemServer();
7822        }
7823    }
7824
7825    /**
7826     * Returns whether it is possible for the caller to initiate provisioning of a managed profile
7827     * or device, setting itself as the device or profile owner.
7828     *
7829     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7830     * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
7831     * @return whether provisioning a managed profile or device is possible.
7832     * @throws IllegalArgumentException if the supplied action is not valid.
7833     */
7834    public boolean isProvisioningAllowed(@NonNull String action) {
7835        throwIfParentInstance("isProvisioningAllowed");
7836        try {
7837            return mService.isProvisioningAllowed(action, mContext.getPackageName());
7838        } catch (RemoteException re) {
7839            throw re.rethrowFromSystemServer();
7840        }
7841    }
7842
7843    /**
7844     * Checks whether it is possible to initiate provisioning a managed device,
7845     * profile or user, setting the given package as owner.
7846     *
7847     * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
7848     *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
7849     *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
7850     *        {@link #ACTION_PROVISION_MANAGED_USER}
7851     * @param packageName The package of the component that would be set as device, user, or profile
7852     *        owner.
7853     * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
7854     * @hide
7855     */
7856    public @ProvisioningPreCondition int checkProvisioningPreCondition(
7857            String action, @NonNull String packageName) {
7858        try {
7859            return mService.checkProvisioningPreCondition(action, packageName);
7860        } catch (RemoteException re) {
7861            throw re.rethrowFromSystemServer();
7862        }
7863    }
7864
7865    /**
7866     * Return if this user is a managed profile of another user. An admin can become the profile
7867     * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
7868     * user with {@link #createAndManageUser}
7869     * @param admin Which profile owner this request is associated with.
7870     * @return if this user is a managed profile of another user.
7871     */
7872    public boolean isManagedProfile(@NonNull ComponentName admin) {
7873        throwIfParentInstance("isManagedProfile");
7874        try {
7875            return mService.isManagedProfile(admin);
7876        } catch (RemoteException re) {
7877            throw re.rethrowFromSystemServer();
7878        }
7879    }
7880
7881    /**
7882     * @hide
7883     * Return if this user is a system-only user. An admin can manage a device from a system only
7884     * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
7885     * @param admin Which device owner this request is associated with.
7886     * @return if this user is a system-only user.
7887     */
7888    public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
7889        try {
7890            return mService.isSystemOnlyUser(admin);
7891        } catch (RemoteException re) {
7892            throw re.rethrowFromSystemServer();
7893        }
7894    }
7895
7896    /**
7897     * Called by device owner to get the MAC address of the Wi-Fi device.
7898     *
7899     * @param admin Which device owner this request is associated with.
7900     * @return the MAC address of the Wi-Fi device, or null when the information is not available.
7901     *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
7902     *         <p>
7903     *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
7904     * @throws SecurityException if {@code admin} is not a device owner.
7905     */
7906    public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
7907        throwIfParentInstance("getWifiMacAddress");
7908        try {
7909            return mService.getWifiMacAddress(admin);
7910        } catch (RemoteException re) {
7911            throw re.rethrowFromSystemServer();
7912        }
7913    }
7914
7915    /**
7916     * Called by device owner to reboot the device. If there is an ongoing call on the device,
7917     * throws an {@link IllegalStateException}.
7918     * @param admin Which device owner the request is associated with.
7919     * @throws IllegalStateException if device has an ongoing call.
7920     * @throws SecurityException if {@code admin} is not a device owner.
7921     * @see TelephonyManager#CALL_STATE_IDLE
7922     */
7923    public void reboot(@NonNull ComponentName admin) {
7924        throwIfParentInstance("reboot");
7925        try {
7926            mService.reboot(admin);
7927        } catch (RemoteException re) {
7928            throw re.rethrowFromSystemServer();
7929        }
7930    }
7931
7932    /**
7933     * Called by a device admin to set the short support message. This will be displayed to the user
7934     * in settings screens where funtionality has been disabled by the admin. The message should be
7935     * limited to a short statement such as "This setting is disabled by your administrator. Contact
7936     * someone@example.com for support." If the message is longer than 200 characters it may be
7937     * truncated.
7938     * <p>
7939     * If the short support message needs to be localized, it is the responsibility of the
7940     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7941     * and set a new version of this string accordingly.
7942     *
7943     * @see #setLongSupportMessage
7944     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7945     * @param message Short message to be displayed to the user in settings or null to clear the
7946     *            existing message.
7947     * @throws SecurityException if {@code admin} is not an active administrator.
7948     */
7949    public void setShortSupportMessage(@NonNull ComponentName admin,
7950            @Nullable CharSequence message) {
7951        throwIfParentInstance("setShortSupportMessage");
7952        if (mService != null) {
7953            try {
7954                mService.setShortSupportMessage(admin, message);
7955            } catch (RemoteException e) {
7956                throw e.rethrowFromSystemServer();
7957            }
7958        }
7959    }
7960
7961    /**
7962     * Called by a device admin to get the short support message.
7963     *
7964     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7965     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
7966     *         null if no message has been set.
7967     * @throws SecurityException if {@code admin} is not an active administrator.
7968     */
7969    public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
7970        throwIfParentInstance("getShortSupportMessage");
7971        if (mService != null) {
7972            try {
7973                return mService.getShortSupportMessage(admin);
7974            } catch (RemoteException e) {
7975                throw e.rethrowFromSystemServer();
7976            }
7977        }
7978        return null;
7979    }
7980
7981    /**
7982     * Called by a device admin to set the long support message. This will be displayed to the user
7983     * in the device administators settings screen.
7984     * <p>
7985     * If the long support message needs to be localized, it is the responsibility of the
7986     * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
7987     * and set a new version of this string accordingly.
7988     *
7989     * @see #setShortSupportMessage
7990     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7991     * @param message Long message to be displayed to the user in settings or null to clear the
7992     *            existing message.
7993     * @throws SecurityException if {@code admin} is not an active administrator.
7994     */
7995    public void setLongSupportMessage(@NonNull ComponentName admin,
7996            @Nullable CharSequence message) {
7997        throwIfParentInstance("setLongSupportMessage");
7998        if (mService != null) {
7999            try {
8000                mService.setLongSupportMessage(admin, message);
8001            } catch (RemoteException e) {
8002                throw e.rethrowFromSystemServer();
8003            }
8004        }
8005    }
8006
8007    /**
8008     * Called by a device admin to get the long support message.
8009     *
8010     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8011     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
8012     *         null if no message has been set.
8013     * @throws SecurityException if {@code admin} is not an active administrator.
8014     */
8015    public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
8016        throwIfParentInstance("getLongSupportMessage");
8017        if (mService != null) {
8018            try {
8019                return mService.getLongSupportMessage(admin);
8020            } catch (RemoteException e) {
8021                throw e.rethrowFromSystemServer();
8022            }
8023        }
8024        return null;
8025    }
8026
8027    /**
8028     * Called by the system to get the short support message.
8029     *
8030     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8031     * @param userHandle user id the admin is running as.
8032     * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
8033     *
8034     * @hide
8035     */
8036    public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
8037            int userHandle) {
8038        if (mService != null) {
8039            try {
8040                return mService.getShortSupportMessageForUser(admin, userHandle);
8041            } catch (RemoteException e) {
8042                throw e.rethrowFromSystemServer();
8043            }
8044        }
8045        return null;
8046    }
8047
8048
8049    /**
8050     * Called by the system to get the long support message.
8051     *
8052     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8053     * @param userHandle user id the admin is running as.
8054     * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
8055     *
8056     * @hide
8057     */
8058    public @Nullable CharSequence getLongSupportMessageForUser(
8059            @NonNull ComponentName admin, int userHandle) {
8060        if (mService != null) {
8061            try {
8062                return mService.getLongSupportMessageForUser(admin, userHandle);
8063            } catch (RemoteException e) {
8064                throw e.rethrowFromSystemServer();
8065            }
8066        }
8067        return null;
8068    }
8069
8070    /**
8071     * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
8072     * whose calls act on the parent profile.
8073     *
8074     * <p>The following methods are supported for the parent instance, all other methods will
8075     * throw a SecurityException when called on the parent instance:
8076     * <ul>
8077     * <li>{@link #getPasswordQuality}</li>
8078     * <li>{@link #setPasswordQuality}</li>
8079     * <li>{@link #getPasswordMinimumLength}</li>
8080     * <li>{@link #setPasswordMinimumLength}</li>
8081     * <li>{@link #getPasswordMinimumUpperCase}</li>
8082     * <li>{@link #setPasswordMinimumUpperCase}</li>
8083     * <li>{@link #getPasswordMinimumLowerCase}</li>
8084     * <li>{@link #setPasswordMinimumLowerCase}</li>
8085     * <li>{@link #getPasswordMinimumLetters}</li>
8086     * <li>{@link #setPasswordMinimumLetters}</li>
8087     * <li>{@link #getPasswordMinimumNumeric}</li>
8088     * <li>{@link #setPasswordMinimumNumeric}</li>
8089     * <li>{@link #getPasswordMinimumSymbols}</li>
8090     * <li>{@link #setPasswordMinimumSymbols}</li>
8091     * <li>{@link #getPasswordMinimumNonLetter}</li>
8092     * <li>{@link #setPasswordMinimumNonLetter}</li>
8093     * <li>{@link #getPasswordHistoryLength}</li>
8094     * <li>{@link #setPasswordHistoryLength}</li>
8095     * <li>{@link #getPasswordExpirationTimeout}</li>
8096     * <li>{@link #setPasswordExpirationTimeout}</li>
8097     * <li>{@link #getPasswordExpiration}</li>
8098     * <li>{@link #getPasswordMaximumLength}</li>
8099     * <li>{@link #isActivePasswordSufficient}</li>
8100     * <li>{@link #getCurrentFailedPasswordAttempts}</li>
8101     * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
8102     * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
8103     * <li>{@link #getMaximumTimeToLock}</li>
8104     * <li>{@link #setMaximumTimeToLock}</li>
8105     * <li>{@link #lockNow}</li>
8106     * <li>{@link #getKeyguardDisabledFeatures}</li>
8107     * <li>{@link #setKeyguardDisabledFeatures}</li>
8108     * <li>{@link #getTrustAgentConfiguration}</li>
8109     * <li>{@link #setTrustAgentConfiguration}</li>
8110     * <li>{@link #getRequiredStrongAuthTimeout}</li>
8111     * <li>{@link #setRequiredStrongAuthTimeout}</li>
8112     * </ul>
8113     *
8114     * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
8115     * @throws SecurityException if {@code admin} is not a profile owner.
8116     */
8117    public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
8118        throwIfParentInstance("getParentProfileInstance");
8119        try {
8120            if (!mService.isManagedProfile(admin)) {
8121                throw new SecurityException("The current user does not have a parent profile.");
8122            }
8123            return new DevicePolicyManager(mContext, mService, true);
8124        } catch (RemoteException e) {
8125            throw e.rethrowFromSystemServer();
8126        }
8127    }
8128
8129    /**
8130     * Called by device owner to control the security logging feature.
8131     *
8132     * <p> Security logs contain various information intended for security auditing purposes.
8133     * See {@link SecurityEvent} for details.
8134     *
8135     * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
8136     * are unaffiliated secondary users or profiles on the device, regardless of whether the
8137     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
8138     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
8139     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
8140     *
8141     * @param admin Which device owner this request is associated with.
8142     * @param enabled whether security logging should be enabled or not.
8143     * @throws SecurityException if {@code admin} is not a device owner.
8144     * @see #setAffiliationIds
8145     * @see #retrieveSecurityLogs
8146     */
8147    public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
8148        throwIfParentInstance("setSecurityLoggingEnabled");
8149        try {
8150            mService.setSecurityLoggingEnabled(admin, enabled);
8151        } catch (RemoteException re) {
8152            throw re.rethrowFromSystemServer();
8153        }
8154    }
8155
8156    /**
8157     * Return whether security logging is enabled or not by the device owner.
8158     *
8159     * <p>Can only be called by the device owner, otherwise a {@link SecurityException} will be
8160     * thrown.
8161     *
8162     * @param admin Which device owner this request is associated with.
8163     * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
8164     * @throws SecurityException if {@code admin} is not a device owner.
8165     */
8166    public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
8167        throwIfParentInstance("isSecurityLoggingEnabled");
8168        try {
8169            return mService.isSecurityLoggingEnabled(admin);
8170        } catch (RemoteException re) {
8171            throw re.rethrowFromSystemServer();
8172        }
8173    }
8174
8175    /**
8176     * Called by device owner to retrieve all new security logging entries since the last call to
8177     * this API after device boots.
8178     *
8179     * <p> Access to the logs is rate limited and it will only return new logs after the device
8180     * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
8181     *
8182     * <p>If there is any other user or profile on the device, it must be affiliated with the
8183     * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8184     *
8185     * @param admin Which device owner this request is associated with.
8186     * @return the new batch of security logs which is a list of {@link SecurityEvent},
8187     * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
8188     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8189     * profile or secondary user that is not affiliated with the device.
8190     * @see #isAffiliatedUser
8191     * @see DeviceAdminReceiver#onSecurityLogsAvailable
8192     */
8193    public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
8194        throwIfParentInstance("retrieveSecurityLogs");
8195        try {
8196            ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
8197            if (list != null) {
8198                return list.getList();
8199            } else {
8200                // Rate limit exceeded.
8201                return null;
8202            }
8203        } catch (RemoteException re) {
8204            throw re.rethrowFromSystemServer();
8205        }
8206    }
8207
8208    /**
8209     * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
8210     * profile.
8211     *
8212     * @hide
8213     */
8214    public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
8215        mContext.checkSelfPermission(
8216                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
8217        if (!uInfo.isManagedProfile()) {
8218            throw new SecurityException("The user " + uInfo.id
8219                    + " does not have a parent profile.");
8220        }
8221        return new DevicePolicyManager(mContext, mService, true);
8222    }
8223
8224    /**
8225     * Called by device owners to retrieve device logs from before the device's last reboot.
8226     * <p>
8227     * <strong> This API is not supported on all devices. Calling this API on unsupported devices
8228     * will result in {@code null} being returned. The device logs are retrieved from a RAM region
8229     * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
8230     * about data corruption when parsing. </strong>
8231     *
8232     * <p>If there is any other user or profile on the device, it must be affiliated with the
8233     * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8234     *
8235     * @param admin Which device owner this request is associated with.
8236     * @return Device logs from before the latest reboot of the system, or {@code null} if this API
8237     *         is not supported on the device.
8238     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8239     * profile or secondary user that is not affiliated with the device.
8240     * @see #isAffiliatedUser
8241     * @see #retrieveSecurityLogs
8242     */
8243    public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
8244            @NonNull ComponentName admin) {
8245        throwIfParentInstance("retrievePreRebootSecurityLogs");
8246        try {
8247            ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
8248            if (list != null) {
8249                return list.getList();
8250            } else {
8251                return null;
8252            }
8253        } catch (RemoteException re) {
8254            throw re.rethrowFromSystemServer();
8255        }
8256    }
8257
8258    /**
8259     * Called by a profile owner of a managed profile to set the color used for customization. This
8260     * color is used as background color of the confirm credentials screen for that user. The
8261     * default color is teal (#00796B).
8262     * <p>
8263     * The confirm credentials screen can be created using
8264     * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
8265     *
8266     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8267     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
8268     * @throws SecurityException if {@code admin} is not a profile owner.
8269     */
8270    public void setOrganizationColor(@NonNull ComponentName admin, int color) {
8271        throwIfParentInstance("setOrganizationColor");
8272        try {
8273            // always enforce alpha channel to have 100% opacity
8274            color |= 0xFF000000;
8275            mService.setOrganizationColor(admin, color);
8276        } catch (RemoteException re) {
8277            throw re.rethrowFromSystemServer();
8278        }
8279    }
8280
8281    /**
8282     * @hide
8283     *
8284     * Sets the color used for customization.
8285     *
8286     * @param color The 24bit (0xRRGGBB) representation of the color to be used.
8287     * @param userId which user to set the color to.
8288     * @RequiresPermission(allOf = {
8289     *       Manifest.permission.MANAGE_USERS,
8290     *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
8291     */
8292    public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
8293        try {
8294            // always enforce alpha channel to have 100% opacity
8295            color |= 0xFF000000;
8296            mService.setOrganizationColorForUser(color, userId);
8297        } catch (RemoteException re) {
8298            throw re.rethrowFromSystemServer();
8299        }
8300    }
8301
8302    /**
8303     * Called by a profile owner of a managed profile to retrieve the color used for customization.
8304     * This color is used as background color of the confirm credentials screen for that user.
8305     *
8306     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8307     * @return The 24bit (0xRRGGBB) representation of the color to be used.
8308     * @throws SecurityException if {@code admin} is not a profile owner.
8309     */
8310    public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
8311        throwIfParentInstance("getOrganizationColor");
8312        try {
8313            return mService.getOrganizationColor(admin);
8314        } catch (RemoteException re) {
8315            throw re.rethrowFromSystemServer();
8316        }
8317    }
8318
8319    /**
8320     * @hide
8321     * Retrieve the customization color for a given user.
8322     *
8323     * @param userHandle The user id of the user we're interested in.
8324     * @return The 24bit (0xRRGGBB) representation of the color to be used.
8325     */
8326    public @ColorInt int getOrganizationColorForUser(int userHandle) {
8327        try {
8328            return mService.getOrganizationColorForUser(userHandle);
8329        } catch (RemoteException re) {
8330            throw re.rethrowFromSystemServer();
8331        }
8332    }
8333
8334    /**
8335     * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
8336     * the organization under management.
8337     *
8338     * <p>If the organization name needs to be localized, it is the responsibility of the {@link
8339     * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
8340     * a new version of this string accordingly.
8341     *
8342     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8343     * @param title The organization name or {@code null} to clear a previously set name.
8344     * @throws SecurityException if {@code admin} is not a device or profile owner.
8345     */
8346    public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
8347        throwIfParentInstance("setOrganizationName");
8348        try {
8349            mService.setOrganizationName(admin, title);
8350        } catch (RemoteException re) {
8351            throw re.rethrowFromSystemServer();
8352        }
8353    }
8354
8355    /**
8356     * Called by a profile owner of a managed profile to retrieve the name of the organization under
8357     * management.
8358     *
8359     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8360     * @return The organization name or {@code null} if none is set.
8361     * @throws SecurityException if {@code admin} is not a profile owner.
8362     */
8363    public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
8364        throwIfParentInstance("getOrganizationName");
8365        try {
8366            return mService.getOrganizationName(admin);
8367        } catch (RemoteException re) {
8368            throw re.rethrowFromSystemServer();
8369        }
8370    }
8371
8372    /**
8373     * Called by the system to retrieve the name of the organization managing the device.
8374     *
8375     * @return The organization name or {@code null} if none is set.
8376     * @throws SecurityException if the caller is not the device owner, does not hold the
8377     *         MANAGE_USERS permission and is not the system.
8378     *
8379     * @hide
8380     */
8381    @SystemApi
8382    @TestApi
8383    @SuppressLint("Doclava125")
8384    public @Nullable CharSequence getDeviceOwnerOrganizationName() {
8385        try {
8386            return mService.getDeviceOwnerOrganizationName();
8387        } catch (RemoteException re) {
8388            throw re.rethrowFromSystemServer();
8389        }
8390    }
8391
8392    /**
8393     * Retrieve the default title message used in the confirm credentials screen for a given user.
8394     *
8395     * @param userHandle The user id of the user we're interested in.
8396     * @return The organization name or {@code null} if none is set.
8397     *
8398     * @hide
8399     */
8400    public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
8401        try {
8402            return mService.getOrganizationNameForUser(userHandle);
8403        } catch (RemoteException re) {
8404            throw re.rethrowFromSystemServer();
8405        }
8406    }
8407
8408    /**
8409     * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
8410     *         return {@link #STATE_USER_UNMANAGED}
8411     * @hide
8412     */
8413    @SystemApi
8414    @UserProvisioningState
8415    public int getUserProvisioningState() {
8416        throwIfParentInstance("getUserProvisioningState");
8417        if (mService != null) {
8418            try {
8419                return mService.getUserProvisioningState();
8420            } catch (RemoteException e) {
8421                throw e.rethrowFromSystemServer();
8422            }
8423        }
8424        return STATE_USER_UNMANAGED;
8425    }
8426
8427    /**
8428     * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
8429     *
8430     * @param state to store
8431     * @param userHandle for user
8432     * @hide
8433     */
8434    public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
8435        if (mService != null) {
8436            try {
8437                mService.setUserProvisioningState(state, userHandle);
8438            } catch (RemoteException e) {
8439                throw e.rethrowFromSystemServer();
8440            }
8441        }
8442    }
8443
8444    /**
8445     * Indicates the entity that controls the device or profile owner. Two users/profiles are
8446     * affiliated if the set of ids set by their device or profile owners intersect.
8447     *
8448     * <p>A user/profile that is affiliated with the device owner user is considered to be
8449     * affiliated with the device.
8450     *
8451     * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
8452     * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user or profile
8453     * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
8454     * affiliation ids are set by its profile owner as soon as possible after the user/profile is
8455     * created.
8456     *
8457     * @param admin Which profile or device owner this request is associated with.
8458     * @param ids A set of opaque non-empty affiliation ids.
8459     *
8460     * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
8461     * @see #isAffiliatedUser
8462     */
8463    public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
8464        throwIfParentInstance("setAffiliationIds");
8465        if (ids == null) {
8466            throw new IllegalArgumentException("ids must not be null");
8467        }
8468        try {
8469            mService.setAffiliationIds(admin, new ArrayList<>(ids));
8470        } catch (RemoteException e) {
8471            throw e.rethrowFromSystemServer();
8472        }
8473    }
8474
8475    /**
8476     * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
8477     * empty set if none have been set.
8478     */
8479    public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
8480        throwIfParentInstance("getAffiliationIds");
8481        try {
8482            return new ArraySet<>(mService.getAffiliationIds(admin));
8483        } catch (RemoteException e) {
8484            throw e.rethrowFromSystemServer();
8485        }
8486    }
8487
8488    /**
8489     * Returns whether this user/profile is affiliated with the device.
8490     * <p>
8491     * By definition, the user that the device owner runs on is always affiliated with the device.
8492     * Any other user/profile is considered affiliated with the device if the set specified by its
8493     * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
8494     * @see #setAffiliationIds
8495     */
8496    public boolean isAffiliatedUser() {
8497        throwIfParentInstance("isAffiliatedUser");
8498        try {
8499            return mService.isAffiliatedUser();
8500        } catch (RemoteException e) {
8501            throw e.rethrowFromSystemServer();
8502        }
8503    }
8504
8505    /**
8506     * @hide
8507     * Returns whether the uninstall for {@code packageName} for the current user is in queue
8508     * to be started
8509     * @param packageName the package to check for
8510     * @return whether the uninstall intent for {@code packageName} is pending
8511     */
8512    public boolean isUninstallInQueue(String packageName) {
8513        try {
8514            return mService.isUninstallInQueue(packageName);
8515        } catch (RemoteException re) {
8516            throw re.rethrowFromSystemServer();
8517        }
8518    }
8519
8520    /**
8521     * @hide
8522     * @param packageName the package containing active DAs to be uninstalled
8523     */
8524    public void uninstallPackageWithActiveAdmins(String packageName) {
8525        try {
8526            mService.uninstallPackageWithActiveAdmins(packageName);
8527        } catch (RemoteException re) {
8528            throw re.rethrowFromSystemServer();
8529        }
8530    }
8531
8532    /**
8533     * @hide
8534     * Remove a test admin synchronously without sending it a broadcast about being removed.
8535     * If the admin is a profile owner or device owner it will still be removed.
8536     *
8537     * @param userHandle user id to remove the admin for.
8538     * @param admin The administration compononent to remove.
8539     * @throws SecurityException if the caller is not shell / root or the admin package
8540     *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
8541     */
8542    public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
8543        try {
8544            mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
8545        } catch (RemoteException re) {
8546            throw re.rethrowFromSystemServer();
8547        }
8548    }
8549
8550    /**
8551     * Returns whether the device has been provisioned.
8552     *
8553     * <p>Not for use by third-party applications.
8554     *
8555     * @hide
8556     */
8557    @SystemApi
8558    public boolean isDeviceProvisioned() {
8559        try {
8560            return mService.isDeviceProvisioned();
8561        } catch (RemoteException re) {
8562            throw re.rethrowFromSystemServer();
8563        }
8564    }
8565
8566    /**
8567      * Writes that the provisioning configuration has been applied.
8568      *
8569      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
8570      * permission.
8571      *
8572      * <p>Not for use by third-party applications.
8573      *
8574      * @hide
8575      */
8576    @SystemApi
8577    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8578    public void setDeviceProvisioningConfigApplied() {
8579        try {
8580            mService.setDeviceProvisioningConfigApplied();
8581        } catch (RemoteException re) {
8582            throw re.rethrowFromSystemServer();
8583        }
8584    }
8585
8586    /**
8587     * Returns whether the provisioning configuration has been applied.
8588     *
8589     * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
8590     *
8591     * <p>Not for use by third-party applications.
8592     *
8593     * @return whether the provisioning configuration has been applied.
8594     *
8595     * @hide
8596     */
8597    @SystemApi
8598    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8599    public boolean isDeviceProvisioningConfigApplied() {
8600        try {
8601            return mService.isDeviceProvisioningConfigApplied();
8602        } catch (RemoteException re) {
8603            throw re.rethrowFromSystemServer();
8604        }
8605    }
8606
8607    /**
8608     * @hide
8609     * Force update user setup completed status. This API has no effect on user build.
8610     * @throws {@link SecurityException} if the caller has no
8611     *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
8612     *         not {@link UserHandle#SYSTEM_USER}
8613     */
8614    public void forceUpdateUserSetupComplete() {
8615        try {
8616            mService.forceUpdateUserSetupComplete();
8617        } catch (RemoteException re) {
8618            throw re.rethrowFromSystemServer();
8619        }
8620    }
8621
8622    private void throwIfParentInstance(String functionName) {
8623        if (mParentInstance) {
8624            throw new SecurityException(functionName + " cannot be called on the parent instance");
8625        }
8626    }
8627
8628    /**
8629     * Allows the device owner to enable or disable the backup service.
8630     *
8631     * <p> Backup service manages all backup and restore mechanisms on the device. Setting this to
8632     * false will prevent data from being backed up or restored.
8633     *
8634     * <p> Backup service is off by default when device owner is present.
8635     *
8636     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8637     * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
8638     * @throws SecurityException if {@code admin} is not a device owner.
8639     */
8640    public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
8641        throwIfParentInstance("setBackupServiceEnabled");
8642        try {
8643            mService.setBackupServiceEnabled(admin, enabled);
8644        } catch (RemoteException re) {
8645            throw re.rethrowFromSystemServer();
8646        }
8647    }
8648
8649    /**
8650     * Return whether the backup service is enabled by the device owner.
8651     *
8652     * <p> Backup service manages all backup and restore mechanisms on the device.
8653     *
8654     * @return {@code true} if backup service is enabled, {@code false} otherwise.
8655     * @see #setBackupServiceEnabled
8656     */
8657    public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
8658        throwIfParentInstance("isBackupServiceEnabled");
8659        try {
8660            return mService.isBackupServiceEnabled(admin);
8661        } catch (RemoteException re) {
8662            throw re.rethrowFromSystemServer();
8663        }
8664    }
8665
8666    /**
8667     * Called by a device owner to control the network logging feature.
8668     *
8669     * <p> Network logs contain DNS lookup and connect() library call events. The following library
8670     *     functions are recorded while network logging is active:
8671     *     <ul>
8672     *       <li>{@code getaddrinfo()}</li>
8673     *       <li>{@code gethostbyname()}</li>
8674     *       <li>{@code connect()}</li>
8675     *     </ul>
8676     *
8677     * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
8678     *     full system call logging; event reporting is enabled by default for all processes but not
8679     *     strongly enforced.
8680     *     Events from applications using alternative implementations of libc, making direct kernel
8681     *     calls, or deliberately obfuscating traffic may not be recorded.
8682     *
8683     * <p> Some common network events may not be reported. For example:
8684     *     <ul>
8685     *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
8686     *           an alternative system for name resolution, and so avoid calling
8687     *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
8688     *       <li>Applications may use datagram sockets for performance reasons, for example
8689     *           for a game client. Calling {@code connect()} is unnecessary for this kind of
8690     *           socket, so it will not trigger a network event.</li>
8691     *     </ul>
8692     *
8693     * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
8694     *     always-on VPN service.
8695     *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
8696     *     and {@link android.net.VpnService} for details.
8697     *
8698     * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
8699     * are unaffiliated secondary users or profiles on the device, regardless of whether the
8700     * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
8701     * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
8702     * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
8703     *
8704     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8705     * @param enabled whether network logging should be enabled or not.
8706     * @throws SecurityException if {@code admin} is not a device owner.
8707     * @see #setAffiliationIds
8708     * @see #retrieveNetworkLogs
8709     */
8710    public void setNetworkLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
8711        throwIfParentInstance("setNetworkLoggingEnabled");
8712        try {
8713            mService.setNetworkLoggingEnabled(admin, enabled);
8714        } catch (RemoteException re) {
8715            throw re.rethrowFromSystemServer();
8716        }
8717    }
8718
8719    /**
8720     * Return whether network logging is enabled by a device owner.
8721     *
8722     * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
8723     * be {@code null} if the caller has MANAGE_USERS permission.
8724     * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
8725     * @throws SecurityException if {@code admin} is not a device owner and caller has
8726     * no MANAGE_USERS permission
8727     */
8728    public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
8729        throwIfParentInstance("isNetworkLoggingEnabled");
8730        try {
8731            return mService.isNetworkLoggingEnabled(admin);
8732        } catch (RemoteException re) {
8733            throw re.rethrowFromSystemServer();
8734        }
8735    }
8736
8737    /**
8738     * Called by device owner to retrieve the most recent batch of network logging events.
8739     * A device owner has to provide a batchToken provided as part of
8740     * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
8741     * token of the most recent available batch of logs, {@code null} will be returned.
8742     *
8743     * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
8744     *
8745     * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
8746     *
8747     * <p> Access to the logs is rate limited and this method will only return a new batch of logs
8748     * after the device device owner has been notified via
8749     * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
8750     *
8751     * <p>If a secondary user or profile is created, calling this method will throw a
8752     * {@link SecurityException} until all users become affiliated again. It will also no longer be
8753     * possible to retrieve the network logs batch with the most recent batchToken provided
8754     * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
8755     * {@link DevicePolicyManager#setAffiliationIds}.
8756     *
8757     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8758     * @param batchToken A token of the batch to retrieve
8759     * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
8760     *        {@code null} if the batch represented by batchToken is no longer available or if
8761     *        logging is disabled.
8762     * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8763     * profile or secondary user that is not affiliated with the device.
8764     * @see #setAffiliationIds
8765     * @see DeviceAdminReceiver#onNetworkLogsAvailable
8766     */
8767    public @Nullable List<NetworkEvent> retrieveNetworkLogs(@NonNull ComponentName admin,
8768            long batchToken) {
8769        throwIfParentInstance("retrieveNetworkLogs");
8770        try {
8771            return mService.retrieveNetworkLogs(admin, batchToken);
8772        } catch (RemoteException re) {
8773            throw re.rethrowFromSystemServer();
8774        }
8775    }
8776
8777    /**
8778     * Called by a device owner to bind to a service from a profile owner or vice versa.
8779     * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
8780     * device/profile owners are allowed to bind to services of another profile/device owner.
8781     * <p>
8782     * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
8783     * Note that the {@link Context} used to obtain this
8784     * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
8785     * to bind to the {@link android.app.Service}.
8786     *
8787     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8788     * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
8789     *        explicit component name or a package name to match an
8790     *        {@link IntentFilter} published by a service.
8791     * @param conn Receives information as the service is started and stopped in main thread. This
8792     *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
8793     * @param flags Operation options for the binding operation. See
8794     *        {@link Context#bindService(Intent, ServiceConnection, int)}.
8795     * @param targetUser Which user to bind to. Must be one of the users returned by
8796     *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
8797     *        be thrown.
8798     * @return If you have successfully bound to the service, {@code true} is returned;
8799     *         {@code false} is returned if the connection is not made and you will not
8800     *         receive the service object.
8801     *
8802     * @see Context#bindService(Intent, ServiceConnection, int)
8803     * @see #getBindDeviceAdminTargetUsers(ComponentName)
8804     */
8805    public boolean bindDeviceAdminServiceAsUser(
8806            @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
8807            @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
8808        throwIfParentInstance("bindDeviceAdminServiceAsUser");
8809        // Keep this in sync with ContextImpl.bindServiceCommon.
8810        try {
8811            final IServiceConnection sd = mContext.getServiceDispatcher(
8812                    conn, mContext.getMainThreadHandler(), flags);
8813            serviceIntent.prepareToLeaveProcess(mContext);
8814            return mService.bindDeviceAdminServiceAsUser(admin,
8815                    mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
8816                    sd, flags, targetUser.getIdentifier());
8817        } catch (RemoteException re) {
8818            throw re.rethrowFromSystemServer();
8819        }
8820    }
8821
8822    /**
8823     * Returns the list of target users that the calling device or profile owner can use when
8824     * calling {@link #bindDeviceAdminServiceAsUser}.
8825     * <p>
8826     * A device owner can bind to a service from a profile owner and vice versa, provided that:
8827     * <ul>
8828     * <li>Both belong to the same package name.
8829     * <li>Both users are affiliated. See {@link #setAffiliationIds}.
8830     * </ul>
8831     */
8832    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
8833        throwIfParentInstance("getBindDeviceAdminTargetUsers");
8834        try {
8835            return mService.getBindDeviceAdminTargetUsers(admin);
8836        } catch (RemoteException re) {
8837            throw re.rethrowFromSystemServer();
8838        }
8839    }
8840
8841    /**
8842     * Called by the system to get the time at which the device owner last retrieved security
8843     * logging entries.
8844     *
8845     * @return the time at which the device owner most recently retrieved security logging entries,
8846     *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
8847     * @throws SecurityException if the caller is not the device owner, does not hold the
8848     *         MANAGE_USERS permission and is not the system.
8849     *
8850     * @hide
8851     */
8852    @TestApi
8853    public long getLastSecurityLogRetrievalTime() {
8854        try {
8855            return mService.getLastSecurityLogRetrievalTime();
8856        } catch (RemoteException re) {
8857            throw re.rethrowFromSystemServer();
8858        }
8859    }
8860
8861    /**
8862     * Called by the system to get the time at which the device owner last requested a bug report.
8863     *
8864     * @return the time at which the device owner most recently requested a bug report, in
8865     *         milliseconds since epoch; -1 if a bug report was never requested.
8866     * @throws SecurityException if the caller is not the device owner, does not hold the
8867     *         MANAGE_USERS permission and is not the system.
8868     *
8869     * @hide
8870     */
8871    @TestApi
8872    public long getLastBugReportRequestTime() {
8873        try {
8874            return mService.getLastBugReportRequestTime();
8875        } catch (RemoteException re) {
8876            throw re.rethrowFromSystemServer();
8877        }
8878    }
8879
8880    /**
8881     * Called by the system to get the time at which the device owner last retrieved network logging
8882     * events.
8883     *
8884     * @return the time at which the device owner most recently retrieved network logging events, in
8885     *         milliseconds since epoch; -1 if network logging events were never retrieved.
8886     * @throws SecurityException if the caller is not the device owner, does not hold the
8887     *         MANAGE_USERS permission and is not the system.
8888     *
8889     * @hide
8890     */
8891    @TestApi
8892    public long getLastNetworkLogRetrievalTime() {
8893        try {
8894            return mService.getLastNetworkLogRetrievalTime();
8895        } catch (RemoteException re) {
8896            throw re.rethrowFromSystemServer();
8897        }
8898    }
8899
8900    /**
8901     * Called by the system to find out whether the current user's IME was set by the device/profile
8902     * owner or the user.
8903     *
8904     * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
8905     *         otherwise.
8906     * @throws SecurityException if the caller is not the device owner/profile owner.
8907     *
8908     * @hide
8909     */
8910    @TestApi
8911    public boolean isCurrentInputMethodSetByOwner() {
8912        try {
8913            return mService.isCurrentInputMethodSetByOwner();
8914        } catch (RemoteException re) {
8915            throw re.rethrowFromSystemServer();
8916        }
8917    }
8918
8919    /**
8920     * Called by the system to get a list of CA certificates that were installed by the device or
8921     * profile owner.
8922     *
8923     * <p> The caller must be the target user's device owner/profile Owner or hold the
8924     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
8925     *
8926     * @param user The user for whom to retrieve information.
8927     * @return list of aliases identifying CA certificates installed by the device or profile owner
8928     * @throws SecurityException if the caller does not have permission to retrieve information
8929     *         about the given user's CA certificates.
8930     *
8931     * @hide
8932     */
8933    @TestApi
8934    public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
8935        try {
8936            return mService.getOwnerInstalledCaCerts(user).getList();
8937        } catch (RemoteException re) {
8938            throw re.rethrowFromSystemServer();
8939        }
8940    }
8941
8942    /** {@hide} */
8943    @Condemned
8944    @Deprecated
8945    public boolean clearApplicationUserData(@NonNull ComponentName admin,
8946            @NonNull String packageName, @NonNull OnClearApplicationUserDataListener listener,
8947            @NonNull Handler handler) {
8948        return clearApplicationUserData(admin, packageName, listener, new HandlerExecutor(handler));
8949    }
8950
8951    /**
8952     * Called by the device owner or profile owner to clear application user data of a given
8953     * package. The behaviour of this is equivalent to the target application calling
8954     * {@link android.app.ActivityManager#clearApplicationUserData()}.
8955     *
8956     * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
8957     * external storage or user dictionary. This data will not be wiped by calling this API.
8958     *
8959     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8960     * @param packageName The name of the package which will have its user data wiped.
8961     * @param listener A callback object that will inform the caller when the clearing is done.
8962     * @param executor The executor through which the listener should be invoked.
8963     * @throws SecurityException if the caller is not the device owner/profile owner.
8964     * @return whether the clearing succeeded.
8965     */
8966    public boolean clearApplicationUserData(@NonNull ComponentName admin,
8967            @NonNull String packageName, @NonNull OnClearApplicationUserDataListener listener,
8968            @NonNull @CallbackExecutor Executor executor) {
8969        throwIfParentInstance("clearAppData");
8970        Preconditions.checkNotNull(executor);
8971        try {
8972            return mService.clearApplicationUserData(admin, packageName,
8973                    new IPackageDataObserver.Stub() {
8974                        public void onRemoveCompleted(String pkg, boolean succeeded) {
8975                            executor.execute(() ->
8976                                    listener.onApplicationUserDataCleared(pkg, succeeded));
8977                        }
8978                    });
8979        } catch (RemoteException re) {
8980            throw re.rethrowFromSystemServer();
8981        }
8982    }
8983
8984    /**
8985     * Called by a device owner to specify whether logout is enabled for all secondary users. The
8986     * system may show a logout button that stops the user and switches back to the primary user.
8987     *
8988     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8989     * @param enabled whether logout should be enabled or not.
8990     * @throws SecurityException if {@code admin} is not a device owner.
8991     */
8992    public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
8993        throwIfParentInstance("setLogoutEnabled");
8994        try {
8995            mService.setLogoutEnabled(admin, enabled);
8996        } catch (RemoteException re) {
8997            throw re.rethrowFromSystemServer();
8998        }
8999    }
9000
9001    /**
9002     * Returns whether logout is enabled by a device owner.
9003     *
9004     * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
9005     */
9006    public boolean isLogoutEnabled() {
9007        throwIfParentInstance("isLogoutEnabled");
9008        try {
9009            return mService.isLogoutEnabled();
9010        } catch (RemoteException re) {
9011            throw re.rethrowFromSystemServer();
9012        }
9013    }
9014
9015    /**
9016     * Callback used in {@link #clearApplicationUserData}
9017     * to indicate that the clearing of an application's user data is done.
9018     */
9019    public interface OnClearApplicationUserDataListener {
9020        /**
9021         * Method invoked when clearing the application user data has completed.
9022         *
9023         * @param packageName The name of the package which had its user data cleared.
9024         * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
9025         *                  apps and protected system packages.
9026         */
9027        void onApplicationUserDataCleared(String packageName, boolean succeeded);
9028    }
9029
9030    /**
9031     * Returns set of system apps that should be removed during provisioning.
9032     *
9033     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9034     * @param userId ID of the user to be provisioned.
9035     * @param provisioningAction action indicating type of provisioning, should be one of
9036     * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
9037     * {@link #ACTION_PROVISION_MANAGED_USER}.
9038     *
9039     * @hide
9040     */
9041    public Set<String> getDisallowedSystemApps(ComponentName admin, int userId,
9042            String provisioningAction) {
9043        try {
9044            return new ArraySet<>(
9045                    mService.getDisallowedSystemApps(admin, userId, provisioningAction));
9046        } catch (RemoteException re) {
9047            throw re.rethrowFromSystemServer();
9048        }
9049    }
9050
9051    /**
9052     * Changes the current administrator to another one. All policies from the current
9053     * administrator are migrated to the new administrator. The whole operation is atomic -
9054     * the transfer is either complete or not done at all.
9055     *
9056     * <p>Depending on the current administrator (device owner, profile owner), you have the
9057     * following expected behaviour:
9058     * <ul>
9059     *     <li>A device owner can only be transferred to a new device owner</li>
9060     *     <li>A profile owner can only be transferred to a new profile owner</li>
9061     * </ul>
9062     *
9063     * <p>Use the {@code bundle} parameter to pass data to the new administrator. The parameters
9064     * will be received in the
9065     * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)} callback.
9066     *
9067     * @param admin which {@link DeviceAdminReceiver} this request is associated with
9068     * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
9069     * @param bundle data to be sent to the new administrator
9070     * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
9071     * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null},
9072     * both are components in the same package or {@code target} is not an active admin
9073     */
9074    public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
9075            PersistableBundle bundle) {
9076        throwIfParentInstance("transferOwnership");
9077        try {
9078            mService.transferOwnership(admin, target, bundle);
9079        } catch (RemoteException re) {
9080            throw re.rethrowFromSystemServer();
9081        }
9082    }
9083}
9084